MM Flow
FlowScripts

Perfected FlowScript

Cumulative OB Imbalance (COBI) w/ Regime Shifts

COBI w/ Regime Shifts — Perfected Edition is indexed as 249_cumulative_ob_imbalance_cobi_w_regime_shifts.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.9 KB

Lines

484

Native Signal Candidates

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

7/7 guarded

Bull Regime

line 381:9

Trigger

(showShapes) && (crossUp)

Value

smoothedCOBI

Deps

crossUp:var, showShapes:input

Bear Regime

line 391:9

Trigger

(showShapes) && (crossDn)

Value

smoothedCOBI

Deps

crossDn:var, showShapes:input

Zero Cross Up

line 401:9

Trigger

(showShapes) && (zeroUp)

Value

smoothedCOBI

Deps

showShapes:input, zeroUp:var

Zero Cross Down

line 411:9

Trigger

(showShapes) && (zeroDn)

Value

smoothedCOBI

Deps

showShapes:input, zeroDn:var

Extreme Bid

line 421:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedCOBI

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 431:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedCOBI

Deps

extremeDn:var, showShapes:input

Reverting

line 441:9

Trigger

(showShapes) && (revertSignal)

Value

smoothedCOBI

Deps

revertSignal:var, showShapes:input

249_cumulative_ob_imbalance_cobi_w_regime_shifts.flowscript

source path: kscripts/perfected/249_cumulative_ob_imbalance_cobi_w_regime_shifts.flowscript · sha256:adb020a2ff8b1b3d7735a744d4dcf713875fd2e1ab20319f99597c8b267e1014

hash verified
//@version=2
// ============================================================================
// Cumulative OB Imbalance (COBI) w/ Regime Shifts — Perfected Edition
// Author: D (@ddave334)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #cobi, #microstructure, #regime, #imbalance
//
// Production-quality cumulative orderbook imbalance indicator with
// multi-depth depth-weighted composite, exponential-decay accumulation,
// regime-shift detection, and comprehensive fill/shape/histogram visualization.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol)  [−1, +1]
//    Per Cont, Kukanov & Stoikov (2014), OFI linear price-impact model.
// 2. Multi-Level OBI: Σ w_i × OBI_i / Σ w_i  where w_i = decay^(i−1)
//    Per Xu, Gould & Howison (2019), multi-level OFI with decaying weights.
// 3. Cumulative OBI (COBI): COBI_t = (1 − λ) × COBI_{t−1} + OBI_t
//    Per Lillo & Farmer (2004), long-memory order flow justifies cumulative
//    measures; exponential decay λ = 1/decayLen prevents infinite drift.
// 4. Regime Segmentation: Stretched Positive (> upperBound), Stretched Negative
//    (< lowerBound), Neutral (within bounds), Reverting (crossing zero).
//    Per Cartea, Donnelly & Jaimungal (2018) three-segment model extended.
// 5. Pull-to-Zero: When COBI exceeds bounds, it is pulled toward zero per
//    Poterba & Summers (1988) mean-reversion evidence.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI = Σ(E_i × ΔP_i); slope ∝ 1/depth.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//    Studies in Nonlinear Dynamics & Econometrics 8(3), 1. Long-memory order
//    flow justifies cumulative measures over per-bar readings.
//  • 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).
//  • Poterba & Summers (1988), "Mean Reversion in Stock Prices", JFE 22(1):27–59.
//    Empirical evidence of negative autocorrelation at medium horizons; supports
//    pull-to-zero and mean-reversion signal extraction from stretched extremes.
//  • 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="COBI w/ Regime Shifts — Perfected Edition",
    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")

// --- COBI Accumulation ---
var decayLen = input(name="decayLen", type="number", defaultValue=23, label="Decay Length (bars)", constraints={min: 5, max: 200, step: 1}, group="COBI")
var upperBound = input(name="upperBound", type="number", defaultValue=4.0, label="Upper Bound", constraints={min: 0.5, max: 20.0, step: 0.5}, group="COBI")
var lowerBound = input(name="lowerBound", type="number", defaultValue=-4.0, label="Lower Bound", constraints={min: -20.0, max: -0.5, step: 0.5}, group="COBI")
var pullToZero = input(name="pullToZero", type="boolean", defaultValue=true, label="Pull Toward Zero on Bound Hit", group="COBI")
var pullStrength = input(name="pullStrength", type="number", defaultValue=0.15, label="Pull Strength", constraints={min: 0.0, max: 1.0, step: 0.05}, group="COBI")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Threshold", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Threshold", constraints={min: -10.0, max: -0.1, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=3.0, label="Extreme Threshold", constraints={min: 1.0, max: 15.0, step: 0.5}, group="Thresholds")

// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show COBI Histogram", group="Display")
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show COBI Line", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid-Dominant Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask-Dominant 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 Bid Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Ask Color", group="Colors")
var fillBidColor = input(name="fillBidColor", type="color", defaultValue="#26a69a20", label="Fill Bid Color", group="Colors")
var fillAskColor = input(name="fillAskColor", type="color", defaultValue="#ef535020", label="Fill Ask Color", group="Colors")

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

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

// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
// Per Cont et al. (2014), multi-depth bands (1%, 2.5%, 5%, 10%) operationalize
// the finding that price impact slope is inversely proportional to depth.

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
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]
// Per Order Book Filtration and Directional Signal Extraction (2025).

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.

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

// ------------------------------------------------------------------------------
// Cumulative OBI (COBI) with Exponential Decay
// ------------------------------------------------------------------------------
// COBI_t = (1 − λ) × COBI_{t−1} + OBI_t
// λ = 1 / decayLen
// Per Lillo & Farmer (2004), long-memory order flow justifies cumulative
// measures. Exponential decay prevents infinite drift.

var decay = 1.0 / decayLen
static cobiState = 0.0

if (!isnan(compositeOBI) && bookAvailable) {
    cobiState = (1.0 - decay) * cobiState + compositeOBI / 100.0
}

// ------------------------------------------------------------------------------
// Bounds & Pull-to-Zero (Poterba & Summers 1988 mean-reversion)
// ------------------------------------------------------------------------------
// When COBI exceeds bounds, it is pulled toward zero to maintain responsiveness
// and prevent runaway accumulation.

var bounded = cobiState

if (bounded > upperBound) {
    bounded = pullToZero ? bounded - pullStrength * (bounded - upperBound) : upperBound
} else if (bounded < lowerBound) {
    bounded = pullToZero ? bounded + pullStrength * (lowerBound - bounded) : lowerBound
}

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothedCOBI = ema(source=bounded, period=smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (extended Cartea et al. 2018 three-segment model)
// ------------------------------------------------------------------------------
// Regime classification:
//   Stretched Positive:  smoothedCOBI ≥ bullThresh
//   Stretched Negative:  smoothedCOBI ≤ bearThresh
//   Neutral:              bearThresh < smoothedCOBI < bullThresh
//   Extreme:              |smoothedCOBI| ≥ extremeThresh

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

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

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

// Reverting regime: value was beyond threshold and is now returning toward zero
var priorBeyondThresh = !isnan(smoothedCOBI[1]) && (smoothedCOBI[1] >= bullThresh || smoothedCOBI[1] <= bearThresh)
var nowWithinThresh = smoothedCOBI < bullThresh && smoothedCOBI > bearThresh
if (priorBeyondThresh && nowWithinThresh) {
    isReverting = true
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, cumulative events, and zero crosses.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighCOBI = -999999.0
static sessionLowCOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static zeroCrossCount = 0
static lastBarIndex = 0
static lastBounded = 0.0

var currentBarIndex = bar_index[0]

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

    if (bounded > sessionHighCOBI) {
        sessionHighCOBI = bounded
    }
    if (bounded < sessionLowCOBI) {
        sessionLowCOBI = bounded
    }

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

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

    // Zero-cross detection
    if ((lastBounded > 0 && bounded <= 0) || (lastBounded < 0 && bounded >= 0)) {
        zeroCrossCount = zeroCrossCount + 1
    }
    lastBounded = bounded
}

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

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

if (showGuides) {
    hline(value=bullThresh, color=opacity(bidColor, 30), width=1)
    hline(value=bearThresh, color=opacity(askColor, 30), width=1)
    hline(value=upperBound, color=opacity(extremeBidColor, 20), width=1)
    hline(value=lowerBound, color=opacity(extremeAskColor, 20), width=1)
}

// COBI histogram (color-coded by regime)
if (showHistogram) {
    var histColorIdx = regime == 1 ? 0 : (regime == -1 ? 2 : 1)
    plotBar(
        value=smoothedCOBI,
        colors=[bidColor, neutralColor, askColor],
        colorIndex=histColorIdx,
        width=1,
        label=["COBI Histogram"],
        desc=["Cumulative OB Imbalance histogram (positive=bid, negative=ask)"]
    )
}

// COBI line with regime-coded fill area
if (showLine) {
    var lineColorIdx = regime == 1 ? 0 : (regime == -1 ? 1 : 2)
    var lineColors = [bidColor, askColor, neutralColor]
    if (extremeRegime == 1) {
        lineColors = [extremeBidColor, askColor, neutralColor]
        lineColorIdx = 0
    } else if (extremeRegime == -1) {
        lineColors = [bidColor, extremeAskColor, neutralColor]
        lineColorIdx = 1
    }

    plotLine(
        value=smoothedCOBI,
        width=2,
        colors=lineColors,
        colorIndex=lineColorIdx,
        label=["COBI"],
        desc=["Cumulative OB Imbalance with exponential decay and regime coloring"],
        fill=showFill
    )
}

// Fill area between COBI and zero line (regime-colored)
if (showFill) {
    var fillColorIdx = regime == 1 ? 0 : (regime == -1 ? 1 : 2)
    plotLine(
        value=[smoothedCOBI, 0],
        width=1,
        colors=[fillBidColor, fillAskColor, neutralColor],
        colorIndex=fillColorIdx,
        fill=true,
        label=["COBI", "Zero"],
        desc=["Fill between COBI and zero line"]
    )
}

// Individual depth lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=obi1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["OBI 1%"],
        desc=["Order Book Imbalance at 1% depth (shallow book, top-of-book)"]
    )
    plotLine(
        value=obi2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["OBI 2.5%"],
        desc=["Order Book Imbalance at 2.5% depth (near-term liquidity)"]
    )
    plotLine(
        value=obi3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["OBI 5%"],
        desc=["Order Book Imbalance at 5% depth (medium-term absorption)"]
    )
    plotLine(
        value=obi4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["OBI 10%"],
        desc=["Order Book Imbalance at 10% depth (deep book, structural level)"]
    )
}

