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 Detrended Fluctuation Regime Shift is a trend-following expert advisor (EA) built around Detrended Fluctuation Analysis (DFA), a technique borrowed from econophysics and statistical mechanics that measures long-range memory in a noisy time series. Instead of leaning on a moving average crossover or an oscillator, this strategy asks a more fundamental question: is the market's recent behaviour actually structured enough to trend, or is it just random noise dressed up as movement?
DFA answers that with a single number — the scaling exponent, usually written as alpha. When alpha sits near 0.5, the price stream behaves like a pure random walk with no exploitable structure. When alpha climbs above 0.5, the series is persistent: up-moves tend to follow up-moves, which is where genuine trend memory lives. When alpha drops below 0.5, the market is anti-persistent — choppy and mean-reverting. What makes DFA more robust than the classic Hurst rescaled-range statistic is that it fits and removes a local linear trend inside every sub-window before measuring fluctuation, so it is far less fooled by the drifting, non-stationary conditions that forex and index markets live in.
As a learning tool, this strategy suits intermediate traders who want to understand regime detection — the idea that a market isn't always in a state worth trading, and that identifying "when to be active" can matter as much as "which direction to take." It is designed for trending, liquid instruments on intraday timeframes and is best studied as an analytical framework rather than treated as a shortcut. If you are curious how quantitative research separates signal from noise, this EA is a hands-on illustration.
How It Works
The strategy recomputes the DFA exponent on every closed bar and only acts when the market's "memory switches on." Here is the logic in plain English:
- Measuring the regime. On each new bar, the EA takes the last
DfaWindowlog-returns, integrates them into a cumulative profile, then measures the detrended fluctuation across several geometric window sizes. The slope of log-fluctuation versus log-window-size is the alpha exponent. - The entry trigger — a fresh regime shift. The strategy does not trade while alpha loiters in the random-walk zone. It waits for a fresh cross of alpha up through the
AlphaTrendlevel. That single event — the previous bar's alpha at or below the threshold, and the current bar's alpha above it — marks the moment structure appears. - Direction confirmation. A rising alpha tells you that memory has returned, not which way to lean. So the EA adds two directional filters: drift (the net close-to-close displacement over
DriftBars) and structure (the close versus a slowTrendEmaPeriodEMA). - The strategy signals a long when alpha freshly crosses up, drift is positive, and the close is above the trend EMA.
- The strategy signals a short when alpha freshly crosses up, drift is negative, and the close is below the trend EMA.
- Stop-loss logic. Risk is anchored to volatility using the Average True Range (ATR). The initial stop sits
StopAtrMult× ATR away from entry, so the stop widens in fast markets and tightens in quiet ones. - Take-profit logic. The target is placed at
RewardRiskmultiples of the measured risk distance — a default 2.0 reward-to-risk ratio. - Break-even and trailing. Once price moves
BreakevenRrisk-multiples in your favour, the stop is locked to break-even, after which an ATR trail (TrailAtrMult× ATR) follows price but only ever tightens — it never loosens. - Regime-loss exit. This is the strategy's signature safeguard. If alpha falls back below
AlphaExit, the memory that justified the trade is gone, so the position is closed immediately. Cutting a thesis the moment its premise expires is what keeps losing trades small. - One position at a time. The EA holds a single position, tagged with its
Magicnumber, and never stacks or reverses while a trade is live.

Strategy Parameters
| Parameter | Default | Min | Max | Description |
|---|---|---|---|---|
| DfaWindow | 128 | 64 | 256 | Number of recent log-returns used to compute the DFA alpha exponent. Larger values smooth the regime read but react more slowly. |
| AlphaTrend | 0.55 | 0.52 | 0.72 | The alpha level whose fresh up-cross arms an entry. Higher values demand stronger persistence before trading. |
| AlphaExit | 0.50 | 0.40 | 0.55 | The regime-loss exit level. If alpha falls below this, the open trade is closed. Automatically kept below AlphaTrend. |
| TrendEmaPeriod | 50 | 20 | 200 | Period of the slow structure EMA used to confirm trade direction. |
| DriftBars | 20 | 5 | 60 | Lookback (in bars) for the net-displacement "drift" that sets direction. |
| AtrPeriod | 14 | 5 | 40 | ATR period used for stop distance, trailing, and volatility scaling. |
| StopAtrMult | 1.5 | 0.5 | 4.0 | Initial stop distance as a multiple of ATR. |
| RewardRisk | 2.0 | 1.0 | 5.0 | Take-profit distance as a multiple of the initial risk. |
| BreakevenR | 1.0 | 0.3 | 2.0 | Profit in risk-multiples required before the stop is locked to break-even. |
| TrailAtrMult | 1.5 | 0.5 | 4.0 | ATR multiple used for the trailing stop after break-even is reached. |
| Lots | 0.05 | 0.01 | 1.0 | Fixed trade volume in lots. |

Recommended Chart Settings
The Detrended Fluctuation Regime Shift is designed to run on a single timeframe — whatever chart you attach it to — because every price query uses the primary symbol and period rather than any hardcoded timeframe. In research and design it is intended for trending, liquid markets around the M30 to H1 range, such as major forex pairs or liquid index CFDs where DFA has enough clean data to measure long-range structure. Lower timeframes tend to be dominated by microstructure noise that pushes alpha toward the random-walk zone, while very high timeframes produce too few regime shifts to study. Remember that DFA is a statistical estimator: results will vary meaningfully across symbols, spreads, and market conditions, so treat any single configuration as a starting point for your own testing rather than a finished setting.
How to Install on MetaTrader 5
- Download the
.ex5file 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 this approach is selectivity. Because it only engages after a fresh alpha cross and requires drift and structure to agree, the strategy sits out large stretches of directionless market — precisely the conditions that grind down naive trend-followers. The regime-loss exit adds a second layer of discipline by refusing to hold a position once the statistical justification for it evaporates.
That selectivity is also its main limitation. DFA is a lagging measure by nature: by the time alpha has crossed the threshold, part of the move may already be underway, so entries can feel late. Being a computation over a rolling window, alpha can also flicker around the trigger level in transitional markets, producing occasional false starts that the ATR stop must absorb. Like all trend-following logic, this strategy can underperform in tightly range-bound or violently whipsawing conditions, and news-driven volatility spikes can breach a volatility-scaled stop before the trailing logic ever engages. It is not a market-neutral system — extended sideways regimes will simply keep it flat, which some traders find frustrating even though that inactivity is by design. Study how alpha behaves on your chosen instrument before committing to any live use.
Risk Management Tips
Regardless of how a strategy is engineered, sound risk management is what protects an account over time. Consider the following general principles:
- Position sizing: Size trades so that a single loss is a small, survivable fraction of your account. The fixed
Lotsdefault is deliberately conservative — scale it to your own balance, not the other way around. - The 1–2% rule: Many educators suggest risking no more than 1–2% of account equity on any single trade so that a string of losses cannot do lasting damage.
- Demo first: Test the EA on a demo account across different symbols and market phases before considering real capital. This lets you observe how often it trades and how the regime-loss exit behaves.
- Understand drawdown: Even a well-designed system experiences losing streaks. Know the maximum drawdown you are willing to tolerate and how it feels in practice, not just in theory.
- Never over-leverage: Leverage magnifies losses as readily as gains. Keep it modest while you are learning how the strategy reacts.
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: DetrendedFluctuationRegimeShift.ex5 (23 downloads)
- Source Code: DetrendedFluctuationRegimeShift.mq5 (28 downloads)
- Documentation: DetrendedFluctuationRegimeShift.pdf (24 downloads)