Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Trading and crypto

Risk controls in MetaTrader 4 and 5: orders, limits, code

The risk controls in MetaTrader 4 and 5: server-side and trailing stops, sizing from tick values, stop-out levels, terminal safeguards and EA guards in code.

CloudSat teamNovember 18, 20267 min read
Abstract illustration of a winding chart line passing through a series of glowing gates and rails, each one placed at a different height along the path
On this pageWhere each control runs

Managing risk is a set of decisions only you can make: how much to lose on a trade, how much exposure to carry, when to stop for the day. MetaTrader's job is to enforce those decisions, and it offers more tools for that than most people use. What matters is knowing where each tool runs, on the broker's server, in your terminal or in your own code, because that decides whether it still protects you when your computer is off. This guide goes through them in that order.

Where each control runs

Control Runs on Still works with the terminal closed?
Stop loss and take profit Broker's trade server Yes
Pending orders and their expiry Broker's trade server Yes
Margin call and stop-out Broker's trade server Yes
Trailing stop Your terminal No: it stops moving
Guards coded in an EA Your terminal No
AutoTrading switch and terminal settings Your terminal Not applicable
Push notifications Your terminal, or the trade server in MT5 if the broker supports it Only the server option

Everything in the lower half depends on a running terminal. That is the practical argument for keeping a terminal that enforces risk rules on a machine that stays on.

Stops on the server, trailing in the terminal

A stop loss or take profit is stored with the position on the broker's server and triggers whether or not your terminal is running. Two limits apply. A triggered stop becomes a market order, so a gap or a fast move fills it at the next available price, which can be worse than the level. And each symbol has a minimum distance between the current price and a stop, shown as the stops level in the symbol's Specification; a stop set closer is rejected, which MQL4 reports as error 130.

The trailing stop is different. Right-click a position, choose Trailing Stop and set a distance, and the terminal moves the stop as the price moves in your favor. It does this from your machine: close the terminal and the stop stays wherever it was last moved.

Size positions from the symbol's own numbers

A position size follows from three things: the amount you have decided to risk, the distance to your stop, and what one price step is worth on that symbol. The last one should never be hard-coded. It differs between symbols and account currencies, and on cross pairs it changes as exchange rates move. Read it from the terminal at the moment you place the order:

// Lots that risk about riskMoney (account currency) with a stop stopDist away (price units).
// Returns 0 when even the minimum volume would risk more than that.
double LotsForRisk(double riskMoney, double stopDist)
{
   double tickValue = MarketInfo(Symbol(), MODE_TICKVALUE);
   double tickSize  = MarketInfo(Symbol(), MODE_TICKSIZE);
   double step      = MarketInfo(Symbol(), MODE_LOTSTEP);
   double minLot    = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot    = MarketInfo(Symbol(), MODE_MAXLOT);
   if(tickValue <= 0 || tickSize <= 0 || stopDist <= 0) return(0);

   double lossPerLot = stopDist / tickSize * tickValue;
   double lots = MathFloor(riskMoney / lossPerLot / step) * step;
   if(lots < minLot) return(0);
   return(MathMin(lots, maxLot));
}

In MQL5, the same values come from SymbolInfoDouble() with SYMBOL_TRADE_TICK_VALUE, SYMBOL_TRADE_TICK_SIZE, SYMBOL_VOLUME_STEP, SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_MAX. Two choices in this function are deliberate: it rounds down, never up, and it returns zero rather than quietly trading the minimum volume when that would exceed the amount you set. The calculation ignores slippage and gaps, so the real loss on a stopped trade can be larger.

Know your broker's stop-out level

When equity falls far enough against the margin in use, the broker warns you (margin call) and then closes positions (stop-out). The levels are set by the broker, sometimes differ between account types, and can be read from code rather than guessed. In MQL4, AccountStopoutLevel() returns the stop-out level and AccountStopoutMode() says whether it is a percentage or an amount of money. In MQL5:

