Pine Script RSI Divergence: How to Identify and Trade with It?

What is RSI Divergence?

RSI divergence occurs when the price of an asset moves in the opposite direction of its Relative Strength Index (RSI). This discrepancy can signal potential trend reversals or continuations. Regular divergence warns of a possible trend reversal, while hidden divergence suggests trend continuation.

  • Regular Bullish Divergence: Price makes lower lows, RSI makes higher lows. Suggests a potential price increase.
  • Regular Bearish Divergence: Price makes higher highs, RSI makes lower highs. Suggests a potential price decrease.
  • Hidden Bullish Divergence: Price makes higher lows, RSI makes lower lows. Suggests a continuation of the existing uptrend.
  • Hidden Bearish Divergence: Price makes lower highs, RSI makes higher highs. Suggests a continuation of the existing downtrend.

Why Use Pine Script for RSI Divergence?

Pine Script, TradingView’s scripting language, allows us to automate the detection and visualization of RSI divergence. We can create custom indicators that automatically identify divergence patterns, generate alerts, and even backtest trading strategies based on these signals. Its built-in functions and plotting capabilities make it ideal for this task.

Basic Pine Script Concepts for Divergence Detection

Before diving into the code, let’s review a few key Pine Script concepts:

  • indicator(): Declares a script as an indicator.
  • rma() or ta.rsi(): Calculates the Relative Strength Index.
  • line.new(): Draws lines on the chart to visualize divergence.
  • plotshape(): Plots shapes on the chart to highlight divergence signals.
  • syminfo.tickerid: Gives you access to the ticker id.
  • input.int(): Define a variable to set RSI length or another variable.

Identifying RSI Divergence with Pine Script Code

Coding RSI Calculation in Pine Script

First, let’s create a simple RSI indicator. We can use ta.rsi() function for this:

//@version=5
indicator(title="RSI", shorttitle="RSI", overlay=false)
rsiLength = input.int(14, title="RSI Length")
rsiValue = ta.rsi(close, rsiLength)
plot(rsiValue, title="RSI", color=color.blue)

This code calculates the RSI using a default length of 14 and plots it on the chart.

Detecting Regular Bullish Divergence

To detect bullish divergence, we need to compare price lows with RSI lows. We’ll use ta.lowest() function to find these lows. Here’s the code snippet:

bullishDivergence = ta.lowest(low, 10) > ta.lowest(low[1], 10) and ta.lowest(rsiValue, 10) < ta.lowest(rsiValue[1], 10)
if bullishDivergence
    label.new(bar_index, low, text="Bullish", color=color.green, style=label.style_labeldown)

This code checks if the price makes a lower low while the RSI makes a higher low within a 10-period lookback window.

Detecting Regular Bearish Divergence

Similarly, for bearish divergence, we compare price highs with RSI highs:

bearishDivergence = ta.highest(high, 10) < ta.highest(high[1], 10) and ta.highest(rsiValue, 10) > ta.highest(rsiValue[1], 10)
if bearishDivergence
    label.new(bar_index, high, text="Bearish", color=color.red, style=label.style_labelup)

This code checks if the price makes a higher high while the RSI makes a lower high.

Detecting Hidden Bullish Divergence

In Hidden bullish divergence Price makes a higher low and RSI makes a lower low.

hiddenBullishDivergence = ta.highest(low, 10) < ta.highest(low[1], 10) and ta.lowest(rsiValue, 10) > ta.lowest(rsiValue[1], 10)
if hiddenBullishDivergence
    label.new(bar_index, low, text="Hidden Bullish", color=color.green, style=label.style_labeldown)

Detecting Hidden Bearish Divergence

In hidden bearish divergence price makes a lower high and RSI makes a higher high.

hiddenBearishDivergence = ta.lowest(high, 10) > ta.lowest(high[1], 10) and ta.highest(rsiValue, 10) < ta.highest(rsiValue[1], 10)
if hiddenBearishDivergence
    label.new(bar_index, high, text="Hidden Bearish", color=color.red, style=label.style_labelup)

Visualizing RSI Divergence on TradingView Charts

Plotting Divergence Lines

To visually connect the divergence points, we can use the line.new() function.

var line bullishLine = na
if bullishDivergence
    if na(bullishLine)
        bullishLine := line.new(bar_index[1], low[1], bar_index, low, color=color.green, width=2)
    else
        line.set_xy1(bullishLine, bar_index[1], low[1])
        line.set_xy2(bullishLine, bar_index, low)

This code draws a line connecting the previous low to the current low when bullish divergence is detected. Similar logic can be applied to bearish divergence.

Highlighting Divergence Signals with Alerts

We can use alert() function to trigger alerts when divergence is detected:

if bullishDivergence
    alert("Bullish Divergence Detected", alert.freq_once_per_bar_close)
if bearishDivergence
    alert("Bearish Divergence Detected", alert.freq_once_per_bar_close)

Customizing the Appearance of Divergence Signals

You can customize the appearance of divergence signals using different colors, shapes, and sizes. For example:

plotshape(bullishDivergence, style=shape.triangleup, color=color.green, size=size.small)
plotshape(bearishDivergence, style=shape.triangledown, color=color.red, size=size.small)

Trading Strategies Using RSI Divergence in Pine Script

Combining RSI Divergence with Other Indicators

RSI divergence can be more effective when combined with other indicators like moving averages, Fibonacci retracements, or volume analysis. For example, you might only take a long trade if bullish divergence occurs near a key support level and the price is above a moving average.

Setting Entry and Exit Points Based on Divergence Signals

  • Entry: Enter a long position when bullish divergence is confirmed and the price breaks above a recent high. Enter a short position when bearish divergence is confirmed and the price breaks below a recent low.
  • Exit: Set stop-loss orders below the recent low for long positions and above the recent high for short positions. Use profit targets based on Fibonacci levels or previous resistance/support levels.

Risk Management with RSI Divergence Strategies

Always use stop-loss orders to limit your potential losses. Adjust your position size based on your risk tolerance and the volatility of the market. Avoid trading divergence signals in highly volatile market conditions.

Advanced Pine Script Techniques for RSI Divergence

Filtering Divergence Signals Based on Volume

You can add a volume filter to improve the quality of divergence signals. For instance, you might require the volume to be above its moving average when divergence occurs.

volumeMA = ta.sma(volume, 20)
bullishDivergenceCondition = bullishDivergence and volume > volumeMA

Backtesting RSI Divergence Strategies in Pine Script

Pine Script’s strategy tester allows you to backtest your divergence strategies. Use strategy() function instead of indicator() and use strategy.entry() and strategy.close() to define your entry and exit conditions. Remember to account for slippage and commissions.

Optimizing RSI Parameters for Divergence Detection

The optimal RSI length can vary depending on the asset and timeframe you are trading. Use the strategy tester to optimize the RSI length and other parameters for your specific strategy.


Leave a Reply