MetaTrader MT4 Indicator 100% Free MQL Source Code

RSI Divergence MT4 Indicator

RaptozGroupBy RaptozGroup
4.9 (120 reviews)
15,000+ Downloads
RSI Divergence MT4 Indicator Chart Setup

RSI Divergence Scanner on MT4 identifying regular and hidden divergence patterns.

The RSI Divergence MT4 Indicator is a free custom tool written in MQL4 for MetaTrader 4. It automatically scans for regular and hidden bullish & bearish RSI divergences, plots trendlines on both price and oscillator subwindows, and alerts traders to high-probability reversal opportunities.

RSI Divergence MT4 Indicator Overview

What Is RSI Divergence in Quantitative Technical Analysis?

The Relative Strength Index (RSI), originally created by J. Welles Wilder Jr., is one of the most widely respected momentum oscillators in modern trading. While standard retail usage focuses primarily on overbought (70+) and oversold (30-) threshold levels, the most statistically robust predictive signal produced by the oscillator is RSI Divergence.

Divergence occurs when the directional trajectory of market price action disagrees with the internal velocity and momentum measured by the RSI. Because momentum always precedes price, divergence warns traders that the prevailing trend is losing underlying institutional participation and is vulnerable to an imminent reversal or deep corrective retracement.

The 4 Core Types of RSI Divergence

RSI divergences are divided into two primary categories: Regular (Classic) Divergence which signals trend reversals, and Hidden Divergence which signals trend continuation.

1. Regular Bullish Divergence (Reversal)

Price makes a Lower Low (LL) while the RSI makes a Higher Low (HL). Indicates selling pressure is drying up at market bottoms, setting up a sharp bullish rally.

2. Regular Bearish Divergence (Reversal)

Price makes a Higher High (HH) while the RSI makes a Lower High (LH). Indicates buyer exhaustion at market tops, setting up a sharp bearish decline.

3. Hidden Bullish Divergence (Continuation)

Price makes a Higher Low (HL) during a pullback while the RSI makes a Lower Low (LL). Confirms strong underlying uptrend continuation.

4. Hidden Bearish Divergence (Continuation)

Price makes a Lower High (LH) during a pullback while the RSI makes a Higher High (HH). Confirms strong underlying downtrend continuation.

RSI Divergence Classification Matrix

Divergence TypePrice ActionRSI OscillatorMarket Outlook
Regular BullishLower Low (LL)Higher Low (HL)Bullish Trend Reversal
Regular BearishHigher High (HH)Lower High (LH)Bearish Trend Reversal
Hidden BullishHigher Low (HL)Lower Low (LL)Bullish Trend Continuation
Hidden BearishLower High (LH)Higher High (HH)Bearish Trend Continuation

Mathematical Formulation of RSI & Smoothed Moving Averages

The calculation of the Relative Strength Index relies on comparing average upward price changes against average downward price changes over a specified lookback period (typically 14 bars):

Relative Strength (RS) = Smoothed Average Gain / Smoothed Average Loss
RSI Formula = 100 − [100 / (1 + RS)]

When price prints an extreme high with a lower RSI value, it indicates that the average gain per candle is decelerating, proving that buying interest is waning even though nominal prices made a marginal new high.

Pro Trader Execution Rules & 5 Common RSI Traps

  • Do Not Short Strong Trending Bull Markets on First Divergence: During strong institutional trend extensions, RSI can remain overbought while generating multiple consecutive minor divergences. Always wait for a structural Change of Character (CHoCH) break before entering.
  • Combine Divergence with Supply & Demand Zones: Divergence has the highest predictive value when it triggers precisely at an unmitigated H4 or Daily Supply/Demand zone.
  • Verify the RSI Median Line (50.0): In a healthy bull trend, pullbacks should bounce above the 40-50 RSI zone (bullish support). In a bear trend, rallies should stall below 50-60.
  • Avoid Low Liquidity Asian Session Scans: False divergences frequently occur during quiet market consolidations. Trade divergence during high-volume London and New York overlaps.
  • Wait for Confirmed Candle Closes: Never enter while the active bar is forming; always wait for the signal arrow candle to close to avoid repainting artifacts.

Supported MT4 Timeframes & Asset Classes

TimeframeBest Trading StyleRecommended Settings
M1 / M5Fast ScalpingRSI Period: 9, Lookback: 50 bars
M15 / M30Intraday TradingRSI Period: 14, Lookback: 100 bars
H1 / H4Day & Swing TradingRSI Period: 14, Lookback: 200 bars
D1 / W1Macro PositionRSI Period: 21, Lookback: 300 bars

Key Features & Capabilities

Automatic detection of Regular and Hidden RSI divergences
Plots divergence connecting lines on chart and indicator subwindow
Configurable RSI period, lookback depth, and overbought/oversold levels
Non-repainting signal arrows based on confirmed closed candle pivots
Real-time audio, popup, and email alert notifications
Compatible with MT4 Build 1420+ across all currency pairs

