Divergence Detection & Combined Indicators
Automatically detecting RSI divergence, building combined volume indicators, and creating composite multi-factor indicators.
From Thrive on YouTube
Watch the matching Thrive video
RSI Divergence Explained: Regular vs Hidden, and When It Lies
Part of Charting and Market Structure. Education only. Not financial advice.
Detecting RSI Divergence Programmatically
Divergence detection is one of the most valuable skills in PineScript development. A divergence occurs when price structure and indicator structure disagree: price makes a new extreme but the oscillator does not confirm it. This signals that the momentum behind the price move is weakening and a reversal may be imminent. Programmatic detection requires identifying pivot points on both price and the oscillator, then comparing the slopes between consecutive pivots.
Identify pivot points
ta.pivotlow() and ta.pivothigh() on both the RSI series and the price series (low for bullish divergence, high for bearish). The pivot functions require a lookback and lookforward parameter: using 5 bars on each side means the pivot is confirmed 5 bars after it occurs, which avoids false readings at the cost of delayed detection.Store previous pivots
var variables to remember the last pivot's price, RSI value, and bar index. Each time a new pivot forms, you compare it against the stored previous pivot. After comparison, update the stored values with the new pivot's data. This creates a rolling two-pivot comparison window.Compare slopes
Draw divergence lines
line.new() to draw lines between the two divergent pivot points on the RSI pane. This creates the classic divergence visualization that traders are accustomed to seeing. Color the lines green for bullish and red for bearish.1//@version=52indicator("RSI Divergence Scanner", overlay=false,3 max_lines_count=100)45rsiLen = input.int(14, "RSI Length")6pivLB = input.int(5, "Pivot Lookback")7maxBars = input.int(60, "Max Bars Between Pivots")89rsi = ta.rsi(close, rsiLen)1011// Detect pivots on RSI12rsiPL = ta.pivotlow(rsi, pivLB, pivLB)13rsiPH = ta.pivothigh(rsi, pivLB, pivLB)1415// Previous pivot tracking16var float prevPLrsi = na17var int prevPLbar = na18var float prevPLprice = na19var float prevPHrsi = na20var int prevPHbar = na21var float prevPHprice = na2223// Bullish divergence: lower low in price, higher low in RSI24bullDiv = false25if not na(rsiPL)26 cBar = bar_index - pivLB27 cPrice = low[pivLB]28 cRSI = rsiPL29 if not na(prevPLrsi) and (cBar - prevPLbar) <= maxBars30 if cPrice < prevPLprice and cRSI > prevPLrsi31 bullDiv := true32 line.new(prevPLbar, prevPLrsi, cBar, cRSI,33 color=color.green, width=2)34 prevPLrsi := cRSI35 prevPLbar := cBar36 prevPLprice := cPrice3738// Bearish divergence: higher high in price, lower high in RSI39bearDiv = false40if not na(rsiPH)41 cBar = bar_index - pivLB42 cPrice = high[pivLB]43 cRSI = rsiPH44 if not na(prevPHrsi) and (cBar - prevPHbar) <= maxBars45 if cPrice > prevPHprice and cRSI < prevPHrsi46 bearDiv := true47 line.new(prevPHbar, prevPHrsi, cBar, cRSI,48 color=color.red, width=2)49 prevPHrsi := cRSI50 prevPHbar := cBar51 prevPHprice := cPrice5253plot(rsi, "RSI", color.white, 2)54hline(70, "OB", color.new(color.red, 60), hline.style_dashed)55hline(30, "OS", color.new(color.green, 60), hline.style_dashed)5657plotshape(bullDiv, "Bull Div", shape.triangleup,58 location.bottom, color.green, offset=-pivLB,59 size=size.small, text="Bull")60plotshape(bearDiv, "Bear Div", shape.triangledown,61 location.top, color.red, offset=-pivLB,62 size=size.small, text="Bear")6364alertcondition(bullDiv, "Bullish Divergence",65 "RSI bullish divergence detected")66alertcondition(bearDiv, "Bearish Divergence",67 "RSI bearish divergence detected")Divergence trading on BTC
Combined Volume Indicator
A single volume bar tells you how much was traded, but it does not tell you the full story. A combined volume indicator merges multiple volume metrics into one view: relative volume (RVOL), volume trend (rising or falling average), volume-price confirmation (did volume support the price move?), and on-balance volume (OBV) trend. This gives you a multi-dimensional view of volume dynamics in a single pane.
1//@version=52indicator("Combined Volume", overlay=false)34avgLen = input.int(20, "Average Length")56// Metrics7avgVol = ta.sma(volume, avgLen)8rvol = volume / avgVol9obv = ta.cum(close > close[1] ? volume :10 close < close[1] ? -volume : 0)11obvEMA = ta.ema(obv, avgLen)1213// Volume-price confirmation14bullVol = close > open and volume > avgVol15bearVol = close < open and volume > avgVol16weakBull = close > open and volume < avgVol17weakBear = close < open and volume < avgVol1819// Color coding20volColor = bullVol ? color.new(color.green, 0) :21 bearVol ? color.new(color.red, 0) :22 weakBull ? color.new(color.green, 60) :23 weakBear ? color.new(color.red, 60) :24 color.new(color.gray, 40)2526plot(rvol, "RVOL", volColor, 2, plot.style_histogram)27hline(1.0, "Average", color.new(color.gray, 60))28hline(2.0, "High Vol", color.new(color.yellow, 60),29 hline.style_dashed)3031// OBV trend arrow on status line32plot(obv > obvEMA ? 1 : -1, "OBV Trend",33 display=display.status_line)| Bright green bars | Bullish candle with above-average volume. Strong buying: the move is supported by real capital. |
| Dim green bars | Bullish candle but below-average volume. Weak buying: the move lacks conviction and may reverse. |
| Bright red bars | Bearish candle with above-average volume. Aggressive selling: the move is supported by real capital. |
| Dim red bars | Bearish candle but below-average volume. Weak selling: the decline may be exhaustion rather than continuation. |
| OBV Trend | On-balance volume above its EMA means cumulative buying pressure is rising. Below means selling pressure dominates. |
Building Composite Multi-Factor Indicators
A composite indicator combines signals from multiple independent systems (RSI, MACD, volume, trend) into a single score. The concept is simple: each sub-indicator contributes a score between -1 and +1, and the composite is the sum. A score of +4 means all four factors agree bullish. This approach forces you to wait for confluence, which dramatically reduces false signals. On ETH, composite scores of +3 or higher have historically preceded moves of 5–15% within the following 5 days.
1//@version=52indicator("Composite Score", overlay=false)34// Factor 1: RSI momentum5rsi = ta.rsi(close, 14)6rsiScore = rsi > 55 ? 1.0 : rsi < 45 ? -1.0 :7 (rsi - 50) / 589// Factor 2: MACD momentum10[macdLine, sigLine, hist] = ta.macd(close, 12, 26, 9)11macdScore = hist > 0 and hist > hist[1] ? 1.0 :12 hist < 0 and hist < hist[1] ? -1.0 :13 hist > 0 ? 0.5 : -0.51415// Factor 3: Volume confirmation16rvol = volume / ta.sma(volume, 20)17volBias = close > open ? 1.0 : -1.018volScore = rvol > 1.5 ? volBias :19 rvol > 1.0 ? volBias * 0.5 : 0.02021// Factor 4: Trend alignment (EMA stack)22ema21 = ta.ema(close, 21)23ema50 = ta.ema(close, 50)24ema200 = ta.ema(close, 200)25trendScore = (close > ema21 ? 0.33 : -0.33) +26 (ema21 > ema50 ? 0.33 : -0.33) +27 (ema50 > ema200 ? 0.34 : -0.34)2829composite = rsiScore + macdScore + volScore + trendScore3031compColor = color.from_gradient(composite, -4, 4,32 color.red, color.green)3334plot(composite, "Composite", compColor, 3,35 plot.style_histogram)36hline(0, "Neutral", color.new(color.gray, 60))37hline(2.5, "Strong Bull", color.new(color.green, 70),38 hline.style_dashed)39hline(-2.5, "Strong Bear", color.new(color.red, 70),40 hline.style_dashed)4142bgcolor(composite > 2.5 ? color.new(color.green, 92) :43 composite < -2.5 ? color.new(color.red, 92) : na)Weighting and calibration
Professional Divergence Scanner with Visual Lines
This advanced divergence scanner goes beyond simple RSI divergence. It detects divergences on RSI, MACD histogram, and the stochastic oscillator simultaneously, drawing lines between divergent pivots and scoring the divergence by how many oscillators agree. A triple-confirmed divergence (all three oscillators diverging) is a rare and powerful signal.
1//@version=52indicator("Pro Divergence Scanner", overlay=false,3 max_lines_count=200, max_labels_count=100)45pivLen = input.int(5, "Pivot Length")6maxBars = input.int(50, "Max Bars Between Pivots")7rsiLen = input.int(14, "RSI Length")89rsi = ta.rsi(close, rsiLen)10[macdL, sigL, hist] = ta.macd(close, 12, 26, 9)1112// Divergence helper function13checkBullDiv(osc, oscPL, prevOsc, prevBar, prevPrice, cBar) =>14 result = false15 if not na(oscPL) and not na(prevOsc)16 cPrice = low[pivLen]17 gap = cBar - prevBar18 if gap > 0 and gap <= maxBars19 if cPrice < prevPrice and oscPL > prevOsc20 result := true21 result2223// Track RSI pivots24rsiPL = ta.pivotlow(rsi, pivLen, pivLen)25var float pRSI = na, var int pRSIbar = na, var float pRSIprice = na2627rsiDiv = false28if not na(rsiPL)29 cBar = bar_index - pivLen30 if checkBullDiv(rsi, rsiPL, pRSI, pRSIbar, pRSIprice, cBar)31 rsiDiv := true32 line.new(pRSIbar, pRSI, cBar, rsiPL,33 color=color.green, width=2)34 pRSI := rsiPL35 pRSIbar := cBar36 pRSIprice := low[pivLen]3738// Track MACD pivots39histPL = ta.pivotlow(hist, pivLen, pivLen)40var float pHist = na, var int pHistBar = na, var float pHistPrice = na4142histDiv = false43if not na(histPL)44 cBar = bar_index - pivLen45 if checkBullDiv(hist, histPL, pHist, pHistBar, pHistPrice, cBar)46 histDiv := true47 pHist := histPL48 pHistBar := cBar49 pHistPrice := low[pivLen]5051// Score52divCount = (rsiDiv ? 1 : 0) + (histDiv ? 1 : 0)5354plot(rsi, "RSI", color.white, 2)55hline(70, "OB", color.new(color.red, 60), hline.style_dashed)56hline(30, "OS", color.new(color.green, 60), hline.style_dashed)5758plotshape(divCount >= 2, "Multi Div", shape.diamond,59 location.bottom, color.yellow, offset=-pivLen,60 size=size.small, text="Multi")61plotshape(rsiDiv and divCount < 2, "RSI Div", shape.circle,62 location.bottom, color.green, offset=-pivLen,63 size=size.tiny)6465bgcolor(divCount >= 2 ? color.new(color.yellow, 90) : na)6667alertcondition(divCount >= 2,68 "Multi-Oscillator Divergence",69 "Bullish divergence confirmed on multiple oscillators")Uses confirmed pivot points rather than arbitrary lookback windows: more accurate, fewer false positives
Checks RSI and MACD histogram simultaneously for divergent pivots
Draws lines between divergent RSI pivots so you can visually verify the divergence quality
Counts how many oscillators show divergence: a score of 2+ means multiple confirmation
Fires alerts only on multi-confirmed divergences, filtering out single-oscillator noise
Ignores pivots that are too far apart: ensures the divergence is from a recent price structure
Trading multi-confirmed divergences
Put this lesson to work
Free on Thrive, no account needed.