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 Regression Residual Reversion strategy is a mean-reversion trading system built around linear regression — a statistical technique that fits a straight "best-fit" line through recent price closes. Rather than measuring how far price has stretched from a flat moving average, this Expert Advisor (EA) fits a sloped trend line through the last several bars and then measures how far the most recent bar sits from that line. It is designed as a study in disciplined, counter-trend "fade the outlier" trading on liquid instruments.
Most simple mean-reversion systems compare price to a horizontal reference such as a moving average. The problem with that approach is drift: in a gently rising or falling market, a bar can look "far from the average" simply because the average is lagging behind, not because price has genuinely over-extended. Regression Residual Reversion addresses this by regressing price on time. The fitted line becomes the market's current expectation of price given its recent drift, and the distance of each bar from that line — the residual — becomes a cleaner statistical measure of how stretched price really is.
This strategy is best suited to traders who want to learn how statistical concepts like least-squares regression, standard error, and standardized scores (z-scores) can be translated into concrete entry and exit rules. It is an intraday, single-timeframe approach designed with liquid forex majors such as EUR/USD in mind. It is an analytical learning tool, not a shortcut — the value here is understanding why each filter exists.
How It Works
The strategy processes signals only when a new bar closes, so it works on completed data rather than a flickering, still-forming candle. Here is what happens on each closed bar:
- Fit the trend line: A least-squares regression line is fitted through the last
RegPeriodcloses (for example, 40 bars). This produces a slope (b) and an intercept (a) describing where the trend line sits and which way it is tilting. - Measure the noise band: The strategy collects every bar's residual (its distance from the fitted line), then takes the root-mean-square of those residuals. This value is the regression standard error (
sigma_r) — a self-scaling estimate of how much price naturally wobbles around the line. It automatically widens in choppy conditions and tightens in calm ones. - Score the outlier: Each bar's residual is divided by the standard error to produce a standardized residual, or z-score. A z-score of −2.2 means the bar closed 2.2 regression-standard-errors below where the trend line says it "should" be.
- Regime gate (flat-slope filter): The strategy only fades when the trend line is essentially flat. The absolute slope, normalized by ATR (Average True Range, a volatility measure), must be at or below
FlatSlopeMax. A steep slope signals a genuine trend is underway, and the strategy simply stands aside rather than fighting it. - Reclaim trigger (no knife-catching): The strategy does not sell the outlier bar itself. Instead, it requires the prior closed bar to have been a genuine outlier (|z| ≥
EntryZ) and the current closed bar to have reclaimed back inside the band (|z| <EntryZ) while remaining on the same side of the line. This is the strategy's way of waiting for reversion to visibly begin before committing.
The entry rules read as follows:
- Long setup: the prior bar was stretched below the line (z ≤ −
EntryZ), the current bar reclaimed upward (−EntryZ< z < 0), and the slope is flat. The strategy signals a BUY. - Short setup: the prior bar was stretched above the line (z ≥ +
EntryZ), the current bar reclaimed downward (0 < z < +EntryZ), and the slope is flat. The strategy signals a SELL.
Stop-loss and take-profit logic:
- The stop-loss is placed just beyond the excursion extreme — below the lowest low of the outlier and reclaim bars for a long (or above the highest high for a short) — with an extra buffer of
StopAtrMult× ATR. - The take-profit is the regression line itself (fair value). Because the line represents where price "should" be, this is a short, high-probability objective rather than an ambitious distant target.
- Two sanity checks apply before any order is sent: the implied stop distance must not exceed
MaxRiskAtr× ATR (a risk cap that rejects overly wide setups), and the target must sit at leastMinTargetAtr× ATR away (so the reward is worth taking).
Trade management: once a position is open, the stop moves to breakeven after price travels BreakevenAtr × ATR in favour, then trails by TrailAtr × ATR behind price. This is intended to keep a winner from round-tripping back into a loss. Only one position per magic number is held at a time.

