MM Flow
FlowScripts

Perfected FlowScript

oi_z rolling-wind

OI Z-Score Rolling Window — Perfected Edition is indexed as 356_oi_z_rolling_wind.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

17.4 KB

Lines

554

Native Signal Candidates

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

10/10 guarded

Fast > Slow

line 416:9

Trigger

(showShapes) && (fastCrossSlowUp)

Value

oiZSlowS

Deps

fastCrossSlowUp:var, showShapes:input

Fast < Slow

line 426:9

Trigger

(showShapes) && (fastCrossSlowDown)

Value

oiZSlowS

Deps

fastCrossSlowDown:var, showShapes:input

Extreme Bull

line 436:9

Trigger

(showShapes) && (extremeBullEntry)

Value

oiZFastS

Deps

extremeBullEntry:var, showShapes:input

Extreme Bear

line 446:9

Trigger

(showShapes) && (extremeBearEntry)

Value

oiZFastS

Deps

extremeBearEntry:var, showShapes:input

Bull Regime

line 456:9

Trigger

(showShapes) && (divBullEntry && !extremeBullEntry)

Value

oiZFastS

Deps

divBullEntry:var, extremeBullEntry:var, showShapes:input

Bear Regime

line 466:9

Trigger

(showShapes) && (divBearEntry && !extremeBearEntry)

Value

oiZFastS

Deps

divBearEntry:var, extremeBearEntry:var, showShapes:input

Zero Cross +

line 476:9

Trigger

(showShapes) && (zeroCrossUp)

Value

0

Deps

showShapes:input, zeroCrossUp:var

Zero Cross -

line 486:9

Trigger

(showShapes) && (zeroCrossDown)

Value

0

Deps

showShapes:input, zeroCrossDown:var

Delta Extreme +

line 496:9

Trigger

(showShapes) && (deltaExtremeBull)

Value

zDelta

Deps

deltaExtremeBull:var, showShapes:input

Delta Extreme -

line 506:9

Trigger

(showShapes) && (deltaExtremeBear)

Value

zDelta

Deps

deltaExtremeBear:var, showShapes:input

356_oi_z_rolling_wind.flowscript

source path: kscripts/perfected/356_oi_z_rolling_wind.flowscript · sha256:ff2762668b8be35173fcebab6a35ac7ca62c7a637db43329af68f660d0aee481

hash verified
//@version=2
// ============================================================================
// OI Z-Score Rolling Window — Perfected Edition
// Author: M (@Muhammad Dinaev) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #oi_z_rolling_wind, #open_interest, #rolling_window, #zscore
//
// Production-quality rolling-window Open Interest z-score indicator.
// Recalculates mean and standard deviation on every bar over the prior N
// periods, making the indicator adaptive to recent market regimes. Features
// dual lookback architecture (fast + slow), divergence detection between
// lookbacks, multi-regime color coding, fill areas, momentum histogram,
// and comprehensive shape alerts.
//
// Research papers underpinning this design:
//  1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts": foundational OI as
//     proxy for information flow and price discovery activity.
//  2. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     rolling zₜ = (xₜ − μₜ₋ₙ:ₜ₋₁) / σₜ₋ₙ:ₜ₋₁; adaptive to recent regime changes
//     rather than fixed historical sample. Underpins the rolling-window design.
//  3. QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI: Mean Reversion
//     Comparison": shorter lookbacks (10–15) give more signals with more noise;
//     longer (20–30) fewer but more robust. Dual lookback captures both horizons.
//  4. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications": negative autocorrelation at medium horizons; supports
//     dynamic threshold calibration to rolling volatility.
// ============================================================================

define(
    title="OI Z-Score Rolling Window — Perfected Edition",
    position="offchart",
    axis=true
)

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

// -- Data Sources --
var symbol = input(
    name="symbol",
    type="string",
    defaultValue="BTCUSDT",
    label="Symbol",
    group="Data Sources"
)
var exchange = input(
    name="exchange",
    type="string",
    defaultValue="BINANCE_FUTURES",
    label="Exchange",
    group="Data Sources"
)

// -- Rolling Window --
var fastLookback = input(
    name="fastLookback",
    type="number",
    defaultValue=20,
    label="Fast Lookback (bars)",
    constraints={min: 5, max: 100, step: 5},
    group="Rolling Window"
)
var slowLookback = input(
    name="slowLookback",
    type="number",
    defaultValue=60,
    label="Slow Lookback (context)",
    constraints={min: 10, max: 200, step: 5},
    group="Rolling Window"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Rolling Window"
)

