OPEN-SOURCE SCRIPT
Обновлено Basis Divergence Oscillator

Basis Divergence Oscillator — TradingView publication description
## Overview
The Basis Divergence Oscillator turns the **futures-versus-spot basis** (the premium or discount of a future to its cash market) into a standardized, bounded oscillator, and then looks for **divergence between price and that basis**. The idea it tests is simple: when price makes a new extreme but the premium does not confirm it, the move is more likely leverage being unwound than fresh demand.
It is a single-pane oscillator. By default it pairs NSE NIFTY index futures with the NSE:NIFTY cash index, but every data input is user-configurable, so it runs on any future that has a cash/spot counterpart, in any market and on any timeframe.
## What it plots
- A z-scored **basis oscillator** (premium expanding = up, premium shrinking toward discount = down), with a glow line and σ-based overbought/oversold levels.
- **Extreme-zone bands** (default ±3σ) with a gradient fill that deepens toward the edge.
- **Divergence lines and labels** drawn on the oscillator — regular (reversal) and hidden (continuation), in two colors.
- **In-band reversal dots** where the oscillator turns inside an extreme zone.
- Optional **price-pane marks** at the confirmation bar (all generated by this one indicator).
- A **background-adaptive status dashboard** (oscillator value in σ, zone, last divergence, last reversal, live basis in points).
## Why these components are combined (mashup rationale)
This script deliberately combines a **cross-symbol calculation**, a **normalization stage**, a **divergence engine** and a **reversal read**, because each one answers a question the others cannot, and none of them is useful here on its own:
1. **Cross-symbol basis (two instruments → one series).** The basis is `chart price − cash/spot reference`. It isolates the small premium/discount component of price, which is driven by cost of carry, financing and leverage/positioning demand — information that the instrument's own price and its own volume do not contain. This is the whole reason a second symbol is pulled: remove either symbol and the basis is undefined. The two-symbol construction is intrinsic, not decorative.
2. **Standardization (rolling z-score).** The raw basis drifts slowly with time-to-expiry and carry, and its scale differs by instrument. The z-score detrends that drift and expresses the basis in standard-deviation units, so "overbought/oversold" and the extreme bands mean the same thing on NIFTY, on a commodity future, or on a crypto perpetual. Without this step the divergence thresholds would not transfer between symbols.
3. **Divergence engine.** A plotted basis line is already common; the original payload here is reading **price-versus-basis disagreement at confirmed pivots**. The engine pairs each new price pivot with the basis oscillator's value, then requires (a) a genuine new price extreme, (b) the basis failing to confirm it, (c) a minimum oscillator gap scaled to the oscillator's own stdev, (d) the two pivots within a maximum bar distance, and (e) optionally an overbought/oversold reading at the pivot. These gates exist so the combination produces meaningful signals rather than noise.
4. **Reversal read.** Independently, the engine flags oscillator turns that occur inside the extreme bands — a complementary "exhaustion" cue to the divergence cue.
In short, the components form one pipeline: **build an independent signal (basis) → make it comparable (z-score) → surface where price and that signal disagree (divergence) and where it exhausts (reversal).** They are read together; each is incomplete alone.
## How it works (method)
- `basis = price − request.security(reference, close)` on the chart's timeframe (no lookahead).
- `oscillator = z-score(basis, normalization window)`, optionally EMA-smoothed.
- Regular and hidden divergence are detected from confirmed `pivothigh`/`pivotlow` pivots and filtered by the gates above.
- Reversals are oscillator pivots that print within the ±extreme bands.
- Pivots confirm a few bars after they occur, so a printed signal does not repaint afterward. The confirmation lag equals the pivot length.
## How to use it
1. Put the indicator on a **future** (e.g. NIFTY index futures).
2. In **Data source**, set **Reference (cash/spot) symbol** to that instrument's spot (default NSE:NIFTY). A mismatched reference makes the basis meaningless.
3. Read divergence as **context, not a trigger**: a bearish divergence (price higher high, basis lower high) says the advance is not backed by premium; a bullish divergence says the opposite. Confirm with your own structure, levels and risk process.
4. Tune the **pivot length**, **max gap** and **min oscillator gap** to your timeframe; raise them for fewer, cleaner signals.
## Originality
This is an original implementation. It is not a basis line and not a generic divergence script: it is the specific combination of a cross-symbol basis, σ-standardization that makes the read portable across markets, a multi-gate divergence engine (magnitude + distance + extreme-zone), hidden-divergence and in-band reversal detection, and a background-adaptive dashboard. The code is written from scratch; helper functions use only their arguments and built-ins.
## Credits
The basis (futures premium/discount) is explained by the **cost-of-carry / theory-of-storage** framework in futures-pricing economics — foundational work by N. Kaldor (1939) and H. Working (1948–49). **Price/oscillator divergence** is a long-established, publicly documented technical-analysis technique. This script is not affiliated with, nor endorsed by, any third party.
## Notes / limitations
- The basis needs a clean reference feed and a matched contract; on illiquid or mismatched references, or when spot and future trade on different clocks, it is noisy.
- Divergence is descriptive context, never a guarantee of reversal.
- If the reference symbol is unavailable the oscillator holds flat and the dashboard shows "n/a".
## Disclaimer
Research and educational tool only. NOT financial advice and no guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
## Overview
The Basis Divergence Oscillator turns the **futures-versus-spot basis** (the premium or discount of a future to its cash market) into a standardized, bounded oscillator, and then looks for **divergence between price and that basis**. The idea it tests is simple: when price makes a new extreme but the premium does not confirm it, the move is more likely leverage being unwound than fresh demand.
It is a single-pane oscillator. By default it pairs NSE NIFTY index futures with the NSE:NIFTY cash index, but every data input is user-configurable, so it runs on any future that has a cash/spot counterpart, in any market and on any timeframe.
## What it plots
- A z-scored **basis oscillator** (premium expanding = up, premium shrinking toward discount = down), with a glow line and σ-based overbought/oversold levels.
- **Extreme-zone bands** (default ±3σ) with a gradient fill that deepens toward the edge.
- **Divergence lines and labels** drawn on the oscillator — regular (reversal) and hidden (continuation), in two colors.
- **In-band reversal dots** where the oscillator turns inside an extreme zone.
- Optional **price-pane marks** at the confirmation bar (all generated by this one indicator).
- A **background-adaptive status dashboard** (oscillator value in σ, zone, last divergence, last reversal, live basis in points).
## Why these components are combined (mashup rationale)
This script deliberately combines a **cross-symbol calculation**, a **normalization stage**, a **divergence engine** and a **reversal read**, because each one answers a question the others cannot, and none of them is useful here on its own:
1. **Cross-symbol basis (two instruments → one series).** The basis is `chart price − cash/spot reference`. It isolates the small premium/discount component of price, which is driven by cost of carry, financing and leverage/positioning demand — information that the instrument's own price and its own volume do not contain. This is the whole reason a second symbol is pulled: remove either symbol and the basis is undefined. The two-symbol construction is intrinsic, not decorative.
2. **Standardization (rolling z-score).** The raw basis drifts slowly with time-to-expiry and carry, and its scale differs by instrument. The z-score detrends that drift and expresses the basis in standard-deviation units, so "overbought/oversold" and the extreme bands mean the same thing on NIFTY, on a commodity future, or on a crypto perpetual. Without this step the divergence thresholds would not transfer between symbols.
3. **Divergence engine.** A plotted basis line is already common; the original payload here is reading **price-versus-basis disagreement at confirmed pivots**. The engine pairs each new price pivot with the basis oscillator's value, then requires (a) a genuine new price extreme, (b) the basis failing to confirm it, (c) a minimum oscillator gap scaled to the oscillator's own stdev, (d) the two pivots within a maximum bar distance, and (e) optionally an overbought/oversold reading at the pivot. These gates exist so the combination produces meaningful signals rather than noise.
4. **Reversal read.** Independently, the engine flags oscillator turns that occur inside the extreme bands — a complementary "exhaustion" cue to the divergence cue.
In short, the components form one pipeline: **build an independent signal (basis) → make it comparable (z-score) → surface where price and that signal disagree (divergence) and where it exhausts (reversal).** They are read together; each is incomplete alone.
## How it works (method)
- `basis = price − request.security(reference, close)` on the chart's timeframe (no lookahead).
- `oscillator = z-score(basis, normalization window)`, optionally EMA-smoothed.
- Regular and hidden divergence are detected from confirmed `pivothigh`/`pivotlow` pivots and filtered by the gates above.
- Reversals are oscillator pivots that print within the ±extreme bands.
- Pivots confirm a few bars after they occur, so a printed signal does not repaint afterward. The confirmation lag equals the pivot length.
## How to use it
1. Put the indicator on a **future** (e.g. NIFTY index futures).
2. In **Data source**, set **Reference (cash/spot) symbol** to that instrument's spot (default NSE:NIFTY). A mismatched reference makes the basis meaningless.
3. Read divergence as **context, not a trigger**: a bearish divergence (price higher high, basis lower high) says the advance is not backed by premium; a bullish divergence says the opposite. Confirm with your own structure, levels and risk process.
4. Tune the **pivot length**, **max gap** and **min oscillator gap** to your timeframe; raise them for fewer, cleaner signals.
## Originality
This is an original implementation. It is not a basis line and not a generic divergence script: it is the specific combination of a cross-symbol basis, σ-standardization that makes the read portable across markets, a multi-gate divergence engine (magnitude + distance + extreme-zone), hidden-divergence and in-band reversal detection, and a background-adaptive dashboard. The code is written from scratch; helper functions use only their arguments and built-ins.
## Credits
The basis (futures premium/discount) is explained by the **cost-of-carry / theory-of-storage** framework in futures-pricing economics — foundational work by N. Kaldor (1939) and H. Working (1948–49). **Price/oscillator divergence** is a long-established, publicly documented technical-analysis technique. This script is not affiliated with, nor endorsed by, any third party.
## Notes / limitations
- The basis needs a clean reference feed and a matched contract; on illiquid or mismatched references, or when spot and future trade on different clocks, it is noisy.
- Divergence is descriptive context, never a guarantee of reversal.
- If the reference symbol is unavailable the oscillator holds flat and the dashboard shows "n/a".
## Disclaimer
Research and educational tool only. NOT financial advice and no guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
Информация о релизе
Basis Divergence Oscillator — update notesForward calibration added. Every divergence and reversal class (Reg Bull/Bear, Hidden Bull/Bear, Rev +/−) now opens a forward sample resolved by a triple-barrier (profit / stop / horizon), uniqueness-weighted and recency-decayed, reported as an edge over a zone-matched base rate (for a bearish-from-overbought basis divergence: "how often does price fall after simply being overbought?") with a Wilson interval and a multiple-testing-corrected significance star — so you can see which basis divergences actually pay.
Identity strip showing name · symbol · timeframe on the chart (theme-adaptive).
Exports bus: EXP_Osc, EXP_OscZ, EXP_Zone, EXP_Bias, EXP_RegDiv, EXP_HidDiv, EXP_Reversal, EXP_BullEdge, EXP_BearEdge, plus EXP_Basis and EXP_DataLive.
Pro dashboard adds a per-class calibration table (n · Hit% ± Wilson · base · edge, * = significant); settings reorganized into 7 groups; all toggles default-on; reference symbol stays NSE:NIFTY; author credits (Kaldor, Working) kept in the header, out of the UI.
Educational only — not financial advice. Calibration is in-sample, forward-measured at fixed barriers; the basis needs a clean, matched reference feed. Validate out-of-sample.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.