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 Kernel Regression Envelope Reversion strategy is a mean-reversion system built on Nadaraya-Watson kernel regression — a statistical smoothing technique that estimates a market's "fair value" by taking a Gaussian-weighted average of recent closing prices. Unlike a simple moving average (which weights every bar equally) or an exponential moving average (which decays weights in a fixed way), a kernel regression assigns the newest bars the most influence and tapers that influence smoothly using a tunable bandwidth. The result is a very smooth, low-lag estimate of where price "should" be, without the whipsaw of a short average or the sluggishness of a long one.
Around that central kernel line, the strategy draws a volatility-adaptive envelope using a weighted mean absolute deviation (MAD) — a robust measure of how far price typically strays from fair value. When price stretches outside this envelope and then snaps back inside on the same bar, the strategy interprets that as an exhaustion-and-reclaim event and fades the move, targeting a return to the kernel line itself. This is a classic reversion trading style: it assumes that in balanced markets, prices oscillate around a central value rather than trending indefinitely.
This strategy is best suited to traders who want to study how kernel smoothing, adaptive envelopes, and regime filtering fit together in a single rules-based system. It is designed for balanced, ranging conditions — not for trend-riding. As an educational tool, it demonstrates several important concepts at once: causal (non-repainting) indicator design, volatility self-scaling, and the use of a regime gate to avoid fading genuine trends. It is not a shortcut to results, and understanding why each condition exists is the real value here.
How It Works
The strategy evaluates its logic once per newly closed bar on the selected timeframe. It is causal and non-repainting — only the current and past closed bars feed every calculation, so signals never change after the fact. Here is what happens on each closed bar:
- Build the kernel line (nw): The strategy computes a Gaussian-weighted average of the last
KernelPeriodcloses, anchored on the just-closed bar. Recent bars carry the most weight; theBandwidthparameter controls how quickly that weight fades. This producesnw, the smooth fair-value estimate. - Build the envelope: It measures the weighted MAD — the average weighted distance of closes from
nw— and places an Upper band atnw + BandMult × MADand a Lower band atnw − BandMult × MAD. Because the MAD grows and shrinks with volatility, the envelope self-adjusts to market conditions. - Apply the regime gate: Fading only makes sense in a range, not a trend. The strategy measures the kernel line's own slope over
SlopeLookbackbars and normalizes it by the Average True Range (ATR). If the absolute slope exceedsMaxSlopeAtr, a real trend is judged to be underway and the strategy stands aside — no trade. - Wait for the reclaim trigger (long): The strategy signals a long setup only when the bar's low pierced below the Lower band (over-stretched to the downside), the bar closed back above the Lower band (reclaimed the envelope), and the bar is bullish (close above open — the snap-back has begun). This avoids catching a bar that is still extending.
- Wait for the reclaim trigger (short): A short setup requires the mirror image — the bar's high pierced above the Upper band, the bar closed back below it, and the bar is bearish (close below open).
- Take-profit logic: For both directions, the target is
nwitself — the kernel mean acts as a magnet that price tends to be pulled back toward. This is a structural target, not an arbitrary distance. - Stop-loss logic: The stop is placed one ATR-based distance from entry (
AtrStopMult × ATR) — below entry for longs, above entry for shorts. The stop therefore adapts to current volatility. - Reward-to-risk filter: Before sending an order, the strategy checks that the distance to
nw(the reward) divided by the stop distance (the risk) is at leastMinRewardRisk. Setups where price is already too close to the kernel line to justify the stop are rejected. - Housekeeping filters: Only one position per magic number is held at a time, and new entries are skipped if the current spread exceeds
MaxSpreadPoints, avoiding costly fills.
Every exit is handled by the ATR stop or the kernel-line take-profit — there is no discretionary management once a trade is live.

