MM Flow
FlowScripts

Perfected FlowScript

Volume Bubbles • [Leviathan]

Volume Bubbles [Leviathan] V2 is indexed as 005_volume_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

16.8 KB

Lines

465

Native Signal Candidates

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

8/8 guarded

Vol Bubble

line 317:5

Trigger

(showTotalBubbles && mode == "Total Volume" && volRegime >= 1)

Value

volY

Deps

mode:input, showTotalBubbles:input, volRegime:var

Delta Bubble

line 335:5

Trigger

(showDeltaBubbles && mode == "Volume Delta" && deltaRegime >= 1)

Value

deltaY

Deps

deltaRegime:var, mode:input, showDeltaBubbles:input

Buy Vol

line 359:9

Trigger

(mode == "Buy & Sell Volume" && volRegime >= 1) && (buyAbsZ >= threshold)

Value

bars.high[0]

Deps

buyAbsZ:var, mode:input, threshold:input, volRegime:var

Sell Vol

line 369:9

Trigger

(mode == "Buy & Sell Volume" && volRegime >= 1) && (sellAbsZ >= threshold)

Value

bars.low[0]

Deps

mode:input, sellAbsZ:var, threshold:input, volRegime:var

Extreme Vol+

line 393:9

Trigger

(showExtremeShapes) && (extremeVolUp)

Value

bars.high[0]

Deps

extremeVolUp:var, showExtremeShapes:input

Extreme Vol-

line 403:9

Trigger

(showExtremeShapes) && (extremeVolDn)

Value

bars.low[0]

Deps

extremeVolDn:var, showExtremeShapes:input

Extreme Delta+

line 413:9

Trigger

(showExtremeShapes) && (extremeDeltaUp)

Value

bars.high[0]

Deps

extremeDeltaUp:var, showExtremeShapes:input

Extreme Delta-

line 423:9

Trigger

(showExtremeShapes) && (extremeDeltaDn)

Value

bars.low[0]

Deps

extremeDeltaDn:var, showExtremeShapes:input

005_volume_bubbles_leviathan.flowscript

source path: kscripts/perfected/005_volume_bubbles_leviathan.flowscript · sha256:52b4d2b433977515464977eec9552d59b567b6defd4775a9072af898e1b03fa2

hash verified
//@version=2
// ============================================================================
// Volume Bubbles [Leviathan] V2 — Production-Quality Volume Microstructure
// Author: Leviathan (@Leviathan) | Perfected by: kScript Perfection Engineer
// Tags: CORE, ADVANCED, #volume, #leviathan, #zscore, #bubbles, #orderflow
//
// On-chart bubble visualization of volume magnitude and statistical
// significance. Each bubble's size scales with absolute volume magnitude,
// while its color follows a z-score over a rolling window so anomalous
// bars stand out from the baseline. Three display modes: total volume,
// volume delta, or separate buy and sell volumes. Opacity dynamically
// scales with statistical significance per the VPIN framework.
//
// FORMULA FOUNDATION:
// 1. Volume Z-Score: Z = (V − μ_V) / σ_V  where μ_V = SMA(V, N), σ_V = StdDev(V, N)
//    Per standard statistical process control; Z > 2 flags anomalous
//    volume (≈95% confidence under normal approximation).
// 2. Volume Delta (ΔV): ΔV = BuyVol − SellVol per Lee & Ready (1991) classification.
// 3. Delta Z-Score: Z_Δ = (ΔV − μ_Δ) / σ_Δ  — flags buy/sell dominance anomalies.
// 4. Bubble Size: r = sizeMult × min(20, max(2, |Z|)) per Bouchaud et al. (2009)
//    square-root impact law: visual impact scales sublinearly with raw volume.
// 5. Opacity Scaling: α = min(100, baseOpacity + |Z| × 15) — higher statistical
//    significance = more visually prominent per VPIN (Easley, López de Prado & O'Hara 2012).
//
// RESEARCH BASIS:
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    J. Finance 46(2), 733–746. Foundational buy/sell trade classification;
//    ~85–93% accuracy on NYSE TORQ data. [^1]
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World" (VPIN), Rev. Financial Studies 25(5), 1457–1493.
//    Volume-bucket + statistical-significance framework; VPIN anticipated
//    the 2010 Flash Crash by >1 hour. [^2]
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand", Handbook of Financial Markets. Square-root impact law
//    explains absorption and exhaustion at extreme volume; sublinear scaling. [^3]
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market", Studies
//    in Nonlinear Dynamics & Econometrics 8(3), 1–35. Power-law decay in order-
//    flow autocorrelation motivates cumulative volume visualization. [^4]
//  • Finucane (2000), "A Direct Test of Methods for Inferring Trade Direction",
//    JFQA 35(4), 553–576. Cautions that classification accuracy degrades during
//    volatile periods; delta should be treated as relative, not absolute. [^5]
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Order flow imbalance drives price
//    changes linearly; validates delta as a leading price predictor. [^6]
// ============================================================================

