MM Flow
FlowScripts

Perfected FlowScript

Volume Bubbles • [Leviathan] (Fork)

Volume Bubbles [Leviathan] Fork V2 is indexed as 059_volume_bubbles_leviathan_fork.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.3 KB

Lines

291

Native Signal Candidates

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

5/5 guarded

Volume Bubble

line 206:5

Trigger

(showBubbles && isBig)

Value

bubbleY

Deps

isBig:timeseries, showBubbles:input

Extreme Volume Up

line 220:5

Trigger

(showShapes && regime == 2)

Value

l

Deps

regime:var, showShapes:input

Extreme Volume Down

line 229:5

Trigger

(showShapes && regime == -2)

Value

h

Deps

regime:var, showShapes:input

Volume Up

line 238:5

Trigger

(showShapes && regime == 1)

Value

l

Deps

regime:var, showShapes:input

Volume Down

line 247:5

Trigger

(showShapes && regime == -1)

Value

h

Deps

regime:var, showShapes:input

059_volume_bubbles_leviathan_fork.flowscript

source path: kscripts/perfected/059_volume_bubbles_leviathan_fork.flowscript · sha256:22c3b689f3f85a964cfa21ee7c2b4b7d20aa8219c72341e2562ad41c6d1cdde5

hash verified
//@version=2
// ============================================================================
// Volume Bubbles [Leviathan] Fork V2 — Multi-Mode Volume Significance Visualiser
// Author: Tzen Yang (@Tzen Yang) | Perfected by: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #volume, #leviathan, #zscore, #bubbles, #orderflow
//
// Fork of Leviathan's volume bubble concept with three modes (total volume,
// volume delta, buy/sell separate), z-score sizing, regime-coded color mapping,
// opacity scaling, and extreme-event shape markers.
//
// FORMULA FOUNDATION:
// 1. Z-Score Normalisation: z_t = (metric_t − μ_t) / σ_t over rolling window W.
//    Per Zhao & Palomar (2018); bubble size ∝ |z_t| / threshold.
// 2. VPIN Framework: Easley, López de Prado & O'Hara (2012) — volume events
//    exceeding ±2σ flag informed trading / flow toxicity.
// 3. Square-Root Impact Law: Bouchaud, Farmer & Lillo (2009) — large volume
//    may not move price (absorption) or may signal exhaustion.
// 4. Long Memory: Lillo & Farmer (2004) — order flow autocorrelations decay
//    as power law; volume clustering at price levels persists over time.
// 5. Lee-Ready (1991): tick-rule classification for buy/sell volume estimation.
//
// 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.
//    Volume-synchronized probability of informed trading; elevated VPIN flags
//    adverse selection. 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; liquidity memory time.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market".
//    Order flow power-law autocorrelation decay; persistent clustering.
//  • 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 at ±1σ, ±2σ.
// ============================================================================

