MM Flow
FlowScripts

Perfected FlowScript

OI Delta Z-Score

OI Delta Z-Score V2 is indexed as 082_oi_delta_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

13.4 KB

Lines

415

Native Signal Candidates

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

6/6 guarded

+3σ Build

line 323:9

Trigger

(showShapes) && (crossUp3)

Value

z

Deps

crossUp3:var, showShapes:input

-3σ Reduce

line 333:9

Trigger

(showShapes) && (crossDn3)

Value

z

Deps

crossDn3:var, showShapes:input

+2σ Build

line 343:9

Trigger

(showShapes) && (crossUp2)

Value

z

Deps

crossUp2:var, showShapes:input

-2σ Reduce

line 353:9

Trigger

(showShapes) && (crossDn2)

Value

z

Deps

crossDn2:var, showShapes:input

+1σ Build

line 363:9

Trigger

(showShapes) && (crossUp1)

Value

z

Deps

crossUp1:var, showShapes:input

-1σ Reduce

line 373:9

Trigger

(showShapes) && (crossDn1)

Value

z

Deps

crossDn1:var, showShapes:input

082_oi_delta_z_score.flowscript

source path: kscripts/perfected/082_oi_delta_z_score.flowscript · sha256:b5bcc3f9e97079fe1acd1a41b2e4de48c79698d752be31039b7b1d2458aeb194

hash verified
//@version=2
// ============================================================================
// OI Delta Z-Score V2 — Production-Quality Open Interest Microstructure Indicator
// Author: BackQuant (@BackQuant) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #open_interest, #oi_delta, #zscore, #positioning, #microstructure
//
// Standardizes bar-to-bar open interest change (dOI = OI - OI[1]) into a rolling
// z-score with ±1/2/3σ bands, regime detection, fill visualization, and extreme
// event markers. Positive = position build; negative = position reduction.
// Magnitude shows how unusual the change is relative to the rolling window.
//
// FORMULA FOUNDATION:
// 1. OI Delta: dOI_t = OI_t - OI_{t-1}
// 2. Rolling Z-Score: z_t = (dOI_t - μ_t) / σ_t
//    where μ_t = SMA(dOI, lookback), σ_t = stdev(dOI, lookback)
//    per Zhao & Palomar (2018), z-bar normalization for mean-reverting portfolios.
// 3. Sigma Bands: ±1σ (normal range), ±2σ (warning), ±3σ (extreme event)
//    per standard Gaussian thresholds; <1% probability beyond ±3σ.
// 4. Regime Segmentation: Position Build (z > +1), Neutral (-1 ≤ z ≤ +1),
//    Position Reduction (z < -1), with Extreme Build (>+2) and Extreme Reduction (<-2).
//
// 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.
//    OI levels contain information about future volatility; unexpected OI changes
//    carry more predictive power than absolute levels.
//  • Yang Xu et al. (2021), "An Empirical Analysis of the Price Volatility
//    Characteristics of China's Soybean Futures Market". Unexpected OI changes
//    > expected in volatility impact; validates dOI as an information-flow proxy.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    z-bar = (z - mu) / sigma; entry thresholds at d * sigma.
//  • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//    Rev. Financial Studies 22(6), 2201–2238. Liquidity spirals and position
//    unwinding mechanics explain why extreme OI reductions coincide with volatility.
//  • Bian et al. (2023), "Deleveraging Commonality", J. Financial Economics.
//    Systematic deleveraging creates fire-sale cascades; OI delta extremes flag
//    deleveraging risk before price moves fully reflect it.
// ============================================================================

define(
    title="OI Delta Z-Score V2",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Z-Score Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback Window",
    constraints={min: 10, max: 200, step: 1},
    group="Z-Score Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Smoothing EMA Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Settings"
)

// --- Thresholds ---
var band1 = input(
    name="band1",
    type="number",
    defaultValue=1.0,
    label="1σ Band (±)",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Thresholds"
)
var band2 = input(
    name="band2",
    type="number",
    defaultValue=2.0,
    label="2σ Band (±)",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)
