Skip to main content

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

Watch the series
RSI Divergence Explained: Regular vs Hidden, and When It Lies

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.

1

Identify pivot points

Use 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.
2

Store previous pivots

Use 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.
3

Compare slopes

For bullish divergence: check if the current price pivot is lower than the previous price pivot (lower low) AND the current RSI pivot is higher than the previous RSI pivot (higher low). For bearish divergence: price makes a higher high but RSI makes a lower high. The pivots must be within a maximum bar distance to ensure they are relevant.
4

Draw divergence lines

Use 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.
pine-Complete RSI divergence detector with line drawing
1//@version=5
2indicator("RSI Divergence Scanner", overlay=false,
3 max_lines_count=100)
4
5rsiLen = input.int(14, "RSI Length")
6pivLB = input.int(5, "Pivot Lookback")
7maxBars = input.int(60, "Max Bars Between Pivots")
8
9rsi = ta.rsi(close, rsiLen)
10
11// Detect pivots on RSI
12rsiPL = ta.pivotlow(rsi, pivLB, pivLB)
13rsiPH = ta.pivothigh(rsi, pivLB, pivLB)
14
15// Previous pivot tracking
16var float prevPLrsi = na
17var int prevPLbar = na
18var float prevPLprice = na
19var float prevPHrsi = na
20var int prevPHbar = na
21var float prevPHprice = na
22
23// Bullish divergence: lower low in price, higher low in RSI
24bullDiv = false
25if not na(rsiPL)
26 cBar = bar_index - pivLB
27 cPrice = low[pivLB]
28 cRSI = rsiPL
29 if not na(prevPLrsi) and (cBar - prevPLbar) <= maxBars
30 if cPrice < prevPLprice and cRSI > prevPLrsi
31 bullDiv := true
32 line.new(prevPLbar, prevPLrsi, cBar, cRSI,
33 color=color.green, width=2)
34 prevPLrsi := cRSI
35 prevPLbar := cBar
36 prevPLprice := cPrice
37
38// Bearish divergence: higher high in price, lower high in RSI
39bearDiv = false
40if not na(rsiPH)
41 cBar = bar_index - pivLB
42 cPrice = high[pivLB]
43 cRSI = rsiPH
44 if not na(prevPHrsi) and (cBar - prevPHbar) <= maxBars
45 if cPrice > prevPHprice and cRSI < prevPHrsi
46 bearDiv := true
47 line.new(prevPHbar, prevPHrsi, cBar, cRSI,
48 color=color.red, width=2)
49 prevPHrsi := cRSI
50 prevPHbar := cBar
51 prevPHprice := cPrice
52
53plot(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)
56
57plotshape(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")
63
64alertcondition(bullDiv, "Bullish Divergence",
65 "RSI bullish divergence detected")
66alertcondition(bearDiv, "Bearish Divergence",
67 "RSI bearish divergence detected")

Divergence trading on BTC

On BTC daily charts, RSI divergences at the 30 and 70 levels are among the most reliable reversal signals in crypto. Bullish divergences forming with RSI below 35 at a major support level have historically preceded rallies of 15–30%. The key is patience: wait for the divergence to form completely (the second pivot must be confirmed), then wait for a price trigger (break above the trendline connecting the two lows) before entering.

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.

pine-Multi-metric combined volume indicator
1//@version=5
2indicator("Combined Volume", overlay=false)
3
4avgLen = input.int(20, "Average Length")
5
6// Metrics
7avgVol = ta.sma(volume, avgLen)
8rvol = volume / avgVol
9obv = ta.cum(close > close[1] ? volume :
10 close < close[1] ? -volume : 0)
11obvEMA = ta.ema(obv, avgLen)
12
13// Volume-price confirmation
14bullVol = close > open and volume > avgVol
15bearVol = close < open and volume > avgVol
16weakBull = close > open and volume < avgVol
17weakBear = close < open and volume < avgVol
18
19// Color coding
20volColor = 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)
25
26plot(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)
30
31// OBV trend arrow on status line
32plot(obv > obvEMA ? 1 : -1, "OBV Trend",
33 display=display.status_line)
Bright green barsBullish candle with above-average volume. Strong buying: the move is supported by real capital.
Dim green barsBullish candle but below-average volume. Weak buying: the move lacks conviction and may reverse.
Bright red barsBearish candle with above-average volume. Aggressive selling: the move is supported by real capital.
Dim red barsBearish candle but below-average volume. Weak selling: the decline may be exhaustion rather than continuation.
OBV TrendOn-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.