define(
    title="Volume Bubbles [Leviathan] Fork 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=1.5, label="Significance Threshold (|z|)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var bubbleScale = input(name="bubbleScale", type="number", defaultValue=3.0, label="Bubble Scale", constraints={min: 1.0, max: 10.0, step: 1.0}, group="Computation")
var maxBubbleSize = input(name="maxBubbleSize", type="number", defaultValue=14, 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")

// --- Mode ---
var mode = input(name="mode", type="select", defaultValue="delta", label="Bubble Mode", options=["total", "delta", "buy", "sell"], group="Mode")

// --- 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 upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish/Up Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish/Down Color", group="Colors")
var neutralCol = input(name="neutralCol", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeUpColor = input(name="extremeUpColor", type="color", defaultValue="#00e676", label="Extreme Bullish Color", group="Colors")
var extremeDnColor = input(name="extremeDnColor", type="color", defaultValue="#ff1744", label="Extreme Bearish 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
}

// ------------------------------------------------------------------------------
// Tick-Rule Classification with Taker Feed Priority
// ------------------------------------------------------------------------------
// Lee-Ready (1991) tick test fallback when direct taker feed is unavailable.
// This classification is essential for all modes except "total" volume.

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 delta = buyVol - selVol

// ------------------------------------------------------------------------------
// Selected Metric & Z-Score
// ------------------------------------------------------------------------------
// Mode determines which volume metric is analysed:
//   total → raw volume
//   delta → buy minus sell (signed volume)
//   buy   → buyer-initiated volume only
//   sell  → seller-initiated volume only
// Z-score standardises the metric over the rolling lookback window.

timeseries metric = mode == "total" ? v : (mode == "delta" ? delta : (mode == "buy" ? buyVol : selVol))

timeseries m = sma(metric, zLen)
timeseries sd = stdev(metric, zLen)
timeseries z = sd > 0 ? (metric - m) / sd : 0.0

timeseries absZ = abs(z)

// ------------------------------------------------------------------------------
// Bubble Logic — z-score sizing, regime color coding, opacity scaling
// ------------------------------------------------------------------------------
// Bubbles appear when |z| exceeds the significance threshold.
// Position: buy/delta-positive near lows; sell/delta-negative near highs.
// Size scales linearly with z-score magnitude, capped at maxBubbleSize.

timeseries isBig = absZ > zThreshold
timeseries bubbleY = mode == "sell" ? h : l

// Bubble size scales with z-score magnitude
timeseries size = math.min(bubbleScale * absZ / zThreshold, maxBubbleSize)

// Regime-coded color mapping (five-tier: extreme bull, bull, neutral, bear, extreme bear)
timeseries bubbleColor = z >= zThreshold * extremeMult ? extremeUpColor :
                         z >= zThreshold ? upColor :
                         z <= -zThreshold * extremeMult ? extremeDnColor :
                         z <= -zThreshold ? dnColor :
                         neutralCol

// Opacity scalars by regime tier (fixed for visual consistency)
var normalOpacity = 70
var extremeOpacity = 95

// ------------------------------------------------------------------------------
// Regime Detection & Static Tracking
// ------------------------------------------------------------------------------
// Five-regime classification: extreme bull (2), bull (1), neutral (0),
// bear (-1), extreme bear (-2). Static variables track cumulative event
// counts and session statistics for context-aware analysis.

var regime = 0   // 0 = neutral, 1 = bull, -1 = bear, 2 = extreme bull, -2 = extreme bear
if (z >= zThreshold * extremeMult) {
    regime = 2
} else if (z >= zThreshold) {
    regime = 1
} else if (z <= -zThreshold * extremeMult) {
    regime = -2
} else if (z <= -zThreshold) {
    regime = -1
}

static lastRegime = 0
static bullCount = 0
static bearCount = 0
static extremeBullCount = 0
static extremeBearCount = 0
static lastBarIndex = 0
static sessionMaxZ = 0.0
static sessionMinZ = 0.0

var currentBarIndex = bar_index[0]

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

    if (absZ > sessionMaxZ) {
        sessionMaxZ = absZ
    }
    if (z < sessionMinZ) {
        sessionMinZ = z
    }

    if (regime == 2 && lastRegime != 2) {
        extremeBullCount = extremeBullCount + 1
    } else if (regime == 1 && lastRegime != 1) {
        bullCount = bullCount + 1
    } else if (regime == -2 && lastRegime != -2) {
        extremeBearCount = extremeBearCount + 1
    } else if (regime == -1 && lastRegime != -1) {
        bearCount = bearCount + 1
    }

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

// ------------------------------------------------------------------------------
// Visualization
// ------------------------------------------------------------------------------

// 1. Volume bubbles with z-score sizing and regime-coded colors
//    Circles sized by statistical significance; color by regime tier.
if (showBubbles && isBig) {
    plotShape(
        value=bubbleY,
        shape="circle",
        colorIndex=regime == 2 || regime == -2 ? opacity(bubbleColor, extremeOpacity) : opacity(bubbleColor, normalOpacity),
        width=size,
        label=["Volume Bubble"],
        desc=["Statistically significant volume event (|z| > threshold); size ∝ significance"]
    )
}

// 2. Extreme shapes (different markers for different regime tiers)
//    Diamonds for extreme events, triangles for standard significant events.
//    Spatial placement: bullish near lows, bearish near highs.
if (showShapes && regime == 2) {
    plotShape(
        value=l,
        shape="diamond",
        colorIndex=extremeUpColor,
        width=5,
        label=["Extreme Volume Up"],
        desc=["Extreme volume bubble: z > 1.5× threshold; potential absorption / continuation"]
    )
} else if (showShapes && regime == -2) {
    plotShape(
        value=h,
        shape="diamond",
        colorIndex=extremeDnColor,
        width=5,
        label=["Extreme Volume Down"],
        desc=["Extreme volume bubble: z < -1.5× threshold; potential absorption / continuation"]
    )
} else if (showShapes && regime == 1) {
    plotShape(
        value=l,
        shape="triangleup",
        colorIndex=upColor,
        width=4,
        label=["Volume Up"],
        desc=["Significant volume bubble: z > threshold"]
    )
} else if (showShapes && regime == -1) {
    plotShape(
        value=h,
        shape="triangledown",
        colorIndex=dnColor,
        width=4,
        label=["Volume Down"],
        desc=["Significant volume bubble: z < -threshold"]
    )
}

// 3. Optional z-score line (for context and divergence analysis)
if (showZLine) {
    plotLine(
        value=z,
        width=1,
        colors=[upColor, dnColor, neutralCol],
        colorIndex=regime > 0 ? 0 : (regime < 0 ? 1 : 2),
        label=["Volume Z-Score"],
        desc=["Rolling z-score of selected volume metric; context for bubble events"]
    )
}

// 4. Optional event-count lines (diagnostic)
if (showCounts) {
    plotLine(
        value=bullCount,
        width=1,
        colors=[opacity(upColor, 40)],
        label=["Bull Event Count"],
        desc=["Cumulative count of bullish volume bubble events"]
    )
    plotLine(
        value=bearCount,
        width=1,
        colors=[opacity(dnColor, 40)],
        label=["Bear Event Count"],
        desc=["Cumulative count of bearish volume bubble events"]
    )
}

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