Indicator · Pine Script v5 · On the chart

RSI Divergence

by Web3Degenerate· code credited to ZenAndTheArtOfTrading / www.PineScriptMastery.com

The indicator detects RSI divergences on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code85
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

85 lines of Pine Script v5 from advanced-pine-script/5.Indicators/19.Detecting-RSI-Divergence.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

19.Detecting-RSI-Divergence.pine
// Bullish RSI Divergene - generally price moves opposite direction

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / www.PineScriptMastery.com
// @version=5
indicator("Pine-Script.com: RSI Divergence", overlay=true)

// Get user input
int i_MaxDistance       = input.int(title="Max Bar Distance", defval=50)
int i_RSI_Length        = input.int(title="RSI Length", defval=14, minval=1)
float i_RSI_Overbought  = input.float(title="RSI Overbought", defval=70.0)
float i_RSI_Oversold    = input.float(title="RSI Oversold", defval=30.0)

// Get RSI value
rsiValue = ta.rsi(close, i_RSI_Length)

// --------- BULLISH DIVERGENCE --------- //
var float checkFirstLow     = na
var float initialLowPrice   = na
var float initialLowRSI     = na
var int initialLowIndex     = na
bool bullishDivergence      = false
float swingLowRSI           = ta.lowest(rsiValue, 5)

// Save lowest low while RSI is oversold, and store it when market leaves OS condition
if (rsiValue < i_RSI_Oversold or rsiValue[1] < i_RSI_Oversold)
    if not na(initialLowPrice)
        initialLowPrice := na
    if na(checkFirstLow) or low < checkFirstLow
        checkFirstLow := low
        initialLowIndex := bar_index
        initialLowRSI := swingLowRSI
else
    // RSI is no longer OS, save lowest price during OS condition and reset temporary low
    if not na(checkFirstLow)
        initialLowPrice := checkFirstLow
    checkFirstLow := na

// Check for a second low that is lower than the first, and with a higher RSI value, and within our max distance
if low[1] < initialLowPrice and low > low[1] and swingLowRSI > initialLowRSI and bar_index - initialLowIndex <= i_MaxDistance
    bullishDivergence := true
    line.new(initialLowIndex, initialLowPrice, bar_index - 1, low[1], color=color.green, width=2)
    initialLowPrice := na

// Draw bearish divergence signal
plotshape(bullishDivergence, "Bullish Divergence", shape.triangleup, location.belowbar, color.green)

// --------- BEARISH DIVERGENCE --------- //
var float checkFirstHigh    = na
var float initialHighPrice  = na
var float initialHighRSI    = na
var int initialHighIndex    = na
bool bearishDivergence      = false
float swingHighRSI          = ta.highest(rsiValue, 5)

// Save highest high while RSI is overbought, and store it when market leaves OB condition
if (rsiValue > i_RSI_Overbought or rsiValue[1] > i_RSI_Overbought)
    if not na(initialHighPrice)
        initialHighPrice := na
    if na(checkFirstHigh) or high > checkFirstHigh
        checkFirstHigh := high
        initialHighIndex := bar_index
        initialHighRSI := swingHighRSI
else
    // RSI is no longer OB, save highest price during OB condition and reset temporary high
    if not na(checkFirstHigh)
        initialHighPrice := checkFirstHigh
    checkFirstHigh := na

// Check for a second high that is higher than the first, and with a lower RSI value, and within our max distance
if high[1] > initialHighPrice and high < high[1] and swingHighRSI < initialHighRSI and bar_index - initialHighIndex <= i_MaxDistance
    bearishDivergence := true
    line.new(initialHighIndex, initialHighPrice, bar_index - 1, high[1], color=color.red, width=2)
    initialHighPrice := na

// Draw bearish divergence signal
plotshape(bearishDivergence, "Bearish Divergence", shape.triangledown, location.abovebar, color.red)

// --------- ALERTS --------- //
if bearishDivergence
    alert("Bearish RSI Divergence Detected - RSI Difference:" + str.tostring(initialHighRSI - swingHighRSI, "#.##"), alert.freq_once_per_bar_close)
if bullishDivergence
    alert("Bullish RSI Divergence Detected - RSI Difference:" + str.tostring(swingLowRSI - initialLowRSI, "#.##"), alert.freq_once_per_bar_close)
alertcondition(bearishDivergence, "RSI Bearish Divergence", "RSI Bearish Divergence Detected")
alertcondition(bullishDivergence, "RSI Bullish Divergence", "RSI Bullish Divergence Detected")

Overview

RSI Divergence calculates the RSI using the close prices with a configurable length and identifies potential trend reversals by comparing swings in price and RSI values. Bullish divergence is signaled when price forms a lower low while the RSI forms a higher low within the maximum bar distance. Bearish divergence occurs when price makes a higher high but RSI makes a lower high. The script plots green upward triangles below the bar for bullish signals and red downward triangles above the bar for bearish signals, connecting the divergence points with lines. Main settings include the maximum bar distance for the divergence, RSI calculation length, overbought and oversold thresholds. It draws on the main price chart panel without additional panes.

Details

Published by

Web3Degenerate on GitHub

Code credit

ZenAndTheArtOfTrading / www.PineScriptMastery.com, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Max Bar Distanceint50i_MaxDistance
RSI Lengthint14i_RSI_Length
RSI Overboughtfloat70.0i_RSI_Overbought
RSI Oversoldfloat30.0i_RSI_Oversold
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This overlay indicator looks for regular price divergences against a set of oscillators, using pivot highs and lows. It compares those pivots with RSI, MACD and its histogram, stochastic, CCI, momentum, OBV, a directional oscillator, volume-weighted MACD, Chai

Indicator v5 DivergenceOscillators & momentum Repaints
Updated 7 weeks ago · None stated GitHub repository of Snag - Best Futures V3

RSI Divergence Scanner

by TradersPost
228 stars

The RSI Divergence Scanner calculates the Relative Strength Index and identifies regular and hidden bullish or bearish divergences against price using pivot high and low points. It plots divergence lines and customizable labels directly on the price chart. Inp

Indicator v6 Oscillators & momentumDivergence
Updated 3 months ago · None stated GitHub repository of RSI Divergence Scanner

Price Divergence

by capissimo
114 stars

This indicator detects regular and hidden divergences across multiple technical factors plotted directly on the price chart. It evaluates price highs and lows against peaks and troughs identified by a five-bar fractal mechanism on RSI, RSI Stochastic, MACD, re

Indicator v4 DivergenceOscillators & momentum
Updated 1 year ago · None stated GitHub repository of Price Divergence

RSI Div at dVWAP StDev

by cryptorife
75 stars

This indicator marks RSI divergences only when price trades beyond daily VWAP standard-deviation bands. It compares recent RSI extremes with price highs and lows over a lookback window, and it treats a divergence as valid only while RSI stays beyond overbought

Indicator v4 DivergenceOscillators & momentum Repaints
Updated 3 years ago · GPL-3.0 GitHub repository of RSI Div at dVWAP StDev

This indicator builds a momentum score from the rate of change of close, using a lookback that expands or contracts with ATR relative to its standard deviation. It divides that rate of change by price standard deviation, scales the result, and weights it by vo

Indicator v5 Oscillators & momentumVolatility & bands Repaints
Updated 8 weeks ago · None stated GitHub repository of Adaptive Volatility-Adjusted Momentum Score

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers