Retrying a failed order looks simple: if OrderSend fails, call it again. In practice a naive loop is one of the easiest ways to open two positions when you wanted one. Here is the policy I use.
Split the return codes into three groups
- Safe to retry after a fresh price: TRADE_RETCODE_REQUOTE, TRADE_RETCODE_PRICE_CHANGED, TRADE_RETCODE_PRICE_OFF.
- Never retry automatically: TRADE_RETCODE_NO_MONEY, TRADE_RETCODE_INVALID_STOPS, TRADE_RETCODE_MARKET_CLOSED, TRADE_RETCODE_TRADE_DISABLED. These need a human or a change in logic.
- Unknown outcome: TRADE_RETCODE_TIMEOUT, or OrderSend returning false with no clear code. The order may or may not exist on the server.
Handle the unknown case first
For the third group, do not resend. Wait briefly, then scan PositionsTotal and OrdersTotal for your magic number and a comment you set per signal, for example a signal id. Only if nothing matches do you treat it as a real failure.
bool AlreadyOpened(const string sigId, const long magic)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong t = PositionGetTicket(i);
if(t == 0) continue;
if(PositionGetInteger(POSITION_MAGIC) == magic &&
PositionGetString(POSITION_COMMENT) == sigId)
return true;
}
return false;
}
Bound the retries
Cap the loop at two or three attempts, refresh the price with SymbolInfoTick before each one, and stop if the price has moved beyond your allowed deviation. A missed trade costs one opportunity. A duplicated trade doubles your risk without you noticing.
Log every attempt
Write the signal id, attempt number, return code and price to the journal. When something goes wrong at 3am, that log is the only way to tell a broker problem from a code problem.
Top comments (1)
Handling the unknown-outcome case first is the part most retry loops get wrong, so good to see it up front. One gap we've hit with the same pattern: by the time you scan, the order may have opened and already closed (stop hit or a fast exit), so a check of open positions says "not found" and the loop resends. Checking recent deals in history for the same signal id closes that hole. And since some brokers rewrite or trim the comment field, it's worth keeping the signal id in your own log as well, not only on the server side.