Counting pending orders with Ctrade problem - page 2

 
Vladimir Karputov:
In OnInit (), you need to initialize the 'm_symbol' and 'm_trade' objects. See examples in CodeBase.

I looked in the CodeBase for m_symbol' and 'm_trade  objects. It still opens many pending orders. Instead of one

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>

CTrade trade;
CTrade m_trade;
CPositionInfo m_position;
CSymbolInfo m_symbol;
COrderInfo m_order;
CDealInfo  m_deal; 

input int MagicNumber=01;
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int OnInit(void)
 {
  m_symbol.Name(Symbol());
  m_symbol.Refresh();
  m_trade.SetExpertMagicNumber(MagicNumber);

  trade.LogLevel(LOG_LEVEL_ERRORS);
  trade.SetMarginMode();
  m_trade.SetTypeFillingBySymbol(m_symbol.Name());
  trade.SetTypeFillingBySymbol(Symbol());
  return(INIT_SUCCEEDED);
  //return(0);
 }

bool OrdersPending(void)
 {
  for(int b=OrdersTotal()-1;b>=0;b--)
  if(m_order.SelectByIndex(b))
  if(m_order.Symbol()==m_symbol.Name()&&m_order.Magic()==MagicNumber)
  return(true);
  
  return(false);
 }
 
void Buy()
 {
  double Pips=0;
  double TickSize=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  if(TickSize==0.00001||TickSize==0.001)
  Pips=TickSize*10;
  else Pips=TickSize;
  
  double Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  double Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
  
  double CloseBar=iClose(NULL,0,1);
  double CloseBarNext=iClose(NULL,0,2);
  double OpenBar=iOpen(NULL,0,1);
  double OpenBarNext=iOpen(NULL,0,2);
  double HighBar=iHigh(NULL,0,1);
  double HighBarNext=iHigh(NULL,0,2);
  double LowBar=iLow(NULL,0,1);
  double LowBarNext=iLow(NULL,0,2);
  double EngulfingBuy=LowBar<LowBarNext&&HighBar>HighBarNext&&CloseBar>OpenBarNext&&OpenBar<CloseBar&&OpenBarNext>CloseBarNext;
  double HaramiBuy=OpenBarNext>CloseBarNext&&CloseBar>OpenBar&&HighBarNext>HighBar&&OpenBarNext>CloseBar&&LowBarNext<LowBar;
  
  if(HaramiBuy)
  {
   trade.BuyStop(0.01,Ask+2*Pips,NULL,0,0,0,0,"JackBuda");
  }
  
  else if(EngulfingBuy)
  {
   trade.BuyStop(0.01,Ask+2*Pips,NULL,0,0,0,0,"JackBuda");
  }
 }
 
void Sell()
 {
  double Pips=0;
  double TickSize=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  if(TickSize==0.00001||TickSize==0.001)
  Pips=TickSize*10;
  else Pips=TickSize;
  
  double Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  double Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
  
  double CloseBar=iClose(NULL,0,1);
  double CloseBarNext=iClose(NULL,0,2);
  double OpenBar=iOpen(NULL,0,1);
  double OpenBarNext=iOpen(NULL,0,2);
  double HighBar=iHigh(NULL,0,1);
  double HighBarNext=iHigh(NULL,0,2);
  double LowBar=iLow(NULL,0,1);
  double LowBarNext=iLow(NULL,0,2);
  
  double EngulfingSell=LowBar<LowBarNext&&HighBar>HighBarNext&&CloseBar<OpenBarNext&&OpenBar>CloseBar&&OpenBarNext<CloseBarNext;
  double HaramiSell=OpenBarNext<CloseBarNext&&CloseBar<OpenBar&&HighBarNext<HighBar&&OpenBarNext<CloseBar&&LowBarNext>LowBar;
  
  if(HaramiSell)
  {
   trade.SellStop(0.01,Bid-2*Pips,NULL,0,0,0,0,"JackBuda");
  }
  
  else if(EngulfingSell)
  {
   trade.SellStop(0.01,Bid-2*Pips,NULL,0,0,0,0,"JackBuda");
  }
  
 }  

