MM Flow
FlowScripts

Perfected FlowScript

Orderbook Z-score

Orderbook Z-Score V2 is indexed as 085_orderbook_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.8 KB

Lines

338

Native Signal Candidates

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

6/6 guarded

Extreme High OBI

line 278:9

Trigger

(showShapes) && (crossUp2)

Value

smoothedZ

Deps

crossUp2:var, showShapes:input

Extreme Low OBI

line 288:9

Trigger

(showShapes) && (crossDn2)

Value

smoothedZ

Deps

crossDn2:var, showShapes:input

Elevated High OBI

line 298:9

Trigger

(showShapes) && (crossUp1)

Value

smoothedZ

Deps

crossUp1:var, showShapes:input

Elevated Low OBI

line 308:9

Trigger

(showShapes) && (crossDn1)

Value

smoothedZ

Deps

crossDn1:var, showShapes:input

Exit Extreme+

line 318:9

Trigger

(showShapes) && (exitExtremePos)

Value

smoothedZ

Deps

exitExtremePos:var, showShapes:input

Exit Extreme-

line 328:9

Trigger

(showShapes) && (exitExtremeNeg)

Value

smoothedZ

Deps

exitExtremeNeg:var, showShapes:input

085_orderbook_z_score.flowscript

source path: kscripts/perfected/085_orderbook_z_score.flowscript · sha256:d5fee2891846c06e3a07cfca3eb4ccac3c54e521854cd095c463a7b30a871738

hash verified
//@version=2
// ============================================================================
// Orderbook Z-Score V2 — Production-Quality Statistical Orderbook Indicator
// Author: abetrade (@abetrade)  |  Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #orderbook, #zscore, #microstructure, #meanreversion, #OBI
//
// Standardizes orderbook imbalance (OBI) into a z-score to identify statistically
// unusual orderbook states relative to recent history. Includes ±1/2/3σ bands with
// fill visualization, five-segment regime detection, color-coded line and bars,
// and shape markers for threshold crossings.
//
// FORMULA FOUNDATION:
// 1. Orderbook Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
//    per Cont, Kukanov & Stoikov (2014). Linear relationship with price changes.
// 2. Z-Score Normalization: z = (OBI − μ_OBI) / σ_OBI per Zhao & Palomar (2018).
//    Entry thresholds at d × σ_z (typically d = 1, 2, 3). Enables cross-asset
//    comparability and mean-reversion signal detection.
// 3. Five-Segment Regime Classification: Extreme+ (z > +2), Elevated+ (+1 < z ≤ +2),
//    Neutral (−1 ≤ z ≤ +1), Elevated− (−2 ≤ z < −1), Extreme− (z < −2).
//    per standard normal distribution: ~68% within ±1σ, ~95% within ±2σ, ~99.7%
//    within ±3σ. Readings beyond these thresholds are statistically rare.
// 4. Order Book Filtration (2025): OBI values close to ±1 indicate extreme imbalance
//    predictive of price movement direction. Trade-based OBI(T) eliminates flickering
//    quote noise.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI = (bid volume − ask volume) /
//    (bid volume + ask volume); linear relation with price changes; slope ∝ 1/depth.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE Trans. Signal Processing. z̄_t = (z_t − μ_z) / σ_z; entry thresholds at
//    d × σ_z. Formalizes z-score normalization for trading signal extraction.
//  • Order Book Filtration and Directional Signal Extraction at High Frequency (2025),
//    arXiv:2507.22712. OBI close to ±1 indicates extreme imbalance predictive of
//    price movement direction. Trade-based OBI(T) eliminates flickering quote noise.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime segmentation
//    of volume imbalance predicts future price direction.
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price Predictor",
//    Market Microstructure & Liquidity 2(1), 1650006. Queue imbalance logistic
//    regression shows significant next-tick direction prediction.
// ============================================================================

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

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Orderbook Configuration ---
var depth = input(name="depth", type="number", defaultValue=5.0, label="Depth Band (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")

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

// --- Bands ---
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show ±1/2/3σ Band Lines", group="Bands")
var showBandFill = input(name="showBandFill", type="boolean", defaultValue=true, label="Show Band Fill Areas", group="Bands")

