Perfected FlowScript
Open Interest Delta
OI Delta [Leviathan] Perfected is indexed as 039_open_interest_delta.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
13.9 KB
Lines
328
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Sig OI+
line 261:9
Trigger
(showShapes) && (sigUp)
Value
oiDelta
Deps
showShapes:input, sigUp:var
Sig OI-
line 271:9
Trigger
(showShapes) && (sigDn)
Value
oiDelta
Deps
showShapes:input, sigDn:var
Strong Trend
line 288:9
Trigger
(showShapes) && (regimeToStrong)
Value
oiDelta
Deps
regimeToStrong:var, showShapes:input
Short Cover
line 298:9
Trigger
(showShapes) && (regimeToCover)
Value
oiDelta
Deps
regimeToCover:var, showShapes:input
New Shorts
line 308:9
Trigger
(showShapes) && (regimeToShorts)
Value
oiDelta
Deps
regimeToShorts:var, showShapes:input
Liquidation
line 318:9
Trigger
(showShapes) && (regimeToLiquid)
Value
oiDelta
Deps
regimeToLiquid:var, showShapes:input
039_open_interest_delta.flowscript
source path: kscripts/perfected/039_open_interest_delta.flowscript · sha256:07b535291fad2c4502b7c21475e6fe7a5de590523e762a13eebb156d493ed295
//@version=2
// ============================================================================
// Open Interest Delta [Leviathan Perfected]
// Author: BackQuant (@BackQuant) | Perfected by: kScript_Perfection_Engineer
// Tags: FUTURES, #openinterest, #oidelta, #positioning, #regime
//
// Bar-to-bar change in open interest (first difference of OI) with price
// direction interpretation, four-quadrant regime classification, and shape
// markers for significant OI changes. Implements the classical OI + Price +
// Volume framework for trend strength assessment.
//
// FORMULA FOUNDATION:
// 1. OI First Difference: ΔOI_t = OI_t − OI_{t−1}. The most direct measure of
// net positioning change per bar. Positive = new contracts opened;
// negative = contracts closed. Per Yang Xu et al. (2021): unexpected OI
// changes carry more predictive power than absolute levels.
// 2. Classical Four-Quadrant Framework (BBA curriculum / ATAS 2019):
// (a) Rising price + Rising OI → Strong trend with new participation
// (b) Rising price + Falling OI → Short covering / squeeze (weak trend)
// (c) Falling price + Rising OI → New shorts entering (bearish confirmation)
// (d) Falling price + Falling OI → Long liquidation / capitulation
// 3. OI Change Percentage: %ΔOI = (OI_t − OI_{t−1}) / OI_{t−1} × 100.
// Normalizes for instruments with different OI scales.
// 4. Significant Change Detection: |ΔOI| > k × SMA(|ΔOI|, N) flags bars
// with above-average positioning activity. Per Yang Xu et al. (2021),
// above-average OI changes are information flow proxies.
//
// RESEARCH BASIS:
// • Yang Xu et al. (2021), "Empirical Analysis of Price Volatility
// Characteristics of China's Soybean Futures Market". Complex. 2021.
// Decomposes OI into expected/unexpected components; unexpected changes
// have larger impact on price volatility — validates OI delta as a
// real-time information flow indicator.
// • Chen, Cuny & Haugen (1995), J. Finance 50(1), 281–300. OI levels predict
// future volatility; OI changes proxy for information arrival rate.
// • Christensen, Krogstrup, Kwan & Lustig (2017), NBER WP 23766. Aggregate OI
// predicts futures returns; positive coefficient on OI in return regressions.
// • ATAS Platform (2019), "Open Interest. How to use it in trading?".
// Bar-mode OI tracking: when Delta shows seller initiative but OI grows,
// both sides accumulate positions — "position building" signal precedes
// breakout moves from consolidation.
// • Chart Champions (2025), "How to Read Open Interest and Delta in Trading".
// Comprehensive cheat sheet for OI + Price + Volume combinations.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// RFS 22(6), 2201–2238. Liquidity spirals explain OI collapse during
// margin-driven liquidation cascades.
// ============================================================================
define(
title="OI Delta [Leviathan] Perfected",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ---------------------------------------------------------------------------
// --- Mode Group ---
var usePct = input(name="usePct", type="boolean", defaultValue=false, label="Use Percent Change", group="Mode")
// --- Smoothing Group ---
var maLen = input(name="maLen", type="number", defaultValue=14, label="MA Length", constraints={min: 1, max: 100, step: 1}, group="Smoothing")
var useEma = input(name="useEma", type="boolean", defaultValue=true, label="Use EMA (off = SMA)", group="Smoothing")
// --- Thresholds Group ---
var sigMult = input(name="sigMult", type="number", defaultValue=2.0, label="Significant Change Multiplier", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Thresholds")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Significant Change Shapes", group="Thresholds")
// --- Display Group ---
var showMA = input(name="showMA", type="boolean", defaultValue=true, label="Show MA Line", group="Display")
var showZero = input(name="showZero", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")
// --- Colors Group ---
var strongTrendColor = input(name="strongTrendColor", type="color", defaultValue="#00e676", label="Strong Trend Color", group="Colors")
var shortCoverColor = input(name="shortCoverColor", type="color", defaultValue="#ffeb3b", label="Short Cover Color", group="Colors")
var newShortsColor = input(name="newShortsColor", type="color", defaultValue="#ff1744", label="New Shorts Color", group="Colors")
var liquidationColor = input(name="liquidationColor", type="color", defaultValue="#ff5722", label="Liquidation Color", group="Colors")
var maColor = input(name="maColor", type="color", defaultValue="#ffffff", label="MA Color", group="Colors")
var sigUpColor = input(name="sigUpColor", type="color", defaultValue="#26a69a", label="Significant Up Color", group="Colors")
var sigDnColor = input(name="sigDnColor", type="color", defaultValue="#ef5350", label="Significant Down Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = oiTS.close
timeseries close = pxTS.close
timeseries high = pxTS.high
timeseries low = pxTS.low
timeseries vol = pxTS.volume
// NaN guard — prevent execution before data is loaded (Yang Xu et al. 2021 data-integrity best practice)
if (isnan(oi[0]) || isnan(close[0]) || isnan(vol[0])) {
return
}
// ---------------------------------------------------------------------------
// Core Computation — First Difference of OI
// ---------------------------------------------------------------------------
timeseries oiDeltaAbs = oi - oi[1]
timeseries oiDeltaPct = oi[1] != 0 ? (oi - oi[1]) / oi[1] * 100.0 : 0.0
timeseries oiDelta = usePct ? oiDeltaPct : oiDeltaAbs
timeseries oiDeltaAbsVal = abs(oiDelta)
timeseries avgDeltaAbs = sma(oiDeltaAbsVal, maLen)
timeseries oiMA = useEma ? ema(oiDelta, maLen) : sma(oiDelta, maLen)
// ---------------------------------------------------------------------------
// Price Direction + OI Direction → Four-Quadrant Regime Classification
// ---------------------------------------------------------------------------
// Per the classical BBA/ATAS framework:
// Q1: price ↑ + OI ↑ = Strong trend (new money confirming direction)
// Q2: price ↑ + OI ↓ = Short covering (weak trend, no new participation)
// Q3: price ↓ + OI ↑ = New shorts (bearish with fresh positioning)
// Q4: price ↓ + OI ↓ = Liquidation (forced exit, potential capitulation)
var priceUp = close > close[1]
var priceDn = close < close[1]
var priceFlat = close == close[1]
var oiUp = oiDelta > 0
var oiDn = oiDelta < 0
var oiFlat = oiDelta == 0
var regime = 0 // 0=neutral, 1=strong trend, 2=short covering, 3=new shorts, 4=liquidation
if (priceUp && oiUp) {
regime = 1
} else if (priceUp && oiDn) {
regime = 2
} else if (priceDn && oiUp) {
regime = 3
} else if (priceDn && oiDn) {
regime = 4
}
// Regime color selection
var regimeColor = neutralColor
if (regime == 1) {
regimeColor = strongTrendColor
} else if (regime == 2) {
regimeColor = shortCoverColor
} else if (regime == 3) {
regimeColor = newShortsColor
} else if (regime == 4) {
regimeColor = liquidationColor
}
// ---------------------------------------------------------------------------
// Significant Change Detection (|ΔOI| > k × SMA(|ΔOI|))
// ---------------------------------------------------------------------------
var sigUp = oiDelta > 0 && oiDeltaAbsVal > sigMult * avgDeltaAbs && avgDeltaAbs > 0
var sigDn = oiDelta < 0 && oiDeltaAbsVal > sigMult * avgDeltaAbs && avgDeltaAbs > 0
// ---------------------------------------------------------------------------
// Static State Tracking (Trend state persistence across bars)
// ---------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and significant change counts.
static lastBarIndex = 0
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDelta = -999999999.0
static sessionLowDelta = 999999999.0
static sigUpCount = 0
static sigDnCount = 0
static strongTrendCount = 0
static shortCoverCount = 0
static newShortsCount = 0
static liquidationCount = 0
static totalBars = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
totalBars = totalBars + 1
// Session delta extremes
if (oiDelta > sessionHighDelta) {
sessionHighDelta = oiDelta
}
if (oiDelta < sessionLowDelta) {
sessionLowDelta = oiDelta
}
// Regime change tracking
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
// Regime occurrence counting
if (regime == 1) {
strongTrendCount = strongTrendCount + 1
} else if (regime == 2) {
shortCoverCount = shortCoverCount + 1
} else if (regime == 3) {
newShortsCount = newShortsCount + 1
} else if (regime == 4) {
liquidationCount = liquidationCount + 1
}
// Significant change counting
if (sigUp) {
sigUpCount = sigUpCount + 1
}
if (sigDn) {
sigDnCount = sigDnCount + 1
}
}
// ---------------------------------------------------------------------------
// Plotting — Bar Histogram, Line Overlay, Fill, Shapes, HLine
// ---------------------------------------------------------------------------
// --- Zero line ---
if (showZero) {
hline(value=0, color="#ffffff40", width=1)
}
// --- OI Delta as bar histogram with regime-colored fills ---
if (showFill) {
plotBar(
value=oiDelta,
colors=[strongTrendColor, shortCoverColor, newShortsColor, liquidationColor],
colorIndex=regime == 1 ? 0 : (regime == 2 ? 1 : (regime == 3 ? 2 : 3)),
width=1,
label=["OI Delta"],
desc=["Per-bar OI change with four-quadrant regime coloring per classical OI+Price framework"]
)
} else {
plotBar(
value=oiDelta,
colors=[sigUpColor, sigDnColor],
width=1,
label=["OI Delta"],
desc=["Per-bar OI change: positive = new positions, negative = position closures"]
)
}
// --- MA line overlay ---
if (showMA) {
plotLine(
value=oiMA,
width=lineWidth,
colors=[maColor],
label=["OI Delta " + (useEma ? "EMA" : "SMA")],
desc=["Smoothed OI delta for trend persistence filter; slope indicates positioning momentum"]
)
}
// --- Significant change shape markers ---
if (showShapes) {
if (sigUp) {
plotShape(
value=oiDelta,
shape="triangleup",
color=sigUpColor,
width=shapeSize + 1,
label=["Sig OI+"],
desc=["Significant OI increase: ΔOI > " + sigMult + "× SMA(|ΔOI|) — new positions building per Yang Xu et al. (2021)"]
)
}
if (sigDn) {
plotShape(
value=oiDelta,
shape="triangledown",
color=sigDnColor,
width=shapeSize + 1,
label=["Sig OI-"],
desc=["Significant OI decrease: |ΔOI| > " + sigMult + "× SMA(|ΔOI|) — positions closing, potential capitulation"]
)
}
// Regime transition shapes (only on first bar of new regime with significant change)
var regimeToStrong = regime == 1 && !isnan(regime[1]) && regime[1] != 1 && oiDeltaAbsVal > avgDeltaAbs
var regimeToCover = regime == 2 && !isnan(regime[1]) && regime[1] != 2 && oiDeltaAbsVal > avgDeltaAbs
var regimeToShorts = regime == 3 && !isnan(regime[1]) && regime[1] != 3 && oiDeltaAbsVal > avgDeltaAbs
var regimeToLiquid = regime == 4 && !isnan(regime[1]) && regime[1] != 4 && oiDeltaAbsVal > avgDeltaAbs
if (regimeToStrong) {
plotShape(
value=oiDelta,
shape="diamond",
color=strongTrendColor,
width=shapeSize + 1,
label=["Strong Trend"],
desc=["Rising price + Rising OI = strong trend with new participation (classic bullish confirmation)"]
)
}
if (regimeToCover) {
plotShape(
value=oiDelta,
shape="diamond",
color=shortCoverColor,
width=shapeSize + 1,
label=["Short Cover"],
desc=["Rising price + Falling OI = short covering / squeeze — weak trend, no new money entering"]
)
}
if (regimeToShorts) {
plotShape(
value=oiDelta,
shape="diamond",
color=newShortsColor,
width=shapeSize + 1,
label=["New Shorts"],
desc=["Falling price + Rising OI = new shorts entering — bearish confirmation with fresh positioning"]
)
}
if (regimeToLiquid) {
plotShape(
value=oiDelta,
shape="diamond",
color=liquidationColor,
width=shapeSize + 1,
label=["Liquidation"],
desc=["Falling price + Falling OI = long liquidation / capitulation — forced exit, potential bottoming per Brunnermeier & Pedersen (2009)"]
)
}
}