false-positive result with OrderType()

 

Hi Folks,

I've got some serious problem with the coding of a order management for my EA. So to show you a snippet of my code:

   // check if orders are existing which needs to be closed
   int total = OrdersTotal();   
   for(cnt = 0; cnt < total; cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() == OP_BUY)
      {
         if( // conditions for exit LONG positions .... // )
         {
            OrderClose(OrderTicket(), OrderLots(), Ask, 5, Green);
            Print("COND1:: LONG order closed ...");
         }
      }
      else
      {
         if( // conditions for exit SHORT positions .... // )
         {
            OrderClose(OrderTicket(), OrderLots(), Bid, 5, Green);
            Print("COND2:: SHORT order closed ...");
         }
      }
   }


Okay, and now the problem is, that when I enter the market SHORT the trade is going to be closed on the next bar. When I track this action in the terminal I can read the message "COND1:: LONG Order closed by...". So, well, the market conditions in this moment are right for exit any long positions and enter short but I've got no buy order open instead the code closes my sell order!

I think that the condition

if(OrderType() == OP_BUY)

produces a false positive result. Is there anything I can do to avoid this issue?

Bests,

TheScalper

 
void ClosePositions(string sy="", int op=-1, int mn=-1) {
int i, k=OrdersTotal();

if (sy=="0") sy=Symbol();
for (i=k-1; i>=0; i--) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
if (mn<0 || OrderMagicNumber()==mn) ClosePosBySelect();
}
}
}
}
}
 

Thanks Britanec for your code, but this doesn't solve the problem. I do not want to close any open positions instead I want under some circumstances that the code closes a buy (and only buy!) or sell (and only sell!) position.

 
Ahhh, the order was placed wrong....I've made an error - code is working! ;)
 
You MUST count DOWN when closing/deleting