MM Flow
FlowScripts

Perfected FlowScript

DOM

DOM Aggregated Depth of Market [Perfected] is indexed as 089_dom.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

15.0 KB

Lines

363

Native Signal Candidates

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

5/5 guarded

Bid-Heavy Regime

line 313:9

Trigger

(showShapes) && (crossUp)

Value

smCumImb

Deps

crossUp:var, showShapes:input

Ask-Heavy Regime

line 323:9

Trigger

(showShapes) && (crossDn)

Value

smCumImb

Deps

crossDn:var, showShapes:input

Extreme Bid DOM

line 333:9

Trigger

(showShapes) && (extremeUp)

Value

smCumImb

Deps

extremeUp:var, showShapes:input

Extreme Ask DOM

line 343:9

Trigger

(showShapes) && (extremeDn)

Value

smCumImb

Deps

extremeDn:var, showShapes:input

Level Flip

line 353:9

Trigger

(showShapes) && (levelFlip)

Value

smCumImb

Deps

levelFlip:var, showShapes:input

089_dom.flowscript

source path: kscripts/perfected/089_dom.flowscript · sha256:68b1ff8a3952d73db54d431dd0eecd933ee8d364d4e0f8295ecc3560f7425654

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// DOM Aggregated Depth of Market — Multi-Level Liquidity Visualization [Perfected]
// Author: M (@maxication) — Perfected by kScript_Perfection_Engineer
// Tags: FLOW, #orderbook, #dom, #depth, #liquidity, #microstructure, #imbalance
//
// Aggregated Depth of Market (DOM) visualization for 1–10% orderbook depth
// bands, showing liquidity distribution across price levels, cumulative
// bid/ask depth, per-level imbalance, and composite imbalance detection.
// Reveals where liquidity is concentrated and whether bids or asks dominate
// at each depth layer.
//
// FORMULA FOUNDATION:
// 1. Bid/Ask Depth: sumBids(book, depth%) and sumAsks(book, depth%) per
//    Xu, Gould & Howison (2019); deeper levels contain predictive information.
// 2. Imbalance Ratio: (Bid − Ask) / (Bid + Ask) ∈ [−1, +1] per Cont, Kukanov &
//    Stoikov (2014) and Order Book Filtration (2025).
// 3. Cumulative Depth: rolling aggregation across depth bands to reveal
//    structural liquidity walls per Lehalle & Laruelle (2018).
// 4. Per-Level Delta: bid_i − ask_i at each depth to identify where
//    pressure shifts from bid-heavy to ask-heavy (inflection analysis).
//
// RESEARCH BASIS:
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-depth aggregation improves prediction.
//  • Wu, Mahfouz, Magazzeni & Veloso (2021), "Towards Robust Representation of
//    Limit Order Books for Deep Learning Models", ICAIF-2021. LOBs as self-
//    evolving processes; deeper spatial-temporal features needed.
//  • Lehalle & Laruelle (2018), "Market Microstructure in Practice" (2nd Ed.).
//    Propagator models for intraday price impact; liquidity predicts future.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events".
//    Linear price-impact model; slope ∝ 1/depth.
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//    Predictor". Queue imbalance logistic regression for next-tick direction.
// ============================================================================

define(
    title="DOM Aggregated Depth of Market [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.0, 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")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=10, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var smoothDepth = input(name="smoothDepth", type="boolean", defaultValue=true, label="Smooth Depth Series", group="Smoothing")

// --- Imbalance Thresholds ---
var strongImbThresh = input(name="strongImbThresh", type="number", defaultValue=0.5, label="Strong Imbalance Threshold", constraints={min: 0.1, max: 0.95, step: 0.05}, group="Thresholds")
var extremeImbThresh = input(name="extremeImbThresh", type="number", defaultValue=0.75, label="Extreme Imbalance Threshold", constraints={min: 0.5, max: 0.99, step: 0.05}, group="Thresholds")

// --- Display ---
var showBidAsk = input(name="showBidAsk", type="boolean", defaultValue=true, label="Show Bid/Ask Depth Lines", group="Display")
var showCumulative = input(name="showCumulative", type="boolean", defaultValue=true, label="Show Cumulative Depth", group="Display")
var showPerLevel = input(name="showPerLevel", type="boolean", defaultValue=true, label="Show Per-Level Imbalance", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Imbalance", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Depth Delta (Bid − Ask)", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Imbalance Shapes", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid Depth Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask Depth Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var imbBidColor = input(name="imbBidColor", type="color", defaultValue="#00e676", label="Bid-Heavy Imbalance Color", group="Colors")
var imbAskColor = input(name="imbAskColor", type="color", defaultValue="#ff1744", label="Ask-Heavy Imbalance Color", group="Colors")
var compositeColor = input(name="compositeColor", type="color", defaultValue="#ff9800", label="Composite Imbalance Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries book = source("orderbook", currentSymbol, currentExchange)

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

// ---------------------------------------------------------------------------
// Order Book Aggregation at Four Depth Bands
// ---------------------------------------------------------------------------
// Per-level bid/ask sums. No math.floor() wrapper — depth is float percentage.

var bid1 = sumBids(book, depth1)
var ask1 = sumAsks(book, depth1)
var bid2 = sumBids(book, depth2)
var ask2 = sumAsks(book, depth2)
var bid3 = sumBids(book, depth3)
var ask3 = sumAsks(book, depth3)
var bid4 = sumBids(book, depth4)
var ask4 = sumAsks(book, depth4)

// Book availability check
var bookAvailable = bid1 > 0 && ask1 > 0 && bid2 > 0 && ask2 > 0 && bid3 > 0 && ask3 > 0 && bid4 > 0 && ask4 > 0

// ---------------------------------------------------------------------------
// Cumulative Depth (structural liquidity walls)
// ---------------------------------------------------------------------------
var cumBid1 = bid1
var cumAsk1 = ask1
var cumBid2 = bid1 + bid2
var cumAsk2 = ask1 + ask2
var cumBid3 = cumBid2 + bid3
var cumAsk3 = cumAsk2 + ask3
var cumBid4 = cumBid3 + bid4
var cumAsk4 = cumAsk3 + ask4

var totalLiq = cumBid4 + cumAsk4

// ---------------------------------------------------------------------------
// Per-Level Imbalance Ratios
// ---------------------------------------------------------------------------
// Imbalance at each depth band: (Bid − Ask) / (Bid + Ask)

var imb1 = bookAvailable && (bid1 + ask1) > 0 ? (bid1 - ask1) / (bid1 + ask1) : 0.0
var imb2 = bookAvailable && (bid2 + ask2) > 0 ? (bid2 - ask2) / (bid2 + ask2) : 0.0
var imb3 = bookAvailable && (bid3 + ask3) > 0 ? (bid3 - ask3) / (bid3 + ask3) : 0.0
var imb4 = bookAvailable && (bid4 + ask4) > 0 ? (bid4 - ask4) / (bid4 + ask4) : 0.0

// Cumulative imbalance (full 10% depth)
var cumImb = totalLiq > 0 ? (cumBid4 - cumAsk4) / totalLiq : 0.0

// Depth delta per level (bid − ask in raw units)
var delta1 = bid1 - ask1
var delta2 = bid2 - ask2
var delta3 = bid3 - ask3
var delta4 = bid4 - ask4

// ---------------------------------------------------------------------------
// Smoothing
// ---------------------------------------------------------------------------
var smCumBid = smoothDepth ? ema(cumBid4, smoothLen) : cumBid4
var smCumAsk = smoothDepth ? ema(cumAsk4, smoothLen) : cumAsk4
var smCumImb = smoothDepth ? ema(cumImb, smoothLen) : cumImb
var smDelta = smoothDepth ? ema(delta1 + delta2 + delta3 + delta4, smoothLen) : (delta1 + delta2 + delta3 + delta4)

// ---------------------------------------------------------------------------
// Regime Detection (imbalance strength classification)
// ---------------------------------------------------------------------------
var cumRegime = 0  // 0 = neutral, 1 = bid-heavy, -1 = ask-heavy
var extremeRegime = 0  // 0 = normal, 1 = extreme bid, -1 = extreme ask

if (smCumImb >= strongImbThresh) {
    cumRegime = 1
} else if (smCumImb <= -strongImbThresh) {
    cumRegime = -1
}

if (smCumImb >= extremeImbThresh) {
    extremeRegime = 1
} else if (smCumImb <= -extremeImbThresh) {
    extremeRegime = -1
}

// Per-level regime (for shape triggers at individual depths)
var reg1 = imb1 >= strongImbThresh ? 1 : (imb1 <= -strongImbThresh ? -1 : 0)
var reg4 = imb4 >= strongImbThresh ? 1 : (imb4 <= -strongImbThresh ? -1 : 0)

// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
static sessionHighImb = -999999.0
static sessionLowImb = 999999.0
static sessionHighBid = 0.0
static sessionHighAsk = 0.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (cumImb > sessionHighImb) {
        sessionHighImb = cumImb
    }
    if (cumImb < sessionLowImb) {
        sessionLowImb = cumImb
    }
    if (cumBid4 > sessionHighBid) {
        sessionHighBid = cumBid4
    }
    if (cumAsk4 > sessionHighAsk) {
        sessionHighAsk = cumAsk4
    }

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

// ---------------------------------------------------------------------------
// Cross & Extreme Detection (shape triggers)
// ---------------------------------------------------------------------------
var crossUp = smCumImb >= strongImbThresh && !isnan(smCumImb[1]) && smCumImb[1] < strongImbThresh
var crossDn = smCumImb <= -strongImbThresh && !isnan(smCumImb[1]) && smCumImb[1] > -strongImbThresh
var extremeUp = smCumImb >= extremeImbThresh && !isnan(smCumImb[1]) && smCumImb[1] < extremeImbThresh
var extremeDn = smCumImb <= -extremeImbThresh && !isnan(smCumImb[1]) && smCumImb[1] > -extremeImbThresh
var levelFlip = (reg1 == 1 && reg4 == -1) || (reg1 == -1 && reg4 == 1)

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

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

// --- Bid / Ask Cumulative Depth Lines ---
if (showBidAsk) {
    plotLine(
        value=smCumBid,
        width=lineWidth,
        colors=[bidColor],
        label=["Cum Bid Depth"],
        desc=["Cumulative bid depth up to 10% (smoothed)"]
    )
    plotLine(
        value=smCumAsk,
        width=lineWidth,
        colors=[askColor],
        label=["Cum Ask Depth"],
        desc=["Cumulative ask depth up to 10% (smoothed)"]
    )
}

// --- Cumulative Depth Fill (between bid and ask) ---
if (showCumulative) {
    plotLine(
        value=([smCumAsk, smCumBid]),
        width=1,
        colors=[opacity(askColor, 15), opacity(bidColor, 15)],
        colorIndex=cumRegime == 1 ? 1 : 0,
        fill=true,
        label=["Depth Spread Fill"],
        desc=["Filled area between cumulative bid and ask depth (regime-colored)"]
    )
}

// --- Per-Level Imbalance Lines ---
if (showPerLevel) {
    plotLine(
        value=imb1,
        width=1,
        colors=[opacity(imbBidColor, 50)],
        label=["Imb 1%"],
        desc=["Imbalance ratio at 1% depth (shallow book)"]
    )
    plotLine(
        value=imb2,
        width=1,
        colors=[opacity(imbBidColor, 40)],
        label=["Imb 2%"],
        desc=["Imbalance ratio at 2% depth"]
    )
    plotLine(
        value=imb3,
        width=1,
        colors=[opacity(imbAskColor, 40)],
        label=["Imb 5%"],
        desc=["Imbalance ratio at 5% depth"]
    )
    plotLine(
        value=imb4,
        width=1,
        colors=[opacity(imbAskColor, 50)],
        label=["Imb 10%"],
        desc=["Imbalance ratio at 10% depth (deep book)"]
    )
}

// --- Composite Imbalance Line ---
if (showComposite) {
    plotLine(
        value=smCumImb,
        width=lineWidth,
        colors=[imbBidColor, imbAskColor, neutralColor],
        colorIndex=cumRegime == 1 ? 0 : (cumRegime == -1 ? 1 : 2),
        label=["Composite Imbalance"],
        desc=["Cumulative imbalance ratio up to 10% depth (regime-coded)"]
    )
}

// --- Depth Delta (Bid − Ask) ---
if (showDelta) {
    plotLine(
        value=smDelta,
        width=1,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=smDelta > 0 ? 0 : (smDelta < 0 ? 1 : 2),
        label=["Depth Delta"],
        desc=["Net depth delta (bid − ask) across all four depth bands"]
    )
}

// --- Imbalance Shapes ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=smCumImb,
            shape="triangleup",
            colorIndex=imbBidColor,
            width=shapeSize + 1,
            label=["Bid-Heavy Regime"],
            desc=["Cumulative imbalance crossed into bid-heavy regime"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smCumImb,
            shape="triangledown",
            colorIndex=imbAskColor,
            width=shapeSize + 1,
            label=["Ask-Heavy Regime"],
            desc=["Cumulative imbalance crossed into ask-heavy regime"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smCumImb,
            shape="diamond",
            colorIndex=imbBidColor,
            width=shapeSize + 2,
            label=["Extreme Bid DOM"],
            desc=["Extreme bid dominance in cumulative DOM — deep book buy wall"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smCumImb,
            shape="diamond",
            colorIndex=imbAskColor,
            width=shapeSize + 2,
            label=["Extreme Ask DOM"],
            desc=["Extreme ask dominance in cumulative DOM — deep book sell wall"]
        )
    }
    if (levelFlip) {
        plotShape(
            value=smCumImb,
            shape="circle",
            colorIndex=compositeColor,
            width=shapeSize,
            label=["Level Flip"],
            desc=["Shallow (1%) and deep (10%) imbalance regimes diverge — inflection signal"]
        )
    }
}