Skip to content

EA Doctor rule · Trade requests

CTrade call result not checked

A CTrade method such as Buy(), Sell() or PositionClose() is called as a plain statement, so its failure is never seen.

Why it matters

The standard library's CTrade methods (Buy(), Sell(), PositionOpen(), PositionClose(), PositionModify(), the pending-order methods) send a trade request and return true only when it passed the basic checks. What the server answered is in ResultRetcode().

Called as a statement, a refused order, a close that did not happen or a stop that was not moved leaves the EA's picture of the account wrong: it may think a position is closed while it is still open.

When the rule fires

A method that sends a request (Buy, Sell, PositionOpen, PositionClose, PositionClosePartial, PositionCloseBy, PositionModify, BuyLimit, SellLimit, BuyStop, SellStop, OrderOpen, OrderModify, OrderDelete) is called on a variable declared as CTrade, stands on its own as a statement, and the function reads none of ResultRetcode(), ResultRetcodeDescription(), ResultDeal(), ResultOrder() or GetLastError() after it.

When it stays quiet

The call is used in a condition or an assignment, or one of those results is read after it in the same function.

How to fix it

  1. Test the return value: if(!trade.Buy(…)) and log trade.ResultRetcodeDescription().
  2. After a true, check trade.ResultRetcode(): TRADE_RETCODE_DONE for a market order, TRADE_RETCODE_PLACED for a pending one.
  3. Keep the deal or order ticket (ResultDeal(), ResultOrder()) when the EA needs to follow the trade.

Code that fires it

MQL5 · fires this rule
void OpenBuy()
  {
   trade.SetExpertMagicNumber(InpMagic);
   trade.Buy(InpLots, _Symbol);
  }

Fixed code

MQL5 · fixed
bool OpenBuy()
  {
   trade.SetExpertMagicNumber(InpMagic);
   if(!trade.Buy(InpLots, _Symbol))
     {
      PrintFormat("Buy failed: retcode %u (%s)", trade.ResultRetcode(), trade.ResultRetcodeDescription());
      return(false);
     }
   if(trade.ResultRetcode() != TRADE_RETCODE_DONE)
     {
      PrintFormat("Buy not filled: retcode %u (%s)", trade.ResultRetcode(), trade.ResultRetcodeDescription());
      return(false);
     }
   return(true);
  }

The fixed code shows this rule’s fix and compiles in MetaEditor for MetaTrader 5 (with CTrade trade, InpLots and InpMagic declared, as in a typical EA). Other rules may still apply to it as a fragment: check your whole EA.

More rules on trade requests

Sources

Get your EA fixed

Check a whole EA for this and 29 other mistakes with EA Doctor, free and in your browser. Or send it to us: we confirm the price in writing, then fix it.