Disclaimer: This article is for educational and informational purposes only. It does not constitute financial or investment advice. Trading forex and CFDs carries significant risk of loss. Past performance of any strategy — including backtests — does not guarantee future results. Never trade with money you cannot afford to lose.
What Is This Strategy?
The Median Absolute Deviation Reversion strategy is an indicator-based, mean-reversion Expert Advisor (EA) for MetaTrader 5 built around a robust-statistics twist on the classic "fade the extreme" approach. Instead of centering price on a moving average and measuring stretch with standard deviation — the machinery behind Bollinger Bands and conventional z-scores — it uses two of the most outlier-resistant estimators in statistics: the median of recent closing prices as the "fair value" center, and the Median Absolute Deviation (MAD) as the dispersion (spread) measure. Mean reversion simply refers to the tendency of price to snap back toward an average value after an unusually large move.
The problem this design tries to solve is well known to anyone who has run a standard reversion system: a single violent spike bar drags the arithmetic mean toward itself and inflates the standard-deviation band. The system then either chases the spike or refuses to fade it. The median and MAD are far less sensitive to a lone extreme value, so the strategy's estimate of "how stretched price is" stays stable even when one bar goes haywire. The strategy converts this into a robust z-score, rz = (close − median) / (1.4826 × MAD), where the constant 1.4826 rescales MAD so that it matches standard deviation for normally distributed data.
As a learning tool, this EA is best suited to traders who want to understand range-trading logic, robust statistics, and the importance of regime filters. It is designed for range-bound, choppy market conditions — historically the environment where reversion approaches behave most predictably — and it is explicitly not designed to trade trends. If you are studying how to separate "range" from "trend" and how to fade stretched price without being run over by a genuine breakout, this strategy is a clear, self-contained example.
How It Works
The strategy acts once per closed bar on the chart's primary timeframe. On each new bar it rebuilds a rolling window of recent closes, computes the robust center and scale, and then evaluates entries, exits, and trade management. Here is the logic in plain English:
- Fair value (center): The strategy takes the median of the last
Lookbackclosing prices. The median is the middle value, so a single spike cannot pull it far off. - Dispersion (scale): It computes the Median Absolute Deviation — the median of how far each close sits from the median — then multiplies by 1.4826 to get a "robust scale" comparable to standard deviation.
- Robust z-score:
rz = (latest close − median) / robust scale. A large negativerzmeans price is stretched well below fair value; a large positiverzmeans it is stretched well above. - Flatness (range) filter: Fading a real trend is the fastest way to sink a reversion system, so entries are gated by a drift check. The strategy compares the median of the newer half of the window with the median of the older half. If that difference (measured in robust-scale units) exceeds
FlatnessMax, the market is considered to be trending and no new trade is taken. - Turn-confirmation candle: A same-direction candle is required so the strategy fades a stretch that is starting to snap back, not one still extending.
Entry conditions:
- Long (buy): The strategy signals a long when
rzis at or below−EntryZ(price stretched down), the range is flat, and the just-closed bar is bullish (close above open) — interpreted as a downward stretch that may be turning up. - Short (sell): The strategy signals a short when
rzis at or above+EntryZ(price stretched up), the range is flat, and the just-closed bar is bearish (close below open) — a upward stretch that may be turning down.
Exit, stop-loss, and take-profit logic:
- Take-profit: The target is the median itself — the robust fair value. The idea is to capture the snap-back to the center, not a home run. As a safeguard, if the median sits on the wrong side of the entry price, the take-profit is placed a stop-distance away instead.
- Stop-loss: The stop is placed at a distance of
AtrStopMult × ATRfrom entry, where ATR (Average True Range) is a standard volatility measure. This scales the risk distance to current market volatility. - Early exit: Even before the take-profit is hit, an open trade is closed once
rzreverts back through zero — that is, once price has reclaimed fair value, the reason for the trade is gone. - One position at a time: The strategy holds a single position per magic number and never stacks trades.

