Function to close orders based on FIFO not closing single orders

To add comments, please log in or register
Steve H
125
Steve H  

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
20312
Keith Watford  
  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.

Steve H
125
Steve H  
Thank you just tested it and seems to be working!
Sukumar Sikdar
101
Sukumar Sikdar  

Forum Posting 31July2019

Writing an EA, as MQ4 Novice. US account- must respect FIFO. 
Expert Community Members, please help/guide me write the following function calls.
I would appreciate working / tested codes with notes/comments to learn correctly :

1.       MOOPPrice (string symbol, int type (for buy or sell) – to return a double in broker digits.
(MOOPPrice stands for MyOldestOpenPositionPrice)

2.       MOOPSize (string symbol, int type (for buy or sell) – to return a double in broker lot size (0.01 to 1.00)
(MOOPSize stands for MyOldestOpenPositionSize)

3.       MOOPProfit (string symbol, int type (for buy or sell) – to return a double in broker digits.
(MOOPProfit stands for MyOldestOpenPositionProfit)

4.       MNOPAPrice (string symbol, int type (for buy or sell) – to return a double in broker digits.
(MNOPAPrice stands for = MyNetOpenPositionAveragePrice)

5.       MOOPTicket (string symbol, int type (for buy or sell) – to return int ticket# for my oldest open position.
(MOOPTicket stands for MyOldestOpenPositionTicket)

6.       MOOPTime (string symbol, int type (for buy or sell) – to return a datetime.
(MOOPTime stands for MyOldestOpenPositionTime)

7.       Close_MOOP (string symbol, int type (for buy or sell) – to close my oldest open position
(Close_MOOP stands for Close MyOldestOpenPosition (Respect FIFO))

Thank you in advance.
DaDu Sukumar Sikdar | sukumar@sikdar.com | skype= sukumarsikdar |

William Roeder
20207
William Roeder  
  1. Sukumar Sikdar: I would appreciate working / tested codes
    We all do. You haven't stated a problem, you stated a want. Show us your attempt (using the CODE button) and state the nature of your problem.
              No free help
              urgent help.

    Or pay someone. Top of every page is the link Freelance.

  2. In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading,) while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing:
    1. For non-FIFO (non-US brokers), (or the EA only opens one order per symbol,) you can simply count down, in a position loop, and you won't miss orders. Get in the habit of always counting down.
                Loops and Closing or Deleting Orders - MQL4 programming forum
      For In First Out (FIFO rules-US brokers,) and you (potentially) process multiple orders per symbol, you must find the earliest order, close it, and on a successful operation, reprocess all remaining positions.
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16

    2. and check OrderSelect in case earlier positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    3. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask) or (be direction independent and use) OrderClosePrice().

To add comments, please log in or register