Problem closing positions

 
Hi, I am creating an EA but I have a problem.

I created two functions to close all opened positions Buy and Sell , but I do not understand why sometimes not all positions are closed by running this code:


//-------------------------------------------
//  this function close all Sell positions
//-------------------------------------------

void CloseAllSell()
  {
  for(int i=0; i<OrdersTotal(); i++) 
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
         break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         if(OrderType()==OP_SELL)
           {
               OrderClose( OrderTicket(), OrderLots(), Ask, 5, Red );
           }
        }
     }

  }

//-------------------------------------------
//  this function close all Buy positions
//-------------------------------------------

void CloseAllBuy()
  { 
  for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
         break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         if(OrderType()==OP_BUY)
           {         
            OrderClose( OrderTicket(), OrderLots(), Bid, 5, Red );
           }

        }
     }

  }

I'm doing something wrong?


 

This has been covered many many times, and recently as well.

Do not count up in the loop 

for(int i=0; i<OrdersTotal(); i++)

 Count down

for(int i=OrdersTotal()-1; i>=0; i--)
 
  1. Count down Loops and Closing or Deleting Orders - MQL4 forum
  2. Don't paste code
    Play video
    Please edit your post.
    For large amounts of code, attach it.
 
I tried this solution but the problem still persists
 
giovi61:
I tried this solution but the problem still persists
OrderClose is a boolean function, so check whether it returns true or false. If false, GetLastError and print to find out why it failed
Reason: