DEV Community

Omais Ali
Omais Ali

Posted on

What the MQL5 CTrade class does for you, and what it quietly does not

Most MQL5 code samples use the CTrade class from the standard library. It is a good choice, but a lot of EA bugs come from assuming it does more than it does. Here is what it actually handles and where you still need your own code.

What CTrade handles

  1. Filling the MqlTradeRequest structure for you. Buy, Sell, PositionClose and PositionModify build the request with the right action and fields.
  2. Setting the magic number and deviation once with SetExpertMagicNumber and SetDeviationInPoints.
  3. Choosing a filling type if you call SetTypeFillingBySymbol with the symbol.
  4. Keeping the last result, which you can read with ResultRetcode, ResultOrder and ResultDeal.

What it does not handle

  1. It does not normalize your lot size to the volume step or check minimum and maximum volume. Pass 0.123 lots and the broker rejects it.
  2. It does not check stop distance against SYMBOL_TRADE_STOPS_LEVEL. A stop too close to price gets rejected with invalid stops.
  3. It does not retry. If the server returns a requote or price changed, the call simply fails.
  4. The boolean return value is not the fill result. True means the request passed basic checks and was sent.

A pattern that covers the gaps

bool OpenBuy(CTrade &trade, double lots, double sl, double tp)
{
   lots = NormalizeLots(_Symbol, lots);           // your own step rounding
   if(lots <= 0.0) return false;

   if(!trade.Buy(lots, _Symbol, 0.0, sl, tp))
   {
      PrintFormat("Buy send failed: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription());
      return false;
   }
   uint rc = trade.ResultRetcode();
   if(rc != TRADE_RETCODE_DONE && rc != TRADE_RETCODE_PLACED)
   {
      PrintFormat("Buy not filled: %u %s", rc, trade.ResultRetcodeDescription());
      return false;
   }
   return true;
}
Enter fullscreen mode Exit fullscreen mode

Takeaway

Use CTrade for the request plumbing, but keep lot normalization, stop level checks, retry rules and retcode checks in your own code. Those four gaps cause most of the "it worked in the tester" support tickets.

Top comments (0)