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 Runs Test Regime Switch is an MetaTrader 5 expert advisor built around the Wald-Wolfowitz runs test, a classical statistical tool borrowed from probability theory and repurposed here as a live market-regime classifier. A "runs test" measures whether a sequence of up and down moves is more streaky, more choppy, or simply as random as a coin toss. In trading terms, that translates directly into the question every discretionary trader wrestles with: is this market trending, ranging, or just noise? The strategy answers that question with a number rather than a gut feeling, and then adapts its behaviour to match.
What makes this approach distinctive is that it does not commit to a single trading style. Most systems are either momentum systems (they buy strength and sell weakness) or mean-reversion systems (they fade extremes back toward an average). The Runs Test Regime Switch runs both playbooks and lets the statistic decide which one is appropriate right now. When the runs test detects long same-sign streaks — a sign of genuine persistence — the strategy trades with the drift. When it detects excessive back-and-forth alternation — a sign of a range-bound, anti-persistent market — the strategy fades stretched prices back toward a rolling mean. When the sequence looks statistically indistinguishable from a random walk, it stands aside entirely.
As a learning tool, this strategy is well suited to intermediate traders who want to understand regime detection and adaptive systems. It demonstrates how a single, well-understood statistic can gate two opposing logics, and how ATR-based risk can be applied consistently across both. It is a strategy analysis worth studying for the concept of regime switching, not a shortcut to results.
How It Works
The strategy evaluates its rules once per completed bar on a single timeframe (the chart timeframe you attach it to). On each new bar it computes a runs-test z-score from the signs of recent close-to-close changes, then routes to one of three outcomes.
Computing the regime signal:
- The strategy looks at the last
WindowNbar-to-bar close changes and records each as up (+) or down (−). Flat changes are skipped because they carry no sign. - It counts the number of "runs" — maximal blocks of the same sign — and compares that count to what a purely random sequence would produce, expressed as a z-score.
- A strongly negative z-score means fewer runs than chance (long streaks) → a persistent / trending regime.
- A strongly positive z-score means more runs than chance (rapid alternation) → an anti-persistent / ranging regime.
- A z-score near zero means the sequence is statistically random → no trade.
Entry logic — Momentum book (trending regime):
- Triggered when the z-score is at or below the negative
ZThreshold. - The strategy measures the net price move across the window. If the market has drifted up, it signals a long ("TrendUp"); if it has drifted down, it signals a short ("TrendDown").
- The goal is to align with the direction the persistence has already established.
Entry logic — Mean-reversion book (ranging regime):
- Triggered when the z-score is at or above the positive
ZThreshold. - The strategy compares the latest close to a
RevPeriodsimple moving average (the rolling mean). - If price is stretched above the mean by at least
MinStretchAtr× ATR, it signals a short back toward the mean ("RangeFadeDown"). If stretched below by the same amount, it signals a long ("RangeFadeUp"). - The Average True Range (ATR) — a measure of typical bar volatility — ensures the "stretch" requirement scales with market conditions rather than a fixed pip distance.
Stop-loss logic:
- Every trade, in both books, places a stop at
SlAtrMult× ATR away from entry. This keeps risk proportional to current volatility instead of a static value.
Take-profit logic:
- The momentum book targets a fixed
TpAtrMult× ATR distance in the trade's direction. - The mean-reversion book aims back to the rolling mean when that mean sits beyond the entry; otherwise it falls back to the same ATR-multiple target as a guard.
- Only one position per magic number is held at a time, so the stop and target manage the exit before any new signal is considered.

