Indicator · Pine Script v4 · Own pane

Relative Strength Index - Divergences - Libertus

by theonetrade· code credited to by Libertus - 2021

This indicator calculates the Relative Strength Index (RSI) and automatically detects bullish and bearish divergences relative to price movements over a customizable lookback window.

View on GitHub

GitHub stars34on the repository
Pine versionv4older, still runs
Lines of code99
Settings9inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

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

99 lines of Pine Script v4 from assets/indicator/bit-exact/relative_strength_index_divergences_libertus_42wcFfql.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

relative_strength_index_divergences_libertus_42wcFfql.pine
//@version=4
// Copyright by Libertus - 2021
// RSI Divergences v3.3
// Free for private use
study(title="Relative Strength Index - Divergences - Libertus", shorttitle="RSI Div - Lib")
len = input(14, minval=1, title="RSI Length")
ob = input(defval=70, title="Overbought", type=input.integer, minval=0, maxval=100)
os = input(defval=30, title="Oversold", type=input.integer, minval=0, maxval=100)
omid = input(defval=50, title="Midline value", type=input.integer, minval=0, maxval=100)
omidh = input(defval=false, title="Hide midline")

// RSI code
rsi = rsi(close, len)
band1 = hline(ob)
band0 = hline(os)
band3 = hline(omid, color=color.new(color.black, omidh ? 100 : 80))
plot(rsi, color=(rsi > ob or rsi < os ? color.new(color.red, 0) : color.new(color.black, 0)))
fill(band3, band1, color=color.new(color.lime, 96))
fill(band0, band3, color=color.new(color.red, 96))

// DIVS code
piv = input(false,"Hide pivots?")
shrt = input(false,"Shorter labels?")
hidel = input(false, "Hide labels and color background")
xbars = input(defval=90, title="Div lookback period (bars)?", type=input.integer, minval=1)
hb = abs(highestbars(rsi, xbars)) // Finds bar with highest value in last X bars
lb = abs(lowestbars(rsi, xbars)) // Finds bar with lowest value in last X bars

// Defining variable values, mandatory in Pine 3
max = float(na)
max_rsi = float(na)
min = float(na)
min_rsi = float(na)
pivoth = bool(na)
pivotl = bool(na)
divbear = bool(na)
divbull = bool(na)

// If bar with lowest / highest is current bar, use it's value
max := hb == 0 ? close : na(max[1]) ? close : max[1]
max_rsi := hb == 0 ? rsi : na(max_rsi[1]) ? rsi : max_rsi[1]
min := lb == 0 ? close : na(min[1]) ? close : min[1]
min_rsi := lb == 0 ? rsi : na(min_rsi[1]) ? rsi : min_rsi[1]

// Compare high of current bar being examined with previous bar's high
// If curr bar high is higher than the max bar high in the lookback window range
if close > max // we have a new high
    max := close // change variable "max" to use current bar's high value
if rsi > max_rsi // we have a new high
    max_rsi := rsi // change variable "max_rsi" to use current bar's RSI value
if close < min // we have a new low
    min := close // change variable "min" to use current bar's low value
if rsi < min_rsi // we have a new low
    min_rsi := rsi // change variable "min_rsi" to use current bar's RSI value

// Finds pivot point with at least 2 right candles with lower value
pivoth := (max_rsi == max_rsi[2]) and (max_rsi[2] != max_rsi[3]) ? true : na
pivotl := (min_rsi == min_rsi[2]) and (min_rsi[2] != min_rsi[3]) ? true : na

// Detects divergences between price and indicator with 1 candle delay so it filters out repeating divergences
if (max[1] > max[2]) and (rsi[1] < max_rsi) and (rsi <= rsi[1])
    divbear := true
if (min[1] < min[2]) and (rsi[1] > min_rsi) and (rsi >= rsi[1])
    divbull := true

// Alerts
alertcondition(divbear, title='Bear div', message='Bear div')
alertcondition(divbull, title='Bull div', message='Bull div')
alertcondition(pivoth, title='Pivot high', message='Pivot high')
alertcondition(pivotl, title='Pivot low', message='Pivot low')