void OnStart()
{
   bool pct = AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE) == ACCOUNT_STOPOUT_MODE_PERCENT;
   PrintFormat("Margin call at %.2f%s, stop-out at %.2f%s, margin level now %.2f%%",
               AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL), pct ? "%" : " (money)",
               AccountInfoDouble(ACCOUNT_MARGIN_SO_SO),   pct ? "%" : " (money)",
               AccountInfoDouble(ACCOUNT_MARGIN_LEVEL));
}

Run it as a script on each account you trade, once, and write the answer down.

Guards written into an EA

An EA can enforce limits a person tends to bend: a maximum loss per day, a maximum number of open positions, no new trades when the spread is unusually wide. Here is a compact guard in MQL5 that an EA calls before opening anything:

input double MaxDailyLoss = 200.0;  // account currency, your own figure
input int    MaxPositions = 3;      // counts every position on the account
input int    MaxSpreadPts = 30;     // points

double   dayStartEquity = 0;
datetime dayStart       = 0;

bool GuardsAllowNewTrade()
{
   datetime today = iTime(_Symbol, PERIOD_D1, 0);   // start of the day, server time
   if(today != dayStart)
   {
      dayStart       = today;
      dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
   }
   if(AccountInfoDouble(ACCOUNT_EQUITY) <= dayStartEquity - MaxDailyLoss) return(false);
   if(PositionsTotal() >= MaxPositions)                                   return(false);
   if(SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) > MaxSpreadPts)           return(false);
   return(true);
}

Two weaknesses are worth fixing in a real EA. The starting equity lives in memory, so a terminal restart in the middle of the day resets it; storing it with GlobalVariableSet() keeps it across restarts. And the guard only blocks new trades; whether to close existing ones when the limit is hit is a separate decision to code explicitly.

Terminal settings that prevent mistakes

  • Protective switches. Under Tools > Options > Expert Advisors, automated trading can be disabled automatically when you switch accounts, switch profiles or change a chart's symbol or timeframe. They stop an EA written for a demo or for one symbol from acting on another.
  • The AutoTrading button (MT5: Algo Trading) stops every EA in the terminal from sending orders in one click.
  • One Click Trading removes the confirmation step from manual orders. Leave it off unless you use it.
  • Maximum deviation. On instant-execution accounts, the order window's deviation setting caps how far a fill may differ from the quoted price.
  • The investor password logs in read-only, for any device or person that only needs to watch.

Netting and hedging in MT5

MT5 accounts use one of two accounting systems. On a hedging account, every trade is its own position, and EAs tell theirs apart by magic number. On a netting account, a symbol has only one position at a time: a second EA's buy on the same symbol adds to, reduces or reverses the first EA's position. Each EA's own risk calculation then describes a position that no longer exists as it thinks. Run one EA per symbol on netting accounts, or use a hedging account if several must share a symbol.

Watching from a distance

An EA can call SendNotification() to push a message to the MetaTrader mobile app, using the MetaQuotes ID entered under Tools > Options > Notifications; MT5 accepts up to four IDs. MT5 also offers notifications sent by the trade server, which arrive even when your terminal is off, if the broker supports them. Since every guard in an EA only works while the terminal runs, keeping that terminal on a server, such as CloudSat's Trading RDP, is what keeps the guards in force overnight.

FAQ

Does my stop loss work when MetaTrader is closed?

Yes. Stop loss and take profit orders sit on the broker's server. A trailing stop does not move while the terminal is closed, and EA guards do not run.

Can a stop loss guarantee my maximum loss?

No. A triggered stop is filled at the next available price, so a gap or a fast market can fill it beyond the level. Some brokers sell guaranteed stops on certain products; standard MetaTrader stops are not guaranteed.

What daily loss limit should I set?

That is your decision, based on your account and your own tolerance; nothing here suggests a figure. The code above enforces whatever number you choose.

Why was my stop loss rejected?

Usually because it was closer to the price than the symbol's stops level allows. Check the Specification, and in code, compare your distance with MarketInfo(Symbol(), MODE_STOPLEVEL) in MQL4 or SYMBOL_TRADE_STOPS_LEVEL in MQL5.

Trading involves risk of loss. Nothing in this article is financial advice.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.