void OnTick()
 {
  double AccountBalance=AccountInfoDouble(ACCOUNT_BALANCE);
  
  if(AccountBalance>10&&OrdersPending()<1){Buy();}
  
  if(AccountBalance>10&&OrdersPending()<1){Sell();}
  
  for(int Loop=PositionsTotal()-1;Loop>=0;Loop--)
  {
   if(m_position.SelectByIndex(Loop))
   if(m_position.Symbol()==Symbol())
   {
    double ProfitPips=PositionGetDouble(POSITION_VOLUME)*200;
    double Profit2=PositionGetDouble(POSITION_PROFIT);
    int Type=(int)OrderGetInteger(ORDER_TYPE);
    switch(Type)
    {
     case ORDER_TYPE_BUY:if(Profit2>ProfitPips) m_trade.PositionClose(m_position.Ticket());
     case ORDER_TYPE_SELL:if(Profit2>ProfitPips) m_trade.PositionClose(m_position.Ticket());   
    }
   
   }
  
  } 
   
 }
 
Jack Buda :


Why do you need two identical objects?

CTrade trade;
CTrade m_trade;

And why don't you initialize the object of the CTrade trade class?

 
Vladimir Karputov:

Why do you need two identical objects?

And why don't you initialize the object of the CTrade trade class?

I wasn't aware, I removed it. If I initialize the CTrade, that will give me errors:

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>

//CTrade trade;
CPositionInfo m_position;
CSymbolInfo m_symbol;
COrderInfo m_order;
CDealInfo  m_deal; 

input int MagicNumber=01;
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int OnInit(void)
 {
  CTrade trade;
  
  m_symbol.Name(Symbol());
  m_symbol.Refresh();
  trade.SetExpertMagicNumber(MagicNumber);

  trade.LogLevel(LOG_LEVEL_ERRORS);
  trade.SetMarginMode();
  trade.SetTypeFillingBySymbol(m_symbol.Name());
  trade.SetTypeFillingBySymbol(Symbol());
  return(INIT_SUCCEEDED);
  //return(0);
 }
 
Jack Buda :

I wasn't aware, I removed it. If I initialize the CTrade, that will give me errors:

Initialization block:

   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
 
Jack Buda :

I looked in the CodeBase for m_symbol' and 'm_trade  objects. It still opens many pending orders . Instead of one

What is it???

  for(int Loop=PositionsTotal()-1;Loop>=0;Loop--)
  {
   if(m_position.SelectByIndex(Loop))
   if(m_position.Symbol()==Symbol())
   {
    double ProfitPips=PositionGetDouble(POSITION_VOLUME)*200;
    double Profit2=PositionGetDouble(POSITION_PROFIT);
    int Type=(int)OrderGetInteger(ORDER_TYPE);
    switch(Type)
    {
     case ORDER_TYPE_BUY:if(Profit2>ProfitPips) m_trade.PositionClose(m_position.Ticket());
     case ORDER_TYPE_SELL:if(Profit2>ProfitPips) m_trade.PositionClose(m_position.Ticket());   
    }

You cannot mix POSITIONS and PENDING ORDERS in one heap!

 
Vladimir Karputov:

Initialization block:

Okay I have added the Initialization block

int OnInit(void)
 {
  ResetLastError();
  
  if(m_symbol.Name(Symbol()))
  {
   Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
   return(INIT_FAILED);
   }
  
  m_symbol.Refresh();
  
  trade.SetExpertMagicNumber(MagicNumber);
  trade.LogLevel(LOG_LEVEL_ERRORS);
  trade.SetMarginMode();
  trade.SetTypeFillingBySymbol(m_symbol.Name());
  trade.SetTypeFillingBySymbol(Symbol());
  return(INIT_SUCCEEDED);
  //return(0);
 }

I'm still getting many Pending orders

 
Vladimir Karputov:

What is it???

You cannot mix POSITIONS and PENDING ORDERS in one heap!

I'll change it to:

int Type=m_position.PositionType();
 
Jack Buda:

Okay I have added the Initialization block

I'm still getting many Pending orders

Forum on trading, automated trading systems and testing trading strategies

Counting pending orders with Ctrade problem

Vladimir Karputov, 2021.08.21 14:57

Initialization block:

   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);


Forum on trading, automated trading systems and testing trading strategies

Counting pending orders with Ctrade problem

Vladimir Karputov, 2021.08.18 15:59

Or you can generally use this function:

//+------------------------------------------------------------------+
//| Is pending orders exists                                         |
//+------------------------------------------------------------------+
bool IsPendingOrdersExists(void)
  {
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of current orders
      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==InpMagic)
            return(true);
//---
   return(false);
  }