// Plots divergences and pivots with offest
l = divbear ? 
       label.new (bar_index-1, rsi[1]+1, "BEAR", color=color.red, textcolor=color.white, style=label.style_labeldown, yloc=yloc.price, size=size.small) :
       divbull ?
           label.new (bar_index-1, rsi[1]-1, "BULL", color=color.green, textcolor=color.white, style=label.style_labelup, yloc=yloc.price, size=size.small) :
           pivoth ?
               label.new (bar_index-2, max_rsi+1, "PIVOT", color=color.blue, textcolor=color.white, style=label.style_labeldown, yloc=yloc.price, size=size.small) :
               pivotl ?
                   label.new (bar_index-2, min_rsi-1, "PIVOT", color=color.blue, textcolor=color.white, style=label.style_labelup, yloc=yloc.price, size=size.small) :
                   na

// Shorter labels
if shrt
    label.set_text (l, na)
// Hides pivots or labels
if (piv and (pivoth or pivotl)) or hidel
    label.delete (l)
// Colors indicator background
bgcolor (hidel ? (divbear ? color.new(color.red, 50) : divbull ? color.new(color.green, 50) : na) : na, offset=-1)
bgcolor (hidel ? (piv ? na : (pivoth or pivotl ? color.new(color.blue, 50) : na)) : na, offset=-2)

// Debug tools
// plot(max, color=blue, linewidth=2)
// plot(max_rsi, color=red, linewidth=2)
// plot(hb, color=orange, linewidth=2)
// plot(lb, color=purple, linewidth=1)
// plot(min_rsi, color=lime, linewidth=1)
// plot(min, color=black, linewidth=1)

Overview

Plotted in a separate pane, it displays the RSI line alongside customizable overbought, oversold, and midline thresholds. When divergence conditions or high/low pivot points are detected, the script plots visual labels on the chart and triggers corresponding alerts. Key inputs allow users to adjust RSI length, threshold levels, lookback period, and label display options.

Details

Published by

theonetrade on GitHub

Code credit

by Libertus - 2021, as written in the script's header

Type

Indicator, Pine Script v4

Draws

Separate pane below the 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.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
RSI Lengthint14len
Overboughtint70ob
Oversoldint30os
Midline valueint50omid
Hide midlineboolfalseomidh
Hide pivots?boolfalsepiv
Shorter labels?boolfalseshrt
Hide labels and color backgroundboolfalsehidel
Div lookback period (bars)?int90xbars
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

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
368 stars

This indicator calculates the MACD oscillator from a configurable source with fast and slow lengths, then plots the histogram, MACD line, and signal line in a separate pane. It detects regular bullish divergences (price lower lows with oscillator higher lows),

Indicator v5 Oscillators & momentumDivergence
Updated 3 months ago · None stated GitHub repository of MACD + Divergences [Alorse]
228 stars

This indicator calculates the Relative Strength Index (RSI) across four user-selected timeframes and plots the results in a separate pane. It identifies regular bullish and bearish divergences between price pivot points and the primary timeframe RSI value. Add

Indicator v6 Oscillators & momentumDivergence
Updated 4 months ago · None stated GitHub repository of Multi-Timeframe RSI with Divergence

Bubbles Indicator

by capissimo
114 stars

The Bubbles Indicator measures volatility squeezes and expansion bursts using Bollinger Bands combined with a sinusoid oscillator and RSI divergence. It processes price data through scaled Bollinger Bands to highlight volatility changes while confirming trend

Indicator v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of Bubbles Indicator

RSI [SystemAlpha]

by iamc1oud
56 stars

This indicator plots a standard Relative Strength Index (RSI) in a separate pane alongside customizable overbought and oversold threshold levels with shaded fills. It identifies pivot highs and lows on the oscillator to detect regular and hidden bullish and be

Indicator v4 Oscillators & momentumDivergence Repaints
Updated 3 months ago · None stated GitHub repository of RSI [SystemAlpha]
55 stars

This indicator calculates a 14-period RSI from close and plots it in a separate pane with dotted overbought and dashed oversold lines at 70 and 30. It marks bullish divergence when a five-bar pivot low in price is lower than the price twenty bars earlier while

Indicator v6 Oscillators & momentumDivergence
Updated 7 months ago · Apache-2.0 GitHub repository of RSI Divergence Detector

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