Input Parameters & Settings Guide

Configure the indicator inputs inside MetaTrader MT4 via the Inputs tab upon attaching to your chart:

ParameterDefault ValueDescriptionRecommended
InpRSIPeriod14RSI calculation period length14 for Standard, 9 for Fast Scalping
InpLookbackBars100Bars back to search for divergence peaks100-300 bars
InpDrawTrendLinestrueDraw divergence lines on chart & RSI subwindowTrue
InpAlertOnDivergencetrueEnable audio & popup alerts upon signalTrue
InpOverboughtLevel70.0Overbought reference threshold70.0 (or 80.0 for extreme)
InpOversoldLevel30.0Oversold reference threshold30.0 (or 20.0 for extreme)

Trading Strategy & Entry Rules

1

Step 1: Identify Macro Trend Direction

Use a 200 EMA on the H1/H4 chart to establish primary market trend direction before looking for divergence entries.

2

Step 2: Wait for Confirmed RSI Divergence

Look for confirmed divergence arrows that appear in overbought/oversold extreme zones (above 70 or below 30).

3

Step 3: Check Key Confluence Levels

Ensure the divergence coincides with a major support/resistance level, Supply & Demand zone, or unmitigated Order Block.

4

Step 4: Execute on Closed Candle

Enter on the close of the divergence candle with stop loss positioned safely beyond the recent swing high/low.

5

Step 5: Scale Out Profits at Key Targets

Take 50% profit at the median 50 RSI line, trailing the remainder to the opposing 70/30 extreme level.

MQL4 Source Code

//+------------------------------------------------------------------+
//|                                  RSI_Divergence_Scanner_MT4.mq4  |
//|                    Copyright 2026, TraderSentiments Quant Team   |
//|                                    https://tradersentiments.com  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, TraderSentiments"
#property link      "https://tradersentiments.com/indicators/mt4/oscillators/rsi-divergence-indicator"
#property version   "2.00"
#property strict
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  clrDodgerBlue
#property indicator_color2  clrLimeGreen
#property indicator_color3  clrCrimson
#property indicator_level1  70.0
#property indicator_level2  30.0

input int      InpRSIPeriod        = 14;          // RSI Period
input int      InpLookbackBars     = 100;         // Divergence Lookback Bars
input bool     InpDrawTrendLines   = true;        // Draw Divergence Lines on Chart
input bool     InpAlertOnDivergence= true;        // Popup Alert on Regular/Hidden Divergence

int OnInit() {
   IndicatorShortName("RSI Divergence Scanner MT4 (" + IntegerToString(InpRSIPeriod) + ")");
   return(INIT_SUCCEEDED);
}

How to Install & Compile in MetaTrader MT4

Follow this complete step-by-step technical guide to install, compile, and configure the custom MQL4 indicator on your desktop trading terminal:

Step 1

Download Source File

Download the raw .mq4 source file to your computer using the direct download button below.

Step 2

Open MT4 Data Folder

Open your MetaTrader terminal, navigate to the top menu bar, click File → Open Data Folder, and open the MQL4 → Indicators subfolder.

Step 3

Copy & Compile in MetaEditor

Paste the downloaded file into the Indicators directory. Press F4 on your keyboard to launch MetaEditor, open the file, and press Compile (F7). Ensure the compiler reports 0 errors and 0 warnings.

Step 4

Attach to Chart & Configure

Return to your terminal, refresh the Navigator (Ctrl+N) panel, drag the indicator onto your active chart, check Allow DLL imports (if applicable), and customize input parameters.

Integrating with Expert Advisors (EA) via iCustom()

Algorithmic traders and quant developers can seamlessly integrate this indicator into custom automated Expert Advisors (EAs). Because the indicator calculates values into standardized plot buffers on closed bars, you can query buffer values using native MQL4 functions without recompilation:

// MT4 MQL4 iCustom Calling Syntax Example
double signalBuy  = iCustom(Symbol(), Period(), "RSI_Divergence_Scanner_MT4", 0, 1);
double signalSell = iCustom(Symbol(), Period(), "RSI_Divergence_Scanner_MT4", 1, 1);

if (signalBuy != 0.0 && signalBuy != EMPTY_VALUE) {
    // Bullish signal confirmed on closed bar [1] -> Execute Buy Order
}
if (signalSell != 0.0 && signalSell != EMPTY_VALUE) {
    // Bearish signal confirmed on closed bar [1] -> Execute Sell Order
}

How to Set Up Mobile Push Notifications on iOS & Android

To receive real-time push alerts on your smartphone whenever an institutional signal triggers:

  1. Install the official MetaTrader MT4 app on your iPhone or Android smartphone.
  2. Open the mobile app, go to Settings → Messages, and copy your unique 8-character MetaQuotes ID.
  3. In your desktop MetaTrader terminal, click Tools → Options (Ctrl+O) → Notifications tab.
  4. Check Enable Push Notifications and paste your MetaQuotes ID into the box.
  5. Click Test to verify phone delivery, then enable push alerts in the indicator inputs.

Institutional Risk Management & Capital Preservation Protocol

Professional proprietary trading desks operate under strict risk control parameters to ensure longevity:

  • Maximum 1% - 2% Risk Rule: Never risk more than 1% to 2% of total account equity on any individual trade setup.
  • Minimum 1:2.5 Risk-to-Reward Ratio (RRR): Only execute setups where the potential profit target is at least 2.5 times greater than the stop-loss invalidation distance.
  • Multi-Timeframe Confluence Required: Never take an intraday trade against the primary Daily or 4-Hour trend direction.
  • High-Impact Economic News Awareness: Avoid entering new positions 15 minutes before and after major macroeconomic data releases (such as US Non-Farm Payrolls, CPI Inflation, and central bank FOMC/ECB interest rate announcements).

Strategy Backtesting & Historical Modeling Protocol

Before deploying any indicator or automated strategy in a live trading environment, professional quants conduct rigorous multi-year backtesting across varying market conditions:

  • 99.9% Tick Data Modeling: Use high-precision tick history from reputable data providers (such as Dukascopy or TrueFX) to eliminate spread anomalies and slippage distortion.
  • Spread & Commission Inclusion: Always test with realistic variable spreads and broker commission structures to simulate true real-world execution friction.
  • Out-of-Sample Walk-Forward Optimization: Avoid curve-fitting by validating parameters on 70% in-sample data and testing robustness on 30% out-of-sample data.
  • Monte Carlo Drawdown Analysis: Run randomized trade sequence simulations to calculate the maximum potential drawdown under adverse market volatility regimes.

Virtual Private Server (VPS) & Execution Latency Optimization

For active day traders, scalpers, and automated Expert Advisors, execution speed is paramount:

  • Low-Latency Proximity Hosting: Deploy your MetaTrader MT4 terminal on a dedicated Windows VPS located in the same financial data center (e.g. Equinix LD4 in London or NY4 in New York) as your broker server to achieve sub-millisecond execution times.
  • Terminal Memory Optimization: Go to Tools → Options → Charts and decrease Max bars in chart to 5,000 to conserve CPU and RAM resources.
  • Audio & News Feed Disabling: Turn off unneeded terminal audio event chimes and background news feeds to ensure 100% of CPU cycles are dedicated to indicator calculations.

Common MetaTrader Error Codes & Resolution Matrix

Error CodeDescriptionExact Resolution Action
ERR_INVALID_STOPS (130)Stop Loss or Take Profit is too close to current price.Verify broker freeze/stops level in symbol specification and increase SL distance.
ERR_OFF_QUOTES (136)Broker server has no available liquidity quotes.Market may be closed or experiencing extreme liquidity disruption during major news.
ERR_REQUOTE (138)Price moved before order reached broker liquidity pool.Increase slippage tolerance deviation parameter in your order execution settings.
ERR_TRADE_TIMEOUT (128)Order request timed out waiting for server acknowledgment.Check internet connection latency or migrate terminal to a dedicated trading VPS.

Institutional Quantitative Trading Lexicon

Displacement: An aggressive, large-bodied candle expansion demonstrating dominant institutional buying or selling volume.
Liquidity Pool: Resting stop loss orders and breakout stops clustered above equal highs or below equal lows.
Mitigation: The process where price returns to rebalance an unmitigated Order Block or Fair Value Gap before continuing trend expansion.
Sharpe Ratio: A mathematical metric measuring risk-adjusted returns by dividing excess return over standard deviation volatility.

Broker Execution Models & Raw Spread Compatibility

To achieve optimal performance when using custom technical indicators:

  • ECN / Raw Spread Accounts: Use True ECN accounts with 0.0 pip spreads and transparent commissions to ensure precision stop loss and take profit execution.
  • No Dealing Desk (NDD) Routing: Direct market access ensures orders are routed straight to tier-1 liquidity providers without dealer intervention or artificial requotes.
  • Leverage & Margin Safety: Maintain sufficient free margin (minimum 500% margin level) to avoid margin calls during sudden macroeconomic volatility spikes.

RSI_Divergence_Scanner_MT4.mq4

Version: v2.00File Size: 17.1 KBTotal Downloads: 15,000+License: Free Open SourcePlatform: MetaTrader MT4

Download .mq4
VirusTotal Verified Clean • Zero DLL Dependencies
15,000+ DownloadsCompatible with MT4 Build 1420+

Frequently Asked Questions

No. The indicator calculates divergence only on confirmed closed bar pivots, ensuring historical signals do not repaint.
RaptozGroup
Developed & Audited by RaptozGroup

Quantitative algorithmic trading research desk specializing in MetaTrader MQL4/MQL5 automated systems, institutional order book mechanics, and risk management tools.

RSI_Divergence_Scanner_MT4.mq4
15,000+ DownloadsFree Open Source
Download .mq4