How to close ALL open orders?

 

I am looking for a way to close ALL open orders rather than just the current code I have which closes just 1 order:


void IfOrderExists86()
{
    bool exists = false;
    for (int i=OrdersTotal()-1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
        if (OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == 27)
        {
            exists = true;
        }
    }
    else
    {
        Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
    }
    
    if (exists)
    {
        CloseOrder94();
        
    }
}

void CloseOrder94()
{
    int orderstotal = OrdersTotal();
    int orders = 0;
    int ordticket[30][2];
    for (int i = 0; i < orderstotal; i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() != OP_SELL || OrderSymbol() != Symbol() || OrderMagicNumber() != 27)
        {
            continue;
        }
        ordticket[orders][0] = OrderOpenTime();
        ordticket[orders][1] = OrderTicket();
        orders++;
    }
    if (orders > 1)
    {
        ArrayResize(ordticket,orders);
        ArraySort(ordticket);
    }
    for (i = 0; i < orders; i++)
    {
        if (OrderSelect(ordticket[i][1], SELECT_BY_TICKET) == true)
        {
            bool ret = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 4, Red);
            if (ret == false)
            Print("OrderClose() error - ", ErrorDescription(GetLastError()));
        }
    }
    
}
 
gangsta1:

I am looking for a way to close ALL open orders rather than just the current code I have which closes just 1 order:



read Close 2 Trades   and follow the advice of RaptorUK  and WHRoeder

you do also counting up the loop while you close trades inside your loop that will give errors  

 

This is my script, that works great in my case.

Carefull: this really closes all the open positions, for all the crosses. Not just for the cross in the chart you run the script against. 

int start()
  {
//----
    for(int i=OrdersTotal()-1; i>=0; i--)        
    { 
     if (OrderSelect(i,SELECT_BY_POS)==true) 
       {  
         double ExPrice;
         int Tck=OrderTicket();                                        
         RefreshRates();    
         if (OrderType()==0)  {   
              ExPrice=MarketInfo(OrderSymbol(),MODE_BID);  
              OrderClose(Tck,OrderLots(),ExPrice,3);   
          } else if (OrderType()==1) {                                                            
              ExPrice=MarketInfo(OrderSymbol(),MODE_ASK);
              OrderClose(Tck,OrderLots(),ExPrice,3);             
          }  
          int Err=GetLastError();
          if (Err>0) Print("Error closing position. Ticket: ", Tck, "  Err: #",Err);                            
       }
    }
   
//----
   return(0);
  }
 
Thanks guys, I just removed the magic number and that does the trick! :-)
Reason: