Concept 11 / 52·Momentum·Oscillator reading
‹ Day-of-Week EffectsDonchian Channels ›

Divergence in Pine Script

RSI divergence · regular divergence · hidden divergence · bullish divergence · bearish divergence · momentum divergence

A disagreement between the swings of price and the swings of an oscillator: price makes a new extreme while momentum does not, or the reverse in the hidden form.

Reads best on: Daily and 4-hour charts of liquid stocks, indices and major crypto pairs, where swings are clean enough for pivots to mean something. On fast intraday charts widen the pivot or read a higher timeframe.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
01

Definition

Divergence is a disagreement between price and a momentum oscillator at consecutive swing points. Regular bullish divergence is a lower low in price with a higher low in the oscillator; regular bearish divergence is a higher high in price with a lower high in the oscillator. Hidden divergence is the mirror. In an uptrend it is a higher low in price with a lower low in the oscillator; in a downtrend, a lower high in price with a higher high in the oscillator. It belongs with overbought and oversold in the oscillator-reading family, because it is a way of interpreting a line rather than a line of its own.

Regular divergence says the second push had less momentum behind it than the first. Price went further but the average gain, or the position of the close in the range, did not, so the move is running on less force. That is a warning that the trend is thinning, not a signal that it has ended, and trends often produce two or three divergences before they turn. Hidden divergence says the opposite. The pullback took momentum to a deeper low than the previous pullback while price held a higher low, which is what a healthy trend does when it shakes out weak holders before continuing.

Any oscillator can be used, and RSI, MACD, the stochastic and CCI are the usual choices. The pivots have to be defined mechanically: a swing low is a bar with a lower value than a set number of bars on each side. That means the pivot is only known that many bars later. That lag is the price of a clean definition. The library's script uses RSI 14 with 5 bars on each side. It compares each newly confirmed RSI pivot with the previous one, reads price at the same bars, and prints the mark at the pivot once it is confirmed.

On the chart a divergence looks like two lines drawn between swing points that slope in opposite directions. The first look is often wrong: the oscillator pivot and the price pivot rarely land on the same bar, and drawing the lines between different bars manufactures divergences that were never there. A confirmed divergence marks a pivot; it does not enter a trade. What follows depends on price. A break of the swing that formed after the second pivot turns the warning into a reversal signal, and a failure to break it leaves the divergence as one more sign of a stretched trend.

02

Reading the chart

Define the pivots first, compare the two series at the same bars, and treat the result as a warning that price has to confirm.

  1. Choose the oscillator and the pivot width. RSI 14 with 5 bars each side is the library's default; wider pivots find fewer, larger divergences and confirm later, narrower ones find more and confirm sooner.
  2. Find two consecutive confirmed pivots of the oscillator, two lows or two highs. Confirmed means the required number of bars has printed after the pivot without breaking it.
  3. Read price at the same two bars. A lower price low with a higher oscillator low is regular bullish; a higher price high with a lower oscillator high is regular bearish. The library's script marks these as Long and Short at the pivot bar.
  4. Check for the hidden form if you are trading with a trend. A higher price low with a lower oscillator low in an uptrend is hidden bullish and marks a continuation pullback; the script shows these as small circles when switched on.
  5. Note the confirmation lag. With 5 bars each side the mark appears 5 bars after the pivot, and price has already moved; the trigger is the break of the swing, not the mark itself.
  6. Weigh the context. A regular divergence at a higher-timeframe level, in an overbought or oversold zone, or after a long trend is worth more than one in the middle of a range.
03

The maths

A divergence is a comparison of the direction of two differences at consecutive confirmed pivots of the oscillator.

PivotLowp={1Op<Op−k∧Op<Op+k∀ k∈{1,…,w}0otherwise\mathrm{PivotLow}_p = \begin{cases} 1 & O_p < O_{p-k} \land O_p < O_{p+k} \quad \forall\, k \in \{1, \dots, w\} \\ 0 & \text{otherwise} \end{cases}
RegularBullish={1Plow,2<Plow,1∧Olow,2>Olow,10otherwise\mathrm{RegularBullish} = \begin{cases} 1 & P_{\mathrm{low},2} < P_{\mathrm{low},1} \land O_{\mathrm{low},2} > O_{\mathrm{low},1} \\ 0 & \text{otherwise} \end{cases}
RegularBearish={1Phigh,2>Phigh,1∧Ohigh,2<Ohigh,10otherwise\mathrm{RegularBearish} = \begin{cases} 1 & P_{\mathrm{high},2} > P_{\mathrm{high},1} \land O_{\mathrm{high},2} < O_{\mathrm{high},1} \\ 0 & \text{otherwise} \end{cases}
HiddenBullish={1Plow,2>Plow,1∧Olow,2<Olow,10otherwise\mathrm{HiddenBullish} = \begin{cases} 1 & P_{\mathrm{low},2} > P_{\mathrm{low},1} \land O_{\mathrm{low},2} < O_{\mathrm{low},1} \\ 0 & \text{otherwise} \end{cases}
HiddenBearish={1Phigh,2<Phigh,1∧Ohigh,2>Ohigh,10otherwise\mathrm{HiddenBearish} = \begin{cases} 1 & P_{\mathrm{high},2} < P_{\mathrm{high},1} \land O_{\mathrm{high},2} > O_{\mathrm{high},1} \\ 0 & \text{otherwise} \end{cases}
OpO_pthe oscillator value at bar p
wwthe pivot width, bars on each side, 5 by default
kkan offset from the pivot bar, 1 to w
Plow,1P_{low,1}the price low at the earlier confirmed oscillator pivot low
Plow,2P_{low,2}the price low at the later confirmed oscillator pivot low
Olow,1O_{low,1}the oscillator value at the earlier pivot low
Olow,2O_{low,2}the oscillator value at the later pivot low
Phigh,1,Phigh,2P_{high,1}, P_{high,2}the price highs at the earlier and later oscillator pivot highs
Ohigh,1,Ohigh,2O_{high,1}, O_{high,2}the oscillator values at those pivot highs
PivotLowp\mathrm{PivotLow}_ptrue when bar p is a confirmed pivot low of the oscillator; pivot highs mirror it
RegularBullish,RegularBearish\mathrm{RegularBullish}, \mathrm{RegularBearish}the two regular divergence conditions, marked Long and Short
HiddenBullish,HiddenBearish\mathrm{HiddenBullish}, \mathrm{HiddenBearish}the two hidden divergence conditions, shown as circles when switched on

The library's script finds the pivots on RSI and reads the price high or low at the same bars, so the two series are always compared at identical bars.

A pivot with width w is confirmed w bars after it prints, and the mark is drawn back at the pivot bar; the alert fires on the confirming bar.

Only consecutive pivots are compared. A divergence against a pivot three swings back is not detected, and neither is a triple divergence as one event.

Hidden divergences are off by default and turn on with one switch; regular ones are marked as Long and Short, hidden ones as small circles.

04

Inputs that matter

InputTypicalWhat changing it does
Oscillator length14 (RSI)Shorter lengths produce more pivots and more divergences, many of them trivial; longer lengths find fewer, slower ones.
Pivot width5 bars each sideWider pivots need bigger swings to qualify and confirm later; narrower ones find every wobble and confirm sooner.
Hidden divergencesoffSwitching them on adds the continuation form, which reads with the trend and is useful only once the trend is defined.
05

In practice

  • As a reversal warning: a regular bearish divergence at the end of a long advance, especially with RSI above 70 at the first peak, says the trend is thinning. The trigger is the break of the swing low that formed after the second peak.
  • As a bottom-finding tool: a regular bullish divergence after a decline, with the second RSI low above the first, is the classic sign that downside pressure is fading. The library's script marks it as Long at the confirmed pivot.
  • As a continuation entry: with the trend defined, a hidden bullish divergence at a higher price low is a pullback that washed out momentum without breaking structure. The long entry comes on the turn back up.
  • As a filter on zone exits: an oversold exit on RSI that also carries a bullish divergence has two reasons to hold; the same exit without divergence is a weaker trade in a downtrend.
  • As an alert stream: the script's alerts fire on the confirming bar, so a scan of a watchlist for confirmed divergences produces a short list to check on the price chart.
  • As a multi-timeframe read: a divergence on the daily chart sets the expectation, and the intraday chart provides the entry once price breaks the relevant swing.
06

Where it goes wrong

  • Drawing lines between pivots that do not line up. If the oscillator low and the price low are on different bars, the comparison is invented; use one series to define the pivot and read the other at the same bars.
  • Trading the mark instead of the break. The divergence confirms a pivot; entering there against the trend without a price trigger is how divergence traders get run over.
  • Expecting one divergence to end a trend. Strong trends print two or three before they turn; treat each as a warning and size accordingly.
  • Ignoring the lag. A 5-bar pivot confirms 5 bars late, so the mark sits behind the current bar; plan the entry from the confirmed structure, not from where the mark appears.
07

Compared with

Overbought & Oversold. Overbought and oversold read the oscillator's level; divergence reads the relation between its swings and price's swings. A level says momentum has been high; a divergence says it has been lower on the latest push than the one before. Levels tell you where to look, divergence tells you whether the push is weakening.

Break of Structure. A break of structure is the price event that confirms what a divergence warned about: the swing that formed after the divergent pivot gives way. Divergence comes first and is a probability; the break comes later and is a fact. Trading the break with the divergence behind it combines the two.

Swing Highs & Lows. Swing highs and lows are the raw material: divergence compares the oscillator at the swing bars. The same left and right bar definition that confirms a swing confirms a divergence, and the same lag applies. Reading swings without an oscillator gives structure; adding the oscillator gives the momentum behind it.

MACD. MACD divergence uses the MACD line or the histogram instead of RSI, and because MACD is unbounded it keeps growing in a trend and diverges later. RSI, being bounded, diverges earlier and more often, with more false warnings. The library's detector runs on RSI; the same logic applies to any oscillator.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Open Divergence on the workbench chart
Drawn on real data; then audit, backtest and refine in conversation.
Open in Quant →
09

Questions

  • What is the difference between regular and hidden divergence?

    Regular divergence is price making a new extreme that the oscillator does not confirm: a lower low with a higher oscillator low, or a higher high with a lower oscillator high. It warns of a reversal. Hidden divergence is the oscillator making the new extreme while price does not: a higher price low with a lower oscillator low in an uptrend. It marks a pullback inside a trend and points to continuation.

  • Which oscillator is best for divergence?

    RSI is the most common because it is bounded and smooth, so its pivots are clean and it diverges early. MACD diverges later and less often, with fewer false warnings, because it is unbounded. The stochastic gives many divergences on short lengths, most of them noise. Choose RSI for early warning on daily and 4-hour charts, MACD when you want fewer, larger signals.

  • Why does the divergence mark appear several bars late?

    Because a pivot is only known once enough bars have printed after it without breaking it. With 5 bars on each side, the low is confirmed 5 bars later, and that is when the script can compare it with the previous one. The mark is drawn back at the pivot bar, but the alert fires on the confirming bar. Narrower pivots confirm sooner and find more noise.

  • Is the divergence an entry on its own?

    No. A confirmed divergence tells you the second push had less momentum, which raises the odds of a turn but does not time it, and trends often print several before ending. It is the reason; a price event is the trigger. That can be the break of the swing that formed after the divergent pivot, a zone exit on the oscillator, or a reversal candle at a level.

  • What does the library's divergence script detect?

    Regular divergences between price and a 14-period RSI at confirmed pivots with 5 bars on each side. It marks a bullish one as Long when price prints a lower low and RSI a higher low, and a bearish one as Short at the mirror. Hidden divergences can be switched on and appear as small circles. Marks sit at the pivot bar, and alerts fire when the pivot confirms.

  • Does divergence work on intraday charts?

    Yes, with the same definitions and more noise. On 5-minute bars a 5-bar pivot is 25 minutes each side, so divergences form and confirm within an hour and many of them precede tiny turns. Intraday traders widen the pivot, use a longer RSI, or read divergence on the 15-minute or hourly chart and time the entry on the faster one.