MM Flow
FlowScripts

Perfected FlowScript

Aggregated Open Interest Delta

Aggregated OI Delta [Perfected] is indexed as 099_aggregated_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.0 KB

Lines

449

Native Signal Candidates

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

6/6 guarded

Zero Cross Up

line 358:9

Trigger

(showAlertShapes) && (crossUp)

Value

coreAgg

Deps

crossUp:var, showAlertShapes:input

Zero Cross Down

line 368:9

Trigger

(showAlertShapes) && (crossDown)

Value

coreAgg

Deps

crossDown:var, showAlertShapes:input

MA Cross Up

line 378:9

Trigger

(showAlertShapes) && (maCrossUp)

Value

ma

Deps

maCrossUp:var, showAlertShapes:input

MA Cross Down

line 388:9

Trigger

(showAlertShapes) && (maCrossDown)

Value

ma

Deps

maCrossDown:var, showAlertShapes:input

Z-Extreme High

line 398:9

Trigger

(showAlertShapes) && (zExtremeHigh)

Value

zscore

Deps

showAlertShapes:input, zExtremeHigh:var

Z-Extreme Low

line 408:9

Trigger

(showAlertShapes) && (zExtremeLow)

Value

zscore

Deps

showAlertShapes:input, zExtremeLow:var

099_aggregated_open_interest_delta.flowscript

source path: kscripts/perfected/099_aggregated_open_interest_delta.flowscript · sha256:8de9960b7ad9d0db2a21fe5f33c6cd0fdcb69922b60ac6310fd55420d93846e9

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Aggregated Open Interest Delta [Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #oidelta, #openinterest, #aggregation, #futures, #microstructure
//
// Production-quality aggregated OI delta across multiple perpetual venues
// with z-score normalization, regime detection, color-coded histogram, fill
// visualization, and comprehensive shape markers. Uses static variables for
// stateful tracking of prior OI values and cross detection.
//
// Research papers underpinning this design:
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
//    and Open Interest in Futures Contracts": OI levels contain information about
//    future price volatility; unexpected OI changes carry predictive power.
//  - Yang Xu et al. (2021), "Price Volatility Characteristics of China's Soybean
//    Futures Market": unexpected OI changes > expected in volatility impact;
//    leverage effect amplified by unexpected OI shocks.
//  - Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market Microstructure":
//    CME leads BTC price discovery; multi-venue aggregation captures ecosystem.
//  - Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity":
//    liquidity spirals explain why sudden OI changes precede volatility expansion.
//  - Amberdata (2026), "Leverage & Liquidations: The $31B Deleveraging":
//    5% OI liquidation intensity triggers cascade; 15% APR funding = overheating.
// ============================================================================

define(
    title="Aggregated OI Delta [Perfected]",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs — grouped with constraints
// ---------------------------------------------------------------------------

// --- Aggregation Settings ---
var maLen = input(
    name="maLen",
    type="number",
    defaultValue=14,
    label="MA Length",
    constraints={min: 2, max: 100, step: 1},
    group="Aggregation"
)
var smoothMA = input(
    name="smoothMA",
    type="boolean",
    defaultValue=true,
    label="Smooth with MA",
    group="Aggregation"
)
var useEMA = input(
    name="useEMA",
    type="boolean",
    defaultValue=false,
    label="Use EMA (off=SMA)",
    group="Aggregation"
)
var aggMode = input(
    name="aggMode",
    type="select",
    defaultValue="Sum",
    label="Aggregation Mode",
    options=["Sum", "Weighted"],
    group="Aggregation"
)
var unitMode = input(
    name="unitMode",
    type="select",
    defaultValue="Native",
    label="Unit Mode",
    options=["Native", "USD Notional"],
    group="Aggregation"
)
var useChartPrice = input(
    name="useChartPrice",
    type="boolean",
    defaultValue=true,
    label="Use Chart Price for USD Notional",
    group="Aggregation"
)

// --- Z-Score ---
var showZscore = input(
    name="showZscore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score",
    group="Z-Score"
)
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 200, step: 5},
    group="Z-Score"
)
var zExtreme = input(
    name="zExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.25},
    group="Z-Score"
)

