ERR_TRADE_MODIFY_DENIED on OrderClose()

 

I'm getting this weird error occurring very frequently, when performing an OrderClose(). The close fails, with error code 145, ERR_TRADE_MODIFY_DENIED, which means "modification denied because order too close to market". But I'm not modifying an order, I'm just trying to close it! This is occurring in the Strategy Tester. As a workaround I've put in code that will retry closing the orders on subsequent entries into start(). That eventually works, but it sometimes results in closes 5 pips away from where it ought to be closed at. One additional point of explanation, although this code fragment is written to close open tickets and delete pending tickets, in this application, there are no pending tickets being used. I'm running the latest MT4, Build 222.

Anyone with any idea of the problem? Source code snippet follows.

totalorders = OrdersTotal(); // necessary because it changes on every cycle of loop

for(cnt = totalorders; cnt > 0; cnt--) // list must be traversed from end to beginning
{
if( OrderSelect(cnt-1, SELECT_BY_POS, MODE_TRADES) )
{
mode = OrderType();
if(OrderSymbol() == Symbol())
{
if(mode == OP_BUY )
if( !OrderClose(OrderTicket(), OrderLots(), Bid, slippage, Blue) ) //changed OrderClosePrice() to Bid
{
errorcode = GetLastError();
if(errorcode == ERR_TRADE_MODIFY_DENIED)
Print("ERR_TRADE_MODIFY_DENIED1: cnt = ", cnt, " totalorders = ", totalorders, " mode = ", mode, " ticket = ", OrderTicket(), " lots = ", OrderLots(), " Bid = ", dd(Bid));
if( errorcode == ERR_INVALID_TICKET )
Print("CloseAllPositions: Invalid Ticket #", OrderTicket());
else
success = false;
}
if(mode == OP_BUYLIMIT)
if( !OrderDelete(OrderTicket(), Blue) )
{
errorcode = GetLastError();
if( errorcode == ERR_INVALID_TICKET )
Print("CloseAllPositions: Invalid Ticket #", OrderTicket());
else
success = false;
}

if(mode == OP_SELL )
if( !OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Red) ) //changed OrderClosePrice() to Ask
{
errorcode = GetLastError();
if(errorcode == ERR_TRADE_MODIFY_DENIED)
Print("ERR_TRADE_MODIFY_DENIED2: cnt = ", cnt, " totalorders = ", totalorders, " mode = ", mode, " ticket = ", OrderTicket(), " lots = ", OrderLots(), " Ask = ", dd(Ask));
if( errorcode == ERR_INVALID_TICKET )
Print("CloseAllPositions: Invalid Ticket #", OrderTicket());
else
success = false;
}
if( mode == OP_SELLLIMIT)
if( !OrderDelete(OrderTicket(), Red) )
{
errorcode = GetLastError();
if( errorcode == ERR_INVALID_TICKET )
Print("CloseAllPositions: Invalid Ticket #", OrderTicket());
else
success = false;
}
}
}
}

Reason: