OPEN-SOURCE SCRIPT

Open Interest Z-Score [BackQuant]

1 205
Open Interest Z-Score [BackQuant]
A standardized pressure gauge for futures positioning that turns multi venue open interest into a Z score, so you can see how extreme current positioning is relative to its own history and where leverage is stretched, decompressing, or quietly re loading.

What this is
This indicator builds a single synthetic open interest series by aggregating futures OI across major derivatives venues, then standardises that aggregated OI into a rolling Z score. Instead of looking at raw OI or a simple change, you get a normalized signal that says "how many standard deviations away from normal is positioning right now", with optional smoothing, reference bands, and divergence detection against price.

You can render the Z score in several plotting modes:
  • Line for a clean, classic oscillator.
  • Colored line that encodes both sign and momentum of OI Z.
  • Oscillator histogram that makes impulses and compressions obvious.


The script also includes:
  • Aggregated open interest across Binance, Bybit, OKX, Bitget, Kraken, HTX, and Deribit, using multiple contract suffixes where applicable.
  • Choice of OI units, either coin based or converted to USD notional.
  • Standard deviation reference lines and adaptive extreme bands.
  • A flexible smoothing layer with multiple moving average types.
  • Automatic detection of regular and hidden divergences between price and OI Z.
  • Alerts for zero line and ±2 sigma crosses.


Aggregated open interest source
At the core is the same multi venue OI aggregation engine as in the OI RSI tool, adapted from NoveltyTrade's work and extended for this use case. The indicator:
  • Anchors on the current chart symbol and its base currency.
  • Loops over a set of exchanges, gated by user toggles:
    Binance.
    Bybit.
    OKX.
    Bitget.
    Kraken.
    HTX.
    Deribit.
  • For each exchange, loops over several contract suffixes such as USDT.P, USD.P, USDC.P, USD.PM to cover the common perp and margin styles.
  • Requests OI candles for each exchange plus suffix pair into a small custom OI type that carries open, high, low and close of open interest.
  • Converts each OI stream into a common unit via the sw method:
    In COIN mode, OI is normalized relative to the coin.
    In USD mode, OI is scaled by price to approximate notional.
    Exchange specific scaling factors are applied where needed to match contract multipliers.
  • Accumulates all valid OI candles into a single combined OI "candle" by summing open, high, low and close across venues.


The result is oiClose, a synthetic close for aggregated OI that represents cross venue positioning. If there is no valid OI data for the symbol after this process, the script throws a clear runtime error so you know the market is unsupported rather than quietly plotting nonsense.

How the Z score is computed
Once the aggregated OI close is available, the indicator computes a rolling Z score over a configurable lookback:
  • Define subject as the aggregated OI close.
  • Compute a rolling mean of this subject with EMA over Z Score Lookback Period.
  • Compute a rolling standard deviation over the same length.
  • Subtract the mean from the current OI and divide by the standard deviation.


This gives a raw Z score:
  • oi_z_raw = (subject − mean) ÷ stdDev.


Instead of plotting this raw value directly, the script passes it through a smoothing layer:
  • You pick a Smoothing Type and Smoothing Period.
  • Choices include SMA, HMA, EMA, WMA, DEMA, RMA, linear regression, ALMA, TEMA, and T3.
  • The helper ma function applies the chosen smoother to the raw Z score.


The result is oi_z, a smoothed Z score of aggregated open interest. A separate EMA with EMA Period is then applied on oi_z to create a signal line ma that can be used for crossovers and trend reads.

Plotting modes
The Plotting Type input controls how this Z score is rendered:

1) Line
In line mode:
  • The smoothed OI Z score is plotted as a single line using Base Line Color.
  • The EMA overlay is optionally plotted if Show EMA is enabled.
  • This is the cleanest view when you want to treat OI Z like a standard oscillator, watching for zero line crosses, swings, and divergences.


2) Colored Line
Colored line mode adds conditional color logic to the Z score:
  • If the Z score is above zero and rising, it is bright green, representing positive and strengthening positioning pressure.
  • If the Z score is above zero and falling, it shifts to a cooler cyan, representing positive but weakening pressure.
  • If the Z score is below zero and falling, it is bright red, representing negative and strengthening pressure (growing net de risking or shorting).
  • If the Z score is below zero and rising, it is dark red, representing negative but recovering pressure.


This mapping makes it easy to see not only whether OI is above or below its historical mean, but also whether that deviation is intensifying or fading.

3) Oscillator
Oscillator mode turns the Z score into a histogram:
  • The smoothed Z score is plotted as vertical columns around zero.
  • Column colors use the same conditional palette as colored line mode, based on sign and change direction.
  • The histogram base is zero, so bars extend up into positive Z and down into negative Z.


Oscillator mode is useful when you care about impulses in positioning, for example sharp jumps into positive Z that coincide with fast builds in leverage, or deep spikes into negative Z that show aggressive flushes.

4) None
If you only want reference lines, extreme bands, divergences, or alerts without the base oscillator, you can set plotting to None and keep the rest of the tooling active.

The EMA overlay respects plotting mode and only appears when a visible Z score line or histogram is present.

Reference lines and standard deviation levels
The Select Reference Lines input offers two styles:

Standard Deviation Levels
  • Plots small markers at zero.
  • Draws thin horizontal lines at +1, +2, −1 and −2 Z.
  • Acts like a classic Z score ladder, zero as mean, ±1 as normal band, ±2 as outer band.


This mode is ideal if you want a textbook statistical framing, using ±1 and ±2 sigma as standard levels for "normal" versus "extended" positioning.

Extreme Bands
Extreme bands build on the same ±1 and ±2 lines, then add:
  • Upper outer band between +3 and +4 Z.
  • Lower outer band between −3 and −4 Z.
  • Dynamic fill colors inside these bands:
    • If the Z score is positive, the upper band fill turns red with an alpha that scales with the magnitude of |Z|, capped at a chosen max strength. Stronger deviations towards +4 produce more opaque red fills.
    • If the Z score is negative, the lower band fill turns green with the same adaptive alpha logic, highlighting deep negative deviations.
    • Opposite side bands remain a faint neutral white when not in use, so they still provide structural context without shouting.


This creates a visual "danger zone" for position crowding. When the Z score enters these outer bands, open interest is many standard deviations away from its mean and you are dealing with rare but highly loaded positioning states.

Z score as a positioning pressure gauge
Because this is a Z score of aggregated open interest, it measures how unusual current positioning is relative to its own recent history, not just whether OI is rising or falling:
  • Z near zero means total OI is roughly in line with normal conditions for your lookback window.
  • Positive Z means OI is above its recent mean. The further above zero, the more "crowded" or extended positioning is.
  • Negative Z means OI is below its recent mean. Deep negatives often mark post flush environments where leverage has been cleared and the market is under positioned.


The smoothing options help control how much noise you want in the signal:
  • Short Z score lookback and short smoothing will react quickly, suited for short term traders watching intraday positioning shocks.
  • Longer Z score lookback with smoother MA types (EMA, RMA, T3) give a slower, more structural view of where the crowd sits over days to weeks.


Divergences between price and OI Z
The indicator includes automatic divergence detection on the Z score versus price, using pivot highs and lows:
  • You configure Pivot Lookback Left and Pivot Lookback Right to control swing sensitivity.
  • Pivots are detected on the OI Z series.
  • For each eligible pivot, the script compares OI Z and price at the last two pivots.


It looks for four patterns:
  • Regular Bullish – price makes a lower low, OI Z makes a higher low. This can indicate selling exhaustion in positioning even as price washes out. These are marked with a line and a label "ℝ" below the oscillator, in the bullish color.
  • Hidden Bullish – price makes a higher low, OI Z makes a lower low. This suggests continuation potential where price holds up while positioning resets. Marked with "ℍ" in the bullish color.
  • Regular Bearish – price makes a higher high, OI Z makes a lower high. This is a classic warning sign of trend exhaustion, where price pushes higher while OI Z fails to confirm. Marked with "ℝ" in the bearish color.
  • Hidden Bearish – price makes a lower high, OI Z makes a higher high. This is often seen in pullbacks within downtrends, where price retraces but positioning stretches again in the direction of the prevailing move. Marked with "ℍ" in the bearish color.


