MM Flow
FlowScripts

Perfected FlowScript

Open Interest Delta (Fork)

Open Interest Delta Fork V2 is indexed as 240_open_interest_delta_fork.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

11.1 KB

Lines

243

Native Signal Candidates

2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

2/2 guarded

Extreme Bull OI

line 206:5

Trigger

(showShapes && extremeBull)

Value

extremeDiv

Deps

extremeBull:var, showShapes:input

Extreme Bear OI

line 216:5

Trigger

(showShapes && extremeBear)

Value

-extremeDiv

Deps

extremeBear:var, showShapes:input

240_open_interest_delta_fork.flowscript

source path: kscripts/perfected/240_open_interest_delta_fork.flowscript · sha256:15050407a4f4883e61c45c384e1a9f2a16d57fbdca937f9001bb7418074433f1

hash verified
//@version=2

// ============================================================================
// Open Interest Delta Fork V2 — OI Delta with Z-Score, Regime & Shape Alerts
// Author: Tzen Yang (@Tzen Yang) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #oi, #openinterest, #delta, #zscore
//
// This indicator computes the bar-to-bar change in open interest (OI delta)
// and standardizes it via a rolling-window z-score. The resulting signal is
// visualized as a color-coded histogram, a smoothed signal line, and extreme
// event shape markers. Regime detection identifies elevated/depressed
// participation states, while cumulative static tracking captures session
// extremes and extreme-event counts for context-aware alerting.
//
// Academic foundation (exact papers & formulas):
//  1. Chen, Nai-Fu; Cuny, Charles J.; Haugen, Robert A. (1995), "Stock
//     Volatility and the Levels of the Basis and Open Interest in Futures
//     Contracts", Journal of Finance, 50(1), 281–300.
//     [Formula] OI levels contain information about future price volatility.
//     Higher OI = greater information flow and price discovery activity.
//     Unexpected OI changes have larger impact than expected changes.
//     DOI: https://doi.org/10.1111/j.1540-6261.1995.tb05168.x
//
//  2. Yang Xu et al. (2021), "An Empirical Analysis of the Price Volatility
//     Characteristics of China's Soybean Futures Market Based on
//     ARIMA-GJR-GARCH Model", Complexity.
//     [Formula] Unexpected OI shock = ΔOI − E[ΔOI]; leverage effect amplified
//     by unexpected OI shocks. Validates OI delta as more informative than
//     absolute OI levels.
//     DOI: https://doi.org/10.1155/2021/5532264
//
//  3. Zhao, S. & Palomar, D. P. (2018), "Mean-Reverting Portfolio With Budget
//     Constraint", IEEE Transactions on Signal Processing.
//     [Formula] z̄_t = (z_t − μ_z) / σ_z; entry thresholds at d × σ_z
//     (typically d = 1 or 2). Formalizes z-score event triggers for
//     mean-reversion trading and statistical significance filtering.
//
//  4. LeviathanCapital (2024), "Open Interest Delta - By Leviathan".
//     [Formula] OI Delta = OI_current − OI_previous; positive delta clusters
//     act as defense zones where traders committed capital and will defend
//     entries on revisit.
//
//  5. Open Interest in relation to the Price and Volume (BBA curriculum).
//     [Formula] Rising price + Rising OI = strong trend with new participation;
//     Rising price + Falling OI = short covering/squeeze; Falling price +
//     Rising OI = new shorts entering; Falling price + Falling OI = long
//     liquidation/capitulation.
// ============================================================================

define(title="Open Interest Delta Fork V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var exchange = input(name="exchange", type="select", defaultValue="BINANCE_FUTURES",
    label="Exchange", options=["BINANCE_FUTURES","BYBIT","OKEX_SWAP","DERIBIT","HYPERLIQUID_FUTURES"], group="Data Sources")
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Sources")

