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 Median Slope Trend Rider is a trend-following pullback strategy for MetaTrader 5 built around a robust statistical trend estimator called the Theil-Sen slope — the median of every pairwise close-to-close slope measured inside a lookback window. Instead of drawing a trend with an ordinary least-squares (OLS) regression line, which most trend tools rely on, this strategy asks a simpler and more resilient question: across all the pairs of closing prices in the window, what is the typical slope? Taking the median rather than a squared-error fit is what makes the trend read robust.
The reason for this design is practical. Ordinary least-squares minimizes squared error, so a single news spike or stop-run wick — very common on forex majors and metals — can drag an OLS line around and manufacture a trend that is not really there. The Theil-Sen estimator is a non-parametric statistic with roughly a 29% "breakdown point," meaning it stays stable until nearly a third of the sample is contaminated by outliers. In plain terms, the strategy aims to read the underlying trend cleanly and ignore rogue bars, so that pullback entries are less likely to be whipsawed by one abnormal candle.
As a learning tool, the Median Slope Trend Rider is designed for markets that actually trend — a trending forex major or a metal such as EURUSD or XAUUSD on higher timeframes like H1 to H4. It is timeframe-agnostic and will run on whatever chart it is applied to, but it is best studied by traders who want to understand robust statistics, trend filtering, and continuation-style pullback entries. This article is a strategy analysis, not a profit opportunity; the goal is to help you understand how the components fit together.
How It Works
The strategy evaluates the market only on closed bars with a fully formed window, so its signals do not repaint (they do not change after the fact). Here is how it decides what to do:
- Build the robust trend line. Over the last
SlopeWindowclosed bars, the strategy computes the Theil-Sen slope (median of all pairwise close-to-close slopes) and a matching robust intercept (median of the per-point residuals). Together these define a "fair value" line — the robust equivalent of a regression line — at each bar in the window. - Normalize the slope by volatility. The raw slope is measured in price-per-bar, which is not comparable across symbols. The strategy divides it by the ATR (Average True Range, a standard measure of volatility) to express trend strength as a "fraction of an ATR of net drift per bar." This scale-free reading behaves consistently whether you are on EURUSD, XAUUSD, or an index.
- Apply the regime filter. The strategy only looks for trades when a robust trend exists. It signals an uptrend when the normalized slope is greater than or equal to
+SlopeThreshold, and a downtrend when it is less than or equal to−SlopeThreshold. If the normalized slope sits between those bounds, the market is treated as flat or choppy and the strategy stands aside. - Long entry — pullback that reclaims the line. In a confirmed uptrend, the strategy signals a long when the prior closed bar dipped below the robust line (a genuine pullback into value) and the just-closed bar closes back above the line. This is read as the trend resuming, so it buys the reclaim as a continuation rather than a breakout.
- Short entry — mirror image. In a confirmed downtrend, the strategy signals a short when the prior closed bar poked above the line and the just-closed bar closes back below it.
- One position at a time. The strategy holds a single position per magic number and lets the protective stop and target manage the exit — it does not stack trades.
- Stop-loss logic. On entry, a protective stop is placed at a distance of
AtrStopMult × ATRfrom the fill price (below for longs, above for shorts). Because the stop scales with ATR, it adapts to each symbol's volatility instead of using a hard-coded point size. - Take-profit logic. A target is placed at
AtrTpMult × ATRfrom entry. With the default multipliers, this creates a symmetric ATR-based structure where the reward-to-risk relationship is defined by the ratio of the two multipliers.

Strategy Parameters
| Parameter | Default | Min | Max | Description |
|---|---|---|---|---|
| SlopeWindow | 24 | 10 | 60 | Number of closed bars in the Theil-Sen window — the strategy's trend memory. Larger values smooth the trend read; smaller values react faster. |
| SlopeThreshold | 0.03 | 0.00 | 0.30 | Minimum absolute normalized slope (net drift per bar in ATR units) required to call the market a trend. Higher values demand a stronger trend before trading. |
| AtrPeriod | 14 | 5 | 40 | ATR period used both for slope normalization and for the stop/target distances. |
| AtrStopMult | 2.0 | 0.5 | 6.0 | Protective stop-loss distance as a multiple of ATR. |
| AtrTpMult | 3.0 | 0.5 | 10.0 | Take-profit distance as a multiple of ATR. |
| Lots | 0.10 | 0.01 | 1.00 | Trade volume in lots. |
| Magic | 7413 | 0 | 9,999,999 | Magic number used to identify and manage this strategy's own positions. |

Recommended Chart Settings
The Median Slope Trend Rider was designed with a trending forex major or a metal in mind — EURUSD or XAUUSD — on the H1 to H4 timeframes, where robust trend estimation has enough bars to work with and where pullback continuations are common. That said, the strategy is timeframe-agnostic and will run on whatever symbol and timeframe you apply it to. Because market conditions differ across instruments and periods, results will vary; a setting that behaves well on one symbol or timeframe may behave very differently on another. Always study its behavior on your chosen market before drawing conclusions.
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
The main strength of this approach is its robustness to outliers. By taking the median of pairwise slopes rather than fitting a squared-error line, the strategy is designed to hold a steady trend read even when a single spike or wick would distort a conventional regression. Normalizing by ATR also makes the trend-strength reading comparable across symbols, and measuring everything on closed bars means the signals do not repaint. The pullback-reclaim entry is a disciplined continuation logic that historically waits for price to dip into value and then confirm before acting.
There are real limitations to keep in mind. Like all trend-following systems, the Median Slope Trend Rider is designed for trending conditions and may underperform in range-bound, sideways, or sharply mean-reverting markets, where the regime filter may still occasionally admit weak trends that reverse. The Theil-Sen computation grows with the square of the window size, so very large SlopeWindow values increase processing per bar. A fixed ATR-multiple stop and target does not adapt to changing market structure within a trade, and a symmetric setup means some winning moves may be given back if the target is not reached before a reversal. It is also a single-position system, so it does not scale into strong trends. None of these traits are flaws to be hidden — they are trade-offs to understand before you rely on the strategy.
Risk Management Tips
Sound risk management matters more than any single entry rule. As a general educational guideline, many traders aim to risk no more than 1–2% of account equity per trade, and size their positions accordingly rather than trading a fixed lot size regardless of stop distance. Because this strategy sets its stop as an ATR multiple, your actual money-at-risk changes with volatility — so it is worth calculating position size from the current stop distance each time.
Before using any expert advisor with real capital, run it on a demo account to understand how it behaves in live conditions, including spread, slippage, and news events. Study its drawdown — the peak-to-trough decline in equity — so you know what a normal losing streak looks like and can decide whether you could tolerate it. Keep detailed records, avoid over-optimizing parameters to past data, and never commit money you cannot afford to lose.
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: MedianSlopeTrendRider.ex5 (30 downloads)
- Source Code: MedianSlopeTrendRider.mq5 (29 downloads)
- Documentation: MedianSlopeTrendRider.pdf (37 downloads)