Close ALL Open Trades

 

I wanted to quickly delete all trades - whilst testing.

I am testing on several different charts so thought I could have a simple EA to close all records.


If I run (the code below) on a non related chart then it doesn't delete any orders - producing errors 4107 and 129

If I run the EA on the chart which has existing orders then it may or may not work again with similar errors for the orders on the chart only

Can't help feeling the answer is so obvious..... but


if ( close_all == "YES" )

{ t1 = t1 + "\n CLOSE ALL - "+OrdersTotal()+" - Orders ";
Comment(t1);
for (int i=0; i <OrdersTotal(); i++)
{ if (OrderSelect(i,SELECT_BY_POS) == true)
{
OrderClose(OrderTicket(),OrderLots(),OrderOpenPrice(),10000,Red);
int gle1=GetLastError();
OrderClose(OrderTicket(),OrderLots(),OrderOpenPrice(),10000,Red);
int gle2=GetLastError();
MessageBox(i+" OrderTicket() is "+OrderTicket()+" Lots "+OrderLots()+
"\nOrderClose returned the error of "+gle1+" -- and -- "+gle2);
}
}
}
 
#include <stdlib.mqh>
extern bool removeFromThisChartOnly = true;

int start(){
   
   RemoveAllOrders();
   
   return(0);
}
//+------------------------------------------------------------------+




void RemoveAllOrders(){
   for(int i = OrdersTotal() - 1; i >= 0 ; i--){
      OrderSelect(i,SELECT_BY_POS);
      if(OrderSymbol() != Symbol() && removeFromThisChartOnly) continue;
      double price = MarketInfo(OrderSymbol(),MODE_ASK);
      if(OrderType() == OP_BUY) price = MarketInfo(OrderSymbol(),MODE_BID);
      if(OrderType() == OP_BUY || OrderType() == OP_SELL){
         OrderClose(OrderTicket(), OrderLots(),price,5);
      }else{
         OrderDelete(OrderTicket());
      }
      Sleep(100);
      int error = GetLastError();
      if(error > 0)
         Print("Unanticipated error: ", ErrorDescription(error));
      RefreshRates();
   }
}
This should help you get on track....
 
forexCoder:
This should help you get on track....

Fantastic - many thanks
Reason: