MM Flow
FlowScripts

Perfected FlowScript

CME OI Z-Score

CME OI Z-Score — Perfected Edition is indexed as 122_cme_oi_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.3 KB

Lines

426

Native Signal Candidates

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

6/6 guarded

+3σ Extreme

line 334:9

Trigger

(showShapes) && (sigma3Up)

Value

3.0

Deps

showShapes:input, sigma3Up:var

-3σ Extreme

line 344:9

Trigger

(showShapes) && (sigma3Dn)

Value

-3.0

Deps

showShapes:input, sigma3Dn:var

+2σ Elevated

line 354:9

Trigger

(showShapes) && (sigma2Up)

Value

2.0

Deps

showShapes:input, sigma2Up:var

-2σ Elevated

line 364:9

Trigger

(showShapes) && (sigma2Dn)

Value

-2.0

Deps

showShapes:input, sigma2Dn:var

Zero Cross Up

line 374:9

Trigger

(showShapes) && (zCrossUp)

Value

0

Deps

showShapes:input, zCrossUp:var

Zero Cross Dn

line 384:9

Trigger

(showShapes) && (zCrossDn)

Value

0

Deps

showShapes:input, zCrossDn:var

122_cme_oi_z_score.flowscript

source path: kscripts/perfected/122_cme_oi_z_score.flowscript · sha256:91ba79cb8420690186d30d0356162cbac5aff73f03dfbb42d0e1804d24052dab

hash verified
//@version=2
// ============================================================================
// CME OI Z-Score — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, #cme, #oi, #positioning, #zscore
//
// Production-quality open-interest z-score tracker with ±1/2/3σ band fills,
// regime detection, stateful transition tracking, color-coded momentum, and
// comprehensive shape alerts. Standardizes CME futures open interest (BTC/ETH)
// into a rolling z-score to identify unusual positioning versus recent history.
//
// Research papers underpinning this design:
//  1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts". Establishes the
//     foundational OI-volatility relationship. Higher OI is associated with
//     greater information flow, validating elevated OI as "build up of
//     positions" and depressed OI as "de-risking."
//  2. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     Formalizes z-score normalization for trading signals. The z = (OI − mean)
//     / std with ±1/±2 bands follows this exact framework for measuring distance
//     from equilibrium in standard-deviation units.
//  3. TradeAlgo (2026), "COT Report: How to Read Commitments of Traders Data
//     for Futures Trading". Cites a 2018 Journal of Futures Markets study
//     finding that commercial net positioning in top/bottom decile predicted
//     6-month price direction with ~65-70% accuracy.
//  4. Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market Microstructure".
//     Studies BTC trading at CME and spot exchanges, finding CME leads price
//     discovery; validates using OI as a positioning signal.
//  5. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity".
//     The liquidity spiral framework: when funding liquidity tightens, OI
//     changes signal de-risking; when market liquidity improves, OI builds
//     signal leverage expansion. Underpins regime interpretation.
// ============================================================================

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

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

// --- Data Sources ---
var oiSymbol = input(
    name="oiSymbol",
    type="string",
    defaultValue="BTC-PERPETUAL",
    label="OI Symbol",
    group="Data Sources"
)
var oiExchange = input(
    name="oiExchange",
    type="string",
    defaultValue="DERIBIT",
    label="OI Exchange",
    group="Data Sources"
)

// --- Computation ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 10, max: 200, step: 5},
    group="Computation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Computation"
)
var useEma = input(
    name="useEma",
    type="boolean",
    defaultValue=true,
    label="Use EMA (off = SMA)",
    group="Computation"
)

// --- Display ---
var showZ = input(
    name="showZ",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show σ Bands",
    group="Display"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fills",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shapes",
    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 lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#2962ff",
    label="Z-Score Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries oiRaw = open_interest(symbol=oiSymbol, exchange=oiExchange)
timeseries oiSeries = oiRaw.close

if (isnan(oiSeries[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. Z-SCORE COMPUTATION
// -----------------------------------------------------------------------------
// Z_t = (OI_t − μ_t) / σ_t, where μ_t = SMA(OI, W), σ_t = StDev(OI, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.

timeseries oiMean = sma(oiSeries, lookback)
timeseries oiStd = stdev(oiSeries, lookback)
timeseries zRaw = (oiStd > 0) ? (oiSeries - oiMean) / oiStd : 0

// Smoothing
timeseries zEma = ema(zRaw, smoothLen)
timeseries zSma = sma(zRaw, smoothLen)
timeseries zFinal = useEma ? zEma : zSma

// Momentum (change in z-score)
timeseries zHist = zFinal - zFinal[1]

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification by sigma bands:
//   Extreme positive: z > +3σ
//   Elevated positive: +2σ < z ≤ +3σ
//   Notable positive: +1σ < z ≤ +2σ
//   Neutral: −1σ ≤ z ≤ +1σ
//   Notable negative: −2σ ≤ z < −1σ
//   Elevated negative: −3σ ≤ z < −2σ
//   Extreme negative: z < −3σ

var extremePos = zFinal > 3.0
var elevatedPos = zFinal > 2.0 && zFinal <= 3.0
var notablePos = zFinal > 1.0 && zFinal <= 2.0
var neutral = zFinal >= -1.0 && zFinal <= 1.0
var notableNeg = zFinal < -1.0 && zFinal >= -2.0
var elevatedNeg = zFinal < -2.0 && zFinal >= -3.0
var extremeNeg = zFinal < -3.0

var regimeColor = extremePos ? bullColor : (elevatedPos ? transparency(bullColor, 30) : (notablePos ? transparency(bullColor, 50) : (extremeNeg ? bearColor : (elevatedNeg ? transparency(bearColor, 30) : (notableNeg ? transparency(bearColor, 50) : "#9e9e9e")))))

// Regime numeric code for static tracking
var regimeCode = extremePos ? 3 : (elevatedPos ? 2 : (notablePos ? 1 : (extremeNeg ? -3 : (elevatedNeg ? -2 : (notableNeg ? -1 : 0)))))

// -----------------------------------------------------------------------------
// 5. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Tracks regime transitions and duration for context-aware alerting.

static lastRegime = 0
static regimeBars = 0
static prevZ = 0.0

if (regimeCode == lastRegime) {
    regimeBars = regimeBars + 1
} else {
    regimeBars = 0
}
lastRegime = regimeCode
prevZ = zFinal[0]

// Regime change flags
var regimeChange = regimeCode != lastRegime[1]
var extremeEvent = extremePos || extremeNeg

// -----------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var zCrossUp = zFinal > 0 && zFinal[1] <= 0
var zCrossDn = zFinal < 0 && zFinal[1] >= 0
var sigma1Up = zFinal > 1.0 && zFinal[1] <= 1.0
var sigma1Dn = zFinal < -1.0 && zFinal[1] >= -1.0
var sigma2Up = zFinal > 2.0 && zFinal[1] <= 2.0
var sigma2Dn = zFinal < -2.0 && zFinal[1] >= -2.0
var sigma3Up = zFinal > 3.0 && zFinal[1] <= 3.0
var sigma3Dn = zFinal < -3.0 && zFinal[1] >= -3.0

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------
timeseries zeroLine = 0
timeseries sigma1 = 1.0
timeseries sigma2 = 2.0
timeseries sigma3 = 3.0
timeseries negSigma1 = -1.0
timeseries negSigma2 = -2.0
timeseries negSigma3 = -3.0

// --- Z-Score Line (regime-colored) ---
if (showZ) {
    plotLine(
        value=zFinal,
        width=2,
        colors=[regimeColor],
        label=["OI Z-Score"],
        desc=["Smoothed OI z-score (" + lookback + "-bar lookback)"]
    )
}

// --- Z-Score Fill (vs zero line) ---
if (showBandFill) {
    var zBull = zFinal > 0
    plotLine(
        value=[zFinal, zeroLine],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=zBull ? 0 : 1,
        fill=true,
        label=["Z-Score", "Zero"],
        desc=["Fill between OI z-score and zero line"]
    )
}

// --- σ Band Fills ---
if (showBandFill) {
    // Notable zone (+1σ to +2σ, −1σ to −2σ)
    plotLine(
        value=[sigma2, sigma1],
        width=1,
        colors=[transparency("#ff9800", 10)],
        fill=true,
        label=["1σ–2σ"],
        desc=["Notable positive regime zone"]
    )
    plotLine(
        value=[negSigma1, negSigma2],
        width=1,
        colors=[transparency("#ff9800", 10)],
        fill=true,
        label=["-1σ to -2σ"],
        desc=["Notable negative regime zone"]
    )

    // Elevated zone (+2σ to +3σ, −2σ to −3σ)
    plotLine(
        value=[sigma3, sigma2],
        width=1,
        colors=[transparency("#f44336", 5)],
        fill=true,
        label=["2σ–3σ"],
        desc=["Elevated positive regime zone"]
    )
    plotLine(
        value=[negSigma2, negSigma3],
        width=1,
        colors=[transparency("#f44336", 5)],
        fill=true,
        label=["-2σ to -3σ"],
        desc=["Elevated negative regime zone"]
    )
}

// --- σ Band hlines ---
if (showBands) {
    hline(value=0, color="#ffffff30", width=1)
    hline(value=1.0, color="#ffffff20", width=1)
    hline(value=-1.0, color="#ffffff20", width=1)
    hline(value=2.0, color="#ffffff15", width=1)
    hline(value=-2.0, color="#ffffff15", width=1)
    hline(value=3.0, color="#ffffff10", width=1)
    hline(value=-3.0, color="#ffffff10", width=1)
}

// --- Momentum Histogram ---
if (showHistogram) {
    var histBull = zHist > 0
    plotBar(
        value=zHist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["OI Z Momentum"],
        desc=["Change in OI z-score (momentum)"]
    )
}

// --- Regime Shapes ---
if (showShapes) {
    if (sigma3Up) {
        plotShape(
            value=3.0,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["+3σ Extreme"],
            desc=["OI z-score crossed above +3σ: extreme positioning build-up"]
        )
    }
    if (sigma3Dn) {
        plotShape(
            value=-3.0,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["-3σ Extreme"],
            desc=["OI z-score crossed below -3σ: extreme de-risking"]
        )
    }
    if (sigma2Up) {
        plotShape(
            value=2.0,
            shape="xcross",
            colorIndex=transparency(bearColor, 50),
            width=2,
            label=["+2σ Elevated"],
            desc=["OI z-score crossed above +2σ: elevated positioning"]
        )
    }
    if (sigma2Dn) {
        plotShape(
            value=-2.0,
            shape="xcross",
            colorIndex=transparency(bullColor, 50),
            width=2,
            label=["-2σ Elevated"],
            desc=["OI z-score crossed below -2σ: elevated de-risking"]
        )
    }
    if (zCrossUp) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["OI z-score crossed above zero: positioning building"]
        )
    }
    if (zCrossDn) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Zero Cross Dn"],
            desc=["OI z-score crossed below zero: positioning reducing"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extremePos ? "EXTREME+" : (elevatedPos ? "ELEVATED+" : (notablePos ? "NOTABLE+" : (extremeNeg ? "EXTREME-" : (elevatedNeg ? "ELEVATED-" : (notableNeg ? "NOTABLE-" : "NEUTRAL")))))
    var regimeTextColor = extremePos ? bullColor : (extremeNeg ? bearColor : "#9e9e9e")

    plotTable(
        data=[
            ["CME OI Z-Score — Perfected", regimeText],
            ["Z-Score", zFinal[0]],
            ["OI Value", oiSeries[0]],
            ["OI Mean", oiMean[0]],
            ["OI StdDev", oiStd[0]],
            ["Momentum", zHist[0]],
            ["Regime Bars", regimeBars],
            ["Lookback", lookback]
        ],
        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
    )
}