Strategy Parameters
| Parameter | Default | Min | Max | Description | ||
|---|---|---|---|---|---|---|
| RegPeriod | 40 | 15 | 120 | Number of closes fitted for the regression line and residual scale (the lookback window). | ||
| EntryZ | 2.2 | 1.5 | 3.5 | Outlier threshold in regression-standard-errors; how far a bar must stretch to qualify. | ||
| FlatSlopeMax | 0.60 | 0.20 | 1.50 | Maximum | slope | /ATR that still counts as "flat" enough to fade (the trend filter). |
| AtrPeriod | 14 | 7 | 30 | Period of the ATR used for the stop scale and trade management. | ||
| StopAtrMult | 1.0 | 0.5 | 3.0 | Structural-stop buffer, in ATRs, placed beyond the excursion extreme. | ||
| MaxRiskAtr | 2.5 | 1.0 | 5.0 | Rejects setups whose implied stop is wider than this many ATRs (risk cap). | ||
| MinTargetAtr | 0.5 | 0.1 | 3.0 | Requires the fair-value target to be at least this many ATRs away. | ||
| BreakevenAtr | 0.8 | 0.3 | 3.0 | Moves the stop to breakeven once price advances this many ATRs in favour. | ||
| TrailAtr | 1.2 | 0.5 | 4.0 | After breakeven, trails the stop this many ATRs behind price. | ||
| Lots | 0.10 | 0.01 | 1.0 | Trade volume in lots. |

Recommended Chart Settings
Regression Residual Reversion was designed with liquid forex majors such as EUR/USD in mind, on intraday timeframes (for example M15 to H1). Because every price read uses the chart's own timeframe, you can attach it to whichever timeframe you are studying, and the ATR-based stops and self-scaling standard error will adapt to that timeframe's volatility.
Keep in mind that mean-reversion behaviour differs enormously across symbols and sessions. A setting that looks reasonable on EUR/USD during quiet European hours may behave very differently on a volatile pair or during major news. Results will vary across different market conditions, and any timeframe or symbol change should be studied carefully on historical data before further testing.
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
Strengths of this approach. The regression-based reference is genuinely more principled than a flat moving average when a market is drifting, because it separates trend from over-extension. The self-scaling standard error means the "how far is far?" threshold adapts to volatility automatically rather than relying on a fixed pip distance. The flat-slope regime gate is a thoughtful attempt to keep the system from fading strong trends — the single most common way mean-reversion books get hurt. And the reclaim trigger adds evidence that reversion has started before any order goes out.
Known limitations. Mean-reversion strategies, by construction, take many small wins and occasionally suffer larger losses when a supposed outlier turns out to be the start of a real move. No filter is perfect: the flat-slope gate can still be caught out when a range breaks into a trend right after an entry. The take-profit at the regression line is a modest target, which historically pairs small average wins with a stop that must be respected strictly — the reward-to-risk profile depends heavily on the parameter choices.
Where it may underperform. Strong, sustained trends and high-impact news events are the natural enemies of any fade strategy. During a fast directional move, price can remain an "outlier" for many bars, and a reclaim that looks like reversion may only be a pause. The strategy may also produce few signals in very quiet markets where nothing stretches far enough to trigger EntryZ. Treat it as one lens for studying market behaviour, not a complete system.
Risk Management Tips
Sound risk management matters more than any single strategy setting. Consider these general principles as you study this EA:
- Position sizing: size trades so that a losing trade costs only a small, pre-decided fraction of your account. A common educational guideline is risking no more than 1–2% of account equity per trade.
- Use a demo account first: test the EA thoroughly on a demo or historical data before considering any live capital. This lets you observe how the flat-slope gate and reclaim trigger behave in different conditions.
- Understand drawdown: even a system with a favourable historical profile will experience losing streaks. Know the worst peak-to-trough decline you are willing to tolerate before you begin.
- Respect the stop: the structural stop and risk cap are core to this design. Disabling or widening stops undermines the entire low-drawdown intent of the strategy.
- Diversify your study: never rely on a single strategy, symbol, or timeframe. Understanding why a system works — or fails — is more valuable than any specific parameter set.
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: RegressionResidualReversion.ex5 (15 downloads)
- Source Code: RegressionResidualReversion.mq5 (18 downloads)
- Documentation: RegressionResidualReversion.pdf (22 downloads)