MM Flow
FlowScripts

Perfected FlowScript

Orderbook Imbalance Bubbles

Orderbook Imbalance Bubbles is indexed as 070_orderbook_imbalance_bubbles.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

onchart

Axis

false

Size

15.1 KB

Lines

335

Native Signal Candidates

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

4/4 guarded

Unlabeled shape

line 222:5

Trigger

(showBubbles && showBubble)

Value

bubbleY

Deps

showBubble:var, showBubbles:input

Unlabeled shape

line 240:5

Trigger

(showShapes && extremeRegime != 0)

Value

extremeY

Deps

extremeRegime:var, showShapes:input

Z Cross Up

line 256:9

Trigger

(showShapes) && (zCrossUp)

Value

l

Deps

showShapes:input, zCrossUp:var

Z Cross Down

line 266:9

Trigger

(showShapes) && (zCrossDn)

Value

h

Deps

showShapes:input, zCrossDn:var

070_orderbook_imbalance_bubbles.flowscript

source path: kscripts/perfected/070_orderbook_imbalance_bubbles.flowscript · sha256:81630265f0a7a8f9b207743d19e21a830b0ae271b5e30167ad043f7606a6e24e

hash verified
//@version=2
// ============================================================================
// Orderbook Imbalance Bubbles — Perfected Edition
// Author: kiyotaka (@kiyotaka) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #imbalance, #bubbles, #microstructure, #OBI, #zscore
//
// Visualizes orderbook pressure as dynamically-sized bubbles on the main chart,
// with bubble size scaling to the z-score of multi-depth OBI imbalance. Color
// and opacity encode direction and magnitude; shape markers flag extremes.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
//    per Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
// 2. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i where w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019), arXiv:1907.06230.
// 3. Z-Score Normalization: z = (OBI − μ_OBI) / σ_OBI  where μ, σ are rolling
//    mean and standard deviation over a lookback window. This is the standard
//    statistical normalization used in queue-imbalance predictive models
//    per Gould & Bonart (2016), Market Microstructure & Liquidity 2(1), 1650006.
// 4. Regime Segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy
//    (1/3,1) per Cartea, Donnelly & Jaimungal (2018), Appl. Math. Finance 25(1), 1–35.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014). OFI = Σ(E_i × ΔP_i); slope ∝ 1/depth.
//  • Xu, Gould & Howison (2019). Multi-level OFI with decaying weights.
//  • Gould & Bonart (2016). Queue imbalance logistic regression for next-tick
//    direction prediction; z-score normalization improves classification.
//  • Cartea, Donnelly & Jaimungal (2018). Three-regime segmentation predicts
//    future price moves: positive changes preceded by buy-heavy books.
//  • Order Book Filtration and Directional Signal Extraction (2025), arXiv:2507.22712.
//    OBI close to ±1 flags extreme directional imbalance; trade-based OBI(T)
//    eliminates flickering-quote noise.
// ============================================================================

