Download MetaTrader 5
To add comments, please log in or register
Having questions to the author of an article? Discuss them on the Forum!
flexea
120
flexea 2016.09.27 23:24 

Ok so I grabbed this code from another post on this forum, which works great for closing multiple open trades based on FIFO rules. However when there is just 1 open trade to close, it's not closing. What do I need to change to fix this but not break the FIFO capability?


void CloseOrders(int slippage, int magicNumber) {
int x;
  double trades[][4];
  int total=OrdersTotal();
  if(total>0)
  {
  
  ArrayResize(trades,total);
  for(x=total-1;x>=0;x--)
     {
     if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
     if(magicNumber == OrderMagicNumber() && OrderSymbol() == Symbol())
        {
        trades[x][0]=OrderTicket();
        trades[x][1]=OrderProfit()+OrderCommission()+OrderSwap();
        trades[x][2]=OrderLots();
        trades[x][3]=OrderType();
        }
     }
  
  ArraySort(trades,WHOLE_ARRAY,0,MODE_ASCEND);
  x=0;
  while(x<total-1)
     {
     //double profit=trades[x][1]+trades[x+1][1];
        RefreshRates();
        double close_price=Ask;
        if(trades[x][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x][0],trades[x][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        RefreshRates();
        close_price=Ask;
        if(trades[x+1][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x+1][0],trades[x+1][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        x+=2;
     }
     }
}
Keith Watford
Moderator
7873
Keith Watford 2016.09.28 00:11  
  ArrayResize(trades,total);
  int count=0;
  for(x=total-1;x>=0;x--)
     {
     if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES))
     if(magicNumber == OrderMagicNumber() && OrderSymbol() == Symbol())
        {
        trades[count][0]=OrderTicket();
        trades[count][1]=OrderProfit()+OrderCommission()+OrderSwap();
        trades[count][2]=OrderLots();
        trades[count][3]=OrderType();
        count++;
        }
     }
     
  ArrayResize(trades,count);
  ArraySort(trades,WHOLE_ARRAY,0,MODE_ASCEND);
  x=0;
  while(x<count)
     {
        RefreshRates();
        double close_price=Ask;
        if(trades[x][3]==OP_BUY)
           close_price=Bid;
        if(!OrderClose((int)trades[x][0],trades[x][2],close_price,slippage,clrNONE))
           Print("Error closing #",DoubleToStr(trades[x][0],0)," Error code ",GetLastError());
        x++;
     }

Not tested

There is no need to try to close 2 orders per loop, that would not work correctly.

flexea
120
flexea 2016.09.28 00:23  
Thank you just tested it and seems to be working!
/
To add comments, please log in or register