pine-Multi-factor composite scoring system
1//@version=5
2indicator("Composite Score", overlay=false)
3
4// Factor 1: RSI momentum
5rsi = ta.rsi(close, 14)
6rsiScore = rsi > 55 ? 1.0 : rsi < 45 ? -1.0 :
7 (rsi - 50) / 5
8
9// Factor 2: MACD momentum
10[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.5
14
15// Factor 3: Volume confirmation
16rvol = volume / ta.sma(volume, 20)
17volBias = close > open ? 1.0 : -1.0
18volScore = rvol > 1.5 ? volBias :
19 rvol > 1.0 ? volBias * 0.5 : 0.0
20
21// 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)
28
29composite = rsiScore + macdScore + volScore + trendScore
30
31compColor = color.from_gradient(composite, -4, 4,
32 color.red, color.green)
33
34plot(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)
41
42bgcolor(composite > 2.5 ? color.new(color.green, 92) :
43 composite < -2.5 ? color.new(color.red, 92) : na)

Weighting and calibration

In this example, all four factors have equal weight (each contributes -1 to +1 for a total range of -4 to +4). In practice, you may want to weight certain factors more heavily. For example, on trending assets like BTC during a bull market, weighting the trend factor at 2x gives more emphasis to macro alignment. During range-bound periods on ETH, weighting RSI and volume higher emphasizes mean-reversion signals.

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.

pine-Multi-oscillator divergence scanner
1//@version=5
2indicator("Pro Divergence Scanner", overlay=false,
3 max_lines_count=200, max_labels_count=100)
4
5pivLen = input.int(5, "Pivot Length")
6maxBars = input.int(50, "Max Bars Between Pivots")
7rsiLen = input.int(14, "RSI Length")
8
9rsi = ta.rsi(close, rsiLen)
10[macdL, sigL, hist] = ta.macd(close, 12, 26, 9)
11
12// Divergence helper function
13checkBullDiv(osc, oscPL, prevOsc, prevBar, prevPrice, cBar) =>
14 result = false
15 if not na(oscPL) and not na(prevOsc)
16 cPrice = low[pivLen]
17 gap = cBar - prevBar
18 if gap > 0 and gap <= maxBars
19 if cPrice < prevPrice and oscPL > prevOsc
20 result := true
21 result
22
23// Track RSI pivots
24rsiPL = ta.pivotlow(rsi, pivLen, pivLen)
25var float pRSI = na, var int pRSIbar = na, var float pRSIprice = na
26
27rsiDiv = false
28if not na(rsiPL)
29 cBar = bar_index - pivLen
30 if checkBullDiv(rsi, rsiPL, pRSI, pRSIbar, pRSIprice, cBar)
31 rsiDiv := true
32 line.new(pRSIbar, pRSI, cBar, rsiPL,
33 color=color.green, width=2)
34 pRSI := rsiPL
35 pRSIbar := cBar
36 pRSIprice := low[pivLen]
37
38// Track MACD pivots
39histPL = ta.pivotlow(hist, pivLen, pivLen)
40var float pHist = na, var int pHistBar = na, var float pHistPrice = na
41
42histDiv = false
43if not na(histPL)
44 cBar = bar_index - pivLen
45 if checkBullDiv(hist, histPL, pHist, pHistBar, pHistPrice, cBar)
46 histDiv := true
47 pHist := histPL
48 pHistBar := cBar
49 pHistPrice := low[pivLen]
50
51// Score
52divCount = (rsiDiv ? 1 : 0) + (histDiv ? 1 : 0)
53
54plot(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)
57
58plotshape(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)
64
65bgcolor(divCount >= 2 ? color.new(color.yellow, 90) : na)
66
67alertcondition(divCount >= 2,
68 "Multi-Oscillator Divergence",
69 "Bullish divergence confirmed on multiple oscillators")
Pivot-based detection

Uses confirmed pivot points rather than arbitrary lookback windows: more accurate, fewer false positives

Multi-oscillator scanning

Checks RSI and MACD histogram simultaneously for divergent pivots

Visual line drawing

Draws lines between divergent RSI pivots so you can visually verify the divergence quality

Divergence scoring

Counts how many oscillators show divergence: a score of 2+ means multiple confirmation

Alert system

Fires alerts only on multi-confirmed divergences, filtering out single-oscillator noise

Max bar filter

Ignores pivots that are too far apart: ensures the divergence is from a recent price structure

Trading multi-confirmed divergences

On SOL 4H charts, multi-confirmed bullish divergences (RSI + MACD both diverging) near major support zones have historically preceded 10–25% rallies. The setup is rare, you might see one per month, but the hit rate is high. Combine with a trend filter: divergences in the direction of the daily trend are significantly more reliable than counter-trend divergences.

Put this lesson to work

Free on Thrive, no account needed.