How to Spot RSI Divergence with MQL5?

Introduction to RSI Divergence and MQL5

The Relative Strength Index (RSI) is a widely used momentum oscillator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset. Divergence occurs when the price of an asset is moving in the opposite direction of the RSI. This can signal a potential trend reversal.

Understanding RSI Divergence: Bullish and Bearish Signals

  • Bullish Divergence: Price makes lower lows, but RSI makes higher lows. This suggests the downtrend may be weakening, and a potential uptrend is likely.
  • Bearish Divergence: Price makes higher highs, but RSI makes lower highs. This suggests the uptrend may be weakening, and a potential downtrend is likely.

Why Use MQL5 for RSI Divergence Detection?

MQL5 (MetaQuotes Language 5) provides the tools needed to automate the detection of RSI divergence, create custom indicators, and generate trading signals. With MQL5, you can:

  • Automate divergence pattern recognition.
  • Backtest your strategies on historical data.
  • Receive real-time alerts for potential trading opportunities.
  • Customize the indicator to fit your specific trading style.

Setting Up MetaEditor and a New MQL5 Project

  1. Open MetaTrader 5.
  2. Press F4 to open MetaEditor.
  3. In MetaEditor, go to File -> New -> Custom Indicator.
  4. Give your indicator a name (e.g., RSIDivergence) and click Next.
  5. Set the indicator properties. Decide where the indicator output will be displayed (new chart or subwindow).
  6. Click Finish. A template code will be generated.

Implementing the RSI Indicator in MQL5

Accessing RSI Data Using iRSI Function

MQL5 provides the iRSI function to calculate the RSI value. This function retrieves RSI values from a specified symbol, timeframe, and period. Here’s how to use it:

double rsiValue = iRSI(NULL, 0, 14, PRICE_CLOSE, 0);
  • NULL: Current symbol.
  • 0: Current timeframe.
  • 14: RSI period.
  • PRICE_CLOSE: Applied price (close price).
  • 0: Shift (0 for current bar).

Storing RSI Values in Arrays

To detect divergence, you need to store historical RSI values. MQL5 provides dynamic arrays for efficient data management:

double rsiBuffer[];
ArrayResize(rsiBuffer, 100); // Resize the array to store 100 RSI values
ArraySetAsSeries(rsiBuffer, true); // Set as series (latest value at index 0)

for (int i = 0; i < 100; i++) {
    rsiBuffer[i] = iRSI(NULL, 0, 14, PRICE_CLOSE, i);
}

Handling Data Buffers and Time Series

In MQL5, indicators use data buffers to store calculated values for each bar. Using SetIndexBuffer function and INDICATOR_DATA property is key.

#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  Red

double         RSIBuffer[];

int OnInit()
  {
   SetIndexBuffer(0, RSIBuffer, INDICATOR_DATA);
   return(INIT_SUCCEEDED);
  }

It’s important to use ArraySetAsSeries to ensure that the most recent data is always at the beginning of the array (index 0), which simplifies calculations.

Detecting RSI Divergence Patterns

Identifying Price Swings (Highs and Lows)

To detect divergence, you need to identify significant price swings (highs and lows) and corresponding RSI swings. A simple method is to look for local extrema within a specified lookback period.

Comparing Price Swings with RSI Swings

Once you’ve identified price and RSI swings, compare them to detect divergence. For example, to detect bullish divergence:

  1. Identify two consecutive lower lows in price.
  2. Identify two consecutive higher lows in RSI corresponding to the price lows.

Implementing the Divergence Logic: Bullish and Bearish Conditions

bool isBullishDivergence(int index) {
    // Implement logic to compare price lows and RSI lows
    // Return true if bullish divergence is detected, false otherwise
    return false; // Placeholder
}

bool isBearishDivergence(int index) {
    // Implement logic to compare price highs and RSI highs
    // Return true if bearish divergence is detected, false otherwise
    return false; // Placeholder
}

You’ll need to implement the core logic to compare the price and RSI values at identified swing points.

Coding the MQL5 Indicator for Visualizing Divergence

Drawing Divergence Lines on the Chart Using ObjectCreate

To visualize divergence, use the ObjectCreate function to draw trend lines connecting the swing points. It’s important to give each object a unique name.

ObjectCreate(0, "BullishLine" + index, OBJ_TREND, 0, Time[index1], Low[index1], Time[index2], Low[index2]);
ObjectSetInteger(0, "BullishLine" + index, OBJPROP_COLOR, clrGreen);
ObjectSetInteger(0, "BullishLine" + index, OBJPROP_WIDTH, 2);

Customizing the Appearance of Divergence Lines

You can customize the color, style, and width of the divergence lines using ObjectSetInteger and ObjectSetDouble functions. For example:

ObjectSetInteger(0, "BullishLine" + index, OBJPROP_COLOR, clrGreen); // Set color to green
ObjectSetInteger(0, "BullishLine" + index, OBJPROP_WIDTH, 2);   // Set width to 2
ObjectSetInteger(0, "BullishLine" + index, OBJPROP_STYLE, STYLE_DOT);  //Set style to dotted line

Adding Alerts for Divergence Signals

To receive alerts when divergence is detected, use the Alert or PlaySound functions. For example:

if (isBullishDivergence(i)) {
    Alert("Bullish RSI Divergence Detected!");
    PlaySound("alert.wav");
}

Testing, Optimizing, and Deploying the RSI Divergence Indicator

Backtesting the Indicator on Historical Data

Use MetaTrader 5’s Strategy Tester to backtest the indicator on historical data. This helps evaluate its performance and identify potential issues.

Optimizing Parameters for Different Market Conditions

The RSI period, lookback period for swing identification, and other parameters can be optimized using the Strategy Tester’s optimization feature. Experiment with different values to find the settings that work best for various market conditions.

Compiling and Deploying the Indicator on MetaTrader 5

Once you’ve tested and optimized the indicator, compile it in MetaEditor and deploy it to your MetaTrader 5 platform by dragging it from the Navigator window onto a chart.


Leave a Reply