if it returns 'true', it means there are pending orders in the market.


Forum on trading, automated trading systems and testing trading strategies

How to start with MQL5

Vladimir Karputov, 2021.08.21 05:35

The EA can open only one position of the same type

Code: Example One position of one type.mq5

How the Expert Advisor works: the 'CalculateAllPositions' function is called in 'OnTick'. The 'CalculateAllPositions' function calculates 'BUY' and 'SELL' positions.

//+------------------------------------------------------------------+
//|                             Example One position of one type.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Additional features"
input ulong    InpDeviation         = 10;          // Deviation, in Points (1.00045-1.00055=10 points)
input ulong    InpMagic             = 200;         // Magic number
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int count_buys=0,count_sells=0;
   CalculateAllPositions(count_buys,count_sells);
   if(count_buys==0)
     {
      // Search for a BUY signal
     }
   if(count_sells==0)
     {
      // Search for a SELL signal
     }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Calculate all positions Buy and Sell                             |
//+------------------------------------------------------------------+
void CalculateAllPositions(int &count_buys,int &count_sells)
  {
   count_buys=0;
   count_sells=0;
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               count_buys++;
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               count_sells++;
           }
//---
   return;
  }
//+------------------------------------------------------------------+


 

Here is your code. Just rewrite your condition. I have a condition like this:

//+------------------------------------------------------------------+
//|                                        Harami EA Very simple.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.00"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\DealInfo.mqh>
#include <Trade\OrderInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
CAccountInfo   m_account;                    // object of CAccountInfo class
CDealInfo      m_deal;                       // object of CDealInfo class
COrderInfo     m_order;                      // object of COrderInfo class
//--- input parameters
input group             "Pending Order Parameters"
input uint                 InpPendingIndent        = 30;             // Pending: Indent
input group             "Additional features"
input bool                 InpPrintLog             = true;           // Print log
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 236638707;      // Magic number
//---
double   m_pending_indent           = 0.0;      // Pending: Indent            -> double
datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_pending_indent           = 0.0;      // Pending: Indent            -> double
   m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_pending_indent           = InpPendingIndent            * m_symbol.Point();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//---
   if(!IsPendingOrdersExists() && !IsPositionExists())
     {
      MqlTick tick;
      if(!SymbolInfoTick(m_symbol.Name(),tick))
         return;
      MqlRates rates[];
      ArraySetAsSeries(rates,true);
      int start_pos=0,count=6;
      if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)
        {
         m_prev_bars=0;
         return;
        }
      double CloseBar=iClose(NULL,0,1);
      double CloseBarNext=iClose(NULL,0,2);
      double OpenBar=iOpen(NULL,0,1);
      double OpenBarNext=iOpen(NULL,0,2);
      double HighBar=iHigh(NULL,0,1);
      double HighBarNext=iHigh(NULL,0,2);
      double LowBar=iLow(NULL,0,1);
      double LowBarNext=iLow(NULL,0,2);
      double EngulfingBuy=rates[1].low<rates[2].low&&rates[1].high>rates[2].high&&rates[1].close>rates[2].open&&rates[1].open<rates[1].close&&rates[2].open>rates[2].close;
      double HaramiBuy=rates[2].open>rates[2].close&&rates[1].close>rates[1].open&&rates[2].high>rates[1].high&&rates[2].open>rates[1].close&&rates[2].low<rates[1].low;
      //--- BUY Signal
      if(HaramiBuy)
        {
         m_trade.BuyStop(0.01,tick.ask+m_pending_indent);
        }
      //--- SELL Signal
      if(EngulfingBuy)
        {
         m_trade.SellStop(0.01,tick.bid-m_pending_indent);
        }
     }
  }
//+------------------------------------------------------------------+
//| Is pending orders exists                                         |
//+------------------------------------------------------------------+
bool IsPendingOrdersExists(void)
  {
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of current orders
      if(m_order.SelectByIndex(i))     // selects the pending order by index for further access to its properties
         if(m_order.Symbol()==m_symbol.Name() && m_order.Magic()==InpMagic)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+
//| Is position exists                                               |
//+------------------------------------------------------------------+
bool IsPositionExists(void)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+
Files:
 
Vladimir Karputov:

Here is your code. Just rewrite your condition. I have a condition like this:

Thank you Vladimir, it works now
Reason: