MM Flow
FlowScripts

Perfected FlowScript

OB z-score

OB Z-Score V2 (Classic) Perfected is indexed as 348_ob_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

20.4 KB

Lines

467

Native Signal Candidates

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

8/8 guarded

Bull Regime

line 387:9

Trigger

(showShapes) && (crossUp)

Value

obiZS

Deps

crossUp:var, showShapes:input

Bear Regime

line 397:9

Trigger

(showShapes) && (crossDn)

Value

obiZS

Deps

crossDn:var, showShapes:input

Extreme Bid

line 407:9

Trigger

(showShapes) && (extremeUp)

Value

obiZS

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 417:9

Trigger

(showShapes) && (extremeDn)

Value

obiZS

Deps

extremeDn:var, showShapes:input

+2σ Cross

line 427:9

Trigger

(showShapes) && (band2CrossUp)

Value

obiZS

Deps

band2CrossUp:var, showShapes:input

-2σ Cross

line 437:9

Trigger

(showShapes) && (band2CrossDn)

Value

obiZS

Deps

band2CrossDn:var, showShapes:input

+3σ Cross

line 447:9

Trigger

(showShapes) && (band3CrossUp)

Value

obiZS

Deps

band3CrossUp:var, showShapes:input

-3σ Cross

line 457:9

Trigger

(showShapes) && (band3CrossDn)

Value

obiZS

Deps

band3CrossDn:var, showShapes:input

348_ob_z_score.flowscript

source path: kscripts/perfected/348_ob_z_score.flowscript · sha256:2fcc314e2d7322d7adfc0c143b8dbc171e2a1f13647595d3934a737d147979f4

hash verified
//@version=2
// ============================================================================
// OB Z-Score V2 (Classic) — Production-Quality Orderbook Z-Score with Multi-Depth OBI
// Author: I (@Iopl147u)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #zscore, #microstructure, #OBI, #regime
//
// Earlier version of the OB Z-score family with a longer default lookback and
// classical SMA-based smoothing. Multi-depth limit order book imbalance z-score
// with depth-weighted composite, σ-band framework, regime detection, and
// academic microstructure foundations.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol)  [−1, +1]
//    per Cont, Kukanov & Stoikov (2014) and Korean Derivatives Association (2015).
// 2. Z-Score Normalization: z̄ = (OBI − μ_OBI) / σ_OBI  per Zhao & Palomar (2018).
//    Entry thresholds at ±1σ, ±2σ, ±3σ for statistical clarity.
// 3. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i  where w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019), multi-level OFI with decaying weights.
// 4. Regime Segmentation: Sell-heavy (−1, −1/3), Neutral (−1/3, +1/3),
//    Buy-heavy (+1/3, +1) per Cartea, Donnelly & Jaimungal (2018).
// 5. Standard Deviation Bands: ~68.2% within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI linear price-impact model.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    z̄ₜ = (zₜ − μz) / σz; z-score improves threshold clarity.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights.
//  • Order Book Filtration and Directional Signal Extraction (2025). OBI as
//    bounded regime indicator; z-scoring improves threshold discrimination.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//    Predictor", Market Microstructure & Liquidity 2(1), 1650006. Queue
//    imbalance logistic regression for next-tick direction prediction.
// ============================================================================

define(
    title="OB Z-Score V2 (Classic) Perfected",
    position="offchart",
    axis=true
)

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