Each divergence type can be toggled globally via Show Detected Divergences. Internally, the script restricts how far back it will connect pivots, so you do not get stray signals linking very old structures to current bars.

Trading applications

Crowding and squeeze risk
Z scores are a natural way to talk about crowding:
  • High positive Z in aggregated OI means the market is running high leverage compared to its own norm. If price is also extended, the risk of a squeeze or sharp unwind rises.
  • Deep negative Z means leverage has been cleaned out. While it can be painful to sit through, this environment often sets up cleaner new trends, since there is less one sided positioning to unwind.
  • The extreme bands at ±3 to ±4 highlight the rare states where crowding is most intense. You can treat these events as regime markers rather than day to day noise.


Trend confirmation and fade selection
Combine Z score with price and trend:
  • Bull trends with positive and rising Z are supported by fresh leverage, usually more persistent.
  • Bull trends with flat or falling Z while price keeps grinding up can be more fragile. Divergences and extreme bands can help identify which edges you do not want to fade and which you might.
  • In downtrends, deep negative Z that stays pinned can mean persistent de risking. Once the Z score starts to mean revert back toward zero, it can mark the early stages of stabilization.


Event and liquidation context
Around major events, you often see:
  • Rapid spikes in Z as traders rush to position.
  • Reversal and overshoot as liquidations and forced de risking clear the book.
  • A move from positive extremes through zero into negative extremes as the market transitions from crowded to under exposed.


The Z score makes that path obvious, especially in oscillator mode, where you see a block of high positive bars before the crash, then a slab of deep negative bars after the flush.

Settings overview

Z Score group
  • Plotting Type – None, Line, Colored Line, Oscillator.
  • Z Score Lookback Period – window used for mean and standard deviation on aggregated OI.
  • Smoothing Type – SMA, HMA, EMA, WMA, DEMA, RMA, linear regression, ALMA, TEMA or T3.
  • Smoothing Period – length for the selected moving average on the raw Z score.


Moving Average group
  • Show EMA – toggle EMA overlay on Z score.
  • EMA Period – EMA length for the signal line.
  • EMA Color – color of the EMA line.


Thresholds and Reference Lines group
  • Select Reference Lines – None, Standard Deviation Levels, Extreme Bands.
  • Standard deviation lines at 0, ±1, ±2 appear in both modes.
  • Extreme bands add filled zones at ±3 to ±4 with adaptive opacity tied to |Z|.


Extra Plotting and UI
  • Base Line Color – default color for the simple line mode.
  • Line Width – thickness of the oscillator line.
  • Positive Color – positive or bullish condition color.
  • Negative Color – negative or bearish condition color.


Divergences group
  • Show Detected Divergences – master toggle for divergence plotting.
  • Pivot Lookback Left and Pivot Lookback Right – how many bars left and right to define a pivot, controlling divergence sensitivity.


Open Interest Source group
  • OI Units – COIN or USD.
  • Exchange toggles for Binance, Bybit, OKX, Bitget, Kraken, HTX, Deribit.
  • Internally, all enabled exchanges and contract suffixes are aggregated into one synthetic OI series.


Alerts included
The indicator defines alert conditions for several key events:
  • OI Z Score Positive – Z crosses above zero, aggregated OI moves from below mean to above mean.
  • OI Z Score Negative – Z crosses below zero, aggregated OI moves from above mean to below mean.
  • OI Z Score Enters +2σ – Z enters the +2 band and above, marking extended positive positioning.
  • OI Z Score Enters −2σ – Z enters the −2 band and below, marking extended negative positioning.


Tie these into your strategy to be notified when leverage moves from normal to extended states.

Notes
This indicator does not rely on price based oscillators. It is a statistical lens on cross venue open interest, which makes it a complementary tool rather than a replacement for your existing price or volume signals. Use it to:
  • Quantify how unusual current futures positioning is compared to recent history.
  • Identify crowded leverage phases that can fuel squeezes.
  • Spot structural divergences between price and positioning.
  • Frame risk and opportunity around events and regime shifts.


It is not a complete trading system. Combine it with your own entries, exits and risk rules to get the most out of what the Z score is telling you about positioning pressure under the hood of the market.

免责声明

这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。