// Regime transition shapes
if (showShapes) {
    // Cross into bullish regime
    var crossUp = smoothedCOBI >= bullThresh && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] < bullThresh
    // Cross into bearish regime
    var crossDn = smoothedCOBI <= bearThresh && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] > bearThresh
    // Zero cross up
    var zeroUp = smoothedCOBI >= 0 && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] < 0
    // Zero cross down
    var zeroDn = smoothedCOBI <= 0 && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] > 0
    // Extreme bid
    var extremeUp = smoothedCOBI >= extremeThresh && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] < extremeThresh
    // Extreme ask
    var extremeDn = smoothedCOBI <= -extremeThresh && !isnan(smoothedCOBI[1]) && smoothedCOBI[1] > -extremeThresh
    // Reverting signal
    var revertSignal = isReverting && smoothedCOBI < bullThresh && smoothedCOBI > bearThresh

    if (crossUp) {
        plotShape(
            value=smoothedCOBI,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["COBI crossed into bullish regime (buy-heavy cumulative pressure)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedCOBI,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["COBI crossed into bearish regime (sell-heavy cumulative pressure)"]
        )
    }
    if (zeroUp) {
        plotShape(
            value=smoothedCOBI,
            shape="circle",
            color=bidColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["COBI crossed above zero — cumulative pressure flipped bid-dominant"]
        )
    }
    if (zeroDn) {
        plotShape(
            value=smoothedCOBI,
            shape="circle",
            color=askColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["COBI crossed below zero — cumulative pressure flipped ask-dominant"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smoothedCOBI,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — stretched COBI, mean reversion risk rising"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smoothedCOBI,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — stretched COBI, mean reversion risk rising"]
        )
    }
    if (revertSignal) {
        plotShape(
            value=smoothedCOBI,
            shape="xcross",
            color=neutralColor,
            width=2,
            label=["Reverting"],
            desc=["COBI returning from stretched regime toward neutral — mean reversion in progress"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "STRETCHED BID" : (regime == -1 ? "STRETCHED ASK" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
    var extremeText = extremeRegime == 1 ? "EXTREME BID" : (extremeRegime == -1 ? "EXTREME ASK" : "NORMAL")

    plotTable(
        data=[
            ["COBI — Perfected", regimeText],
            ["COBI Value", smoothedCOBI[0]],
            ["Session High", sessionHighCOBI],
            ["Session Low", sessionLowCOBI],
            ["Regime Changes", regimeChangeCount],
            ["Zero Crosses", zeroCrossCount],
            ["Extreme Events", extremeBidCount + extremeAskCount],
            ["Extreme Status", extremeText]
        ],
        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
    )
}