var band3 = input(
    name="band3",
    type="number",
    defaultValue=3.0,
    label="3σ Band (±)",
    constraints={min: 1.5, max: 5.0, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showRawDelta = input(
    name="showRawDelta",
    type="boolean",
    defaultValue=true,
    label="Show Raw dOI Histogram",
    group="Display"
)
var showPriceOverlay = input(
    name="showPriceOverlay",
    type="boolean",
    defaultValue=true,
    label="Show Price Delta Context",
    group="Display"
)
var showSigmaBands = input(
    name="showSigmaBands",
    type="boolean",
    defaultValue=true,
    label="Show Sigma Bands",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)

// --- Colors ---
var buildColor = input(
    name="buildColor",
    type="color",
    defaultValue="#26a69a",
    label="Position Build Color",
    group="Colors"
)
var reduceColor = input(
    name="reduceColor",
    type="color",
    defaultValue="#ef5350",
    label="Position Reduction Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var extremeBuildColor = input(
    name="extremeBuildColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Build Color",
    group="Colors"
)
var extremeReduceColor = input(
    name="extremeReduceColor",
    type="color",
    defaultValue="#ff1744",
    label="Extreme Reduction Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries oiData = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvData.close

if (isnan(close[0]) || isnan(oiData.close[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. COMPUTATION
// -----------------------------------------------------------------------------
// Bar-to-bar OI change
timeseries dOI = oiData.close - oiData.close[1]

// Rolling z-score
timeseries mean = sma(source=dOI, period=lookback)
timeseries std = stdev(source=dOI, period=lookback)
timeseries zRaw = std > 0 ? (dOI - mean) / std : 0

// Smoothed z-score
timeseries z = ema(source=zRaw, period=smoothLen)

// Price change for context
timeseries dPrice = close - close[1]

// Price direction sign
timeseries priceSign = dPrice > 0 ? 1 : (dPrice < 0 ? -1 : 0)

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Five-tier regime: extreme build, build, neutral, reduce, extreme reduce
var regimeExtremeBuild = z > band2
var regimeBuild = z > band1 && z <= band2
var regimeNeutral = z >= -band1 && z <= band1
var regimeReduce = z < -band1 && z >= -band2
var regimeExtremeReduce = z < -band2

// Regime color for main line
var regimeColor = regimeExtremeBuild ? extremeBuildColor : (regimeBuild ? buildColor : (regimeReduce ? reduceColor : (regimeExtremeReduce ? extremeReduceColor : neutralColor)))

// -----------------------------------------------------------------------------
// 5. EXTREME EVENT FLAGS
// -----------------------------------------------------------------------------
// Crossings of ±2σ and ±3σ bands
var crossUp2 = z >= band2 && !isnan(z[1]) && z[1] < band2
var crossDn2 = z <= -band2 && !isnan(z[1]) && z[1] > -band2
var crossUp3 = z >= band3 && !isnan(z[1]) && z[1] < band3
var crossDn3 = z <= -band3 && !isnan(z[1]) && z[1] > -band3
var crossUp1 = z >= band1 && !isnan(z[1]) && z[1] < band1
var crossDn1 = z <= -band1 && !isnan(z[1]) && z[1] > -band1

// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBuildCount = 0
static extremeReduceCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (z > sessionHighZ) {
        sessionHighZ = z
    }
    if (z < sessionLowZ) {
        sessionLowZ = z
    }

    var currentRegime = regimeExtremeBuild ? 2 : (regimeBuild ? 1 : (regimeReduce ? -1 : (regimeExtremeReduce ? -2 : 0)))
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regimeExtremeBuild) {
        extremeBuildCount = extremeBuildCount + 1
    } else if (regimeExtremeReduce) {
        extremeReduceCount = extremeReduceCount + 1
    }
}

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Reference Lines ---
hline(value=0, color="#ffffff40", width=1)
if (showSigmaBands) {
    hline(value=band1, color=opacity(buildColor, 25), width=1)
    hline(value=-band1, color=opacity(reduceColor, 25), width=1)
    hline(value=band2, color=opacity(buildColor, 35), width=1)
    hline(value=-band2, color=opacity(reduceColor, 35), width=1)
    hline(value=band3, color=opacity(buildColor, 20), width=1)
    hline(value=-band3, color=opacity(reduceColor, 20), width=1)
}

// --- Z-Score Line (regime-colored) ---
plotLine(
    value=z,
    width=2,
    colors=[regimeColor],
    label=["OI Delta Z-Score"],
    desc=["Standardized open-interest delta (smoothed). Build = new positions; Reduce = unwinding."]
)

// --- Regime Fill (z vs zero) ---
if (showFill) {
    var fillBuild = z >= 0
    plotLine(
        value=[z, 0],
        width=1,
        colors=[opacity(buildColor, 15), opacity(reduceColor, 15)],
        colorIndex=fillBuild ? 0 : 1,
        fill=true,
        label=["Z-Score", "Zero"],
        desc=["Fill between OI z-score and zero line", "Build/Reduce regime fill"]
    )
}

// --- Raw dOI Histogram ---
if (showRawDelta) {
    plotBar(
        value=dOI,
        colors=[buildColor, reduceColor],
        width=1,
        label=["Raw dOI"],
        desc=["Bar-to-bar open interest change (positive = build, negative = reduction)"]
    )
}

// --- Price Delta Context ---
if (showPriceOverlay) {
    var priceZ = priceSign * 100.0 * math.abs(dPrice) / math.max(0.0001, close)
    plotLine(
        value=priceZ,
        width=1,
        colors=[opacity("#ff9800", 40)],
        label=["Price Delta %"],
        desc=["Price change as percentage for context against OI delta direction"]
    )
}

// --- Extreme Event Shape Markers ---
if (showShapes) {
    if (crossUp3) {
        plotShape(
            value=z,
            shape="diamond",
            color=extremeBuildColor,
            width=4,
            label=["+3σ Build"],
            desc=["Extreme position build: +3σ OI delta event — statistically rare (<0.1%)"]
        )
    }
    if (crossDn3) {
        plotShape(
            value=z,
            shape="diamond",
            color=extremeReduceColor,
            width=4,
            label=["-3σ Reduce"],
            desc=["Extreme position reduction: -3σ OI delta event — potential liquidation/deleveraging"]
        )
    }
    if (crossUp2) {
        plotShape(
            value=z,
            shape="triangleup",
            color=buildColor,
            width=3,
            label=["+2σ Build"],
            desc=["Strong position build: +2σ OI delta crossing — new capital entering"]
        )
    }
    if (crossDn2) {
        plotShape(
            value=z,
            shape="triangledown",
            color=reduceColor,
            width=3,
            label=["-2σ Reduce"],
            desc=["Strong position reduction: -2σ OI delta crossing — capital exiting"]
        )
    }
    if (crossUp1) {
        plotShape(
            value=z,
            shape="circle",
            color=buildColor,
            width=2,
            label=["+1σ Build"],
            desc=["Position build zone entered: above +1σ OI delta"]
        )
    }
    if (crossDn1) {
        plotShape(
            value=z,
            shape="circle",
            color=reduceColor,
            width=2,
            label=["-1σ Reduce"],
            desc=["Position reduction zone entered: below -1σ OI delta"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. SESSION TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeExtremeBuild ? "EXTREME BUILD" : (regimeBuild ? "BUILD" : (regimeReduce ? "REDUCE" : (regimeExtremeReduce ? "EXTREME REDUCE" : "NEUTRAL")))
    var regimeTextColor = regimeExtremeBuild ? extremeBuildColor : (regimeBuild ? buildColor : (regimeReduce ? reduceColor : (regimeExtremeReduce ? extremeReduceColor : neutralColor)))

    plotTable(
        data=[
            ["OI Delta Z-Score — Perfected", regimeText],
            ["Z-Score", z[0]],
            ["Raw dOI", dOI[0]],
            ["OI Mean", mean[0]],
            ["OI Std", std[0]],
            ["Session High Z", sessionHighZ],
            ["Session Low Z", sessionLowZ],
            ["Regime Changes", regimeChangeCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}