// --- Display ---
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show Raw Z-Score (unsmoothed)", group="Display")
var showBarColors = input(name="showBarColors", type="boolean", defaultValue=true, label="Show Colored Z-Score Bars", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Threshold Shape Markers", group="Display")

// --- Colors ---
var posColor = input(name="posColor", type="color", defaultValue="#26a69a", label="Positive Z-Score Color", group="Colors")
var negColor = input(name="negColor", type="color", defaultValue="#ef5350", label="Negative Z-Score Color", group="Colors")
var extremePosColor = input(name="extremePosColor", type="color", defaultValue="#00e676", label="Extreme Positive Color", group="Colors")
var extremeNegColor = input(name="extremeNegColor", type="color", defaultValue="#ff1744", label="Extreme Negative Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Order Book Imbalance (OBI) Computation
// ------------------------------------------------------------------------------
// OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// per Cont, Kukanov & Stoikov (2014).

var bids = sumBids(book, depth)
var asks = sumAsks(book, depth)
var totalVol = bids + asks

var bookAvailable = bids > 0 && asks > 0
var obiRaw = bookAvailable && totalVol > 0 ? (bids - asks) / totalVol : 0.0

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Z_t = (OBI_t − μ_OBI) / σ_OBI over rolling lookback window.

var obiMean = sma(obiRaw, lookback)
var obiStd = stdev(obiRaw, lookback)
var rawZ = obiStd > 0 ? (obiRaw - obiMean) / obiStd : 0.0
var smoothedZ = ema(rawZ, smoothLen)

// ------------------------------------------------------------------------------
// Five-Segment Regime Detection (Standard Normal Thresholds)
// ------------------------------------------------------------------------------
// ~68% within ±1σ, ~95% within ±2σ, ~99.7% within ±3σ.
// Readings beyond ±2σ are statistically rare and likely to revert.

var zRegime = 0  // 0=neutral, 1=elevated+, 2=extreme+, -1=elevated-, -2=extreme-

if (smoothedZ > 2.0) {
    zRegime = 2
} else if (smoothedZ > 1.0) {
    zRegime = 1
} else if (smoothedZ < -2.0) {
    zRegime = -2
} else if (smoothedZ < -1.0) {
    zRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks extreme-event counts, session z-score extremes, and regime transitions.

static lastZRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremePosCount = 0
static extremeNegCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

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

    if (lastZRegime != zRegime) {
        lastZRegime = zRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (zRegime == 2) {
        extremePosCount = extremePosCount + 1
    } else if (zRegime == -2) {
        extremeNegCount = extremeNegCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

// Zero reference line
hline(value=0, color="#ffffff30", width=1)

// Sigma band lines (±1σ, ±2σ, ±3σ) — Zhao & Palomar (2018) threshold framework
if (showBands) {
    hline(value=3, color=opacity(extremePosColor, 15), width=1)
    hline(value=2, color=opacity(extremePosColor, 25), width=1)
    hline(value=1, color=opacity(posColor, 30), width=1)
    hline(value=-1, color=opacity(negColor, 30), width=1)
    hline(value=-2, color=opacity(extremeNegColor, 25), width=1)
    hline(value=-3, color=opacity(extremeNegColor, 15), width=1)
}

// Sigma band fill areas (visual backdrop)
if (showBandFill) {
    // +1σ to +2σ elevated zone
    plotLine(
        value=[1, 2],
        width=0,
        colors=[opacity(posColor, 5)],
        fill=opacity(posColor, 6),
        label=["Elevated+ Zone"],
        desc=["Background fill for elevated positive z-score zone (+1σ to +2σ)"]
    )
    // -1σ to -2σ elevated zone
    plotLine(
        value=[-1, -2],
        width=0,
        colors=[opacity(negColor, 5)],
        fill=opacity(negColor, 6),
        label=["Elevated- Zone"],
        desc=["Background fill for elevated negative z-score zone (-1σ to -2σ)"]
    )
    // +2σ to +3σ extreme zone
    plotLine(
        value=[2, 3],
        width=0,
        colors=[opacity(extremePosColor, 8)],
        fill=opacity(extremePosColor, 8),
        label=["Extreme+ Zone"],
        desc=["Background fill for extreme positive z-score zone (+2σ to +3σ)"]
    )
    // -2σ to -3σ extreme zone
    plotLine(
        value=[-2, -3],
        width=0,
        colors=[opacity(extremeNegColor, 8)],
        fill=opacity(extremeNegColor, 8),
        label=["Extreme- Zone"],
        desc=["Background fill for extreme negative z-score zone (-2σ to -3σ)"]
    )
}

// Z-score line with regime-coded color
var zLineColor = zRegime == 2 ? extremePosColor : (zRegime == 1 ? posColor : (zRegime == -2 ? extremeNegColor : (zRegime == -1 ? negColor : neutralColor)))

plotLine(
    value=smoothedZ,
    width=2,
    colors=[zLineColor],
    label=["Orderbook Z-Score"],
    desc=["Orderbook imbalance z-score: (OBI − SMA) / StdDev. Regime-coded by statistical threshold."]
)

// Fill area between z-score line and zero
plotLine(
    value=[smoothedZ, 0],
    width=0,
    colors=[zLineColor, zLineColor],
    fill=opacity(zLineColor, 12),
    label=["Z Fill", "Zero"],
    desc=["Fill area between z-score line and zero reference", "Zero reference line"]
)

// Raw z-score line (optional, for comparison with smoothed)
if (showRaw) {
    plotLine(
        value=rawZ,
        width=1,
        colors=[opacity(zLineColor, 40)],
        label=["Raw Z-Score"],
        desc=["Unsmoothed orderbook z-score (noisy but responsive)"]
    )
}

// Colored z-score bars (optional histogram view)
if (showBarColors) {
    var barColor = zRegime > 0 ? (zRegime == 2 ? extremePosColor : posColor) : (zRegime < 0 ? (zRegime == -2 ? extremeNegColor : negColor) : neutralColor)
    plotBar(
        value=smoothedZ,
        colors=[barColor],
        width=1,
        label=["Z-Score Bars"],
        desc=["Orderbook z-score as colored histogram bars by statistical regime"]
    )
}

// Extreme deviation shape markers (crossing ±1σ and ±2σ thresholds)
if (showShapes) {
    var crossUp2 = smoothedZ > 2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= 2.0
    var crossDn2 = smoothedZ < -2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= -2.0
    var crossUp1 = smoothedZ > 1.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= 1.0 && smoothedZ[1] > -1.0
    var crossDn1 = smoothedZ < -1.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= -1.0 && smoothedZ[1] < 1.0
    var exitExtremePos = smoothedZ < 2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] >= 2.0
    var exitExtremeNeg = smoothedZ > -2.0 && !isnan(smoothedZ[1]) && smoothedZ[1] <= -2.0

    if (crossUp2) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremePosColor,
            width=4,
            label=["Extreme High OBI"],
            desc=["Z-score crossed above +2σ — statistically unusual buy-heavy orderbook (euphoria risk)"]
        )
    }
    if (crossDn2) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeNegColor,
            width=4,
            label=["Extreme Low OBI"],
            desc=["Z-score crossed below -2σ — statistically unusual sell-heavy orderbook (capitulation risk)"]
        )
    }
    if (crossUp1) {
        plotShape(
            value=smoothedZ,
            shape="triangleup",
            color=posColor,
            width=3,
            label=["Elevated High OBI"],
            desc=["Z-score crossed above +1σ — elevated buy pressure above rolling mean"]
        )
    }
    if (crossDn1) {
        plotShape(
            value=smoothedZ,
            shape="triangledown",
            color=negColor,
            width=3,
            label=["Elevated Low OBI"],
            desc=["Z-score crossed below -1σ — elevated sell pressure below rolling mean"]
        )
    }
    if (exitExtremePos) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Exit Extreme+"],
            desc=["Z-score exited extreme positive zone (mean reversion potential)"]
        )
    }
    if (exitExtremeNeg) {
        plotShape(
            value=smoothedZ,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Exit Extreme-"],
            desc=["Z-score exited extreme negative zone (mean reversion potential)"]
        )
    }
}