define(
    title="Volume Bubbles [Leviathan] V2",
    position="onchart",
    axis=false
)

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

// --- Display Mode ---
var mode = input(
    name="mode",
    type="select",
    defaultValue="Total Volume",
    label="Display Mode",
    options=["Total Volume", "Volume Delta", "Buy & Sell Volume"],
    group="Display Mode"
)

// --- Z-Score Configuration ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score"
)
var threshold = input(
    name="threshold",
    type="number",
    defaultValue=1.5,
    label="Display Threshold (z)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Z-Score"
)
var extremeThreshold = input(
    name="extremeThreshold",
    type="number",
    defaultValue=2.5,
    label="Extreme Event Threshold (z)",
    constraints={min: 1.5, max: 5.0, step: 0.1},
    group="Z-Score"
)

// --- Bubble Aesthetics ---
var sizeMult = input(
    name="sizeMult",
    type="number",
    defaultValue=2.0,
    label="Size Multiplier",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Aesthetics"
)
var baseOpacity = input(
    name="baseOpacity",
    type="number",
    defaultValue=40,
    label="Base Opacity (%)",
    constraints={min: 10, max: 80, step: 5},
    group="Aesthetics"
)
var opacityScaling = input(
    name="opacityScaling",
    type="boolean",
    defaultValue=true,
    label="Opacity Scales with Z-Score",
    group="Aesthetics"
)

// --- Colors ---
var buyColor = input(
    name="buyColor",
    type="color",
    defaultValue="#26a69a",
    label="Buy Dominance Color",
    group="Colors"
)
var sellColor = input(
    name="sellColor",
    type="color",
    defaultValue="#ef5350",
    label="Sell Dominance Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var extremeBuyColor = input(
    name="extremeBuyColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Buy Color",
    group="Colors"
)
var extremeSellColor = input(
    name="extremeSellColor",
    type="color",
    defaultValue="#ff1744",
    label="Extreme Sell Color",
    group="Colors"
)

// --- Display Toggles ---
var showTotalBubbles = input(
    name="showTotalBubbles",
    type="boolean",
    defaultValue=true,
    label="Show Total Volume Bubbles",
    group="Display"
)
var showDeltaBubbles = input(
    name="showDeltaBubbles",
    type="boolean",
    defaultValue=true,
    label="Show Volume Delta Bubbles",
    group="Display"
)
var showExtremeShapes = input(
    name="showExtremeShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Event Shapes",
    group="Display"
)
var showStatsTable = input(
    name="showStatsTable",
    type="boolean",
    defaultValue=true,
    label="Show Session Statistics Table",
    group="Display"
)

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

if (isnan(bars.close[0])) {
    return
}

// ------------------------------------------------------------------------------
// Volume Computation with Classification Fallback (Lee & Ready 1991)
// ------------------------------------------------------------------------------
// Primary: use platform taker volume (buy/sell split) if available.
// Fallback: tick-based classification (close > open = buy, else sell).
// Per Finucane (2000), classification accuracy degrades in volatile periods;
// treat delta as relative, not absolute.

var buyVol = isnum(taker.buy) ? taker.buy : (bars.close[0] > bars.open[0] ? bars.volume[0] : 0)
var sellVol = isnum(taker.sell) ? taker.sell : (bars.close[0] <= bars.open[0] ? bars.volume[0] : 0)
var totalVol = bars.volume[0]
var delta = buyVol - sellVol

// Volume availability guard (Cont et al. 2014 data-integrity best practice)
var volAvailable = totalVol > 0 && !isnan(totalVol)

// ------------------------------------------------------------------------------
// Z-Score Computation — Statistical Process Control Framework
// ------------------------------------------------------------------------------
// Z = (X − μ) / σ; flags bars where volume is anomalous relative to recent
// baseline. Per VPIN (Easley et al. 2012), extreme imbalance in volume
// buckets predicts adverse selection and heightened volatility.

var volMean = sma(source=totalVol, period=lookback)
var volStd = stddev(source=totalVol, period=lookback)
var volZ = volAvailable && volStd > 0 ? (totalVol - volMean) / volStd : 0.0