Strategy Parameters
| Parameter | Default | Min | Max | Description |
|---|---|---|---|---|
| KernelPeriod | 25 | 10 | 100 | Number of closed bars that feed the Nadaraya-Watson kernel regression. |
| Bandwidth | 8.0 | 3.0 | 20.0 | Gaussian bandwidth (h); larger values produce a smoother, slower kernel line. |
| BandMult | 2.0 | 1.0 | 4.0 | Envelope half-width as a multiple of the weighted mean absolute deviation. |
| SlopeLookback | 5 | 2 | 20 | Number of bars over which the kernel slope (the regime gauge) is measured. |
| MaxSlopeAtr | 1.0 | 0.2 | 3.0 | Maximum absolute kernel slope (in ATRs) still considered a fadeable range. |
| AtrPeriod | 14 | 5 | 30 | ATR lookback used for the stop distance and the regime normalization. |
| AtrStopMult | 1.5 | 0.5 | 4.0 | Stop-loss distance beyond entry, expressed in multiples of ATR. |
| MinRewardRisk | 0.7 | 0.3 | 3.0 | Minimum reward-to-risk ratio; rejects setups whose target is too close. |
| MaxSpreadPoints | 80 | 5 | 300 | Skip new entries when the current spread (in points) is wider than this. |
| Lots | 0.10 | 0.01 | 1.0 | Fixed trade volume in lots. |
| Magic | 5417 | 0 | 9,999,999 | Magic number identifying this EA's trades; one position per magic. |

Recommended Chart Settings
This strategy was designed for liquid FX majors or a major index — for example EURUSD, GBPUSD, or US500 — on intraday timeframes from M5 to H1, where balanced ranges tend to dominate the session. These are the conditions in which mean-reversion logic historically has the most opportunity to work, because price oscillates around fair value rather than trending in one direction for long stretches.
The EA reads whatever timeframe the chart is set to at runtime (it never hardcodes a timeframe), so you can experiment across M5, M15, M30, and H1 to see how the kernel line and envelope behave on each. Keep in mind that results will vary significantly across different symbols, timeframes, and market conditions — a setting that suits a quiet ranging pair may behave very differently on a trending or news-driven instrument.
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 the approach. The kernel regression provides a smoother, lower-lag estimate of fair value than a conventional moving average, which can make the reversion reference more stable. The design is thoughtfully layered: the regime gate keeps the system out of strong trends where fading is dangerous, the reclaim trigger avoids catching bars that are still falling or rising, and the envelope, stop, and target all self-scale with volatility. The take-profit is a genuine structural magnet (the kernel line) rather than an arbitrary fixed distance, and the reward-to-risk filter enforces a minimum quality on every setup.
Known limitations. Mean-reversion systems share a well-documented weakness: they perform poorly when a market transitions from ranging to trending. The regime gate mitigates this but cannot eliminate it — a trend can accelerate after a trade is opened, and a fade that "should" revert may instead run into the stop. Kernel regression, like all smoothing, still has some lag, so the fair-value estimate can trail rapid regime changes. The strategy also holds only one position at a time per magic, which limits exposure but may mean missed setups during active sessions. Finally, the fixed Lots sizing does not scale with account equity or per-trade risk.
Conditions where it may underperform. Strong directional trends, high-impact news events, illiquid or wide-spread instruments, and periods of volatility expansion can all challenge this style. The strategy may indicate more frequent stop-outs when ranges break down into trends. Treat it as a lens for studying reversion mechanics rather than a finished, deploy-and-forget system.
Risk Management Tips
Sound risk management matters far more than any single indicator. Consider these general principles:
- Position sizing: Size each trade so that a stop-out costs only a small, predefined fraction of your account. Many educational sources suggest risking no more than 1–2% of account equity per trade.
- Test on a demo account first: Run the EA on a demo or paper account across a variety of market conditions before ever considering real capital. This lets you observe behavior without financial consequences.
- Understand drawdown: Every strategy experiences losing streaks. Study the depth and duration of drawdown the approach can produce, and ask whether you could tolerate it emotionally and financially.
- Respect the spread and costs: The
MaxSpreadPointsfilter helps, but commissions, swaps, and slippage all erode edge — factor them into any evaluation. - Never over-leverage: Leverage amplifies losses as readily as gains. Keep it conservative, especially while learning.
- Keep learning: Use this EA to understand why each rule exists. The goal is education and skill-building, not a shortcut.
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: KernelRegressionEnvelopeReversion.ex5 (30 downloads)
- Source Code: KernelRegressionEnvelopeReversion.mq5 (29 downloads)
- Documentation: KernelRegressionEnvelopeReversion.pdf (30 downloads)