Perfected FlowScript
Open interest Z-Score
Open Interest Z-Score V2 is indexed as 011_open_interest_z_score.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
offchart
Axis
true
Size
14.3 KB
Lines
354
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme High OI
line 294:9
Trigger
(showShapes) && (crossUp2)
Value
smoothedZ
Deps
crossUp2:var, showShapes:input
Extreme Low OI
line 304:9
Trigger
(showShapes) && (crossDn2)
Value
smoothedZ
Deps
crossDn2:var, showShapes:input
Elevated High OI
line 314:9
Trigger
(showShapes) && (crossUp1)
Value
smoothedZ
Deps
crossUp1:var, showShapes:input
Elevated Low OI
line 324:9
Trigger
(showShapes) && (crossDn1)
Value
smoothedZ
Deps
crossDn1:var, showShapes:input
Exit Extreme+
line 334:9
Trigger
(showShapes) && (exitExtremePos)
Value
smoothedZ
Deps
exitExtremePos:var, showShapes:input
Exit Extreme-
line 344:9
Trigger
(showShapes) && (exitExtremeNeg)
Value
smoothedZ
Deps
exitExtremeNeg:var, showShapes:input
011_open_interest_z_score.flowscript
source path: kscripts/perfected/011_open_interest_z_score.flowscript · sha256:3868b7ecbf561938cc6b1020959a8afb0023b26daab4e941107f988a65c9ff4d
//@version=2
// ============================================================================
// Open Interest Z-Score V2 — Production-Grade Futures Positioning Indicator
// Author: abetrade (@abetrade) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #open, #interest, #zscore, #positioning, #futures
//
// Z-score normalization of open interest levels over a rolling window, with
// σ-band visualization, regime-coded color, extreme-deviation shape markers,
// and an OI trend-direction indicator. Flags statistically unusual participation
// useful for detecting late-stage euphoria (high OI z-score) or capitulation
// (low OI z-score).
//
// FORMULA FOUNDATION:
// 1. Z-Score: Z_t = (OI_t − μ_OI) / σ_OI where μ = SMA(OI, N), σ = StdDev(OI, N)
// per Zhao & Palomar (2018) mean-reversion framework.
// 2. Regime Segmentation: Extreme (>±2σ), Elevated (±1σ to ±2σ), Neutral (−1σ to +1σ)
// per standard statistical practice and Christensen et al. (2017) OI predictability.
// 3. OI Trend Direction: slope of SMA(OI, N) — rising OI = new participation;
// falling OI = unwinding / capitulation.
// 4. OI-Price-Volume Framework (classical):
// Rising price + Rising OI = strong trend; Rising price + Falling OI = short squeeze.
//
// RESEARCH BASIS:
// • Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts", J. Finance 50(1), 281–300.
// Foundational link between OI levels and future volatility.
// • Yang Xu et al. (2021), "An Empirical Analysis of the Price Volatility
// Characteristics of China's Soybean Futures Market". Unexpected OI changes
// have larger volatility impact than expected changes — validates z-score
// as a real-time information-flow indicator.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// Z-score normalization framework with entry thresholds at ±1σ or ±2σ.
// • Christensen et al. (2017), "Financialization in Commodity Markets" (NBER 23766).
// Cites Hong & Yogo (2012): aggregate OI coefficient is significantly positive
// for futures returns — OI predicts returns at the commodity level.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Rev. Financial Studies 22(6), 2201–2238. Liquidity spirals: when leverage
// is tight, OI contraction signals deleveraging risk.
// • LeviathanCapital (2024), "Open Interest Delta". OI Delta maps net change in
// open interest at each price level; positive delta clusters act as defense zones.
// ============================================================================
define(
title="Open Interest Z-Score V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Calculation ---
var lookback = input(name="lookback", type="number", defaultValue=30, label="Z-Score Lookback Period", constraints={min: 5, max: 252, step: 1}, group="Calculation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Calculation")
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show Raw Z-Score Line", group="Calculation")
// --- Sigma Bands ---
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show ±1σ / ±2σ / ±3σ Bands", group="Sigma Bands")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Band Fill Areas", group="Sigma Bands")
var showBandLabels = input(name="showBandLabels", type="boolean", defaultValue=false, label="Show Band Label Lines", group="Sigma Bands")
// --- Display ---
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Deviation Shapes", group="Display")
var showTrendIndicator = input(name="showTrendIndicator", type="boolean", defaultValue=true, label="Show OI Trend Direction", group="Display")
var showBarColors = input(name="showBarColors", type="boolean", defaultValue=true, label="Show Colored Z-Score Bars", group="Display")
// --- Colors ---
var posColor = input(name="posColor", type="color", defaultValue="#26a69a", label="Positive Z-Score Color", group="Colors")
var negColor = input(name="negColor", type="color", defaultValue="#ef5350", label="Negative Z-Score Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremePosColor = input(name="extremePosColor", type="color", defaultValue="#00e676", label="Extreme Positive Color", group="Colors")
var extremeNegColor = input(name="extremeNegColor", type="color", defaultValue="#ff1744", label="Extreme Negative Color", group="Colors")
var trendUpColor = input(name="trendUpColor", type="color", defaultValue="#4db6ac", label="OI Rising Color", group="Colors")
var trendDownColor = input(name="trendDownColor", type="color", defaultValue="#ef9a9a", label="OI Falling Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oiClose = oi.close
// NaN guard — prevent execution before OI data is loaded
if (isnan(oiClose[0])) {
return
}
// ------------------------------------------------------------------------------
// Z-Score Computation
// ------------------------------------------------------------------------------
// Z_t = (OI_t − μ_OI) / σ_OI
// per Zhao & Palomar (2018) mean-reversion framework.
var meanOI = sma(oiClose, lookback)
var sdOI = stdev(oiClose, lookback)
var rawZ = sdOI > 0 ? (oiClose - meanOI) / sdOI : 0.0
var smoothedZ = ema(rawZ, smoothLen)
// ------------------------------------------------------------------------------
// OI Trend Direction Indicator
// ------------------------------------------------------------------------------
// Rising OI = new participation entering (trend strength or early euphoria)
// Falling OI = positions unwinding / capitulation / short squeeze
// Uses slope of meanOI over a short lookback to determine direction.
var trendSlope = meanOI - meanOI[5]
var trendUp = trendSlope > 0
var trendDn = trendSlope < 0
var trendFlat = !trendUp && !trendDn
// ------------------------------------------------------------------------------
// Regime Detection (Statistical Thresholds)
// ------------------------------------------------------------------------------
// Five-segment classification based on standard deviation thresholds:
// Extreme High: Z > +2
// Elevated High: +1 < Z ≤ +2
// Neutral: −1 ≤ Z ≤ +1
// Elevated Low: −2 ≤ Z < −1
// Extreme Low: Z < −2
var zRegime = 0 // 0=neutral, 1=elevated+, 2=extreme+, -1=elevated-, -2=extreme-
if (smoothedZ > 2.0) {
zRegime = 2
} else if (smoothedZ > 1.0) {
zRegime = 1
} else if (smoothedZ < -2.0) {
zRegime = -2
} else if (smoothedZ < -1.0) {
zRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks extreme-event counts, session z-score extremes, and regime transitions.
static lastZRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremePosCount = 0
static extremeNegCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (smoothedZ > sessionHighZ) {
sessionHighZ = smoothedZ
}
if (smoothedZ < sessionLowZ) {
sessionLowZ = smoothedZ
}
if (lastZRegime != zRegime) {
lastZRegime = zRegime
regimeChangeCount = regimeChangeCount + 1
}
if (zRegime == 2) {
extremePosCount = extremePosCount + 1
} else if (zRegime == -2) {
extremeNegCount = extremeNegCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types
// ------------------------------------------------------------------------------
// Zero reference line
hline(value=0, color="#ffffff30", width=1)
// Sigma band lines (±1σ, ±2σ, ±3σ) — Zhao & Palomar (2018) threshold framework
if (showBands) {
hline(value=3, color=opacity(extremePosColor, 15), width=1)
hline(value=2, color=opacity(extremePosColor, 25), width=1)
hline(value=1, color=opacity(posColor, 30), width=1)
hline(value=-1, color=opacity(negColor, 30), width=1)
hline(value=-2, color=opacity(extremeNegColor, 25), width=1)
hline(value=-3, color=opacity(extremeNegColor, 15), width=1)
}
// Sigma band fill areas (visual backdrop)
if (showBandFill) {
// +1σ to +2σ elevated zone
plotLine(
value=[1, 2],
width=0,
colors=[opacity(posColor, 5)],
fill=opacity(posColor, 6),
label=["Elevated+ Zone"],
desc=["Background fill for elevated positive z-score zone (+1σ to +2σ)"]
)
// -1σ to -2σ elevated zone
plotLine(
value=[-1, -2],
width=0,
colors=[opacity(negColor, 5)],
fill=opacity(negColor, 6),
label=["Elevated- Zone"],
desc=["Background fill for elevated negative z-score zone (-1σ to -2σ)"]
)
// +2σ to +3σ extreme zone
plotLine(
value=[2, 3],
width=0,
colors=[opacity(extremePosColor, 8)],
fill=opacity(extremePosColor, 8),
label=["Extreme+ Zone"],
desc=["Background fill for extreme positive z-score zone (+2σ to +3σ)"]
)
// -2σ to -3σ extreme zone
plotLine(
value=[-2, -3],
width=0,
colors=[opacity(extremeNegColor, 8)],
fill=opacity(extremeNegColor, 8),
label=["Extreme- Zone"],
desc=["Background fill for extreme negative z-score zone (-2σ to -3σ)"]
)
}
// Z-score line with regime-coded color
var zLineColor = zRegime == 2 ? extremePosColor : (zRegime == 1 ? posColor : (zRegime == -2 ? extremeNegColor : (zRegime == -1 ? negColor : neutralColor)))
plotLine(
value=smoothedZ,
width=2,
colors=[zLineColor],
label=["OI Z-Score"],
desc=["Open Interest z-score: (OI − SMA) / StdDev. Regime-coded by statistical threshold."]
)
// Fill area between z-score line and zero
plotLine(
value=[smoothedZ, 0],
width=0,
colors=[zLineColor, zLineColor],
fill=opacity(zLineColor, 12),
label=["Z Fill", "Zero"],
desc=["Fill area between z-score line and zero reference", "Zero reference line"]
)
// Raw z-score line (optional, for comparison with smoothed)
if (showRaw) {
plotLine(
value=rawZ,
width=1,
colors=[opacity(zLineColor, 40)],
label=["Raw Z-Score"],
desc=["Unsmoothed open interest z-score (noisy but responsive)"]
)
}
// Colored z-score bars (optional histogram view)
if (showBarColors) {
var barColor = zRegime > 0 ? (zRegime == 2 ? extremePosColor : posColor) : (zRegime < 0 ? (zRegime == -2 ? extremeNegColor : negColor) : neutralColor)
plotBar(
value=smoothedZ,
colors=[barColor],
width=1,
label=["Z-Score Bars"],
desc=["Open interest z-score as colored histogram bars"]
)
}
// OI Trend direction indicator (separate faint line)
if (showTrendIndicator) {
var trendVal = trendUp ? 0.15 : (trendDn ? -0.15 : 0.0)
var trendColor = trendUp ? trendUpColor : (trendDn ? trendDownColor : neutralColor)
plotLine(
value=trendVal,
width=1,
colors=[trendColor],
label=["OI Trend"],
desc=["OI trend direction: positive = rising participation, negative = unwinding"]
)
}
// Extreme deviation shape markers (crossing ±2σ thresholds)
if (showShapes) {
var crossUp2 = smoothedZ > 2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= 2.0
var crossDn2 = smoothedZ < -2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= -2.0
var crossUp1 = smoothedZ > 1.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= 1.0 && smoothedZ[1] > -1.0
var crossDn1 = smoothedZ < -1.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= -1.0 && smoothedZ[1] < 1.0
var exitExtremePos = smoothedZ < 2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= 2.0
var exitExtremeNeg = smoothedZ > -2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= -2.0
if (crossUp2) {
plotShape(
value=smoothedZ,
shape="diamond",
color=extremePosColor,
width=4,
label=["Extreme High OI"],
desc=["Z-score crossed above +2σ — statistically unusual high open interest (euphoria risk)"]
)
}
if (crossDn2) {
plotShape(
value=smoothedZ,
shape="diamond",
color=extremeNegColor,
width=4,
label=["Extreme Low OI"],
desc=["Z-score crossed below -2σ — statistically unusual low open interest (capitulation risk)"]
)
}
if (crossUp1) {
plotShape(
value=smoothedZ,
shape="triangleup",
color=posColor,
width=3,
label=["Elevated High OI"],
desc=["Z-score crossed above +1σ — elevated open interest above rolling mean"]
)
}
if (crossDn1) {
plotShape(
value=smoothedZ,
shape="triangledown",
color=negColor,
width=3,
label=["Elevated Low OI"],
desc=["Z-score crossed below -1σ — depressed open interest below rolling mean"]
)
}
if (exitExtremePos) {
plotShape(
value=smoothedZ,
shape="circle",
color=neutralColor,
width=2,
label=["Exit Extreme+"],
desc=["Z-score exited extreme positive zone (mean reversion potential)"]
)
}
if (exitExtremeNeg) {
plotShape(
value=smoothedZ,
shape="circle",
color=neutralColor,
width=2,
label=["Exit Extreme-"],
desc=["Z-score exited extreme negative zone (mean reversion potential)"]
)
}
}