var deltaMean = sma(source=delta, period=lookback)
var deltaStd = stddev(source=delta, period=lookback)
var deltaZ = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0.0

// Buy/sell dominance ratio (additional diagnostic per Chordia et al. 2002)
var dominanceRatio = totalVol > 0 ? buyVol / totalVol : 0.5

// ------------------------------------------------------------------------------
// Bubble Size & Opacity Calculation (Bouchaud et al. 2009 sublinear scaling)
// ------------------------------------------------------------------------------
// Visual impact scales sublinearly with raw z-score to avoid overcrowding.
// Size: r = sizeMult × clamp(|Z|, 2, 20)
// Opacity: α = baseOpacity + |Z| × 15 (capped at 100)

var volAbsZ = abs(volZ)
var deltaAbsZ = abs(deltaZ)

var volSize = sizeMult * math.min(20, math.max(2, volAbsZ))
var deltaSize = sizeMult * math.min(20, math.max(2, deltaAbsZ))

var volOpacity = opacityScaling ? math.min(100, baseOpacity + volAbsZ * 15) : baseOpacity
var deltaOpacity = opacityScaling ? math.min(100, baseOpacity + deltaAbsZ * 15) : baseOpacity

// ------------------------------------------------------------------------------
// Regime Detection — Volume State Classification
// ------------------------------------------------------------------------------
// Volume regimes: Normal (|Z| < threshold), Elevated (threshold ≤ |Z| < extreme),
// Extreme (|Z| ≥ extreme). Per VPIN, extreme volume imbalance flags
// informed trading and potential regime shifts.

var volRegime = 0  // 0 = normal, 1 = elevated, 2 = extreme
var deltaRegime = 0

if (volAbsZ >= extremeThreshold) {
    volRegime = 2
} else if (volAbsZ >= threshold) {
    volRegime = 1
}