define(
    title="Orderbook Imbalance Bubbles",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// 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")

// --- Bubble Display ---
var zScoreLookback = input(name="zScoreLookback", type="number", defaultValue=50, label="Z-Score Lookback (bars)", constraints={min: 10, max: 500, step: 5}, group="Bubble Display")
var bubbleScale = input(name="bubbleScale", type="number", defaultValue=8.0, label="Bubble Size Scale", constraints={min: 1.0, max: 30.0, step: 1.0}, group="Bubble Display")
var bubbleThreshold = input(name="bubbleThreshold", type="number", defaultValue=1.0, label="Z-Score Bubble Threshold", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Bubble Display")
var extremeZScore = input(name="extremeZScore", type="number", defaultValue=2.5, label="Extreme Z-Score Threshold", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Bubble Display")

var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show Imbalance Bubbles", group="Bubble Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shape Markers", group="Bubble Display")
var showHeatmap = input(name="showHeatmap", type="boolean", defaultValue=true, label="Show Imbalance Heatmap (Background)", group="Bubble 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 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 neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

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

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

// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
// Per Cont et al. (2014), the kScript API accepts depth as a float percentage.
// No truncation needed — depth1=1.0 means 1% band, depth2=2.5 means 2.5% band.

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]

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)
// ------------------------------------------------------------------------------
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 Normalization (Gould & Bonart 2016 — logistic regression preprocessing)
// ------------------------------------------------------------------------------
// Rolling mean and standard deviation of composite OBI for z-score computation.
// z = (x − μ) / σ. Higher |z| = more statistically extreme imbalance.

var rollingMean = sma(source=compositeOBI, period=zScoreLookback)
var rollingStd = stddev(source=compositeOBI, period=zScoreLookback)
var zScore = rollingStd > 0 ? (compositeOBI - rollingMean) / rollingStd : 0.0
var absZ = math.abs(zScore)

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Applied to composite OBI: Sell-heavy < −33%, Neutral [−33%, 33%], Buy-heavy > 33%.

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

if (compositeOBI >= 33.0) {
    regime = 1
} else if (compositeOBI <= -33.0) {
    regime = -1
}

if (absZ >= extremeZScore) {
    extremeRegime = regime  // 1 or -1
}

// ------------------------------------------------------------------------------
// Bubble Sizing Logic
// ------------------------------------------------------------------------------
// Bubble size scales with absolute z-score, capped at a maximum visual size.
// Only bubbles with |z| ≥ bubbleThreshold are rendered to reduce noise.

var bubbleSizeRaw = bubbleScale * absZ
var bubbleSize = math.min(bubbleSizeRaw, 16.0)
var showBubble = bookAvailable && absZ >= bubbleThreshold && bubbleSize > 1.0

// Bubble Y-position: below bar for bid-heavy, above bar for ask-heavy
var bubbleY = regime == 1 ? l : (regime == -1 ? h : na)

// Opacity scales inversely with z-score magnitude: more extreme = more opaque
// Base opacity range: 15% (weak) to 85% (extreme)
var opacityPct = math.min(85.0, 15.0 + absZ * 20.0)
var bubbleColor = regime == 1 ? opacity(bidColor, opacityPct) : opacity(askColor, opacityPct)
var extremeBubbleColor = regime == 1 ? opacity(extremeBidColor, opacityPct) : opacity(extremeAskColor, opacityPct)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks session extremes, bubble counts, and regime transitions for analytics.

static lastRegime = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static bubbleCount = 0
static extremeBubbleCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

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

    if (lastRegime != regime) {
        lastRegime = regime
    }

    if (showBubble) {
        bubbleCount = bubbleCount + 1
    }
    if (extremeRegime != 0) {
        extremeBubbleCount = extremeBubbleCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Bubbles, Shapes, Heatmap, and Overlay Lines
// ------------------------------------------------------------------------------

// --- Imbalance Bubbles (main visual) ---
if (showBubbles && showBubble) {
    var bubbleLabel = regime == 1 ? "Bid Bubble" : "Ask Bubble"
    var bubbleDesc = regime == 1
        ? "Bid-heavy imbalance bubble (z=" + zScore + ", OBI=" + compositeOBI + ")"
        : "Ask-heavy imbalance bubble (z=" + zScore + ", OBI=" + compositeOBI + ")"

    plotShape(
        value=bubbleY,
        shape="circle",
        color=extremeRegime != 0 ? extremeBubbleColor : bubbleColor,
        width=bubbleSize,
        label=[bubbleLabel],
        desc=[bubbleDesc]
    )
}

// --- Extreme Shape Markers (diamond for extreme z-scores) ---
if (showShapes && extremeRegime != 0) {
    var extremeY = extremeRegime == 1 ? l : h
    var extremeLabel = extremeRegime == 1 ? "Extreme Bid" : "Extreme Ask"
    var extremeDesc = extremeRegime == 1
        ? "Extreme bid pressure (z=" + zScore + ") — deep book buy-heavy imbalance"
        : "Extreme ask pressure (z=" + zScore + ") — deep book sell-heavy imbalance"

    plotShape(
        value=extremeY,
        shape="diamond",
        color=extremeRegime == 1 ? extremeBidColor : extremeAskColor,
        width=4,
        label=[extremeLabel],
        desc=[extremeDesc]
    )
}

// --- TK-style cross markers for regime transitions (z-score crossing threshold) ---
if (showShapes) {
    var zCrossUp = zScore >= bubbleThreshold && !isnan(zScore[1]) && zScore[1] < bubbleThreshold
    var zCrossDn = zScore <= -bubbleThreshold && !isnan(zScore[1]) && zScore[1] > -bubbleThreshold

    if (zCrossUp) {
        plotShape(
            value=l,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Z Cross Up"],
            desc=["Z-score crossed above bubble threshold — bid pressure emerging"]
        )
    }
    if (zCrossDn) {
        plotShape(
            value=h,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Z Cross Down"],
            desc=["Z-score crossed below bubble threshold — ask pressure emerging"]
        )
    }
}

// --- Imbalance Heatmap Background (subtle overlay behind candles) ---
if (showHeatmap && bookAvailable) {
    var heatmapColor = regime == 1
        ? opacity(bidColor, math.min(30, 5 + absZ * 5))
        : (regime == -1 ? opacity(askColor, math.min(30, 5 + absZ * 5)) : opacity(neutralColor, 5))

    plotLine(
        value=[h, l],
        width=1,
        colors=[heatmapColor, heatmapColor],
        fill=true,
        label=["Heatmap", "Heatmap"],
        desc=["Imbalance heatmap overlay — color intensity ∝ |z-score|"]
    )
}

// --- Composite OBI reference line (anchored at close for context) ---
if (bookAvailable) {
    var obiColor = regime == 1 ? opacity(bidColor, 40) : (regime == -1 ? opacity(askColor, 40) : opacity(neutralColor, 20))
    plotLine(
        value=px + (compositeOBI / 100.0) * atr(source=priceBars, period=14) * 0.5,
        width=1,
        colors=[obiColor],
        label=["OBI Anchor"],
        desc=["Composite OBI anchored to price (visual reference only)"]
    )
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only — summary of session state)
// ------------------------------------------------------------------------------
if (isLastBar && bookAvailable) {
    var regimeText = regime == 1 ? "BUY-HEAVY" : (regime == -1 ? "SELL-HEAVY" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)

    plotTable(
        data=[
            ["Orderbook Imbalance Bubbles", regimeText],
            ["Composite OBI", compositeOBI],
            ["Z-Score", zScore],
            ["Session High Z", sessionHighZ],
            ["Session Low Z", sessionLowZ],
            ["Bubbles Shown", bubbleCount],
            ["Extreme Bubbles", extremeBubbleCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}