OPEN-SOURCE SCRIPT
Aktualisiert RSI Divergence Pro

RSI Divergence Pro
WHAT IT DOES
RSI Divergence Pro is a self-contained RSI that detects all four divergence types (regular bullish, regular bearish, hidden bullish, hidden bearish), draws them on both the RSI pane and the main price chart, and — unlike most divergence tools — keeps a live scoreboard of how each divergence type has actually behaved on the current symbol and timeframe.
It reproduces the standard RSI (same calculation and pane visuals as the built-in: band background, overbought/oversold gradient fills, optional smoothing MA and Bollinger Bands) so it can replace an existing RSI pane one-for-one, then layers divergence detection on top.
WHY IT'S DIFFERENT
1. RSI-anchored pivots. Divergences are detected from pivots on the RSI itself (ta.pivotlow / ta.pivothigh applied to the RSI series), not on price. Marker and line endpoints therefore sit exactly on the RSI curve instead of floating mid-slope, and the RSI — the thing actually diverging — is the source of truth. Price at those same bars supplies the price leg.
2. Built-in outcome tracking. Every confirmed divergence spawns a simulated bracket (entry at the confirmation close, ATR-multiple target and stop, fixed bar horizon). Results are tallied per type into a table: sample size (N), win rate, and average R. This turns the indicator into a measurement instrument — you can see, per symbol and timeframe, whether a given divergence type has shown any edge before you weight it in your analysis.
3. Honest mechanics. Signals confirm a fixed number of bars after the pivot (the right lookback) and never earlier; alerts fire on bar close; the simulator resolves on confirmed bars only, checks the stop before the target when both are touched inside one bar (conservative tie-break), and is gap-aware — a bar opening beyond the stop or target fills at the open, not at the ideal price.
HOW DETECTION WORKS
A pivot low/high on RSI is confirmed after "Pivot Lookback Right" bars. Each newly confirmed pivot is compared to the previous same-side pivot, subject to a minimum/maximum bar-distance gate:
- Regular bullish: price lower low + RSI higher low
- Hidden bullish: price higher low + RSI lower low
- Regular bearish: price higher high + RSI lower high
- Hidden bearish: price lower high + RSI higher high
Each type toggles independently and is styled independently (color, line style, width, transparency).
THE OUTCOME TABLE — READ BEFORE TRUSTING ANY DIVERGENCE
Defaults: entry at the confirmation close, target 2×ATR(14), stop 1×ATR(14), 20-bar horizon (expiry marks to close). All adjustable. With the default 2:1 bracket, average R ≈ 3 × win rate − 1 for non-gap resolutions, so the table's internal consistency can be sanity-checked by eye. These statistics measure raw divergence behavior under one fixed mechanical rule on the loaded chart history. They are not a backtest of a complete trading plan, they are not predictive of future results, and small samples are noise. Open (unresolved) simulations are shown in the table header and excluded from N.
DISPLAY & CUSTOMIZATION
- Lines on the RSI pane, the price chart, or both; info tags toggle per pane independently of the lines
- Tag styles: colored bubble or clean floating text; compact or detailed text (RSI change and price %); hover any tag for the full tooltip (type, RSI from→to, price from→to, bars apart, position vs the 50 line)
- Optional forward projection ray per divergence line, with its own color source, style, width, and transparency
- Optional freshness fade: older lines grow progressively more transparent so the newest stands out
- Discreet pivot tick marks on the RSI curve and on candles, styled per side
- The stock RSI visuals (band background, OB/OS gradients) can each be hidden for a clean pane
- Info table (RSI value, 50-line bias, last pivots, last divergence and its age) and outcome table, each position-selectable; both flash green or red for a configurable number of bars when a new bullish or bearish divergence confirms
- Array-managed object pools with configurable caps keep the script inside Pine's drawing limits; oldest drawings trim automatically and statistics are never trimmed
ALERTS
Five alertcondition triggers (one per type plus "Any RSI Divergence") for the standard alert dialog, and an optional dynamic alert() payload ("Any alert() function call") carrying live detail: ticker, timeframe, type, RSI from→to, price from→to, bars apart.
HOW TO USE IT
Works on any symbol and adapts to the chart timeframe. A reasonable workflow: run all four types with outcome tracking on, let the table accumulate, then disable the types showing no edge on your market and keep those that do. Regular divergences are conventionally read as reversal context and hidden divergences as continuation context; treat both as context alongside your own structure and trend analysis, not as standalone entries.
KNOWN BEHAVIOR / LIMITATIONS
- Confirmation lag is by design: a divergence cannot exist until its pivot confirms, so the signal appears "Pivot Lookback Right" bars after the pivot bar. After confirmation, signals do not repaint.
- Divergence lines and labels connect back to past pivots by nature; the drawing extends into the past, the signal timing does not.
- The outcome simulator works from confirmed OHLC bars; intrabar sequence is unknowable from OHLC, hence the conservative stop-first rule.
- Intended for standard candle/bar charts; synthetic chart types (Heikin Ashi, Renko, etc.) distort the price legs and the simulation.
The base RSI calculation and pane visuals reproduce TradingView's built-in RSI so the script can serve as a drop-in replacement; the divergence detection, drawing system, outcome tracking, and alert logic are original to this script.
For education and analysis only. Nothing here is financial advice, and past behavior of any signal does not guarantee future results.
WHAT IT DOES
RSI Divergence Pro is a self-contained RSI that detects all four divergence types (regular bullish, regular bearish, hidden bullish, hidden bearish), draws them on both the RSI pane and the main price chart, and — unlike most divergence tools — keeps a live scoreboard of how each divergence type has actually behaved on the current symbol and timeframe.
It reproduces the standard RSI (same calculation and pane visuals as the built-in: band background, overbought/oversold gradient fills, optional smoothing MA and Bollinger Bands) so it can replace an existing RSI pane one-for-one, then layers divergence detection on top.
WHY IT'S DIFFERENT
1. RSI-anchored pivots. Divergences are detected from pivots on the RSI itself (ta.pivotlow / ta.pivothigh applied to the RSI series), not on price. Marker and line endpoints therefore sit exactly on the RSI curve instead of floating mid-slope, and the RSI — the thing actually diverging — is the source of truth. Price at those same bars supplies the price leg.
2. Built-in outcome tracking. Every confirmed divergence spawns a simulated bracket (entry at the confirmation close, ATR-multiple target and stop, fixed bar horizon). Results are tallied per type into a table: sample size (N), win rate, and average R. This turns the indicator into a measurement instrument — you can see, per symbol and timeframe, whether a given divergence type has shown any edge before you weight it in your analysis.
3. Honest mechanics. Signals confirm a fixed number of bars after the pivot (the right lookback) and never earlier; alerts fire on bar close; the simulator resolves on confirmed bars only, checks the stop before the target when both are touched inside one bar (conservative tie-break), and is gap-aware — a bar opening beyond the stop or target fills at the open, not at the ideal price.
HOW DETECTION WORKS
A pivot low/high on RSI is confirmed after "Pivot Lookback Right" bars. Each newly confirmed pivot is compared to the previous same-side pivot, subject to a minimum/maximum bar-distance gate:
- Regular bullish: price lower low + RSI higher low
- Hidden bullish: price higher low + RSI lower low
- Regular bearish: price higher high + RSI lower high
- Hidden bearish: price lower high + RSI higher high
Each type toggles independently and is styled independently (color, line style, width, transparency).
THE OUTCOME TABLE — READ BEFORE TRUSTING ANY DIVERGENCE
Defaults: entry at the confirmation close, target 2×ATR(14), stop 1×ATR(14), 20-bar horizon (expiry marks to close). All adjustable. With the default 2:1 bracket, average R ≈ 3 × win rate − 1 for non-gap resolutions, so the table's internal consistency can be sanity-checked by eye. These statistics measure raw divergence behavior under one fixed mechanical rule on the loaded chart history. They are not a backtest of a complete trading plan, they are not predictive of future results, and small samples are noise. Open (unresolved) simulations are shown in the table header and excluded from N.
DISPLAY & CUSTOMIZATION
- Lines on the RSI pane, the price chart, or both; info tags toggle per pane independently of the lines
- Tag styles: colored bubble or clean floating text; compact or detailed text (RSI change and price %); hover any tag for the full tooltip (type, RSI from→to, price from→to, bars apart, position vs the 50 line)
- Optional forward projection ray per divergence line, with its own color source, style, width, and transparency
- Optional freshness fade: older lines grow progressively more transparent so the newest stands out
- Discreet pivot tick marks on the RSI curve and on candles, styled per side
- The stock RSI visuals (band background, OB/OS gradients) can each be hidden for a clean pane
- Info table (RSI value, 50-line bias, last pivots, last divergence and its age) and outcome table, each position-selectable; both flash green or red for a configurable number of bars when a new bullish or bearish divergence confirms
- Array-managed object pools with configurable caps keep the script inside Pine's drawing limits; oldest drawings trim automatically and statistics are never trimmed
ALERTS
Five alertcondition triggers (one per type plus "Any RSI Divergence") for the standard alert dialog, and an optional dynamic alert() payload ("Any alert() function call") carrying live detail: ticker, timeframe, type, RSI from→to, price from→to, bars apart.
HOW TO USE IT
Works on any symbol and adapts to the chart timeframe. A reasonable workflow: run all four types with outcome tracking on, let the table accumulate, then disable the types showing no edge on your market and keep those that do. Regular divergences are conventionally read as reversal context and hidden divergences as continuation context; treat both as context alongside your own structure and trend analysis, not as standalone entries.
KNOWN BEHAVIOR / LIMITATIONS
- Confirmation lag is by design: a divergence cannot exist until its pivot confirms, so the signal appears "Pivot Lookback Right" bars after the pivot bar. After confirmation, signals do not repaint.
- Divergence lines and labels connect back to past pivots by nature; the drawing extends into the past, the signal timing does not.
- The outcome simulator works from confirmed OHLC bars; intrabar sequence is unknowable from OHLC, hence the conservative stop-first rule.
- Intended for standard candle/bar charts; synthetic chart types (Heikin Ashi, Renko, etc.) distort the price legs and the simulation.
The base RSI calculation and pane visuals reproduce TradingView's built-in RSI so the script can serve as a drop-in replacement; the divergence detection, drawing system, outcome tracking, and alert logic are original to this script.
For education and analysis only. Nothing here is financial advice, and past behavior of any signal does not guarantee future results.
Versionshinweise
Changes Made:Split the band background into three inline controls in "RSI Settings": the existing show/hide toggle, plus a new color picker (i_rsiBgCol) and transparency field (i_rsiBgTransp), following the same toggle · color · transparency column pattern as the rest of the script.
The fill() for "RSI Background Fill" now builds its color from those inputs via color.new(i_rsiBgCol, i_rsiBgTransp) instead of the hardcoded color.rgb(126, 87, 194, 90).
Versionshinweise
█ THE EXTERNAL SIGNAL BUSFive hidden data streams (display-none plots — invisible on the chart, selectable in any Source dropdown):
EXT: Regular Div
EXT: Hidden Div
EXT: Any Divergence
EXT: Any Bullish Div
EXT: Any Bearish Div
Protocol: each stream emits +1 on the bar a bullish divergence of its category confirms, −1 for bearish, 0 otherwise — impulse events, one per confirmation. Any script reading a source input can consume them (≥ +0.5 = bullish event, ≤ −0.5 = bearish).
Two ways to use the bus: as a SIGNAL — wire a stream into a companion expectancy-measurement tool and get bracket-simulated statistics for divergences, optionally split by market regime; or as a GATE — qualify another indicator's entries by "a bullish divergence fired within the last N bars." When gating, set the consuming tool's memory window to at least this tool's confirmation lag (the Pivot Lookback Right), so the gate covers the gap between the pivot and its confirmation.
Versionshinweise
v1.1 — Outcome Paint + Wilson Confidence Intervals- Outcome-Painted Divergences (new "Outcome Paint" group, default Off): when the tracker resolves a divergence's simulated bracket, its lines and projections repaint by result — Win/Loss Recolor, or Type Color with dimmed losers. An optional ✓/✗ suffix appends the result to the divergence's tags, with the R multiple and bars-to-resolution added to the tag tooltip. Open trades always render normally until they resolve, and painted lines are exempt from the freshness fade. The chart becomes its own scoreboard.
- Outcome table statistics upgraded: Win% now shows a Wilson 95% confidence interval (58±24 style; exact bounds in each cell's tooltip) and a ★ awarded only when the exact Wilson lower bound clears the bracket's breakeven win rate (stop ÷ (stop + target), shown live in the header). Type rows below the new Min N threshold render dimmed — small samples should look like noise. Same statistical machinery as the Setup Expectancy Lab, so a starred row means the identical thing in both tools.
Defaults preserve existing behavior: rendering is identical to the prior version with Outcome Paint off; only the outcome table's Win% cells and header are upgraded. All statistics remain measurements of historical simulations under one fixed mechanical rule — not predictions of future results.
Versionshinweise
v1.1.2 — Self-auditing outcome tooltips. Hovering a resolved divergence's ✅/❌ tag now shows the complete trade record behind the verdict: how the bracket resolved (stop hit, target hit, gap fill with the actual fill price, or horizon expiry with the marked close), plus the Entry, Stop, and Target prices — with entry stated as "pivot +N bars," since entry occurs at the confirmation close, not at the pivot where the tag sits. Every mark is now verifiable against the chart without ATR math. Tooltip-only: detection, statistics, painting, and rendering are unchanged.Versionshinweise
v1.2 — Recent row (rolling window). The outcome table gains a "Last 20" row: Win% (with the same Wilson 95% CI and breakeven ★) and Exp R over the most recent K resolved trades, pooled across all four divergence types — the drift detector. Compare it against the All row: a healthy lifetime record with a sagging recent window means the divergences' character on this symbol has changed. The row's tooltip carries the window's median R, and the All row's tooltip now carries the lifetime median (medians are robust to gap outliers where means are not). Window size adjustable (default 20); the row is exempt from Min-N dimming — its small sample is by design, and the confidence interval carries the honesty. Same machinery as the Setup Expectancy Lab's Recent row, so the numbers mean the identical thing in both tools. Statistics remain measurements of historical simulations under one fixed rule, not predictions.Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.