OPEN-SOURCE SCRIPT
Обновлено RC Tools - Divergence Detector

RC Tools — Divergence Detector
────────────────────────────────────────────────────────────────────
█ OVERVIEW
Most divergence tools pattern-match swing highs and lows, which is finicky and often technically repaints — pivots can un-confirm as new bars form. This tool instead measures rolling correlation between price and a momentum oscillator of your choice. When price and momentum stop agreeing, that disagreement is the divergence — measured continuously, not detected as a one-off pattern.
█ WHAT IT DOES
Plots the rolling correlation between price and a selectable oscillator (RSI, MACD line, Rate of Change, or a custom source) on a -1 to +1 scale. Classifies each confirmed bar into one of three states — Confirmed Trend, Bearish Divergence, Bullish Divergence — colours the chart background accordingly, and shows a table with the current state, how long price has been in it, and historical base rates (average forward return and win rate) for each divergence state.
█ THE THEORY BEHIND IT
A genuine trend has price and momentum moving together — new highs accompanied by strengthening momentum, new lows by weakening momentum. When that relationship breaks down — price continues in one direction while the oscillator stops confirming it — that is a divergence. Rather than searching for specific swing-point patterns (which depend on exactly which pivots you pick and can shift as price continues), this tool asks the more direct statistical question: over the last N bars, how closely have price and the oscillator actually moved together? A strong positive correlation means they agree. A correlation that has dropped toward zero or negative means they have stopped agreeing, regardless of what any single pivot looks like.
█ HOW IT IS CALCULATED
1. Compute the selected oscillator: RSI, MACD line (fast EMA minus slow EMA), Rate of Change %, or a custom source you provide.
2. Compute the rolling Pearson correlation between price (close) and the oscillator over a configurable window (default 14 bars).
3. If that correlation falls below a threshold (default 0.0), price and momentum are no longer confirming each other — a divergence state.
4. The divergence is labelled Bearish if price has been rising over a short lookback (momentum failing to confirm continued strength) or Bullish if price has been falling (momentum failing to confirm continued weakness).
Classification occurs ONLY on confirmed bar close — the state and the displayed correlation are computed and committed together, so they can never disagree mid-bar or flip back and forth as the current bar forms.
█ SETTINGS & CONFIGURATION
• Oscillator (default RSI) — RSI / MACD Line / Rate of Change % / Custom Source
• RSI / MACD / Rate of Change lookbacks (defaults 14 / 12+26 / 20)
• Correlation Window (default 14 bars) — how far back the co-movement is measured
• Divergence Threshold (default 0.0) — the correlation level below which price and momentum are considered to have stopped agreeing
• Price Direction Lookback (default 5 bars) — used only to label a divergence bullish or bearish
• Forward Return Window (default 20 bars) — the horizon used for the base-rate table
• Paint Main Chart Background — toggle off if you only want the correlation pane
█ HOW TO USE IT
Use it as a warning flag on an existing trend read, not as a standalone entry signal. Example: if you're long into a rally and the background flags Bearish Divergence, that's a cue to tighten risk management or look for confirmation elsewhere before assuming the move continues unchecked — it is not, by itself, a sell signal. Check the base-rate table's sample count before treating any single divergence reading as meaningfully predictive.
Works on any asset and timeframe with sufficient history for the correlation window.
█ LIMITATIONS
• Divergence describes a PRESENT disagreement between price and momentum. It does not predict a reversal, and any use of it as a forecast is a misuse.
• Correlation is measured over a rolling window and is noisy by nature — expect it to cross the threshold repeatedly in choppy, range-bound conditions.
• The oscillator itself is not plotted, only its correlation with price — this keeps the pane on one consistent scale regardless of which oscillator is selected (RSI is bounded 0-100, MACD line is unbounded, etc.).
• The bullish/bearish label depends on a short price-direction lookback, which can flip near genuine turning points independently of the correlation reading itself.
• Historical base-rate stats need a meaningful sample count (check N) before being trusted, especially for less common states.
• This script does NOT repaint. All classification updates on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past behaviour of any divergence state does not indicate future results. Trade at your own risk.
────────────────────────────────────────────────────────────────────
█ OVERVIEW
Most divergence tools pattern-match swing highs and lows, which is finicky and often technically repaints — pivots can un-confirm as new bars form. This tool instead measures rolling correlation between price and a momentum oscillator of your choice. When price and momentum stop agreeing, that disagreement is the divergence — measured continuously, not detected as a one-off pattern.
█ WHAT IT DOES
Plots the rolling correlation between price and a selectable oscillator (RSI, MACD line, Rate of Change, or a custom source) on a -1 to +1 scale. Classifies each confirmed bar into one of three states — Confirmed Trend, Bearish Divergence, Bullish Divergence — colours the chart background accordingly, and shows a table with the current state, how long price has been in it, and historical base rates (average forward return and win rate) for each divergence state.
█ THE THEORY BEHIND IT
A genuine trend has price and momentum moving together — new highs accompanied by strengthening momentum, new lows by weakening momentum. When that relationship breaks down — price continues in one direction while the oscillator stops confirming it — that is a divergence. Rather than searching for specific swing-point patterns (which depend on exactly which pivots you pick and can shift as price continues), this tool asks the more direct statistical question: over the last N bars, how closely have price and the oscillator actually moved together? A strong positive correlation means they agree. A correlation that has dropped toward zero or negative means they have stopped agreeing, regardless of what any single pivot looks like.
█ HOW IT IS CALCULATED
1. Compute the selected oscillator: RSI, MACD line (fast EMA minus slow EMA), Rate of Change %, or a custom source you provide.
2. Compute the rolling Pearson correlation between price (close) and the oscillator over a configurable window (default 14 bars).
3. If that correlation falls below a threshold (default 0.0), price and momentum are no longer confirming each other — a divergence state.
4. The divergence is labelled Bearish if price has been rising over a short lookback (momentum failing to confirm continued strength) or Bullish if price has been falling (momentum failing to confirm continued weakness).
Classification occurs ONLY on confirmed bar close — the state and the displayed correlation are computed and committed together, so they can never disagree mid-bar or flip back and forth as the current bar forms.
█ SETTINGS & CONFIGURATION
• Oscillator (default RSI) — RSI / MACD Line / Rate of Change % / Custom Source
• RSI / MACD / Rate of Change lookbacks (defaults 14 / 12+26 / 20)
• Correlation Window (default 14 bars) — how far back the co-movement is measured
• Divergence Threshold (default 0.0) — the correlation level below which price and momentum are considered to have stopped agreeing
• Price Direction Lookback (default 5 bars) — used only to label a divergence bullish or bearish
• Forward Return Window (default 20 bars) — the horizon used for the base-rate table
• Paint Main Chart Background — toggle off if you only want the correlation pane
█ HOW TO USE IT
Use it as a warning flag on an existing trend read, not as a standalone entry signal. Example: if you're long into a rally and the background flags Bearish Divergence, that's a cue to tighten risk management or look for confirmation elsewhere before assuming the move continues unchecked — it is not, by itself, a sell signal. Check the base-rate table's sample count before treating any single divergence reading as meaningfully predictive.
Works on any asset and timeframe with sufficient history for the correlation window.
█ LIMITATIONS
• Divergence describes a PRESENT disagreement between price and momentum. It does not predict a reversal, and any use of it as a forecast is a misuse.
• Correlation is measured over a rolling window and is noisy by nature — expect it to cross the threshold repeatedly in choppy, range-bound conditions.
• The oscillator itself is not plotted, only its correlation with price — this keeps the pane on one consistent scale regardless of which oscillator is selected (RSI is bounded 0-100, MACD line is unbounded, etc.).
• The bullish/bearish label depends on a short price-direction lookback, which can flip near genuine turning points independently of the correlation reading itself.
• Historical base-rate stats need a meaningful sample count (check N) before being trusted, especially for less common states.
• This script does NOT repaint. All classification updates on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past behaviour of any divergence state does not indicate future results. Trade at your own risk.
Информация о релизе
Removed Performance TableСкрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.