MM Flow
FlowScripts

Perfected FlowScript

Market Order Bubbles • [Leviathan]

Market Order Bubbles V2 is indexed as 048_market_order_bubbles_leviathan.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

12.9 KB

Lines

290

Native Signal Candidates

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

4/4 guarded

Buy Bubble

line 209:5

Trigger

(showBubbles && buySize > 0)

Value

buyY

Deps

buySize:timeseries, showBubbles:input

Sell Bubble

line 220:5

Trigger

(showBubbles && sellSize > 0)

Value

sellY

Deps

sellSize:timeseries, showBubbles:input

Extreme Buy

line 234:5

Trigger

(showShapes && extremeBuy)

Value

l

Deps

extremeBuy:var, showShapes:input

Extreme Sell

line 245:5

Trigger

(showShapes && extremeSell)

Value

h

Deps

extremeSell:var, showShapes:input

048_market_order_bubbles_leviathan.flowscript

source path: kscripts/perfected/048_market_order_bubbles_leviathan.flowscript · sha256:c508c1eb48ba5f77b6eb36e0796840a5babee3bfe86338bf51eac1b38ff74fd8

hash verified
//@version=2
// ============================================================================
// Market Order Bubbles V2 — Statistically Significant Aggressive Flow Visualiser
// Author: Leviathan (@Leviathan) | Perfected by: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #marketorderbubbles, #bubbles, #volumebubbles, #leviathan
//
// Visualises statistically significant aggressive buying and selling activity
// as on-chart bubbles with z-score sizing, opacity scaling, and directional
// color coding. Captures absorption at extremes and informed-flow events.
//
// FORMULA FOUNDATION:
// 1. Signed Volume: V_signed = V_buy − V_sell per bar (Lee-Ready 1991 tick-rule
//    fallback when direct taker feed is unavailable).
// 2. Z-Score Normalisation: z_t = (V_signed − μ) / σ over rolling window W.
//    Per Zhao & Palomar (2018); bubble size ∝ |z_t| / threshold.
// 3. VPIN Framework: Easley, López de Prado & O'Hara (2012) — extreme |z|
//    flags volume-synchronized informed trading / flow toxicity.
// 4. Square-Root Impact Law: Bouchaud, Farmer & Lillo (2009) — large volume
//    events may indicate absorption (sublinear price impact) when bubbles
//    cluster without price follow-through.
// 5. Critical Liquidity: Tóth et al. (2011) — universal character of market
//    impact validates cross-asset bubble significance.
//
// RESEARCH BASIS:
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World" (VPIN). J. Portfolio Management 38(2), 1–15.
//    VPIN = Σ|V_buy − V_sell| / ΣV_total over volume buckets; anticipates
//    market stress events. DOI: 10.3905/jpm.2012.38.2.106
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand". J. Economic Dynamics & Control 32(1), 200–234.
//    Square-root impact law: R_t = λ·Σ V_t^{1/2}; liquidity memory time.
//  • Tóth et al. (2011), "Anomalous Price Impact and the Critical Nature of
//    Liquidity in Financial Markets". Physical Review X 1(2), 021006.
//    Universal square-root impact across diverse markets.
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    J. Finance 46(2), 733–746. Tick-test classification: ~85–93% accuracy.
//    DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    z-score event triggers: z̄_t = (z_t − μ_z) / σ_z; entry at ±2σ.
// ============================================================================

define(
    title="Market Order Bubbles V2",
    position="onchart",
    axis=false
)

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