Strategy Parameters
| Parameter | Default | Min | Max | Description | ||
|---|---|---|---|---|---|---|
| WindowN | 20 | 10 | 60 | Number of close-to-close changes fed into the runs test. Larger values smooth the regime read but react more slowly. | ||
| ZThreshold | 1.5 | 0.5 | 3.0 | The \ | z\ | level beyond which a regime is deemed non-random (trend or range). Higher values demand stronger statistical evidence before trading. |
| RevPeriod | 12 | 5 | 40 | Rolling mean (SMA) period used by the mean-reversion book to define "fair value". | ||
| MinStretchAtr | 0.8 | 0.0 | 3.0 | Minimum distance from the mean, in ATR multiples, required before fading a range. | ||
| AtrPeriod | 14 | 5 | 40 | ATR period used for stops, targets, and the stretch measurement. | ||
| SlAtrMult | 2.0 | 0.5 | 6.0 | Stop-loss distance in ATR multiples (applied in both books). | ||
| TpAtrMult | 3.0 | 0.5 | 8.0 | Take-profit distance in ATR multiples (momentum book and reversion fallback). | ||
| Lots | 0.10 | 0.01 | 1.0 | Order volume in lots. |

Recommended Chart Settings
The Runs Test Regime Switch is designed as a single-timeframe system: every calculation uses the timeframe of the chart you attach it to, so the same code adapts to whatever you select. For studying its behaviour, major forex pairs such as EUR/USD or GBP/USD on the H1 (1-hour) or H4 (4-hour) timeframe are a sensible starting point, because they offer a mix of trending and ranging phases for the regime classifier to distinguish. Higher timeframes also reduce the impact of spread and noise on the sign-of-change calculation.
Because the strategy relies on a statistical window of recent bars, it needs a reasonable amount of price history loaded before it can act. Remember that results will vary considerably across different symbols, timeframes, and market conditions — a setting that behaves well on one instrument may behave very differently on another. Always test 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
Strengths of the approach. The core idea — measuring persistence versus anti-persistence with a formal statistic — is genuinely elegant and well grounded. The runs test has decades of use in statistics for detecting non-randomness, and applying it as a regime filter means the strategy is at least attempting to match its behaviour to the market rather than forcing one style onto every condition. The consistent ATR-based risk framework across both books is a disciplined design choice, and the explicit "stand aside when random" branch is a valuable feature that many systems lack.
Known limitations. The runs test looks only at the sign of each change, not its magnitude, so a market with many tiny alternating moves and one large decisive one can read as "choppy" even when the real money moved in one direction. Regime classification is also inherently lagging: by the time the window shows strong persistence, part of the move may already be over. Whipsaws are possible at regime boundaries, where the z-score hovers near the threshold and flips between books. The WindowN and ZThreshold parameters strongly influence how often and how confidently the strategy trades, and poorly chosen values may leave it either over-trading noise or standing aside indefinitely.
Where it may underperform. Very low-volatility, tightly-ranging conditions can produce frequent flat changes that get skipped, thinning the sample. Sharp news-driven spikes can trigger a fade in the mean-reversion book right before a trend extends against it. As with any regime system, sudden transitions — a range that breaks into a trend, or vice versa — are the hardest moments and where the classifier is most likely to be caught on the wrong side. Treat this EA as a framework to study and stress-test, not a finished solution.
Risk Management Tips
Sound risk management matters more than any single entry signal. Consider the following general principles as you study this strategy:
- Risk a small, fixed fraction per trade. Many educators suggest never risking more than 1–2% of account equity on any single position. Size your
Lotsso the ATR-based stop distance stays within that limit. - Test on a demo account first. Run the EA in a simulated environment for an extended period across different market conditions before considering any live capital.
- Understand drawdown. Every strategy experiences losing streaks. Know how large a peak-to-trough decline you could tolerate emotionally and financially, and study the strategy's behaviour during its worst historical stretches.
- Do not over-optimize. Tuning parameters until a backtest looks perfect ("curve fitting") often produces settings that fail on new data. Prefer robust settings that work reasonably across a range of values.
- Account for costs. Spread, commission, and slippage all erode edge, especially for a system that may trade frequently at regime boundaries.
- Never risk money you cannot afford to lose. Leverage magnifies both gains and losses.
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: RunsTestRegimeSwitch.ex5 (22 downloads)
- Source Code: RunsTestRegimeSwitch.mq5 (12 downloads)
- Documentation: RunsTestRegimeSwitch.pdf (26 downloads)