Blog / Strategy
Strategy

Runs Test Regime Switch

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:

Entry logic — Momentum book (trending regime):

Entry logic — Mean-reversion book (ranging regime):

Stop-loss logic:

Take-profit logic:

runs test regime switch MT5
Illustrative example of the strategy’s entry and exit logic — not real trading results.

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.
runs test regime switch MT5 — MQL5 source code

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

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 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

← Back to Blog