RSI Divergence Guide
Master this indicator with Pine Script code and automated strategies.
What is RSI Divergence?
RSI Divergence detects potential reversals by comparing price action to RSI momentum. A bullish divergence occurs when price makes a lower low but RSI makes a higher low, indicating weakening selling pressure. A bearish divergence occurs when price makes a higher high but RSI makes a lower high.
How to Use This Strategy
Pro Tip: Watch for bullish divergence when price makes a new low but RSI makes a higher low - this often precedes a reversal upward. Bearish divergence (price higher high, RSI lower high) signals potential downside.
Pine Script Code
Copy and paste this code into your TradingView Pine Editor.
PINE SCRIPT V5
//@version=5
indicator("RSI Divergence Detector", overlay=false)
// Inputs
rsiLength = input.int(14, "RSI Length")
pivotLookback = input.int(5, "Pivot Lookback")
// Calculate RSI
rsi = ta.rsi(close, rsiLength)
// Find pivots
pivotLow = ta.pivotlow(rsi, pivotLookback, pivotLookback)
pivotHigh = ta.pivothigh(rsi, pivotLookback, pivotLookback)
// Track previous pivots for divergence detection
var float prevPivotLowPrice = na
var float prevPivotLowRSI = na
var float prevPivotHighPrice = na
var float prevPivotHighRSI = na
// Bullish divergence: Price lower low, RSI higher low
bullishDiv = false
if not na(pivotLow)
if close[pivotLookback] < prevPivotLowPrice and rsi[pivotLookback] > prevPivotLowRSI
bullishDiv := true
prevPivotLowPrice := close[pivotLookback]
prevPivotLowRSI := rsi[pivotLookback]
// Bearish divergence: Price higher high, RSI lower high
bearishDiv = false
if not na(pivotHigh)
if close[pivotLookback] > prevPivotHighPrice and rsi[pivotLookback] < prevPivotHighRSI
bearishDiv := true
prevPivotHighPrice := close[pivotLookback]
prevPivotHighRSI := rsi[pivotLookback]
// Plots
plot(rsi, "RSI", color=color.purple, linewidth=2)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
plotshape(bullishDiv, "Bullish Div", shape.triangleup, location.bottom, color.green, size=size.small)
plotshape(bearishDiv, "Bearish Div", shape.triangledown, location.top, color.red, size=size.small)