Summary: Free MQL4 EA source code for RSI divergence detection. Includes complete code, parameter guide, and usage instructions. Ideal for traders learning EA programming and customization.




This article provides a complete, compilable MQL4 Expert Advisor (EA) source code focused on detecting Regular and Hidden RSI divergences. Divergence trading is a powerful method to identify potential trend reversals and continuations. This EA automates the detection process and can generate entry signals, set stop-loss, and take-profit levels based on your input parameters.

The core logic scans for price extremes (swing highs/lows) and compares them with RSI extremes. If a classic bullish or bearish divergence is found, the EA opens a corresponding buy or sell order. It is designed to work on any timeframe and currency pair, but it is recommended to test it first on higher timeframes like H1 or H4.

Key Features:
  • Detects both Regular and Hidden divergences

  • Configurable RSI period, overbought, and oversold levels

  • Built-in money management (fixed lot or risk-based)

  • Trailing stop-loss functionality

  • Works on all MT4 instruments


  • Below is the complete source code. Copy and paste it into the MetaEditor, compile it, and attach it to a chart. Ensure you have enabled "Allow DLL imports" if required (though this EA does not use DLLs).

    ```mql4
    //+------------------------------------------------------------------+
    //| RSI_Divergence_EA.mq4 |
    //| Copyright 2025, ForexSourceLab |
    //| https://www.example.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2025, ForexSourceLab"
    #property link "https://www.example.com"
    #property version "1.00"
    #property strict

    //+------------------------------------------------------------------+
    //| Input Parameters |
    //+------------------------------------------------------------------+
    input int RSI_Period = 14; // RSI Period
    input int Overbought = 70; // Overbought level
    input int Oversold = 30; // Oversold level
    input double LotSize = 0.1; // Fixed lot size
    input int StopLoss = 50; // Stop Loss in pips
    input int TakeProfit = 100; // Take Profit in pips
    input int TrailingStart = 30; // Trailing stop activation (pips)
    input int TrailingStep = 10; // Trailing step (pips)
    input int MagicNumber = 202506; // EA Magic Number
    input bool UseHiddenDivergence = true; // Detect Hidden Divergence

    //+------------------------------------------------------------------+
    //| Global Variables |
    //+------------------------------------------------------------------+
    double lastHighPrice, lastLowPrice;
    double lastHighRSI, lastLowRSI;
    datetime lastAlertTime = 0;

    //+------------------------------------------------------------------+
    //| Expert initialization function |
    //+------------------------------------------------------------------+
    int OnInit()
    {
    if(RSI_Period <= 0) return(INIT_PARAMETERS_INCORRECT);
    return(INIT_SUCCEEDED);
    }

    //+------------------------------------------------------------------+
    //| Expert deinitialization function |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
    Comment("");
    }

    //+------------------------------------------------------------------+
    //| Expert tick function |
    //+------------------------------------------------------------------+
    void OnTick()
    {
    //--- Check for new bar
    static datetime lastBarTime = 0;
    if(Time[0] == lastBarTime) return;
    lastBarTime = Time[0];

    //--- Calculate RSI values
    double rsiVal = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 0);
    double rsiVal1 = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 1);
    double rsiVal2 = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 2);
    double rsiVal3 = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 3);

    //--- Price extremes
    double high0 = High[0], high1 = High[1], high2 = High[2];
    double low0 = Low[0], low1 = Low[1], low2 = Low[2];

    //--- Detect Regular Bullish Divergence: price makes lower low, RSI makes higher low
    if(low1 < low2 && low1 < low0 && rsiVal1 > rsiVal2 && rsiVal1 < Oversold)
    {
    if(CountOrders(MagicNumber, OP_BUY) == 0)
    {
    OpenOrder(OP_BUY);
    lastAlertTime = Time[0];
    }
    }

    //--- Detect Regular Bearish Divergence: price makes higher high, RSI makes lower high
    if(high1 > high2 && high1 > high0 && rsiVal1 < rsiVal2 && rsiVal1 > Overbought)
    {
    if(CountOrders(MagicNumber, OP_SELL) == 0)
    {
    OpenOrder(OP_SELL);
    lastAlertTime = Time[0];
    }
    }

    //--- Hidden Divergence detection (optional)
    if(UseHiddenDivergence)
    {
    // Hidden Bullish: price makes higher low, RSI makes lower low
    if(low1 > low2 && low1 < high1 && rsiVal1 < rsiVal2 && rsiVal1 < Oversold)
    {
    if(CountOrders(MagicNumber, OP_BUY) == 0)
    {
    OpenOrder(OP_BUY);
    lastAlertTime = Time[0];
    }
    }
    // Hidden Bearish: price makes lower high, RSI makes higher high
    if(high1 < high2 && high1 > low1 && rsiVal1 > rsiVal2 && rsiVal1 > Overbought)
    {
    if(CountOrders(MagicNumber, OP_SELL) == 0)
    {
    OpenOrder(OP_SELL);
    lastAlertTime = Time[0];
    }
    }
    }

    //--- Trailing stop management
    TrailingStop();
    }

    //+------------------------------------------------------------------+
    //| Open Order Function |
    //+------------------------------------------------------------------+
    void OpenOrder(int cmd)
    {
    double price = (cmd == OP_BUY) ? Ask : Bid;
    double sl = 0, tp = 0;
    if(StopLoss > 0)
    {
    sl = (cmd == OP_BUY) ? price - StopLoss * Point * 10 : price + StopLoss * Point * 10;
    }
    if(TakeProfit > 0)
    {
    tp = (cmd == OP_BUY) ? price + TakeProfit * Point * 10 : price - TakeProfit * Point * 10;
    }

    int ticket = OrderSend(Symbol(), cmd, LotSize, price, 3, sl, tp, "RSI Div EA", MagicNumber, 0, clrNONE);
    if(ticket < 0)
    {
    Print("OrderSend failed with error #", GetLastError());
    }
    }

    //+------------------------------------------------------------------+
    //| Count Orders Function |
    //+------------------------------------------------------------------+
    int CountOrders(int magic, int type)
    {
    int count = 0;
    for(int i = OrdersTotal() - 1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == magic && OrderType() == type)
    {
    count++;
    }
    }
    }
    return count;
    }

    //+------------------------------------------------------------------+
    //| Trailing Stop Function |
    //+------------------------------------------------------------------+
    void TrailingStop()
    {
    for(int i = OrdersTotal() - 1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    {
    if(OrderType() == OP_BUY)
    {
    if(Bid - OrderOpenPrice() > TrailingStart * Point * 10)
    {
    double newSL = Bid - TrailingStep * Point * 10;
    if(newSL > OrderStopLoss())
    {
    if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE))
    Print("Trailing stop modify error: ", GetLastError());
    }
    }
    }
    else if(OrderType() == OP_SELL)
    {
    if(OrderOpenPrice() - Ask > TrailingStart * Point * 10)
    {
    double newSL = Ask + TrailingStep * Point * 10;
    if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
    {
    if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE))
    Print("Trailing stop modify error: ", GetLastError());
    }
    }
    }
    }
    }
    }
    }
    //+------------------------------------------------------------------+
    ```

    Usage Instructions:
    1. Open MetaEditor (F4) in MT4.
    2. Create a new Expert Advisor and paste the code.
    3. Compile (F7) and fix any errors if present.
    4. Attach the EA to a chart, adjust the parameters in the Inputs tab.
    5. Enable "Allow live trading" and ensure auto-trading is on.

    Parameter Explanation:
  • `RSI_Period`: Number of bars used for RSI calculation. Default 14.

  • `Overbought`/`Oversold`: Threshold levels for divergence confirmation.

  • `LotSize`: Fixed trade volume.

  • `StopLoss`/`TakeProfit`: In pips. Set to 0 to disable.

  • `TrailingStart`/`TrailingStep`: Activates trailing stop after price moves X pips.

  • `MagicNumber`: Unique identifier for the EA's orders.

  • `UseHiddenDivergence`: Enable/disable hidden divergence detection.


  • This EA is a solid foundation for learning MQL4. You can customize it to add filters, time management, or multi-timeframe confirmation. Always backtest and optimize parameters before live deployment.

    For more advanced strategies and fully optimized EAs with premium support, consider exploring our paid EA packages that include advanced money management, news filters, and multi-currency capabilities.

    Reference: Self-compiled based on standard MQL4 divergence detection logic.