// --- Display ---
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show OI Delta Histogram",
    group="Display"
)
var showMALine = input(
    name="showMALine",
    type="boolean",
    defaultValue=true,
    label="Show MA Line",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="Display"
)
var showZeroLine = input(
    name="showZeroLine",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    group="Display"
)
var showAlertShapes = input(
    name="showAlertShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)
var shapeSize = input(
    name="shapeSize",
    type="number",
    defaultValue=2,
    label="Shape Size",
    constraints={min: 1, max: 4, step: 1},
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var maColor = input(
    name="maColor",
    type="color",
    defaultValue="#ffffff",
    label="MA Line Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ff9800",
    label="Signal Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// Data Sources & NaN Guard
// ---------------------------------------------------------------------------
timeseries oiBybit = open_interest("BTCUSDT", "BYBIT")
timeseries oiOKX = open_interest("BTC-USDT-SWAP", "OKEX_SWAP")
timeseries ohlcvTS = ohlcv(currentSymbol, currentExchange)
timeseries px = ohlcvTS.close

if (isnan(px[0]) || isnan(oiBybit.close[0]) || isnan(oiOKX.close[0])) {
    return
}

// ---------------------------------------------------------------------------
// Static Variables for Stateful Tracking
// ---------------------------------------------------------------------------
static prevOiBybit = -1.0
static prevOiOKX = -1.0
static prevAgg = 0.0

// Initialize on first real bar after NaN guard
if (prevOiBybit < 0) {
    prevOiBybit = oiBybit.close[0]
    prevOiOKX = oiOKX.close[0]
}

// ---------------------------------------------------------------------------
// Per-Venue OI Delta Computation
// ---------------------------------------------------------------------------
// Compute deltas using current vs previous (stateful to avoid repainting issues)
var dBybit = oiBybit.close[0] - prevOiBybit
var dOKX = oiOKX.close[0] - prevOiOKX

// Update state for next bar
prevOiBybit = oiBybit.close[0]
prevOiOKX = oiOKX.close[0]

// Optional USD notional conversion
var conv = (unitMode == "USD Notional") ? px : 1.0
var dBybitN = dBybit * conv
var dOKXN = dOKX * conv

// Apply includes (both venues always on)
var sBybit = dBybitN
var sOKX = dOKXN

// Sum weights of included (default equal weights)
var wSum = 2.0

// Aggregate core
var coreSum = sBybit + sOKX
var coreWgtNum = (sBybit + sOKX) / 2
var coreAgg = (aggMode == "Weighted" && wSum > 0.0) ? coreWgtNum : coreSum

// ---------------------------------------------------------------------------
// Smoothing & Signal
// ---------------------------------------------------------------------------
var maSMA = sma(coreAgg, maLen)
var maEMA = ema(coreAgg, maLen)
var ma = smoothMA ? (useEMA ? maEMA : maSMA) : coreAgg

// Momentum of delta (delta of delta)
var deltaMomentum = coreAgg - prevAgg
prevAgg = coreAgg

// ---------------------------------------------------------------------------
// Z-Score Normalization
// ---------------------------------------------------------------------------
timeseries zRaw = coreAgg
timeseries zMean = sma(source=zRaw, period=zLookback)
timeseries zStd = stddev(source=zRaw, period=zLookback)
timeseries zscore = zStd > 0 ? (zRaw - zMean) / zStd : 0

// ---------------------------------------------------------------------------
// Regime Detection
// ---------------------------------------------------------------------------
// Regime classification:
//   Bullish: coreAgg > ma AND coreAgg > 0 (OI increasing, above trend)
//   Bearish: coreAgg < ma AND coreAgg < 0 (OI decreasing, below trend)
//   Neutral: everything else

var regimeBull = coreAgg > ma && coreAgg > 0
var regimeBear = coreAgg < ma && coreAgg < 0
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

// ---------------------------------------------------------------------------
// Alert Conditions
// ---------------------------------------------------------------------------
// Zero-line cross
var crossUp = coreAgg > 0 && coreAgg[1] <= 0
var crossDown = coreAgg < 0 && coreAgg[1] >= 0

// MA cross
var maCrossUp = coreAgg > ma && coreAgg[1] <= ma[1]
var maCrossDown = coreAgg < ma && coreAgg[1] >= ma[1]

// Z-Score extremes
var zExtremeHigh = zscore > zExtreme && zscore[1] <= zExtreme
var zExtremeLow = zscore < -zExtreme && zscore[1] >= -zExtreme

// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------

// --- Zero Line ---
if (showZeroLine) {
    hline(value=0, color="#ffffff40", width=1)
}

// --- OI Delta Histogram (regime-colored) ---
if (showHistogram) {
    var histBull = coreAgg >= 0
    plotBar(
        value=coreAgg,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["OI Delta"],
        desc=["Aggregated OI delta across venues"]
    )
}

// --- MA Line ---
if (showMALine) {
    plotLine(
        value=ma,
        width=2,
        colors=[maColor],
        label=["OI Delta MA"],
        desc=["Moving average of aggregated OI delta (" + maLen + ")"]
    )
}

// --- Signal Fill (delta vs MA) ---
if (showSignalFill && showMALine) {
    var signalBull = coreAgg > ma
    plotLine(
        value=[coreAgg, ma],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["OI Delta", "MA"],
        desc=["Fill between OI delta and MA"]
    )
}

// --- Z-Score Line ---
if (showZscore) {
    plotLine(
        value=zscore,
        width=2,
        colors=[bullColor, bearColor],
        colorIndex=zscore >= 0 ? 0 : 1,
        label=["Z-Score"],
        desc=["Z-score of aggregated OI delta"]
    )
    plotLine(
        value=0,
        width=1,
        colors=["#ffffff20"],
        label=["Z-Zero"],
        desc=["Z-Score zero line"]
    )
    hline(value=zExtreme, color=transparency(bearColor, 60), width=1)
    hline(value=-zExtreme, color=transparency(bullColor, 60), width=1)
}

// --- Shape Markers ---
if (showAlertShapes) {
    if (crossUp) {
        plotShape(
            value=coreAgg,
            shape="triangleup",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Zero Cross Up"],
            desc=["OI Delta crossed above zero"]
        )
    }
    if (crossDown) {
        plotShape(
            value=coreAgg,
            shape="triangledown",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Zero Cross Down"],
            desc=["OI Delta crossed below zero"]
        )
    }
    if (maCrossUp) {
        plotShape(
            value=ma,
            shape="circle",
            colorIndex=bullColor,
            width=shapeSize,
            label=["MA Cross Up"],
            desc=["OI Delta crossed above MA"]
        )
    }
    if (maCrossDown) {
        plotShape(
            value=ma,
            shape="circle",
            colorIndex=bearColor,
            width=shapeSize,
            label=["MA Cross Down"],
            desc=["OI Delta crossed below MA"]
        )
    }
    if (zExtremeHigh) {
        plotShape(
            value=zscore,
            shape="xcross",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Z-Extreme High"],
            desc=["Z-Score exceeded +" + zExtreme]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=zscore,
            shape="xcross",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Z-Extreme Low"],
            desc=["Z-Score exceeded -" + zExtreme]
        )
    }
}

// ---------------------------------------------------------------------------
// Regime Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
    var unitText = unitMode == "USD Notional" ? " USD" : " Native"

    plotTable(
        data=[
            ["Agg OI Delta [Perfected]", regimeText],
            ["OI Delta", coreAgg[0] + unitText],
            ["OI Delta MA", ma[0] + unitText],
            ["Z-Score", zscore[0]],
            ["Bybit Δ", sBybit[0] + unitText],
            ["OKX Δ", sOKX[0] + unitText]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}