Indicator · Pine Script v4 · On the chart

Stochastic RSI Divergence+

by krosenfeld7

This indicator plots Stochastic RSI %K and %D lines over the price chart.

View on GitHub

Repaints

GitHub stars1on the repository
Pine versionv4older, still runs
Lines of code273
Settings12inputs
LicenceApache-2.0
Last update3 years ago12 May 2023

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

273 lines of Pine Script v4 from Stochastic_RSI_Divergence+.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

Stochastic_RSI_Divergence+.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © krosenfeld7

//@version=4
study(title="Stochastic RSI Divergence+", shorttitle="Stoch RSI Divergence+", overlay = true, format=format.price, precision=2)

barsback         = input(title = "Price Lookback",    type = input.integer, defval = 10, minval = 1)
lookback         = input(title = "Stoch RSI Lookback",type = input.integer, defval = 6,  minval = 1)
shortRangeString = input(title = "Divergence Range",  type = input.string,  defval = "Short", options = ["Short", "Med", "Long"])
priceTolerance   = input(title = "Price Epsilon (%)", type = input.float,   defval = 1.0, minval = 0.0)
stochTolerance   = input(title = "Stoch Epsilon (%)", type = input.float,   defval = 1.0, minval = 0.0)

smoothK = input(3, "K", minval=1)
smoothD = input(3, "D", minval=1)
lengthRSI = input(14, "RSI Length", minval=1)
lengthStoch = input(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")

displayHighLows = input(title = "Display High/Low Pivots", type=input.bool, defval = false)
overlayMode     = input(title = "Overlay Price Chart", type = input.bool, defval = true)

stochOver  = 80
stochUnder = 20

shortRange = 1
if shortRangeString == "Med"
    shortRange := 2
else if shortRangeString == "Long"
    shortRange := 3

overlayModeRed     = color.new(color.red,   transp = not overlayMode ? 0  : 100)
overlayModeBlue    = color.new(color.blue,  transp = not overlayMode ? 0  : 100)
overlayModeWhite   = color.new(color.white, transp = not overlayMode ? 0  : 100)
overlayModeWhite90 = color.new(color.white, transp = not overlayMode ? 90 : 100)
overlayModeWhite80 = color.new(color.white, transp = not overlayMode ? 80 : 100)
overlayModeWhite70 = color.new(color.white, transp = not overlayMode ? 70 : 100)

rsi1 = rsi(src, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

plot(k, title="%K", color=overlayModeBlue, linewidth = 2)
plot(d, title="%D", color=overlayModeRed, linewidth = 2)
h0 = hline(stochOver, "Upper Band", color=(not overlayMode ? color.white : na), linewidth = 1, linestyle = hline.style_dashed)
h1 = hline(stochUnder, "Lower Band", color=(not overlayMode ? color.white : na), linewidth = 1, linestyle = hline.style_dashed)

fill(h0, h1, color=overlayModeWhite70, title="Background")
fill(h0, hline(100, color = (not overlayMode ? color.white : na), linestyle = hline.style_solid, linewidth = 2), color = overlayModeWhite80, title = "Background")
fill(hline(0, color = (not overlayMode ? color.white : na), linestyle = hline.style_solid, linewidth = 2), h1, color = overlayModeWhite80, title = "Background")

var bool priceHighSet = na
var bool priceLowSet  = na
var bool stochHighSet   = na
var bool stochLowSet    = na

currHighK = pivothigh(k, lookback, lookback)
currHighD = pivothigh(d, lookback, lookback)
currLowK  = pivotlow(k,  lookback, lookback)
currLowD  = pivotlow(d,  lookback, lookback)

currHigh = currHighK > currHighD ? currHighK : currHighD
currLow  = currLowK  > currLowD  ? currLowD  : currLowK

lastHighShort = valuewhen(not na(currHigh), currHigh, shortRange)
lastLowShort  = valuewhen(not na(currLow),  currLow,  shortRange)

lowerHighShort  = not na(currHigh) ? lastHighShort > (currHigh * (1 + (stochTolerance / 100))) : false
higherHighShort = not na(currHigh) ? lastHighShort < (currHigh * (1 - (stochTolerance / 100))) : false
lowerLowShort   = not na(currLow)  ? lastLowShort  > (currLow *  (1 + (stochTolerance / 100))) : false
higherLowShort  = not na(currLow)  ? lastLowShort  < (currLow *  (1 - (stochTolerance / 100))) : false

currPriceHigh = pivothigh(high, barsback, barsback)
currPriceLow  = pivotlow(low,   barsback, barsback)

lastPriceHighShort = valuewhen(not na(currPriceHigh), currPriceHigh, shortRange)
lastPriceLowShort  = valuewhen(not na(currPriceLow),  currPriceLow, shortRange)

lowerPriceHighShort  = not na(currPriceHigh) ? lastPriceHighShort > (currPriceHigh * (1 + (priceTolerance / 100))) : false
higherPriceHighShort = not na(currPriceHigh) ? lastPriceHighShort < (currPriceHigh * (1 - (priceTolerance / 100))) : false
lowerPriceLowShort   = not na(currPriceLow)  ? lastPriceLowShort  > (currPriceLow *  (1 + (priceTolerance / 100))) : false
higherPriceLowShort  = not na(currPriceLow)  ? lastPriceLowShort  < (currPriceLow *  (1 - (priceTolerance / 100))) : false

lowerLowRecent   = barssince(lowerLowShort)   < lookback
lowerHighRecent  = barssince(lowerHighShort)  < lookback
higherLowRecent  = barssince(higherLowShort)  < lookback
higherHighRecent = barssince(higherHighShort) < lookback
    
lowerPriceLowRecent   = barssince(lowerPriceLowShort)   < barsback
lowerPriceHighRecent  = barssince(lowerPriceHighShort)  < barsback
higherPriceLowRecent  = barssince(higherPriceLowShort)  < barsback
higherPriceHighRecent = barssince(higherPriceHighShort) < barsback

regShortBullish = lowerPriceLowRecent and higherLowRecent
hidShortBullish = higherPriceLowRecent and lowerLowRecent
regShortBearish = higherPriceHighRecent and lowerHighRecent
hidShortBearish = lowerPriceHighRecent and higherHighRecent

priceHighIndex = barssince(not na(priceHighSet))
priceLowIndex  = barssince(not na(priceLowSet))
stochHighIndex = barssince(not na(stochHighSet))
stochLowIndex  = barssince(not na(stochLowSet))

priceHighSet := not na(currPriceHigh) ? true : na
priceLowSet  := not na(currPriceLow)  ? true : na
stochHighSet := not na(currHigh)      ? true : na
stochLowSet  := not na(currLow)       ? true : na

currPriceHigh := na(currPriceHigh) ? currPriceHigh[1] : currPriceHigh
currPriceLow  := na(currPriceLow)  ? currPriceLow[1]  : currPriceLow
currHigh      := na(currHigh)      ? currHigh[1]      : currHigh
currLow       := na(currLow)       ? currLow[1]       : currLow

newIndexLow = stochLowIndex
newIndexLow2 = bar_index - lookback
if stochLowIndex < lookback
    for i = 0 to lookback
        if stochLowIndex[i] == 0
            newIndexLow := stochLowIndex[i + 1] + (i + 1)
            newIndexLow2 -= i + 1
            break
            
newIndexHigh = stochHighIndex
newIndexHigh2 = bar_index - lookback
if stochHighIndex < lookback
    for i = 0 to lookback
        if stochHighIndex[i] == 0
            newIndexHigh := stochHighIndex[i + 1] + (i + 1)
            newIndexHigh2 -= i + 1
            break
            
newIndexPriceLow = priceLowIndex
newIndexPriceLow2 = bar_index - barsback
if priceLowIndex < barsback
    for i = 0 to barsback
        if priceLowIndex[i] == 0
            newIndexPriceLow := priceLowIndex[i + 1] + (i + 1)
            newIndexPriceLow2 -= i + 1 
            break

newIndexPriceHigh = priceHighIndex
newIndexPriceHigh2 = bar_index - barsback
if priceHighIndex < barsback
    for i = 0 to barsback
        if priceHighIndex[i] == 0
            newIndexPriceHigh += priceHighIndex[i + 1] + 1
            newIndexPriceHigh2 -= i + 1
            break

max_bars_back(stochLowIndex, 500)
max_bars_back(stochHighIndex, 500)
max_bars_back(priceLowIndex, 500)
max_bars_back(priceHighIndex, 500)

if shortRange <= 1
    prevPivot = 0
else
    newIndexLow       += stochLowIndex[newIndexLow + 1] + 1
    newIndexHigh      += stochHighIndex[newIndexHigh + 1] + 1
    newIndexPriceLow  += priceLowIndex[newIndexPriceLow + 1] + 1
    newIndexPriceHigh += priceHighIndex[newIndexPriceHigh + 1] + 1
    
if shortRange == 3
    newIndexLow       += stochLowIndex[newIndexLow + 1] + 1
    newIndexHigh      += stochHighIndex[newIndexHigh + 1] + 1
    newIndexPriceLow  += priceLowIndex[newIndexPriceLow + 1] + 1
    newIndexPriceHigh += priceHighIndex[newIndexPriceHigh + 1] + 1

x_low            = bar_index - lookback - newIndexLow - 1
x_low_mid        = bar_index - lookback - (newIndexLow / 2) - 1
x_high           = bar_index - lookback - newIndexHigh - 1
x_high_mid       = bar_index - lookback - (newIndexHigh / 2) - (lookback / 2)
x_price_low      = bar_index - barsback - newIndexPriceLow - 1
x_price_low_mid  = bar_index - barsback - (newIndexPriceLow / 2)
x_price_high     = bar_index - barsback - newIndexPriceHigh - 1
x_price_high_mid = bar_index - barsback - (newIndexPriceHigh / 2)

var line highPriceLine = na
var line lowPriceLine = na
var line lowStochLine = na
var line highStochLine = na

if (regShortBearish and not regShortBearish[1]) or (hidShortBearish and not hidShortBearish[1])
    if not overlayMode // Stochastic 
        highStochLine := line.new(0, 0, 0, 0)
        line.set_x1(highStochLine, x_high)
        line.set_y1(highStochLine, lastHighShort)
        line.set_x2(highStochLine, newIndexHigh2)
        line.set_y2(highStochLine, currHigh)
        line.set_style(highStochLine, line.style_dotted)
        line.set_width(highStochLine, 2)
        line.set_color(highStochLine, color=regShortBearish ? color.red : color.yellow)
    else
        highPriceLine := line.new(0, 0, 0, 0)
        line.set_x1(highPriceLine, x_price_high)
        line.set_y1(highPriceLine, lastPriceHighShort)
        line.set_x2(highPriceLine, newIndexPriceHigh2)
        line.set_y2(highPriceLine, currPriceHigh)
        line.set_style(highPriceLine, line.style_dotted)
        line.set_width(highPriceLine, 3)
        line.set_color(highPriceLine, color=regShortBearish ? color.red : color.yellow)

if (regShortBullish and not regShortBullish[1]) or (hidShortBullish and not hidShortBullish[1])
    if not overlayMode // Stochastic
        lowStochLine := line.new(0, 0, 0, 0)
        line.set_x1(lowStochLine, x_low)
        line.set_y1(lowStochLine, lastLowShort)
        line.set_x2(lowStochLine, newIndexLow2)
        line.set_y2(lowStochLine, currLow)
        line.set_style(lowStochLine, line.style_dotted)
        line.set_width(lowStochLine, 2)
        line.set_color(lowStochLine, color=regShortBullish ? color.green : color.blue)
    else
        lowPriceLine := line.new(0, 0, 0, 0)
        line.set_x1(lowPriceLine, x_price_low)
        line.set_y1(lowPriceLine, lastPriceLowShort)
        line.set_x2(lowPriceLine, newIndexPriceLow2)
        line.set_y2(lowPriceLine, currPriceLow)
        line.set_style(lowPriceLine, line.style_dotted)
        line.set_width(lowPriceLine, 3)
        line.set_color(lowPriceLine, color=regShortBullish ? color.green : color.blue)

if not overlayMode and displayHighLows // Stochastic
    if lowerHighShort
        label.new(bar_index - lookback, currHigh + 10, style=label.style_triangledown, color=color.new(color.yellow, transp=75), size=size.tiny)
    if higherHighShort
        label.new(bar_index - lookback, currHigh + 10, style=label.style_triangledown, color=color.new(color.green, transp=75), size=size.tiny)
    if lowerLowShort
        label.new(bar_index - lookback, currLow - 10, style=label.style_triangleup, color=color.new(color.red, transp=75), size=size.tiny)
    if higherLowShort
        label.new(bar_index - lookback, currLow - 10, style=label.style_triangleup, color=color.new(color.blue, transp=75), size=size.tiny)
else if displayHighLows
    if lowerPriceHighShort
        label.new(bar_index - barsback, currPriceHigh * 1.05, style=label.style_triangledown, color=color.new(color.yellow, transp=75), size=size.tiny)
    if higherPriceHighShort
        label.new(bar_index - barsback, currPriceHigh * 1.05, style=label.style_triangledown, color=color.new(color.green, transp=75), size=size.tiny)
    if lowerPriceLowShort
        label.new(bar_index - barsback, currPriceLow * 0.95, style=label.style_triangleup, color=color.new(color.red, transp=75), size=size.tiny)
    if higherPriceLowShort
        label.new(bar_index - barsback, currPriceLow * 0.95, style=label.style_triangleup, color=color.new(color.blue, transp=75), size=size.tiny)

labelColor1 = color.new(color.black, transp=25)
// Short Regular Bullish Divergence - trend reversal
// Price makes lower lows while stoch makes higher lows
if regShortBullish and not regShortBullish[1]
    if not overlayMode // Stochastic
        label.new(x_low_mid + 1, (currLow + lastLowShort) / 2, "Reg Bull Div", color=labelColor1, style=label.style_label_up, textcolor=color.green, size=size.small)
    else
        label.new(x_price_low_mid, (currPriceLow + lastPriceLowShort) / 2, "Reg Stoch RSI Bull Div", color=labelColor1, style=label.style_label_up, textcolor=color.green, size=size.normal)

// Short Hidden Bullish Divergence - trend continuation
// Price makes higher lows while stoch makes lower lows
if hidShortBullish and not hidShortBullish[1]
    if not overlayMode // Stochastic
        label.new(x_low_mid, (currLow + lastLowShort) / 2, "Hid Bull Div", color=labelColor1, style=label.style_label_up, textcolor=color.blue, size=size.small)
    else
        label.new(x_price_low_mid, (currPriceLow + lastPriceLowShort) / 2, "Hid Stoch RSI Bull Div", color=labelColor1, style=label.style_label_up, textcolor=color.blue, size=size.normal)


// Short Regular Bearish Divergence - trend reversal
// Price makes higher highs while stoch makes lower highs
if regShortBearish and not regShortBearish[1]
    if not overlayMode // Stochastic
        label.new(x_high_mid + 1, (currHigh + lastHighShort) / 2, " Reg Bear Div", color=labelColor1, textcolor=color.red, size=size.small)
    else
        label.new(x_price_high_mid, (currPriceHigh + lastPriceHighShort) / 2, "Reg Stoch RSI Bear Div", color=labelColor1, textcolor=color.red, size=size.normal)
        
// Short Hidden Bearish Divergence - trend continuation
// Price makes lower highs while stoch makes higher highs
if hidShortBearish and not hidShortBearish[1]
    if not overlayMode // Stochastic
        label.new(x_high_mid, (currHigh + lastHighShort) / 2, "Hid Bear Div", color=labelColor1, textcolor=color.yellow, size=size.small)
    else
        label.new(x_price_high_mid, (currPriceHigh + lastPriceHighShort) / 2, "Hid Stoch RSI Bear Div", color=labelColor1, textcolor=color.yellow, size=size.normal)

Overview

Stochastic RSI Divergence+ detects bullish and bearish divergences by comparing price highs and lows to those of Stochastic RSI within a lookback period. Users set divergence range (short, medium, long), price tolerance, Stochastic tolerance, RSI and Stochastic lengths, smooth K and D values, and source. Pivots may be displayed optionally. Divergence signals indicate potential trend reversals. It repaints on live bars and lacks explicit stop loss or exit rules.

Details

Published by

krosenfeld7 on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Oscillators & momentum, Trend, Divergence

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
Price Lookbackint10barsback
Stoch RSI Lookbackint6lookback
Divergence RangestringShortshortRangeString
Price Epsilon (%)float1.0priceTolerance
Stoch Epsilon (%)float1.0stochTolerance
Kint3smoothK
Dint3smoothD
RSI Lengthint14lengthRSI
Stochastic Lengthint14lengthStoch
RSI Sourcesourceclosesrc
Display High/Low PivotsboolfalsedisplayHighLows
Overlay Price ChartbooltrueoverlayMode
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 plots calendar-spread context for commodity futures on the price chart. It maps the chart symbol to front and next month contracts automatically, or uses manual symbols, then calculates the spread as a difference or ratio. Fast and slow EMAs, a

Indicator v6 TrendOscillators & momentum
Updated yesterday · MIT GitHub repository of Vein: Spread Context [WavesUnchained]
5 stars

This indicator overlays multiple technical analysis tools onto the price chart to evaluate trend direction and trade setups. It computes an exponential moving average, a smoothed Stochastic RSI, a custom Williams Alligator using smoothed moving averages with o

Indicator v4 TrendMoving averages
Updated 3 years ago · Apache-2.0 GitHub repository of 200 EMA + Alligator + Stochastic

Fractals with Divergence Scanner is an overlay indicator that combines Exponential Moving Averages, an eight-line EMA ribbon cloud, and WaveTrend divergence analysis. It calculates baseline EMA trends alongside WaveTrend oscillators to detect regular and hidde

Indicator v5 TrendMoving averages
Updated 5 months ago · None stated GitHub repository of Fractals with Divergence Scanner
2 stars

ARPS Ultimate MultiStrategy Trading combines multiple technical indicators into a single chart overlay. It calculates and plots trend lines, moving averages, Ichimoku cloud components, Williams Alligator lines, and Fibonacci support and resistance levels direc

Indicator v4 TrendOscillators & momentum
Updated 6 months ago · None stated GitHub repository of ARPS Ultimate MultiStrategy Trading

Complexity Trender

by panzmoravylab
2 stars

Complexity Trender is an indicator that combines EMA crossovers, RSI momentum, Stochastic signals, Bollinger Bands, ADX trend strength, volume analysis, and divergence detection to identify trends. It plots labels, trend lines, and a summary table directly on

Indicator v6 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of Complexity Trender

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers