Skip to main content

RSI/MACD Divergence EA Template for MetaTrader 5

Divergence between price and a momentum indicator is one of the most reliable reversal signals in technical analysis. This free EA template automatically detects bullish and bearish divergence using either RSI or MACD, with configurable swing point detection and ATR-based risk management. Best for EURUSD, GBPUSD, and USDJPY on H4 to D1 timeframes. Build it in AlgoStudio without coding and export a production-ready MQL5 Expert Advisor in minutes.

What Is a Divergence Trading Strategy?

Divergence occurs when price action and a momentum indicator move in opposite directions. For example, if price makes a new higher high but the RSI makes a lower high, this bearish divergence suggests that the uptrend is losing momentum and a reversal may be imminent. Conversely, if price makes a lower low but the RSI makes a higher low, this bullish divergence suggests the downtrend is weakening.

Divergence works because momentum typically leads price. When an indicator stops confirming new price extremes, it signals that the underlying buying or selling pressure is fading. The move may continue for a while on pure inertia, but the probability of a reversal increases significantly.

This is a reversal strategy — it goes against the current price direction, which makes proper risk management essential. Divergence signals are not immediate: price can diverge for several bars before reversing. The template uses ATR-based stops and a fixed risk-reward ratio to manage this uncertainty, ensuring losses are controlled while allowing room for the reversal to play out.

How This EA Template Works

BUY SIGNAL: Bullish divergence detected — price makes a lower low while RSI/MACD makes a higher low within the lookback window
SELL SIGNAL: Bearish divergence detected — price makes a higher high while RSI/MACD makes a lower high within the lookback window
EXIT: Stop loss at 1.5x ATR(14) or take profit at 2:1 risk-reward ratio

The EA scans the last N bars (default 20) for swing highs and swing lows in both price and the selected indicator. It then compares the two most recent swing points to determine if divergence exists. The minimum swing bars setting (default 5) ensures that the two swing points are separated by enough bars for the divergence pattern to be meaningful — very close swing points produce unreliable signals.

When using RSI, the indicator value at each price swing point is compared directly. When using MACD, the histogram values at swing points are compared. Both methods are effective, but they detect slightly different types of momentum shifts. RSI divergence is more common and easier to validate visually. MACD divergence tends to signal larger reversals but produces fewer trades.

Default Parameters

These defaults work well on major pairs on H4 and D1 timeframes. All parameters are exported as input variables so you can optimize them in the MT5 Strategy Tester.

ParameterValueType
IndicatorRSI (or MACD)Selection
RSI Period14Indicator
MACD Settings12/26/9Indicator
Lookback Bars20Detection
Min Swing Bars5Detection
Stop Loss1.5x ATR(14)ATR-based
Take Profit2:1 R:RRisk-reward
Position Sizing1% risk per tradeRisk

How to Build This EA Without Coding

1. Create a new project in AlgoStudio

Sign up for free (no credit card required) and click “New Project”. Name your project “Divergence Strategy” and open the visual builder canvas.

2. Add the RSI/MACD Divergence entry strategy block

Drag an RSI/MACD Divergence entry strategy block onto the canvas. Choose RSI or MACD as your indicator. Set the lookback bars to 20 and minimum swing bars to 5. If using RSI, keep the default period of 14. If using MACD, keep the standard 12/26/9 settings.

3. Configure risk management

Set the stop loss to 1.5x ATR(14), take profit to 2:1 risk-reward, and position sizing to 1% risk per trade. Since divergence is a reversal strategy, having proper risk management is critical — not every divergence signal results in a reversal, and losses must be kept small relative to your account.

4. Export, backtest, and optimize

Click Export to generate a .mq5 file. Load it into MetaTrader 5 and backtest on EURUSD H4 or D1 with at least 3 years of historical data. Divergence strategies produce fewer trades, so you need a longer backtest period for meaningful results. Optimize lookback bars (15-30) and minimum swing bars (3-8). Demo trade for 2-3 months before going live.

Optimization Tips

Use higher timeframes for more reliable signals

Divergence on H4 and D1 is far more reliable than on H1 or lower. Higher timeframes produce cleaner swing points and more meaningful divergence patterns. The trade-off is fewer signals — you might get 2-4 trades per month on D1 versus 8-12 on H4. Quality over quantity is the key principle for divergence trading.

Combine with support/resistance levels

Divergence at a key support or resistance level is significantly more powerful than divergence in the middle of a range. If you see bullish divergence right at a major support level, the probability of reversal is much higher. You can add a session filter or time filter to focus on setups that coincide with significant price levels.

Accept lower trade frequency

Divergence strategies inherently produce fewer trades than trend-following or momentum strategies. Trying to increase trade frequency by loosening the detection parameters (fewer lookback bars, less strict swing detection) usually degrades signal quality. If your backtest shows more than 1-2 trades per week on H4, your detection may be too sensitive and you're likely finding false divergence patterns.

Frequently Asked Questions

What is the difference between regular and hidden divergence?
Regular (classic) divergence signals a potential trend reversal: price makes a higher high but the indicator makes a lower high (bearish), or price makes a lower low but the indicator makes a higher low (bullish). Hidden divergence signals trend continuation: price makes a higher low but the indicator makes a lower low (bullish), or price makes a lower high but the indicator makes a higher high (bearish). This template focuses on regular divergence for reversal detection.
Should I use RSI or MACD for divergence detection?
RSI divergence is easier to detect and produces more frequent signals, making it better for beginners. MACD divergence uses the histogram for detection, which can be more precise for identifying momentum shifts. RSI works better on H1-H4 timeframes, while MACD divergence tends to shine on H4-D1. Test both on your target pair and timeframe to see which produces cleaner signals.
How many lookback bars should I use for swing detection?
The default 20 bars works well on H1 and H4. Fewer bars (10-15) detect smaller divergence patterns with more frequent but less reliable signals. More bars (25-40) detect larger, more significant divergence patterns but produce fewer trades. The minimum swing bars setting (default 5) ensures the two swing points are far enough apart for the divergence to be meaningful.
What timeframes work best for divergence trading?
H4 and D1 produce the most reliable divergence signals because swing points are well-defined on higher timeframes. H1 works but generates more false signals. Avoid M5 and M15 where price action is noisy and divergence patterns are unreliable. Divergence is inherently a slower signal — patience with higher timeframes is rewarded.
What win rate should I expect from a divergence strategy?
A well-optimized divergence strategy typically wins 40-50% of trades. Divergence signals are good at identifying potential reversals, but the timing can be imprecise — price may continue against you before reversing. Use a 2:1 risk-reward ratio to ensure profitability even with a moderate win rate. The key edge is catching major turning points where the reward is large.

Build the Divergence EA in minutes

Create this strategy with AlgoStudio's visual builder. Free plan available — no credit card required.

Start Validating — Free

Risk Warning: Trading in financial markets involves substantial risk of loss and is not suitable for every investor. Past performance does not guarantee future results. Always test strategies on a demo account first. AlgoStudio is a strategy validation platform — it does not provide financial advice or guarantee profits. See our Terms of Service for full details.