2
votes

In my mql4 Expert Advisor, I've written this function to close all the buy trades at once. When I test it via the Strategy Tester, it closes some buy trades, but for a few other buy trades it returns the: OrderClose error 4051:invalid ticket for OrderClose function error.

void Close_All_Buy_Trdes(){
   for (int i=0;i<=OrdersTotal();i++){
      OrderSelect(i,SELECT_BY_POS);
      if(OrderType()==OP_BUY {
           OrderClose(OrderTicket(),OrderLots(),Bid,3);
      }
   }
}

What is the reason for this happening?

1

1 Answers

1
votes

Once you close one of the orders the position number will be different for the rest of them... so the loop is trying ro close orders that wont be available at that position anymore.

You could select by ticket number (these don't change) instead of position, but that means having the ticket numbers stored.

If you prefer use position, this is a way of doing this:

void close_all()
{
    int get_out=0,hstTotal=OrdersHistoryTotal();
    if (hstTotal<1) get_out=1;
    while (get_out==0)
    {
        if(!OrderSelect(0,SELECT_BY_POS,MODE_TRADES)) get_out=1;
        else
        {
            //you can add here any specific if condition 
            OrderClose(OrderTicket(),OrderLots(),Bid,3);
        }
        hstTotal=OrdersHistoryTotal();
        if (hstTotal<1) get_out=1;
    }
}

The code always closes the first order(position=0) as many times as necessary while the number of open orders is >=1 (exit condition of the while is: hstTotal<1)