OrderClose fails in Tester - error 138 (requote)

 
for (i = total - 1; i >= 0; i--) {
    if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
    if (OrderCloseTime() != 0) continue;
    if (OrderSymbol() != _Symbol) continue;
    if (OrderType() != 0 && OrderType() != 1) continue;
    if (OrderProfit() > 0)  {
       bool closedOK = OrderClose(OrderTicket(), orderSize1, OrderOpenPrice(), 2, CLR_NONE);
    }
}      


This works every time in live trading, but fails every time in the back tester with error 138 (requote). Any idea why?

TIA.

 
bool closedOK = OrderClose(OrderTicket(), orderSize1, OrderClosePrice(), 2, CLR_NONE);
 
  1. if (OrderCloseTime() != 0) continue;

    Why are you checking the close time? The (MT4) trade list only has open and pending orders.

  2. Don't use negative logic.
    Don't hard code constants.
    for (i = total - 1; i >= 0; i--) {
        if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
        if (OrderCloseTime() != 0) continue;
        if (OrderSymbol() != _Symbol) continue;
        if (OrderType() != 0 && OrderType() != 1) continue;
    Simplified.
    Compare strings last.
    for (i = total - 1; i >= 0; i--)  if(
       OrderSelect(i, SELECT_BY_POS, MODE_TRADES)
    && OrderType() <= OP_SELL
    && OrderSymbol() == _Symbol
    ){
  3. bool closedOK = OrderClose(OrderTicket(), orderSize1, OrderOpenPrice(), 2, CLR_NONE);

    You can't close orders at the open price, only at the market.

    MT4: You can use OrderClosePrice() instead of Bid/Ask and be direction independent — no need to check order type to get the close price.
    MT5: you can use PositionGetDouble(POSITION_PRICE_CURRENT)

  4. You can't just use OrderLots()/2 because that is not a multiple of LotStep, and you can't close or have remaining less than MinLot.

    You also must check if you have already done it, to avoid repeated closing. Alternatives:

    • Move SL to Break Even+1 before the partial close. That way, you know that you already did it.
    • Set a flag in persistent storage (files, global variables w/flush)
    • Open two orders initially, and close one (manually or by TP.) Can't be done in US brokers due to FIFO.

 
fxsaber #:


Yes. Thank you.

 
Thank you William sir, you made my day.