// --- Depth Configuration ---
var depth1 = input(name="depth1", type="number", defaultValue=1.0, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth2 = input(name="depth2", type="number", defaultValue=2.5, label="Depth Band 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth3 = input(name="depth3", type="number", defaultValue=5.0, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth4 = input(name="depth4", type="number", defaultValue=10.0, label="Depth Band 4 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")

var useDepthWeighting = input(name="useDepthWeighting", type="boolean", defaultValue=true, label="Use Depth-Decaying Weights", group="Depth")
var weightDecay = input(name="weightDecay", type="number", defaultValue=0.75, label="Weight Decay Factor", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Depth")

// --- Z-Score Configuration ---
var zLookback = input(name="zLookback", type="number", defaultValue=100, label="Z-Score Lookback", constraints={min: 10, max: 500, step: 5}, group="Z-Score")
var zSmooth = input(name="zSmooth", type="number", defaultValue=5, label="Z-Score SMA Smoothing", constraints={min: 1, max: 50, step: 1}, group="Z-Score")
var band1Mult = input(name="band1Mult", type="number", defaultValue=1.0, label="Band 1 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Z-Score")
var band2Mult = input(name="band2Mult", type="number", defaultValue=2.0, label="Band 2 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Z-Score")
var band3Mult = input(name="band3Mult", type="number", defaultValue=3.0, label="Band 3 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Z-Score")

// --- Regime Thresholds ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Z-Score Threshold (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Z-Score Threshold (σ)", constraints={min: -5.0, max: -0.1, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.5, label="Extreme Z-Score Threshold (σ)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showRawZ = input(name="showRawZ", type="boolean", defaultValue=true, label="Show Raw Z-Score Histogram", group="Display")
var showSmoothZ = input(name="showSmoothZ", type="boolean", defaultValue=true, label="Show Smoothed 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 showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Z-Scores", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid-Dominant / Bullish Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask-Dominant / Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#ffffff", label="±1σ Band Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#ffca28", label="±2σ Band Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#ff6d00", label="±3σ Band 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 (Cont et al. 2014 data-integrity best practice)
if (isnan(px[0]) || isnan(book[0])) {
    return
}

// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
// CRITICAL: The kScript API accepts depth as a float percentage (e.g., 1.0 = 1%).
// Research basis: Cont, Kukanov & Stoikov (2014) showed price impact slope
// is inversely proportional to depth; deeper books absorb imbalance with
// smaller price moves. The multi-depth bands (1%, 2.5%, 5%, 10%) directly
// operationalize this finding.

var bids1 = sumBids(book, depth1)
var asks1 = sumAsks(book, depth1)
var bids2 = sumBids(book, depth2)
var asks2 = sumAsks(book, depth2)
var bids3 = sumBids(book, depth3)
var asks3 = sumAsks(book, depth3)
var bids4 = sumBids(book, depth4)
var asks4 = sumAsks(book, depth4)

// Book availability check — prevents NaN/undefined propagation (Gould & Bonart 2016 robustness)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0

// ------------------------------------------------------------------------------
// OBI Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// OBI = (Bid − Ask) / (Bid + Ask)  ∈ [−1, +1]
// Formula from Order Book Filtration and Directional Signal Extraction (2025)
// and Korean Derivatives Association (2015).

var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var denom4 = bids4 + asks4

var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 * 100.0 : 0.0
var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 * 100.0 : 0.0
var obi3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 * 100.0 : 0.0
var obi4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 * 100.0 : 0.0

// ------------------------------------------------------------------------------
// Depth-Weighted Composite OBI (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level OFI with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3,4.
// Composite = Σ w_i × OBI_i / Σ w_i.
// This significantly improves short-horizon prediction vs. top-of-book alone.

var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
var w4 = useDepthWeighting ? weightDecay * weightDecay * weightDecay : 1.0

var wSum = w1 + w2 + w3 + w4
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / wSum : 0.0

// ------------------------------------------------------------------------------
// Z-Score Computation (Zhao & Palomar 2018) — Classic SMA-based
// ------------------------------------------------------------------------------
// z̄ = (OBI − μ_OBI) / σ_OBI over rolling lookback.
// Surfaces when the imbalance is statistically extreme relative to recent history.
// ~68.2% within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ.
// Classic version uses SMA smoothing rather than EMA for a more conservative,
// slower-reacting signal — consistent with longer lookback philosophy.

timeseries obiMean = sma(compositeOBI, zLookback)
timeseries obiStd = stdev(compositeOBI, zLookback)

// NaN guard: if std is zero or undefined, z-score is zero (no deviation)
var obiZ = (!isnan(obiMean) && !isnan(obiStd) && obiStd > 0) ? (compositeOBI - obiMean) / obiStd : 0.0
timeseries obiZS = sma(obiZ, zSmooth)

// Rolling standard deviation of the z-score itself (for adaptive band width)
timeseries zStd = stdev(obiZ, zLookback)
var zStdSafe = !isnan(zStd) && zStd > 0 ? zStd : 1.0

// ------------------------------------------------------------------------------
// σ-Band Construction (StudyRaid 2026 framework)
// ------------------------------------------------------------------------------
var band1Hi = band1Mult * zStdSafe
var band1Lo = -band1Mult * zStdSafe
var band2Hi = band2Mult * zStdSafe
var band2Lo = -band2Mult * zStdSafe
var band3Hi = band3Mult * zStdSafe
var band3Lo = -band3Mult * zStdSafe

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes based on z-score thresholds:
//   Extreme Bear: z ≤ -extremeThresh
//   Bear:         z ≤ bearThresh
//   Neutral:      bearThresh < z < bullThresh
//   Bull:         z ≥ bullThresh
//   Extreme Bull: z ≥ extremeThresh

var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

if (obiZS >= bullThresh) {
    regime = 1
} else if (obiZS <= bearThresh) {
    regime = -1
}

if (obiZS >= extremeThresh) {
    extremeRegime = 1
} else if (obiZS <= -extremeThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Individual Depth Z-Scores (optional, for granular analysis)
// ------------------------------------------------------------------------------
timeseries mean1 = sma(obi1, zLookback)
timeseries std1 = stdev(obi1, zLookback)
var z1 = (!isnan(mean1) && !isnan(std1) && std1 > 0) ? (obi1 - mean1) / std1 : 0.0

timeseries mean2 = sma(obi2, zLookback)
timeseries std2 = stdev(obi2, zLookback)
var z2 = (!isnan(mean2) && !isnan(std2) && std2 > 0) ? (obi2 - mean2) / std2 : 0.0

timeseries mean3 = sma(obi3, zLookback)
timeseries std3 = stdev(obi3, zLookback)
var z3 = (!isnan(mean3) && !isnan(std3) && std3 > 0) ? (obi3 - mean3) / std3 : 0.0

timeseries mean4 = sma(obi4, zLookback)
timeseries std4 = stdev(obi4, zLookback)
var z4 = (!isnan(mean4) && !isnan(std4) && std4 > 0) ? (obi4 - mean4) / std4 : 0.0

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for z-score extremes, regime transitions, and counters.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

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

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeBidCount = extremeBidCount + 1
    } else if (extremeRegime == -1) {
        extremeAskCount = extremeAskCount + 1
    }
}

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

// Horizontal guide lines — zero line and configurable threshold zones
hline(value=0, color="#ffffff30", width=1)

if (showBands) {
    hline(value=band1Hi, color=opacity(band1Color, 30), width=1)
    hline(value=band1Lo, color=opacity(band1Color, 30), width=1)
    hline(value=band2Hi, color=opacity(band2Color, 25), width=1)
    hline(value=band2Lo, color=opacity(band2Color, 25), width=1)
    hline(value=band3Hi, color=opacity(band3Color, 20), width=1)
    hline(value=band3Lo, color=opacity(band3Color, 20), width=1)
}

// Raw z-score as histogram (bid/ask pressure visualization)
if (showRawZ) {
    plotBar(
        value=obiZ,
        colors=[bidColor, askColor],
        width=1,
        label=["OB Z Raw"],
        desc=["Raw orderbook z-score histogram (positive=bid-heavy, negative=ask-heavy)"]
    )
}

// Smoothed z-score line with regime-coded fill area
if (showSmoothZ) {
    plotLine(
        value=obiZS,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["OB Z-Score (SMA)"],
        desc=["Smoothed orderbook z-score (SMA). Regime: bull/bear/neutral."],
        fill=true
    )
}

// σ-Band fills (regime-colored)
if (showBands && showBandFill) {
    // ±1σ fill
    plotLine(
        value=[band1Lo, band1Hi],
        width=1,
        colors=[opacity(bidColor, 8), opacity(askColor, 8)],
        colorIndex=regime == 1 ? 0 : 1,
        fill=true,
        label=["±1σ Fill"],
        desc=["±1σ band fill (~68.2% of expected values)"]
    )
    // ±2σ fill
    plotLine(
        value=[band2Lo, band2Hi],
        width=1,
        colors=[opacity(bidColor, 5), opacity(askColor, 5)],
        colorIndex=regime == 1 ? 0 : 1,
        fill=true,
        label=["±2σ Fill"],
        desc=["±2σ band fill (~95.4% of expected values)"]
    )
    // ±3σ fill
    plotLine(
        value=[band3Lo, band3Hi],
        width=1,
        colors=[opacity(bidColor, 3), opacity(askColor, 3)],
        colorIndex=regime == 1 ? 0 : 1,
        fill=true,
        label=["±3σ Fill"],
        desc=["±3σ band fill (~99.7% of expected values)"]
    )
}

// Individual depth z-score lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=z1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["Z 1% Depth"],
        desc=["Z-score at 1% depth (shallow book, top-of-book)"]
    )
    plotLine(
        value=z2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["Z 2.5% Depth"],
        desc=["Z-score at 2.5% depth (near-term liquidity)"]
    )
    plotLine(
        value=z3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["Z 5% Depth"],
        desc=["Z-score at 5% depth (medium-term absorption)"]
    )
    plotLine(
        value=z4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["Z 10% Depth"],
        desc=["Z-score at 10% depth (deep book, structural level)"]
    )
}

// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
if (showShapes) {
    var crossUp = obiZS >= bullThresh && !isnan(obiZS[1]) && obiZS[1] < bullThresh
    var crossDn = obiZS <= bearThresh && !isnan(obiZS[1]) && obiZS[1] > bearThresh
    var extremeUp = obiZS >= extremeThresh && !isnan(obiZS[1]) && obiZS[1] < extremeThresh
    var extremeDn = obiZS <= -extremeThresh && !isnan(obiZS[1]) && obiZS[1] > -extremeThresh
    var band1CrossUp = obiZS >= band1Hi && !isnan(obiZS[1]) && obiZS[1] < band1Hi
    var band1CrossDn = obiZS <= band1Lo && !isnan(obiZS[1]) && obiZS[1] > band1Lo
    var band2CrossUp = obiZS >= band2Hi && !isnan(obiZS[1]) && obiZS[1] < band2Hi
    var band2CrossDn = obiZS <= band2Lo && !isnan(obiZS[1]) && obiZS[1] > band2Lo
    var band3CrossUp = obiZS >= band3Hi && !isnan(obiZS[1]) && obiZS[1] < band3Hi
    var band3CrossDn = obiZS <= band3Lo && !isnan(obiZS[1]) && obiZS[1] > band3Lo

    if (crossUp) {
        plotShape(
            value=obiZS,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Z-score crossed into bullish regime (bid-heavy)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=obiZS,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Z-score crossed into bearish regime (ask-heavy)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=obiZS,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — z-score ≥ +extremeThresh"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=obiZS,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — z-score ≤ -extremeThresh"]
        )
    }
    if (band2CrossUp) {
        plotShape(
            value=obiZS,
            shape="circle",
            color=band2Color,
            width=3,
            label=["+2σ Cross"],
            desc=["Z-score crossed above +2σ band (~95.4% boundary)"]
        )
    }
    if (band2CrossDn) {
        plotShape(
            value=obiZS,
            shape="circle",
            color=band2Color,
            width=3,
            label=["-2σ Cross"],
            desc=["Z-score crossed below -2σ band (~95.4% boundary)"]
        )
    }
    if (band3CrossUp) {
        plotShape(
            value=obiZS,
            shape="cross",
            color=band3Color,
            width=3,
            label=["+3σ Cross"],
            desc=["Z-score crossed above +3σ band (~99.7% boundary)"]
        )
    }
    if (band3CrossDn) {
        plotShape(
            value=obiZS,
            shape="cross",
            color=band3Color,
            width=3,
            label=["-3σ Cross"],
            desc=["Z-score crossed below -3σ band (~99.7% boundary)"]
        )
    }
}