if (deltaAbsZ >= extremeThreshold) {
    deltaRegime = 2
} else if (deltaAbsZ >= threshold) {
    deltaRegime = 1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks cumulative volume, extreme event counts, and session highs/lows
// for diagnostic table display.

static sessionTotalVol = 0.0
static sessionBuyVol = 0.0
static sessionSellVol = 0.0
static extremeVolCount = 0
static extremeDeltaCount = 0
static maxVolZ = 0.0
static maxDeltaZ = 0.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex && volAvailable) {
    lastBarIndex = currentBarIndex
    sessionTotalVol = sessionTotalVol + totalVol
    sessionBuyVol = sessionBuyVol + buyVol
    sessionSellVol = sessionSellVol + sellVol

    if (volAbsZ > maxVolZ) {
        maxVolZ = volAbsZ
    }
    if (deltaAbsZ > maxDeltaZ) {
        maxDeltaZ = deltaAbsZ
    }

    if (volRegime == 2) {
        extremeVolCount = extremeVolCount + 1
    }
    if (deltaRegime == 2) {
        extremeDeltaCount = extremeDeltaCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Bubble Visualization with Dynamic Size, Color, and Opacity
// ------------------------------------------------------------------------------

// === Total Volume Mode ===
// Bubbles at bar highs (above-average volume) or lows (below-average volume).
// Color: buy dominance ratio > 0.55 = green; < 0.45 = red; else neutral.
if (showTotalBubbles && mode == "Total Volume" && volRegime >= 1) {
    var volColor = dominanceRatio > 0.55 ? buyColor : (dominanceRatio < 0.45 ? sellColor : neutralColor)
    var volColorFinal = volRegime == 2 ? (volZ > 0 ? extremeBuyColor : extremeSellColor) : volColor
    var volY = volZ > 0 ? bars.high[0] : bars.low[0]

    plotShape(
        value=volY,
        shape="circle",
        color=opacity(volColorFinal, volOpacity),
        width=volSize,
        label=["Vol Bubble"],
        desc=["Volume Z=" + volZ + " | BuyRatio=" + dominanceRatio + " | Total=" + totalVol]
    )
}

// === Volume Delta Mode ===
// Bubbles centered at close price, color coded by delta direction.
// Positive delta (buy pressure) = green above close; negative = red below close.
if (showDeltaBubbles && mode == "Volume Delta" && deltaRegime >= 1) {
    var deltaColor = deltaZ > 0 ? buyColor : sellColor
    var deltaColorFinal = deltaRegime == 2 ? (deltaZ > 0 ? extremeBuyColor : extremeSellColor) : deltaColor
    var deltaY = deltaZ > 0 ? bars.high[0] : bars.low[0]

    plotShape(
        value=deltaY,
        shape="circle",
        color=opacity(deltaColorFinal, deltaOpacity),
        width=deltaSize,
        label=["Delta Bubble"],
        desc=["Delta Z=" + deltaZ + " | Buy=" + buyVol + " | Sell=" + sellVol]
    )
}

// === Buy & Sell Separate Mode ===
// Two bubble sets: buy bubbles above highs, sell bubbles below lows.
// Size scales with respective buy/sell contribution z-scores.
if (mode == "Buy & Sell Volume" && volRegime >= 1) {
    var buyZ = volStd > 0 ? (buyVol - volMean * 0.5) / volStd : 0.0
    var sellZ = volStd > 0 ? (sellVol - volMean * 0.5) / volStd : 0.0
    var buyAbsZ = abs(buyZ)
    var sellAbsZ = abs(sellZ)
    var buySize = sizeMult * math.min(20, math.max(2, buyAbsZ))
    var sellSize = sizeMult * math.min(20, math.max(2, sellAbsZ))
    var buyOp = opacityScaling ? math.min(100, baseOpacity + buyAbsZ * 15) : baseOpacity
    var sellOp = opacityScaling ? math.min(100, baseOpacity + sellAbsZ * 15) : baseOpacity

    if (buyAbsZ >= threshold) {
        plotShape(
            value=bars.high[0],
            shape="circle",
            color=opacity(buyColor, buyOp),
            width=buySize,
            label=["Buy Vol"],
            desc=["Buy volume bubble | Buy=" + buyVol + " | Z=" + buyZ]
        )
    }
    if (sellAbsZ >= threshold) {
        plotShape(
            value=bars.low[0],
            shape="circle",
            color=opacity(sellColor, sellOp),
            width=sellSize,
            label=["Sell Vol"],
            desc=["Sell volume bubble | Sell=" + sellVol + " | Z=" + sellZ]
        )
    }
}

// ------------------------------------------------------------------------------
// Extreme Event Shape Markers (VPIN-style anomaly detection)
// ------------------------------------------------------------------------------
// Diamond shapes for extreme volume events (|Z| ≥ extremeThreshold).
// Per Easley et al. (2012), these flag potential toxic flow / informed trading.

if (showExtremeShapes) {
    var extremeVolUp = volZ >= extremeThreshold
    var extremeVolDn = volZ <= -extremeThreshold
    var extremeDeltaUp = deltaZ >= extremeThreshold
    var extremeDeltaDn = deltaZ <= -extremeThreshold

    if (extremeVolUp) {
        plotShape(
            value=bars.high[0],
            shape="diamond",
            color=extremeBuyColor,
            width=5,
            label=["Extreme Vol+"],
            desc=["Extreme volume spike (Z=" + volZ + ") — potential absorption/continuation"]
        )
    }
    if (extremeVolDn) {
        plotShape(
            value=bars.low[0],
            shape="diamond",
            color=extremeSellColor,
            width=5,
            label=["Extreme Vol-"],
            desc=["Extreme volume collapse (Z=" + volZ + ") — potential exhaustion"]
        )
    }
    if (extremeDeltaUp) {
        plotShape(
            value=bars.high[0],
            shape="triangleup",
            color=extremeBuyColor,
            width=4,
            label=["Extreme Delta+"],
            desc=["Extreme buy delta (Z=" + deltaZ + ") — aggressive ask-lifting"]
        )
    }
    if (extremeDeltaDn) {
        plotShape(
            value=bars.low[0],
            shape="triangledown",
            color=extremeSellColor,
            width=4,
            label=["Extreme Delta-"],
            desc=["Extreme sell delta (Z=" + deltaZ + ") — aggressive bid-hitting"]
        )
    }
}

// ------------------------------------------------------------------------------
// Session Statistics Table (last bar only)
// ------------------------------------------------------------------------------
if (showStatsTable && isLastBar) {
    var buyPct = sessionTotalVol > 0 ? (sessionBuyVol / sessionTotalVol * 100.0) : 50.0
    var sellPct = 100.0 - buyPct

    plotTable(
        data=[
            ["Volume Bubbles V2", "Session Stats"],
            ["Total Volume", sessionTotalVol],
            ["Buy Volume (%)", buyPct],
            ["Sell Volume (%)", sellPct],
            ["Max Vol Z-Score", maxVolZ],
            ["Max Delta Z-Score", maxDeltaZ],
            ["Extreme Vol Events", extremeVolCount],
            ["Extreme Delta Events", extremeDeltaCount]
        ],
        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
    )
}