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
- Filling the MqlTradeRequest structure for you. Buy, Sell, PositionClose and PositionModify build the request with the right action and fields.
- Setting the magic number and deviation once with SetExpertMagicNumber and SetDeviationInPoints.
- Choosing a filling type if you call SetTypeFillingBySymbol with the symbol.
- Keeping the last result, which you can read with ResultRetcode, ResultOrder and ResultDeal.
What it does not handle
- 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.
- It does not check stop distance against SYMBOL_TRADE_STOPS_LEVEL. A stop too close to price gets rejected with invalid stops.
- It does not retry. If the server returns a requote or price changed, the call simply fails.
- 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;
}
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)