Problem with total amount of open orders

 

Hi Everyone.  I have tried every bit of advise that I can find on this forum, but none seems to work.  Will someone please help.  I believe the issue lies with my OrderTotal function.  I am trading 10 currency pairs, i.e. I have the EA open on 10 charts.  This is a simple hedging strategy.  I want the EA to open a trade (long or short) depending on signals.  If the trade goes my way, Trailingstop or Take profit.  If, however, the trade goes against me, I want it to open a trade in the opposite direction.  The code I am using seems to work but then sometimes it gets stuck, i.e. it no longer open any trades.  Also, when there are one or two trades open on one pair, it does not seem to want to open any trades on any other pairs.

 Here is my code

int start()
{
     {
     if (OrdersTotal() == 0)
     if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*0.0001, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
         }

  for(int i=OrdersTotal()-1; i>=0; i--) 
  {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      if (OrderSymbol()==Symbol())
      //Calculate the point value in case there are extra digits in the quotes
      if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
      else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);

//calculate new lotsize of hedge based on lotsize of current open trade*Multiplier
      double lots = NormalizeDouble(OrderLots() * Multiplier, 2); 
      
     if (OrderType() == OP_BUY) 
      {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *PointValue,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *PointValue,Digits))
            {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *PointValue,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
              }
            }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*PointValue,Digits))
            if(OrdersTotal() == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*PointValue, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
          }
 
  1. You need to filter the trades.
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
          if (OrderSymbol()==Symbol())
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;  // These
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;// four
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01; // lines
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);                    // Execute only on Symbol orders.
    
          double lots = NormalizeDouble(OrderLots() * Multiplier, 2);  // This and below are always executed
          if (OrderType() == OP_BUY)                                   // Symbol is irrelevant.             
    
    With braces.
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
          if (OrderSymbol()==Symbol())
    {                                                                   // Rest of code executes only on Symbol orders.
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    
          double lots = NormalizeDouble(OrderLots() * Multiplier, 2); 
          
          if (OrderType() == OP_BUY) 
             :
    }

  2. On a 4 digit broker, point = 0.0001
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    
    Fixed and simplified.
    PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    if(MarketInfo(OrderSymbol(), MODE_DIGITS) % 2 = 1) PointValue *= 10;

  3. Since everything inside the braces is Symbol(), every MarketInfo can be replaced with predefined variables
  4. Don't hard code numbers.
    Check your return codes What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*0.0001, 0, "Original", magicNumber, 0, Blue);
 

1.  Thank you so much for your help.  I have added a brace as suggested, but the EA still only opens a trade on one currency pair.  It will not open a trade on any of the other charts even though the buy condition have been met.  I've been stuck on this for weeks, will you please take another look.

2.  EDIT: No longer required

3.  My code now looks like this 

int start()
{
  {
    if (OrdersTotal() == 0)
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
  }       

  for(int i=OrdersTotal()-1; i>=0; i--) 
    {
      //calculate new lotsize of hedge based on lotsize of current open trade*Multiplier
      double lots = NormalizeDouble(OrderLots() * Multiplier, 2);
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      if (OrderSymbol()==Symbol())
    { 
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(OrdersTotal() == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }
 
    if (OrdersTotal() == 0)
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*PointValue, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
If an order is open on any pair, it will not open another order until OrdersTotal()==0 again
 
GumRai:
If an order is open on any pair, it will not open another order until OrdersTotal()==0 again

Thank you for your help. I need to limit the first original order to only one trade.  I do not want the EA to continue opening orders when the buy condition is met.  So I added the Orderstotal to limit this.  This code, however seems to interfere with the code here

else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(OrdersTotal() == 1) //<----------
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());

 Here I only want the EA to open one hedge per open trade, hence OrderTotal ==1

So what is then the best way to limit the number of trades, i.e. one original trade and one hedge trade?  Thank you 

 
Trader3000: So what is then the best way to limit the number of trades, i.e. one original trade and one hedge trade?
  1. So count the number of orders that are open on the current chart. OrdersTotal returns the number of orders that are open on all charts.
  2. Not filtering by magic number makes EA incompatible with all others (including itself on other TFs,) and manual trading Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 forum
 

Thank you very much for everyone's help.  I have solved the issue and the EA will now open a trade on all the charts when the buy condition is met, however, nothing below this is now working.  The EA is not calling the Trailingstop or Hedge functions.  Will someone please take a look and let me know what I did wrong because I am unable to figure it out.  

int start()
{ 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   double lots = NormalizeDouble(OrderLots() * Multiplier, 2);
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
    {
         result=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
    
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
 else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(total == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }
 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   double lots = NormalizeDouble(OrderLots() * Multiplier, 2);

I don't know exactly what you are doing, but I suggest that you avoid naming 2 variables with the only difference being a capital letter. It is easy to confuse the 2, especially when others who are reading your code may well have adopted the convention that variables that start with a capital letter are Globalscope.

No order has been selected, so OrderLots() could be anything


    
     if (OrderType() == OP_BUY) 

This would use the values from the last order selected in the previous loop, it may not be the correct magic number or symbol.

 

Thank you for your reply.  What I'm trying to do is have the EA open the first original trade wherethe lotsize is a percentage of my equity.  If the trade goes against

me, the EA must open one hedge in the opposite direction, but here the lotsize must be 3 times the original lotsize (OrderLots).  Even though it appears as if no

order has been selected, it didn't seem to affect the operation.  I have now placed the Lots directly in the OrderSend function, but neither the trailingstop nor

the hedge is triggered when they should. Both worked perfectly prior to me adding this

total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }

 

int start()
{ 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
    {
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(total == 1)
            result=OrderSend(Symbol(), OP_SELL, NormalizeDouble(OrderLots() * Multiplier, 2), Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }

 I believe my braces {} are not in the right places

 
I already told you in the second part of my previous post
 

Thank you so much for all the help so far.  I am making progress.  I now have it so that everything seems to work the way it should except that the EA ignores the condition for opening a hedge trade.  It sometimes (but not always) opens a hedge trade even when the conditions have not been met.  Also the TrailingStop does not always kick in.  I think I am still missing braces {} somewhere.  My code now looks like this.  Will someone please take a look for me.  Thank you.

int start()
{ 
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
    {
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits)) //<------- THIS IS BEING IGNORED SOMETIMES (I THINK)
            if(total == 1)
            {
            result=OrderSend(Symbol(), OP_SELL, NormalizeDouble(OrderLots() * Multiplier, 2), Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
            }
       }
      // else if (OrderType() == OP_SELL)
      // ... 

 GumRai:

This would use the values from the last order selected in the previous loop, it may not be the correct magic number or symbol.


I have tried to fix this by changing the braces.  Is that the best way, or do I need to duplicate and add the OrderSelect function everytime before OrderSend?  Thank you