// -- Thresholds --
var divThreshold = input(
    name="divThreshold",
    type="number",
    defaultValue=2.0,
    label="Divergence Threshold (±σ)",
    constraints={min: 0.5, max: 4.0, step: 0.5},
    group="Thresholds"
)
var extremeThreshold = input(
    name="extremeThreshold",
    type="number",
    defaultValue=3.0,
    label="Extreme Divergence Threshold (±σ)",
    constraints={min: 2.0, max: 6.0, step: 0.5},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=false,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Thresholds"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.0,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Thresholds"
)

// -- Display --
var showFastZ = input(
    name="showFastZ",
    type="boolean",
    defaultValue=true,
    label="Show Fast Z-Score",
    group="Display"
)
var showSlowZ = input(
    name="showSlowZ",
    type="boolean",
    defaultValue=true,
    label="Show Slow Z-Score (Context)",
    group="Display"
)
var showZDelta = input(
    name="showZDelta",
    type="boolean",
    defaultValue=true,
    label="Show Z Delta (Fast − Slow)",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Fast vs Slow Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z Delta Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// -- Colors --
var fastColor = input(
    name="fastColor",
    type="color",
    defaultValue="#26c6da",
    label="Fast Z Color",
    group="Colors"
)
var slowColor = input(
    name="slowColor",
    type="color",
    defaultValue="#ff9800",
    label="Slow Z Color",
    group="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 extremeBullColor = input(
    name="extremeBullColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Bull Color",
    group="Colors"
)
var extremeBearColor = input(
    name="extremeBearColor",
    type="color",
    defaultValue="#d50000",
    label="Extreme Bear Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries oi = open_interest(symbol=symbol, exchange=exchange)

// Halt until OI feed has loaded to avoid NaN propagation
if (isnan(oi.close[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. ROLLING-WINDOW Z-SCORE COMPUTATION
// ---------------------------------------------------------------------------
// Fast lookback: adaptive to recent regime changes; more signals, more noise.
// Slow lookback: stable context line; fewer signals, higher robustness.

timeseries oiMeanFast = sma(oi.close, fastLookback)
timeseries oiStdFast = stddev(oi.close, fastLookback)
// Guard: if σ == 0, emit 0 to prevent division-by-zero
timeseries oiZFast = (oiStdFast > 0) ? (oi.close - oiMeanFast) / oiStdFast : 0

timeseries oiMeanSlow = sma(oi.close, slowLookback)
timeseries oiStdSlow = stddev(oi.close, slowLookback)
timeseries oiZSlow = (oiStdSlow > 0) ? (oi.close - oiMeanSlow) / oiStdSlow : 0

// Smoothing
timeseries oiZFastS = ema(oiZFast, smoothLen)
timeseries oiZSlowS = ema(oiZSlow, smoothLen)

// Z Delta captures regime acceleration: fast z-score diverging from slow
// context signals a shift in recent OI behavior relative to longer-term norm.
timeseries zDelta = oiZFastS - oiZSlowS

// ---------------------------------------------------------------------------
// 4. DYNAMIC THRESHOLDS
// ---------------------------------------------------------------------------
// Calibrate divergence / extreme bands by rolling volatility of fast z-score.

timeseries zVol = stddev(oiZFastS, volLookback)
var dynDiv = useDynamic ? math.max(0.5, divThreshold + zVol * volMultiplier) : divThreshold
var dynExtreme = useDynamic ? math.max(1.5, extremeThreshold + zVol * volMultiplier * 1.5) : extremeThreshold

// Guard: ensure bands never invert
if (dynExtreme <= dynDiv) {
    dynExtreme = divThreshold + 1.0
    dynDiv = divThreshold
}

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION (Fast Z-Score based)
// ---------------------------------------------------------------------------
var extremeBull = oiZFastS > dynExtreme
var bullRegime = oiZFastS > dynDiv && !extremeBull
var extremeBear = oiZFastS < -dynExtreme
var bearRegime = oiZFastS < -dynDiv && !extremeBear
var neutralRegime = !extremeBull && !bullRegime && !extremeBear && !bearRegime

var fastRegColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))

// Z Delta regime (acceleration/deceleration)
var deltaBull = zDelta > dynDiv
var deltaBear = zDelta < -dynDiv
var deltaNeutral = !deltaBull && !deltaBear

var deltaRegColor = deltaBull ? bullColor : (deltaBear ? bearColor : neutralColor)

// ---------------------------------------------------------------------------
// 6. STATIC TRACKING — Consecutive regime bars
// ---------------------------------------------------------------------------
static lastRegime = 0
static divBullBars = 0
static divBearBars = 0
static extremeBullBars = 0
static extremeBearBars = 0

if (extremeBull) {
    extremeBullBars = extremeBullBars + 1
    extremeBearBars = 0
    lastRegime = 2
} else if (bullRegime) {
    divBullBars = divBullBars + 1
    divBearBars = 0
    extremeBearBars = 0
    lastRegime = 1
} else if (extremeBear) {
    extremeBearBars = extremeBearBars + 1
    extremeBullBars = 0
    lastRegime = -2
} else if (bearRegime) {
    divBearBars = divBearBars + 1
    divBullBars = 0
    extremeBullBars = 0
    lastRegime = -1
} else {
    divBullBars = 0
    divBearBars = 0
    extremeBullBars = 0
    extremeBearBars = 0
    lastRegime = 0
}

// ---------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Fast vs Slow divergence events (regime acceleration)
var fastCrossSlowUp = oiZFastS > oiZSlowS && oiZFastS[1] <= oiZSlowS[1]
var fastCrossSlowDown = oiZFastS < oiZSlowS && oiZFastS[1] >= oiZSlowS[1]

// Extreme regime entries
var extremeBullEntry = extremeBull && !extremeBull[1]
var extremeBearEntry = extremeBear && !extremeBear[1]
var divBullEntry = bullRegime && !bullRegime[1]
var divBearEntry = bearRegime && !bearRegime[1]

// Zero-line crossings
var zeroCrossUp = oiZFastS > 0 && oiZFastS[1] <= 0
var zeroCrossDown = oiZFastS < 0 && oiZFastS[1] >= 0

// Z Delta extreme crossings
var deltaExtremeBull = zDelta > dynExtreme && zDelta[1] <= dynExtreme
var deltaExtremeBear = zDelta < -dynExtreme && zDelta[1] >= -dynExtreme

// ---------------------------------------------------------------------------
// 8. PLOTTING
// ---------------------------------------------------------------------------

// -- Midline & Thresholds --
hline(value=0, color="#ffffff20", width=1)

if (showFastZ || showSlowZ) {
    hline(value=dynDiv, color=transparency(bullColor, 60), width=1)
    hline(value=-dynDiv, color=transparency(bearColor, 60), width=1)
    hline(value=dynExtreme, color=transparency(extremeBullColor, 50), width=1)
    hline(value=-dynExtreme, color=transparency(extremeBearColor, 50), width=1)
}

// -- Fast Z-Score (regime-colored) --
if (showFastZ) {
    plotLine(
        value=oiZFastS,
        width=2,
        colors=[fastRegColor],
        label=["Rolling Z (Fast)"],
        desc=["Rolling-window OI z-score fast (" + fastLookback + ", adaptive regime-colored)"]
    )
}

// -- Slow Z-Score (context line) --
if (showSlowZ) {
    plotLine(
        value=oiZSlowS,
        width=1,
        colors=[slowColor],
        label=["Rolling Z (Slow)"],
        desc=["Rolling-window OI z-score slow context (" + slowLookback + ")"]
    )
}

// -- Fill between Fast and Slow Z --
if (showFill) {
    var fastAboveSlow = oiZFastS > oiZSlowS
    plotLine(
        value=[oiZFastS, oiZSlowS],
        width=1,
        colors=[transparency(bullColor, 25), transparency(bearColor, 25)],
        colorIndex=fastAboveSlow ? 0 : 1,
        fill=true,
        label=["Fast Z", "Slow Z"],
        desc=["Fill between fast and slow rolling z-scores"]
    )
}

// -- Z Delta (regime-colored line) --
if (showZDelta) {
    plotLine(
        value=zDelta,
        width=2,
        colors=[deltaRegColor],
        label=["Z Delta"],
        desc=["Fast minus slow z-score; regime acceleration / deceleration (regime-colored)"]
    )
}

// -- Z Delta Histogram --
if (showHistogram) {
    var histBull = zDelta >= 0
    plotBar(
        value=zDelta,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Z Delta Histogram"],
        desc=["Histogram of fast minus slow z-score (regime color-coded)"]
    )
}

// -- Shape Markers --
if (showShapes) {
    if (fastCrossSlowUp) {
        plotShape(
            value=oiZSlowS,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Fast > Slow"],
            desc=["Fast z-score crossed above slow z-score — short-term OI accelerating above context"]
        )
    }
    if (fastCrossSlowDown) {
        plotShape(
            value=oiZSlowS,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Fast < Slow"],
            desc=["Fast z-score crossed below slow z-score — short-term OI decelerating below context"]
        )
    }
    if (extremeBullEntry) {
        plotShape(
            value=oiZFastS,
            shape="triangleup",
            colorIndex=extremeBullColor,
            width=3,
            label=["Extreme Bull"],
            desc=["Fast z-score entered extreme bullish regime (>" + dynExtreme + ") — euphoria / crowded longs"]
        )
    }
    if (extremeBearEntry) {
        plotShape(
            value=oiZFastS,
            shape="triangledown",
            colorIndex=extremeBearColor,
            width=3,
            label=["Extreme Bear"],
            desc=["Fast z-score entered extreme bearish regime (<" + -dynExtreme + ") — capitulation / crowded shorts"]
        )
    }
    if (divBullEntry && !extremeBullEntry) {
        plotShape(
            value=oiZFastS,
            shape="arrowup",
            colorIndex=bullColor,
            width=2,
            label=["Bull Regime"],
            desc=["Fast z-score crossed above divergence threshold (" + dynDiv + ")"]
        )
    }
    if (divBearEntry && !extremeBearEntry) {
        plotShape(
            value=oiZFastS,
            shape="arrowdown",
            colorIndex=bearColor,
            width=2,
            label=["Bear Regime"],
            desc=["Fast z-score crossed below divergence threshold (" + -dynDiv + ")"]
        )
    }
    if (zeroCrossUp) {
        plotShape(
            value=0,
            shape="diamond",
            colorIndex=bullColor,
            width=2,
            label=["Zero Cross +"],
            desc=["Fast z-score crossed above zero — OI participation turning positive vs recent mean"]
        )
    }
    if (zeroCrossDown) {
        plotShape(
            value=0,
            shape="diamond",
            colorIndex=bearColor,
            width=2,
            label=["Zero Cross -"],
            desc=["Fast z-score crossed below zero — OI participation turning negative vs recent mean"]
        )
    }
    if (deltaExtremeBull) {
        plotShape(
            value=zDelta,
            shape="triangleup",
            colorIndex=extremeBullColor,
            width=2,
            label=["Delta Extreme +"],
            desc=["Z delta entered extreme positive territory — fast OI diverging strongly above slow context"]
        )
    }
    if (deltaExtremeBear) {
        plotShape(
            value=zDelta,
            shape="triangledown",
            colorIndex=extremeBearColor,
            width=2,
            label=["Delta Extreme -"],
            desc=["Z delta entered extreme negative territory — fast OI diverging strongly below slow context"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extremeBull ? "EXTREME BULL" : (bullRegime ? "BULL" : (extremeBear ? "EXTREME BEAR" : (bearRegime ? "BEAR" : "NEUTRAL")))
    var regimeTextColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))
    var divLabel = useDynamic ? "Dyn Div: ±" + dynDiv : "Static Div: ±" + divThreshold
    var extLabel = useDynamic ? "Dyn Extreme: ±" + dynExtreme : "Static Extreme: ±" + extremeThreshold

    plotTable(
        data=[
            ["OI Z Rolling Window — Perfected", regimeText],
            ["Fast Z (" + fastLookback + ")", oiZFastS[0]],
            ["Slow Z (" + slowLookback + ")", oiZSlowS[0]],
            ["Z Delta", zDelta[0]],
            ["Fast σ", oiStdFast[0]],
            ["Slow σ", oiStdSlow[0]],
            ["Raw OI", oi.close[0]],
            [divLabel, extLabel],
            ["Bull Bars", divBullBars],
            ["Bear Bars", divBearBars],
            ["Extreme Bull Bars", extremeBullBars],
            ["Extreme Bear Bars", extremeBearBars]
        ],
        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
    )
}