// --- Computation ---
var zLen = input(name="zLen", type="number", defaultValue=50, label="Z-Score Lookback (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var zThreshold = input(name="zThreshold", type="number", defaultValue=2.0, label="Significance Threshold (|z|)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var bubbleScale = input(name="bubbleScale", type="number", defaultValue=4.0, label="Bubble Size Multiplier", constraints={min: 1.0, max: 10.0, step: 1.0}, group="Computation")
var maxBubbleSize = input(name="maxBubbleSize", type="number", defaultValue=12, label="Max Bubble Size", constraints={min: 4, max: 20, step: 1}, group="Computation")
var extremeMult = input(name="extremeMult", type="number", defaultValue=1.5, label="Extreme Event Multiplier", constraints={min: 1.0, max: 3.0, step: 0.5}, group="Computation")

// --- Display ---
var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show Bubbles", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showZLine = input(name="showZLine", type="boolean", defaultValue=false, label="Show Z-Score Line", group="Display")
var showCounts = input(name="showCounts", type="boolean", defaultValue=false, label="Show Event Count Lines", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Buy Bubble Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Sell Bubble Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Sell Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume

timeseries taker = source("taker_volume", currentSymbol, currentExchange)

// NaN guard — halt until price data is loaded to prevent NaN propagation
if (isnan(c[0])) {
    return
}

// ------------------------------------------------------------------------------
// Signed Volume (Taker Feed Priority + Lee-Ready 1991 Fallback)
// ------------------------------------------------------------------------------
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, we prefer the direct feed for higher accuracy.
// This is the foundational classification for all volume delta calculations.

timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)

timeseries buyVol = isnum(taker.buy) ? taker.buy : (range_ > 0 ? v * (upW / range_) : v * 0.5)
timeseries selVol = isnum(taker.sell) ? taker.sell : (range_ > 0 ? v * (dnW / range_) : v * 0.5)
timeseries signed = buyVol - selVol

// ------------------------------------------------------------------------------
// Z-Score Normalisation (all denominators guarded against zero)
// ------------------------------------------------------------------------------
// Z_t = (Signed_t − μ_t) / σ_t, where μ_t = SMA(Signed, W), σ_t = StDev(Signed, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
// Per Zhao & Palomar (2018) and the VPIN statistical framework.

timeseries sMean = sma(signed, zLen)
timeseries sStd = stdev(signed, zLen)
timeseries sZ = sStd > 0 ? (signed - sMean) / sStd : 0.0

timeseries absZ = abs(sZ)

// ------------------------------------------------------------------------------
// Bubble Logic — z-score sizing with opacity scaling
// ------------------------------------------------------------------------------
// Bubble size scales linearly with |z| / threshold, capped at maxBubbleSize.
// Bubbles are placed below price for buy events (near lows) and above price
// for sell events (near highs) to create spatial relationship with price action.
// Opacity is scaled by significance: higher |z| = more visually prominent.

timeseries isBuyBubble = sZ > zThreshold
timeseries isSellBubble = sZ < -zThreshold
timeseries buyY = isBuyBubble ? l : na
timeseries sellY = isSellBubble ? h : na

// Bubble size scales with z-score magnitude, capped at maxBubbleSize
timeseries buySize = isBuyBubble ? math.min(bubbleScale * absZ / zThreshold, maxBubbleSize) : 0
timeseries sellSize = isSellBubble ? math.min(bubbleScale * absZ / zThreshold, maxBubbleSize) : 0

// Opacity scalars (fixed tiers based on significance level)
var buyOpacity = 60
var sellOpacity = 60
var extremeBuyOpacity = 90
var extremeSellOpacity = 90

// ------------------------------------------------------------------------------
// Regime Detection (Extreme Market Order Classification)
// ------------------------------------------------------------------------------
// Extreme events are defined as |z| > threshold × extremeMult (default 1.5×).
// These flag potential absorption or informed trading events beyond the
// standard significance threshold.

var extremeBuy = sZ > zThreshold * extremeMult
var extremeSell = sZ < -zThreshold * extremeMult
var regime = sZ > zThreshold ? 1 : (sZ < -zThreshold ? -1 : 0)

// ------------------------------------------------------------------------------
// Static State Tracking (Event-level persistence)
// ------------------------------------------------------------------------------
// Tracks consecutive bars in each regime for context-aware alerting.
// Also tracks cumulative event counts for the optional diagnostic lines.
// Persistence enables detection of sustained aggressive flow vs. one-off spikes.

static lastRegime = 0
static buyEventCount = 0
static sellEventCount = 0
static extremeBuyCount = 0
static extremeSellCount = 0
static consecutiveBuyBars = 0
static consecutiveSellBars = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (regime == 1) {
        consecutiveBuyBars = consecutiveBuyBars + 1
        consecutiveSellBars = 0
    } else if (regime == -1) {
        consecutiveSellBars = consecutiveSellBars + 1
        consecutiveBuyBars = 0
    } else {
        consecutiveBuyBars = 0
        consecutiveSellBars = 0
    }

    if (regime == 1 && lastRegime != 1) {
        buyEventCount = buyEventCount + 1
        lastRegime = 1
    } else if (regime == -1 && lastRegime != -1) {
        sellEventCount = sellEventCount + 1
        lastRegime = -1
    } else if (regime == 0) {
        lastRegime = 0
    }

    if (extremeBuy) {
        extremeBuyCount = extremeBuyCount + 1
    }
    if (extremeSell) {
        extremeSellCount = extremeSellCount + 1
    }
}

// ------------------------------------------------------------------------------
// Visualization — Multiple types: bubble, shape, line, hline
// ------------------------------------------------------------------------------

// 1. Bubbles with z-score sizing and directional color coding
//    Buy bubbles at lows (green tones), sell bubbles at highs (red tones).
//    Size ∝ |z-score| so more significant events are visually larger.
if (showBubbles && buySize > 0) {
    plotShape(
        value=buyY,
        shape="circle",
        colorIndex=opacity(bidColor, extremeBuy ? extremeBuyOpacity : buyOpacity),
        width=buySize,
        label=["Buy Bubble"],
        desc=["Statistically significant aggressive buying (z > threshold); size ∝ |z|"]
    )
}

if (showBubbles && sellSize > 0) {
    plotShape(
        value=sellY,
        shape="circle",
        colorIndex=opacity(askColor, extremeSell ? extremeSellOpacity : sellOpacity),
        width=sellSize,
        label=["Sell Bubble"],
        desc=["Statistically significant aggressive selling (z < -threshold); size ∝ |z|"]
    )
}

// 2. Extreme market order shapes (diamonds for extreme events)
//    Diamonds mark events beyond the extreme multiplier (default 1.5× threshold).
//    These often indicate absorption, exhaustion, or informed flow.
if (showShapes && extremeBuy) {
    plotShape(
        value=l,
        shape="diamond",
        colorIndex=extremeBidColor,
        width=4,
        label=["Extreme Buy"],
        desc=["Extreme aggressive buying event: z > 1.5× threshold; potential absorption / continuation"]
    )
}

if (showShapes && extremeSell) {
    plotShape(
        value=h,
        shape="diamond",
        colorIndex=extremeAskColor,
        width=4,
        label=["Extreme Sell"],
        desc=["Extreme aggressive selling event: z < -1.5× threshold; potential absorption / continuation"]
    )
}

// 3. Optional z-score line (for context and divergence analysis)
//    Plots the raw signed-volume z-score as a reference line.
if (showZLine) {
    plotLine(
        value=sZ,
        width=1,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Signed Volume Z"],
        desc=["Rolling z-score of signed volume; context for bubble events and divergence detection"]
    )
}

// 4. Optional event-count lines (diagnostic)
if (showCounts) {
    plotLine(
        value=buyEventCount,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["Buy Event Count"],
        desc=["Cumulative count of buy bubble events since session start"]
    )
    plotLine(
        value=sellEventCount,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["Sell Event Count"],
        desc=["Cumulative count of sell bubble events since session start"]
    )
}

// 5. Reference thresholds
hline(value=0, color="#ffffff30", width=1)
hline(value=zThreshold, color=opacity(bidColor, 20), width=1)
hline(value=-zThreshold, color=opacity(askColor, 20), width=1)