// -- Computation --
var usePct = input(name="usePct", type="boolean", defaultValue=false, label="Use Percent Change", group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var maLen = input(name="maLen", type="number", defaultValue=14, label="MA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var useEMA = input(name="useEMA", type="boolean", defaultValue=true, label="Use EMA (off=SMA)", group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Regime Threshold (σ)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Event Threshold (σ)", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")

// -- Display --
var showRawDelta = input(name="showRawDelta", type="boolean", defaultValue=true,  label="Show Raw OI Delta", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true,  label="Show OI Delta Z-Score", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true,  label="Show Smoothed Signal", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true,  label="Show Extreme Shapes", group="Display")
var showCumOI = input(name="showCumOI", type="boolean", defaultValue=false, label="Show Cumulative OI Change", group="Display")

// -- Colors --
var posColor = input(name="posColor", type="color", defaultValue="#26a69a", label="Positive Color", group="Colors")
var negColor = input(name="negColor", type="color", defaultValue="#ef5350", label="Negative Color", group="Colors")
var bullDivColor = input(name="bullDivColor", type="color", defaultValue="#00c853", label="Bullish Divergence Color", group="Colors")
var bearDivColor = input(name="bearDivColor", type="color", defaultValue="#d50000", label="Bearish Divergence Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var signalColor = input(name="signalColor", type="color", defaultValue="#ffeb3b", label="Signal Line Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff9100", label="Extreme Shape Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries oi = open_interest(symbol=symbol, exchange=exchange)
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close

// Guard: halt until external feed has loaded to avoid NaN propagation
if (isnan(oi.close[0]) || isnan(close[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 OI Delta (absolute or percent change) --
// Chen, Cuny & Haugen (1995): unexpected OI changes carry more information
// than absolute levels. Yang Xu et al. (2021): unexpected OI shocks amplify
// volatility more than expected changes.
timeseries oiDelta = usePct
    ? ((oi.close - oi.close[1]) / (oi.close[1] > 0 ? oi.close[1] : 1)) * 100.0
    : (oi.close - oi.close[1])

// -- 3.2 Z-score normalization (all denominators guarded against zero) --
// Zhao & Palomar (2018): z_t = (X_t − μ) / σ; entry thresholds at d × σ_z.
timeseries oiMean = sma(oiDelta, zWindow)
timeseries oiStd  = stdev(oiDelta, zWindow)
timeseries oiZ = (oiStd > 0) ? (oiDelta - oiMean) / oiStd : 0.0

// -- 3.3 Smoothed signal line (EMA or SMA per user choice) --
timeseries sig = useEMA ? ema(oiZ, maLen) : sma(oiZ, maLen)

// -- 3.4 Regime detection (configurable thresholds, no magic numbers) --
var bullishRegime = oiZ > divThreshold
var bearishRegime = oiZ < -divThreshold
var extremeBull = oiZ > extremeDiv
var extremeBear = oiZ < -extremeDiv
var neutralRegime = !bullishRegime && !bearishRegime

// -- 3.5 Static state tracking (session-level persistence) --
// Tracks cumulative OI change, session extremes, and extreme-event counts.
static cumOI = 0.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    // Cumulative OI change (guarded against NaN)
    if (!isnan(oiDelta[0])) {
        cumOI = cumOI + oiDelta[0]
    }

    // Session extremes
    if (oiZ > sessionHighZ) {
        sessionHighZ = oiZ
    }
    if (oiZ < sessionLowZ) {
        sessionLowZ = oiZ
    }

    // Extreme event counting
    if (extremeBull) {
        extremeBullCount = extremeBullCount + 1
    } else if (extremeBear) {
        extremeBearCount = extremeBearCount + 1
    }
}

// -- 3.6 Zero-line helper for fill areas --
timeseries zeroLine = 0.0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Raw OI Delta as color-coded histogram bars (sign-based)
if (showRawDelta) {
    plotBar(
        value=oiDelta,
        colors=[posColor, negColor],
        width=1,
        label=["OI Delta Raw"],
        desc=["Bar-to-bar open interest change; positive = net positions added, negative = net positions closed"]
    )
}

// 4.2 OI Delta Z-score as color-coded histogram (regime-coded + fill)
if (showZScore) {
    timeseries zColorIdx = bullishRegime ? 0 : (bearishRegime ? 1 : 2)
    plotLine(
        value=([oiZ, zeroLine]),
        width=2,
        colors=[bullDivColor, bearDivColor, neutralColor],
        colorIndex=zColorIdx,
        label=["OI Delta Z-Score"],
        desc=["Rolling z-score of OI delta; filled histogram colour-coded by regime"],
        fill=true
    )
}

// 4.3 Smoothed signal line with regime-coded fill area
if (showSignal) {
    plotLine(
        value=sig,
        width=2,
        colors=[signalColor],
        label=["OI Delta Signal"],
        desc=["Smoothed OI delta z-score (EMA or SMA); persistence filter for regime shifts"]
    )
}

// 4.4 Extreme event shapes (plotShape) — triangle alerts on z-score extremes
if (showShapes && extremeBull) {
    plotShape(
        value=extremeDiv,
        shape="triangleup",
        color=bullDivColor,
        width=3,
        label=["Extreme Bull OI"],
        desc=["OI delta z-score above +extreme threshold; potential new long build or squeeze risk"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=-extremeDiv,
        shape="triangledown",
        color=bearDivColor,
        width=3,
        label=["Extreme Bear OI"],
        desc=["OI delta z-score below −extreme threshold; potential long liquidation or capitulation"]
    )
}

// 4.5 Optional cumulative OI change line (true cumulative from static state)
if (showCumOI) {
    plotLine(
        value=cumOI,
        width=1,
        colors=[signalColor],
        label=["Cumulative OI Δ"],
        desc=["True cumulative open interest change from first bar; static-tracked across session"]
    )
}

// 4.6 Reference thresholds (hline) — zero line and configurable sigma zones
hline(value=0,                color="#ffffff30", width=1)
hline(value=divThreshold,     color=opacity(bullDivColor, 30), width=1)
hline(value=-divThreshold,    color=opacity(bearDivColor, 30), width=1)
hline(value=extremeDiv,       color=opacity(extremeColor, 20), width=1)
hline(value=-extremeDiv,      color=opacity(extremeColor, 20), width=1)