Skip to content

EA Doctor rule · Volume and money

No margin check before a new trade

The EA opens trades without asking whether the free margin covers them, so it keeps sending orders that the server refuses with 10019.

Why it matters

When the free margin does not cover a new position, the server refuses it with 10019 (not enough money). An EA that never checks sends the same request on every signal and fills the journal; with a growing lot (martingale, grid) it finds out at the worst moment.

OrderCalcMargin() returns the margin a trade needs before it is sent, and OrderCheck() checks a whole request, including the margin, without sending it.

When the rule fires

The EA opens trades and never calls OrderCalcMargin(), OrderCheck() or CAccountInfo FreeMarginCheck() / MaxLotCheck() / MarginCheck(), and never reads ACCOUNT_MARGIN_FREE.

When it stays quiet

Any of those is used anywhere in the file.

How to fix it

  1. Before each entry, compute the margin with OrderCalcMargin(type, symbol, lots, price, margin).
  2. Compare it with AccountInfoDouble(ACCOUNT_MARGIN_FREE) and skip (or reduce) the trade when it does not fit.
  3. For complete requests, OrderCheck() gives the margin and the free margin after the trade in one call.

Code that fires it

MQL5 · fires this rule
void OpenBuy(const double lots)
  {
   trade.SetExpertMagicNumber(InpMagic);
   if(!trade.Buy(lots, _Symbol))
      Print("Buy failed: ", trade.ResultRetcodeDescription());
  }

Fixed code

MQL5 · fixed
bool EnoughMargin(const ENUM_ORDER_TYPE type, const double lots)
  {
   const double price = SymbolInfoDouble(_Symbol, type == ORDER_TYPE_BUY ? SYMBOL_ASK : SYMBOL_BID);
   double margin = 0.0;
   if(!OrderCalcMargin(type, _Symbol, lots, price, margin))
      return(false);
   return(margin <= AccountInfoDouble(ACCOUNT_MARGIN_FREE));
  }

void OpenBuy(const double lots)
  {
   if(!EnoughMargin(ORDER_TYPE_BUY, lots))
     {
      Print("Not enough free margin for ", lots, " lots");
      return;
     }
   trade.SetExpertMagicNumber(InpMagic);
   if(!trade.Buy(lots, _Symbol))
      Print("Buy failed: ", trade.ResultRetcodeDescription());
  }

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 volume and money

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.