MM Flow
FlowScripts

Perfected FlowScript

LOB

LOB Orderbook Imbalance V2 is indexed as 336_lob.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.3 KB

Lines

389

Native Signal Candidates

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

4/4 guarded

Bull Regime

line 317:9

Trigger

(showShapes) && (crossUp)

Value

displayValue

Deps

crossUp:var, showShapes:input

Bear Regime

line 327:9

Trigger

(showShapes) && (crossDn)

Value

displayValue

Deps

crossDn:var, showShapes:input

Extreme Bid

line 337:9

Trigger

(showShapes) && (extremeUp)

Value

displayValue

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 347:9

Trigger

(showShapes) && (extremeDn)

Value

displayValue

Deps

extremeDn:var, showShapes:input

336_lob.flowscript

source path: kscripts/perfected/336_lob.flowscript · sha256:28903ac38118ae9404596196162a1ab476d73fb258b43be27ade342042fd5688

hash verified
//@version=2
// ============================================================================
// LOB V2 — Limit Order Book Imbalance Pressure (Perfected Edition)
// Author: L (@Luv Chen)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #lob, #microstructure, #OBI, #depth, #zscore
//
// Multi-depth limit order book imbalance with depth-weighted composite,
// z-score normalization, regime detection, and academic microstructure foundations.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// 2. 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.
// 3. Z-Score Normalization: zOBI = (OBI − μ_OBI) / σ_OBI  per standard statistical practice.
// 4. Regime Segmentation: Extreme Bid (>2σ), Bid (>1σ), Neutral, Ask (<−1σ), Extreme Ask (<−2σ)
//    per Cartea, Donnelly & Jaimungal (2018) three-regime extension.
//
// 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.
//  • 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.
//  • Order Book Filtration and Directional Signal Extraction (2025). OBI as
//    bounded regime indicator; |OBI| → 1 flags directional extremes.
// ============================================================================

define(
    title="LOB Orderbook Imbalance V2",
    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 ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 1}, group="Z-Score")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Z-Score")

// --- 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.5, max: 5.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Threshold (σ)", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show Raw OBI Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", 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")

// ------------------------------------------------------------------------------
// 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
// ------------------------------------------------------------------------------
// CRITICAL: kScript sumBids/sumAsks accept float percentages (e.g., 1.0 = 1%).
// Do NOT use math.floor() which would truncate to integer levels and lose
// precision (e.g., 2.5% → 2%). This follows Cont et al. (2014) multi-depth
// operationalization: deeper books absorb imbalance with smaller price moves.

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)

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)

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.
// 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

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothed1 = ema(obi1, smoothLen)
var smoothed2 = ema(obi2, smoothLen)
var smoothed3 = ema(obi3, smoothLen)
var smoothed4 = ema(obi4, smoothLen)
var smoothedComposite = ema(compositeOBI, smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization
// ------------------------------------------------------------------------------
// Per standard statistical practice: z = (x − μ) / σ.
// Normalizes the composite OBI to units of standard deviation from its
// rolling mean, enabling cross-asset comparison and regime thresholding.

var obiMean = sma(smoothedComposite, zLookback)
var obiStd = stddev(smoothedComposite, zLookback)
var obiZ = useZScore && obiStd > 0 ? (smoothedComposite - obiMean) / obiStd : smoothedComposite

// Use z-scored or raw value for regime and plotting
var displayValue = useZScore ? obiZ : smoothedComposite

// ------------------------------------------------------------------------------
// Regime Detection (Cartea et al. 2018 three-segment model extended to five)
// ------------------------------------------------------------------------------
// Segmented into five regimes for finer granularity:
//   Extreme Bid:  displayValue ≥ extremeThresh
//   Bid:          bullThresh ≤ displayValue < extremeThresh
//   Neutral:      bearThresh < displayValue < bullThresh
//   Ask:          -extremeThresh < displayValue ≤ bearThresh
//   Extreme Ask:  displayValue ≤ -extremeThresh

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

if (displayValue >= extremeThresh) {
    regime = 1
    extremeRegime = 1
} else if (displayValue >= bullThresh) {
    regime = 1
    extremeRegime = 0
} else if (displayValue <= -extremeThresh) {
    regime = -1
    extremeRegime = -1
} else if (displayValue <= bearThresh) {
    regime = -1
    extremeRegime = 0
} else {
    regime = 0
    extremeRegime = 0
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex
    if (displayValue > sessionHighOBI) {
        sessionHighOBI = displayValue
    }
    if (displayValue < sessionLowOBI) {
        sessionLowOBI = displayValue
    }
    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 (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

// Horizontal guide lines
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=extremeThresh, color=opacity(extremeBidColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeAskColor, 20), width=1)
}

// Raw composite OBI as histogram bars (regime-colored)
if (showRawBars) {
    plotBar(
        value=displayValue,
        colors=[extremeBidColor, bidColor, neutralColor, askColor, extremeAskColor],
        colorIndex=extremeRegime == 1 ? 0 : (regime == 1 ? 1 : (regime == 0 ? 2 : (regime == -1 ? 3 : 4))),
        width=1,
        label=["OBI Histogram"],
        desc=["Depth-weighted composite OBI (z-scored if enabled) with regime coloring"]
    )
}

// Smoothed composite line with regime-coded fill area
if (showComposite) {
    plotLine(
        value=displayValue,
        width=2,
        colors=[extremeBidColor, bidColor, neutralColor, askColor, extremeAskColor],
        colorIndex=extremeRegime == 1 ? 0 : (regime == 1 ? 1 : (regime == 0 ? 2 : (regime == -1 ? 3 : 4))),
        label=["Composite OBI"],
        desc=["Depth-weighted composite OBI with regime coloring and fill"],
        fill=true
    )
}

// Z-score line (when enabled)
if (showZScore && useZScore) {
    plotLine(
        value=obiZ,
        width=2,
        colors=[extremeBidColor, bidColor, neutralColor, askColor, extremeAskColor],
        colorIndex=extremeRegime == 1 ? 0 : (regime == 1 ? 1 : (regime == 0 ? 2 : (regime == -1 ? 3 : 4))),
        label=["OBI Z-Score"],
        desc=["Z-score normalized OBI (σ units from rolling mean)"]
    )
}

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

// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
if (showShapes) {
    var crossUp = displayValue >= bullThresh && !isnan(displayValue[1]) && displayValue[1] < bullThresh
    var crossDn = displayValue <= bearThresh && !isnan(displayValue[1]) && displayValue[1] > bearThresh
    var extremeUp = displayValue >= extremeThresh && !isnan(displayValue[1]) && displayValue[1] < extremeThresh
    var extremeDn = displayValue <= -extremeThresh && !isnan(displayValue[1]) && displayValue[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=displayValue,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite OBI crossed into bullish regime (buy-heavy)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=displayValue,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite OBI crossed into bearish regime (sell-heavy)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=displayValue,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=displayValue,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
        )
    }
}

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

    plotTable(
        data=[
            ["LOB Imbalance V2", regimeText],
            ["Composite OBI", smoothedComposite[0]],
            ["Z-Score", obiZ[0]],
            ["Session High", sessionHighOBI],
            ["Session Low", sessionLowOBI],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Bid Bars", extremeBidCount],
            ["Extreme Ask Bars", extremeAskCount]
        ],
        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
    )
}