MQL5
MQL5 in the real world
The workshop notebook of an Expert Advisor developer who has shipped to a prop firm: the traps the MetaQuotes docs stay silent on (tick_value vs point on gold and indices, retcodes 10014/10016, freeze level) and the money management that survives a funded account — dual risk+margin clamp, realized+floating drawdown, expectancy in R. Code that passes OrderSend on the first try, with any broker.
20 featured snippets
- Lot sizing by risk percentageComputes the exact volume so that a hit stop-loss costs a precise amount, via SYMBOL_TRADE_TICK_VALUE and SYMBOL_TRADE_TICK_SIZE — works on Forex, indices and metals.
- Maximum lot allowed by margin (OrderCalcMargin)Computes the maximum volume affordable within a given margin budget. OrderCalcMargin accounts for the actual leverage, the symbol's calculation type (Forex, CFD, futures) and the margin currency.
- Money value of one point for 1 lotConverts the smallest price change into account currency. The detour through tick_value/tick_size is mandatory: on gold and indices, a tick isn't always worth 1 point.
- Final lot: double clamp on risk + marginCombines risk-based sizing and the margin cap in a single function: the volume kept is the more constraining of the two, never the other way around.
- Trailing stop with a minimum step (anti-spam)Moves the SL only when the improvement exceeds a minimum step — avoids flooding the server with one-point modifications on every tick, a classic cause of request banning.
- Respecting SYMBOL_TRADE_STOPS_LEVELAdjusts an SL/TP that's too close to the current price to the minimum distance imposed by the broker — without this check, OrderSend fails with "Invalid stops" (retcode 10016).
- Virtual stop-loss (invisible to the broker)Keeps the exit level in memory and closes at market when it's crossed — the SL never appears on the server. Reserve it for cases where the EA runs 24/7 on a VPS.
- Detecting the supported filling mode (FOK/IOC)Reads the SYMBOL_FILLING_MODE mask to pick a filling type the server accepts — sending an unsupported mode is one of the most frequent causes of "Unsupported filling mode".
- Moving-average crossover detection (no repaint)Compares the last two CLOSED values of the fast and slow MAs: a crossover confirmed at the close never "un-crosses", unlike a test on the in-progress candle.
- New-bar detectionCompares the open timestamp of the current candle with the stored one: logic runs once per candle, whatever the tick flow. Multi-symbol-compatible version.
- Currencies involved in a symbol (base, profit, margin)Extracts a symbol's currencies for relevant news filtering: on indices and metals, the profit currency (often USD) is the only usable key, since the base currency isn't actually a currency.
- Pearson correlation between two symbolsComputes the correlation of returns (not raw prices, which always overstate correlation) over N candles aligned via CopyClose.
- Net exposure by currencyBreaks each Forex position down into long/short exposure per currency (base bought, quote sold) to reveal hidden concentration — three "different" trades can be a single USD bet.
- Atomic lock between EAs (SetOnCondition)GlobalVariableSetOnCondition is an atomic test-and-set operation: only one of the competing EAs gets the lock, the others fail cleanly — the poor man's mutex in MQL5.
- Equity curve smoothness (R² as a criterion)Measures the linearity of the equity curve via the R² coefficient of determination computed on the cumulative profits of the deals — a straight-line equity beats the same profit in a zigzag.
- Pips vs points: conversion by digitsOn a 5-digit broker, 1 pip = 10 points; on 3 digits (JPY), 1 pip = 10 points too, but on 2/4 digits 1 pip = 1 point. This function makes "in pips" inputs portable everywhere.
- Rounding a price to the tick size (not NormalizeDouble)On gold, indices or futures, the quote step (SYMBOL_TRADE_TICK_SIZE) can be 0.25 or 0.05: NormalizeDouble isn't enough, you have to quantize the price to a multiple of the tick.
- Daily drawdown guardrail (realized + floating)Compares current equity (which includes the floating P/L) with start-of-day equity and cuts everything when the threshold is crossed — the exact metric prop firms monitor.
- System expectancy (expectancy in R)Computes win rate, average win and average loss over the history, then expectancy per trade in currency AND in multiples of R — the single number that tells you whether the system is worth running.
- Win/loss streak analysisWalks the trade history to measure the longest winning streak, the longest losing streak and the current run, then derives a sizing recommendation — the statistical foundation of money management that survives.