Strategy Parameters
| Parameter | Default | Min | Max | Description |
|---|---|---|---|---|
| Lookback | 40 | 16 | 120 | Number of recent closed bars used to compute the median and MAD window. Larger values give a smoother, slower fair-value estimate. |
| EntryZ | 2.5 | 1.5 | 4.0 | Robust z-score threshold for entries. Higher values demand a more extreme stretch before fading, producing fewer but more selective signals. |
| FlatnessMax | 1.0 | 0.3 | 2.5 | Maximum allowed robust drift between the older and newer halves of the window. Lower values enforce a stricter "range only" filter. |
| AtrPeriod | 14 | 5 | 30 | Number of bars used to calculate the Average True Range for stop-distance sizing. |
| AtrStopMult | 1.8 | 0.5 | 4.0 | Multiplier applied to ATR to set the stop-loss distance from entry. Higher values give wider stops. |
| Lots | 0.10 | 0.01 | 1.0 | Fixed order volume (position size) in lots for each trade. |

Recommended Chart Settings
This strategy is single-timeframe and indicator-based: it reads whatever symbol and timeframe the chart is set to, so it adapts to the chart it is attached to. Its design favors range-prone FX crosses — pairs such as EURGBP or EURCHF that historically spend long stretches oscillating rather than trending — on intraday timeframes (for example M15 to H1), where mean-reversion behavior is more common. That said, no symbol or timeframe is universally "correct," and behavior will vary considerably across different pairs and market regimes. Treat the recommended settings as a starting point for study and testing, not a fixed prescription, and always validate on a demo account first.
How to Install on MetaTrader 5
- Download the .ex5 file from the link below
- Copy it to your MT5
MQL5\Expertsfolder - Restart MetaTrader 5 or refresh the Navigator panel
- Drag the EA onto a chart matching the recommended symbol and timeframe
- Configure the input parameters and enable Algo Trading
What to Consider Before Using This EA
The core strength of the Median Absolute Deviation Reversion approach is its resistance to outliers. By centering on the median and scaling with MAD, the strategy avoids a common failure mode of Bollinger- and z-score-based systems, where one spike distorts both the fair-value estimate and the band width. The added flatness filter and confirmation candle are thoughtful guards against the classic reversion trap of fading a market that is actually trending.
However, this approach has known limitations that you should understand before relying on it. Mean reversion, by definition, bets against continuation — so its Achilles' heel is a strong, sustained trend or a structural breakout. The flatness filter reduces this risk but cannot eliminate it; a range can break the moment after a trade is opened. Because the take-profit targets the median (a modest snap-back) while the stop is a volatility-scaled distance away, the reward on winning trades may be smaller than the risk on losing ones, which places extra importance on the hit rate. Robust statistics also react more slowly than their classical counterparts, so the fair value may lag when conditions shift regime.
Conditions where this strategy may underperform include trending or news-driven markets, low-liquidity sessions with erratic spikes, and instruments that do not exhibit stable ranging behavior. It is a specialized tool for a specific regime, not an all-weather system. Use it to study when fading works and why filters matter — not as a guaranteed edge.
Risk Management Tips
Sound risk management matters far more than any single entry rule. Consider these general principles as you study this EA:
- Risk a small, fixed fraction per trade. Many educational sources suggest risking no more than 1–2% of account equity on any single position, sizing your lots accordingly rather than using a fixed volume blindly.
- Test on a demo account first. Run the strategy in a risk-free simulated environment across varied market conditions before ever considering real capital.
- Understand drawdown. Every strategy experiences losing streaks. Know the historical worst-case peak-to-trough decline you could tolerate emotionally and financially.
- Mind the reward-to-risk balance. Because this system targets a modest reversion while using a volatility-based stop, pay close attention to how many winners you need to offset losers.
- Diversify and avoid over-optimization. Curve-fitting parameters to one historical period rarely holds up. Favor robust settings that work across multiple periods and pairs.
- Never trade money you cannot afford to lose, and treat automated systems as tools that require ongoing supervision, not "set and forget" solutions.
Risk Warning
Trading foreign exchange, CFDs, and other leveraged financial instruments involves substantial risk of loss and is not suitable for all investors. The strategies and tools discussed on this page are provided for educational purposes only and do not constitute financial advice, investment recommendations, or solicitation to trade. Always consult a qualified financial adviser before making trading decisions. Past backtest performance is not indicative of future results.
Downloads
- Expert Advisor: MedianAbsoluteDeviationReversion.ex5 (29 downloads)
- Source Code: MedianAbsoluteDeviationReversion.mq5 (30 downloads)
- Documentation: MedianAbsoluteDeviationReversion.pdf (30 downloads)