RSI Divergence Flagger
Relative Strength Index (RSI) divergences occur when price reaches a new extreme (higher high or lower low) while RSI fails to do so. This pattern suggests momentum is not confirming the price move, potentially signaling a reversal. The RSI Divergence Flagger uses strict pivot detection rules to identify only substantial divergences, filtering out minor noise and improving signal reliability. Traders and technical analysts use divergence flags to detect potential trend exhaustion and early reversal setups.
//@version=6
indicator("RSI Divergence Flagger", overlay=true)
// Inputs
rsiLength = input.int(14, title="RSI Length", minval=2)
pivotLookback = input.int(5, title="Pivot Lookback", minval=1, maxval=20)
showPivots = input.bool(false, title="Show Pivot Points")
// Calculate RSI
rsi = ta.rsi(close, rsiLength)
// Strict pivot detection: price/RSI must be highest/lowest over 2*lookback+1 bars
lookbackLen = pivotLookback * 2 + 1
isPriceHighPivot = high == ta.highest(high, lookbackLen)
isPriceLowPivot = low == ta.lowest(low, lookbackLen)
isRsiHighPivot = rsi == ta.highest(rsi, lookbackLen)
isRsiLowPivot = rsi == ta.lowest(rsi, lookbackLen)
// Both price and RSI must pivot together to form valid divergence basis
validHighPivot = isPriceHighPivot and isRsiHighPivot
validLowPivot = isPriceLowPivot and isRsiLowPivot
// Storage for prior pivot values
var float lastPriceHigh = na
var float lastRsiHigh = na
var float lastPriceLow = na
var float lastRsiLow = na
// Divergence detection
bearishDiv = false
bullishDiv = false
if validHighPivot
if not na(lastPriceHigh)
if high > lastPriceHigh and rsi < lastRsiHigh
bearishDiv := true
lastPriceHigh := high
lastRsiHigh := rsi
if validLowPivot
if not na(lastPriceLow)
if low < lastPriceLow and rsi > lastRsiLow
bullishDiv := true
lastPriceLow := low
lastRsiLow := rsi
// Plot divergences
plotshape(bearishDiv, title="Bearish Divergence", style=shape.arrowdown, location=location.abovebar, color=color.new(color.red, 0), size=size.small)
plotshape(bullishDiv, title="Bullish Divergence", style=shape.arrowup, location=location.belowbar, color=color.new(color.green, 0), size=size.small)
// Plot pivot markers (optional)
plotshape(showPivots and isPriceHighPivot, title="Price High Pivot", style=shape.circle, location=location.abovebar, color=color.new(color.orange, 50), size=size.tiny)
plotshape(showPivots and isPriceLowPivot, title="Price Low Pivot", style=shape.circle, location=location.belowbar, color=color.new(color.orange, 50), size=size.tiny)
// Plot RSI
plot(rsi, title="RSI", color=color.blue, linewidth=1)
hline(70, "Overbought", color=color.gray, linestyle=hline.style_dashed)
hline(30, "Oversold", color=color.gray, linestyle=hline.style_dashed)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted)
How the code works
The indicator operates on a two-stage pivot detection logic. First, it identifies price pivots by testing whether the current bar's high or low is the maximum or minimum value across a lookback window (defined as 2 × pivotLookback + 1 bars). This ensures only substantial extremes are flagged, not minor local touches. The same strict comparison is applied to RSI values at the same bar.
The condition validHighPivot = isPriceHighPivot and isRsiHighPivot requires that price and RSI reach their lookback extremes on the same bar, establishing a baseline pivot pair. The code then stores these values in lastPriceHigh and lastRsiHigh using Pine Script's var keyword, which persists data across bars.
When a second valid pivot of the same type (high or low) is detected, the code compares it to the stored prior pivot. A bearish divergence is flagged when the new price high exceeds the old price high, but the new RSI high is lower than the old RSI high (momentum failing to confirm higher prices). Conversely, a bullish divergence flags when the new price low is lower than the prior low, yet the new RSI low is higher (momentum improving on lower prices). These comparisons detect the momentum failure that typically precedes reversals. The showPivots toggle allows optional visualization of all identified pivot points for verification.
Reading it on a chart
When the indicator displays a red downward arrow above a price bar, a bearish divergence has been flagged: price has made a new swing high, but RSI has failed to reach an equivalent strength reading compared to the prior swing high. This suggests diminishing momentum despite advancing prices, a pattern often associated with trend exhaustion or impending pullback risk.
A green upward arrow below a price bar indicates a bullish divergence: price has reached a new swing low, but RSI has posted a higher low than the previous swing low. This signals that selling pressure is weakening even as prices fall further, potentially indicating a bounce or reversal higher may follow.
The blue RSI line and gray reference levels (70 overbought, 30 oversold, 50 midline) provide context. Divergences in overbought/oversold zones (RSI above 70 or below 30) are considered more significant by some practitioners, though the indicator does not filter on these levels and flags all qualifying cases. Optional pivot circles (when toggled on) show where the strict pivot rules have identified highs and lows, useful for validating the divergence basis.
Limitations
Divergence flagging is not a prediction tool and does not guarantee reversals. Markets frequently continue in their original direction after divergence signals; the pattern merely indicates a loss of momentum confirmation, not an inevitable turn. The strict pivot rules, requiring price and RSI to reach their lookback extremes on the same bar, may cause the indicator to miss valid divergences in trending markets where price leads and momentum confirmation lags. False positives occur in choppy, sideways markets where many pivots are detected with little price impact.
The indicator relies entirely on RSI, a bounded oscillator with mathematical properties that can create artificial divergences when price ranges expand or contract sharply; RSI hitting an extreme does not always indicate genuine momentum. The lookback period (default 5 bars, creating an 11-bar window) is arbitrary; adjusting it will produce different pivot counts and divergence frequencies with no objective "correct" setting for all markets. Small adjustments to inputs can dramatically alter output, making the indicator sensitive to parameter tuning. Divergences may persist for many bars without resolution, creating a lag between signal generation and market action. The indicator offers no stop-loss levels, position sizing guidance, or confirmation from other data sources; divergence alone does not constitute a trading plan.
Key definitions
RSI (Relative Strength Index): A momentum oscillator scaled 0-100 that measures the magnitude of price changes to evaluate overbought or oversold conditions. [1]
Pivot high: A price bar whose high is the maximum value over a lookback period, marking a local swing top.
Pivot low: A price bar whose low is the minimum value over a lookback period, marking a local swing bottom.
Bearish divergence: When price reaches a new swing high but momentum (RSI) fails to reach a corresponding high, suggesting weakening upside momentum.
Bullish divergence: When price reaches a new swing low but momentum (RSI) reaches a higher low than the prior swing low, suggesting weakening downside momentum.
Momentum confirmation: The condition where price extremes are supported by similar extremes in an oscillator, indicating the move is backed by participant conviction.
References
- Wilder, J. W., New Concepts in Technical Trading Systems, Trend Research (1978).
- CME Group, "Technical Analysis and Market Profile," Education Resource (n.d.). Https://www.cmegroup.com/education/
- Investopedia, "Relative Strength Index (RSI)," Financial Definitions. Https://www.investopedia.com/terms/r/rsi.asp
- Bulkowski, T. N., Encyclopedia of Chart Patterns (2nd ed.), John Wiley & Sons (2005).
- TradingView, "Pine Script v6 Reference Manual," Documentation. Https://www.tradingview.com/pine-script-docs/
Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.
Last reviewed by the PropLedger research pipeline: 2026-08-30. Educational research on historical data, not financial advice.
Keep reading
Round Number and Quarter Level Grid
Free open-source Pine Script indicator: round number and quarter level grid. Full code and a plain-English walkthrough.
Day-of-Week Performance Table
Free open-source Pine Script indicator: day-of-week performance table. Full code and a plain-English walkthrough.
Gap Tracker: Overnight Gap Size and Fill Status
Free open-source Pine Script indicator: gap tracker: overnight gap size and fill status. Full code and a plain-English walkthrough.