MM Flow
FlowScripts

Perfected FlowScript

Optimized Volume Bubbles v2

Optimized Volume Bubbles v2 — Perfected Edition is indexed as 133_optimized_volume_bubbles_v2.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

13.7 KB

Lines

417

Native Signal Candidates

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

9/9 guarded

Unlabeled shape

line 279:5

Trigger

(mode == "Total" && abs(vZ) > threshold)

Value

pos

Deps

mode:input, threshold:input, vZ:timeseries

Buy Vol

line 292:5

Trigger

(mode == "Buy" && bvZ > threshold)

Value

l

Deps

bvZ:timeseries, mode:input, threshold:input

Sell Vol

line 305:5

Trigger

(mode == "Sell" && svZ > threshold)

Value

h

Deps

mode:input, svZ:timeseries, threshold:input

Buy

line 319:9

Trigger

(mode == "Buy & Sell") && (bvZ > threshold)

Value

l

Deps

bvZ:timeseries, mode:input, threshold:input

Sell

line 330:9

Trigger

(mode == "Buy & Sell") && (svZ > threshold)

Value

h

Deps

mode:input, svZ:timeseries, threshold:input

Vol Spike

line 344:9

Trigger

(showShapes) && (totalExtremeUp)

Value

l

Deps

showShapes:input, totalExtremeUp:var

Vol Drop

line 354:9

Trigger

(showShapes) && (totalExtremeDown)

Value

h

Deps

showShapes:input, totalExtremeDown:var

Buy Spike

line 364:9

Trigger

(showShapes) && (buyExtreme)

Value

l

Deps

buyExtreme:var, showShapes:input

Sell Spike

line 374:9

Trigger

(showShapes) && (sellExtreme)

Value

h

Deps

sellExtreme:var, showShapes:input

133_optimized_volume_bubbles_v2.flowscript

source path: kscripts/perfected/133_optimized_volume_bubbles_v2.flowscript · sha256:3ba95be4abef32350901c1d9564a7771daaded8139c6553946c52decf069e8ed

hash verified
//@version=2
// ============================================================================
// Optimized Volume Bubbles v2 — Perfected Edition
// Author: A (@AldousHuxleyy) | Enhanced by kScript Perfection Engineer
// Tags: CORE, ADVANCED, #volume, #indicators, #zscore, #bubbles, #orderflow
//
// Production-quality volume bubble visualization with z-score standardization,
// buy/sell classification via BVC-style midpoint logic, and comprehensive
// shape/opacity/fill visualization. Bubble size scales with z-score magnitude,
// color codes by direction, and opacity scales with extremity.
//
// Research papers underpinning this design:
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     OFI-price impact linearity validates volume extremes as leading indicators
//     for price movement. Volume bars beyond ±2σ are the most likely to move price.
//  2. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score standardization framework; z = (x − μ) / σ identifies statistical
//     outliers as potential mean-reversion inflection points.
//  3. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//     Activity": BVC method classifies volume probabilistically using price-change
//     distribution within bars. The midpoint-based buy/sell split here is a proxy.
//  4. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes":
//     square-root impact law explains why extreme volume may not move price
//     proportionally. Bubble sizing (clamped) follows this sublinear impact logic.
//  5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//     foundational trade classification methodology. Quote-midpoint comparison
//     with ~85-93% accuracy is the ancestor of all volume direction classification.
// ============================================================================

define(
    title="Optimized Volume Bubbles v2 — Perfected Edition",
    position="onchart",
    axis=false
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Z-Score Settings ---
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score Settings"
)
var threshold = input(
    name="threshold",
    type="number",
    defaultValue=1.5,
    label="Bubble Threshold (std)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Z-Score Settings"
)
var maxSize = input(
    name="maxSize",
    type="number",
    defaultValue=8,
    label="Max Bubble Size",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Settings"
)

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

// --- Display ---
var showLine = input(
    name="showLine",
    type="boolean",
    defaultValue=true,
    label="Show Volume Z Line",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal Shapes",
    group="Display"
)
var showBgBands = input(
    name="showBgBands",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Bands",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Session Table",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

if (isnan(c[0]) || isnan(v[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. BAR CLASSIFICATION (BVC-style midpoint proxy)
// -----------------------------------------------------------------------------
// Per Easley et al. (2012), BVC uses probabilistic classification based on
// price-change distribution within a bar. Here we use a simplified midpoint
// proxy: close >= midpoint = buyer-aggressive, close < midpoint = seller-aggressive.
// This is the Lee-Ready (1991) quote-rule ancestor applied in aggregate.

timeseries mid = (h + l) / 2.0
timeseries buyV = (c >= mid) ? v : 0.0
timeseries sellV = (c < mid) ? v : 0.0

// -----------------------------------------------------------------------------
// 4. Z-SCORES (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// z = (x − μ) / σ over rolling lookback. Guards against division by zero.

timeseries vMean = sma(v, zLen)
timeseries vStd = stddev(v, zLen)
timeseries vZ = (v - vMean) / max(vStd, 1e-9)

timeseries bvMean = sma(buyV, zLen)
timeseries bvStd = stddev(buyV, zLen)
timeseries bvZ = (buyV - bvMean) / max(bvStd, 1e-9)

timeseries svMean = sma(sellV, zLen)
timeseries svStd = stddev(sellV, zLen)
timeseries svZ = (sellV - svMean) / max(svStd, 1e-9)

// -----------------------------------------------------------------------------
// 5. BUBBLE SIZE & OPACITY SCALING
// -----------------------------------------------------------------------------
// Bubble size scales linearly with z-score magnitude, clamped to maxSize.
// Opacity scales with z-score: higher z = more opaque (more significant).
// Per Bouchaud et al. (2009) square-root impact law, extreme volume does not
// imply proportional price impact; clamping prevents visual distortion.

timeseries bubbleSize = min(abs(vZ) * 3.0, maxSize)
timeseries buyBubbleSize = min(abs(bvZ) * 3.0, maxSize)
timeseries sellBubbleSize = min(abs(svZ) * 3.0, maxSize)

// Opacity: base 30%, scales to 100% as z-score approaches maxSize/3.0
var maxZ = maxSize / 3.0
timeseries opacityFactor = min(abs(vZ) / maxZ, 1.0)
timeseries buyOpacity = min(abs(bvZ) / maxZ, 1.0)
timeseries sellOpacity = min(abs(svZ) / maxZ, 1.0)

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime based on volume z-score direction and bar classification.

timeseries vZColor = (vZ >= 0) ? bullColor : bearColor
var regimeBull = bvZ > threshold && bvZ > svZ
var regimeBear = svZ > threshold && svZ > bvZ
var regimeNeutral = !regimeBull && !regimeBear

// -----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var totalExtremeUp = vZ > threshold && vZ[1] <= threshold
var totalExtremeDown = vZ < -threshold && vZ[1] >= -threshold
var buyExtreme = bvZ > threshold && bvZ[1] <= threshold
var sellExtreme = svZ > threshold && svZ[1] <= threshold

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static sessionHighVZ = -999999.0
static sessionLowVZ = 999999.0
static sessionHighBVZ = -999999.0
static sessionHighSVZ = -999999.0
static totalBubbleCount = 0
static buyBubbleCount = 0
static sellBubbleCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (vZ[0] > sessionHighVZ) {
        sessionHighVZ = vZ[0]
    }
    if (vZ[0] < sessionLowVZ) {
        sessionLowVZ = vZ[0]
    }
    if (bvZ[0] > sessionHighBVZ) {
        sessionHighBVZ = bvZ[0]
    }
    if (svZ[0] > sessionHighSVZ) {
        sessionHighSVZ = svZ[0]
    }

    if (abs(vZ[0]) > threshold) {
        totalBubbleCount = totalBubbleCount + 1
    }
    if (bvZ[0] > threshold) {
        buyBubbleCount = buyBubbleCount + 1
    }
    if (svZ[0] > threshold) {
        sellBubbleCount = sellBubbleCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Z-Score Bands (horizontal guides) ---
if (showBgBands) {
    hline(value=0, color="#ffffff30", width=1)
    hline(value=threshold, color=transparency(bullColor, 60), width=1)
    hline(value=-threshold, color=transparency(bearColor, 60), width=1)
    hline(value=threshold * 2, color=transparency(bullColor, 40), width=1)
    hline(value=-threshold * 2, color=transparency(bearColor, 40), width=1)
}

// --- Volume Z Line (regime-colored) ---
if (showLine) {
    plotLine(
        value=vZ,
        width=2,
        colors=[vZColor],
        label=["Volume Z"],
        desc=["Volume z-score (standardized volume deviation, " + zLen + " lookback)"]
    )
}

// --- Bubbles: Total mode ---
if (mode == "Total" && abs(vZ) > threshold) {
    var bc = (vZ >= threshold) ? bullColor : bearColor
    var op = 30 + round(70 * opacityFactor)
    var pos = (vZ >= threshold) ? l : h
    var lbl = (vZ >= threshold) ? "High Vol" : "Low Vol"
    var dsc = (vZ >= threshold) ? "Statistically significant volume bar (z=" + vZ + ")" : "Below-normal volume bar (z=" + vZ + ")"
    plotShape(
        value=pos,
        shape="circle",
        color=transparency(bc, op),
        width=bubbleSize,
        label=[lbl],
        desc=[dsc]
    )
}

// --- Bubbles: Buy mode ---
if (mode == "Buy" && bvZ > threshold) {
    var bop = 30 + round(70 * buyOpacity)
    plotShape(
        value=l,
        shape="circle",
        color=transparency(bullColor, bop),
        width=buyBubbleSize,
        label=["Buy Vol"],
        desc=["Statistically significant buy volume (z=" + bvZ + ")"]
    )
}

// --- Bubbles: Sell mode ---
if (mode == "Sell" && svZ > threshold) {
    var sop = 30 + round(70 * sellOpacity)
    plotShape(
        value=h,
        shape="circle",
        color=transparency(bearColor, sop),
        width=sellBubbleSize,
        label=["Sell Vol"],
        desc=["Statistically significant sell volume (z=" + svZ + ")"]
    )
}

// --- Bubbles: Buy & Sell mode ---
if (mode == "Buy & Sell") {
    if (bvZ > threshold) {
        var bop2 = 30 + round(70 * buyOpacity)
        plotShape(
            value=l,
            shape="circle",
            color=transparency(bullColor, bop2),
            width=buyBubbleSize,
            label=["Buy"],
            desc=["Significant buy volume (z=" + bvZ + ")"]
        )
    }
    if (svZ > threshold) {
        var sop2 = 30 + round(70 * sellOpacity)
        plotShape(
            value=h,
            shape="circle",
            color=transparency(bearColor, sop2),
            width=sellBubbleSize,
            label=["Sell"],
            desc=["Significant sell volume (z=" + svZ + ")"]
        )
    }
}

// --- Signal Shapes (extreme events) ---
if (showShapes) {
    if (totalExtremeUp) {
        plotShape(
            value=l,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Vol Spike"],
            desc=["Total volume extreme spike (z=" + vZ + ") — absorption or initiation"]
        )
    }
    if (totalExtremeDown) {
        plotShape(
            value=h,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Vol Drop"],
            desc=["Total volume extreme drop (z=" + vZ + ") — exhaustion or low participation"]
        )
    }
    if (buyExtreme) {
        plotShape(
            value=l,
            shape="diamond",
            color=bullColor,
            width=3,
            label=["Buy Spike"],
            desc=["Buy volume extreme spike (z=" + bvZ + ") — aggressive buyer dominance"]
        )
    }
    if (sellExtreme) {
        plotShape(
            value=h,
            shape="diamond",
            color=bearColor,
            width=3,
            label=["Sell Spike"],
            desc=["Sell volume extreme spike (z=" + svZ + ") — aggressive seller dominance"]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. SESSION TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar && showTable) {
    var regimeText = regimeBull ? "BUY-HEAVY" : (regimeBear ? "SELL-HEAVY" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Volume Bubbles — Perfected", regimeText],
            ["Volume Z", vZ[0]],
            ["Buy Z", bvZ[0]],
            ["Sell Z", svZ[0]],
            ["Session High Vol Z", sessionHighVZ],
            ["Session Low Vol Z", sessionLowVZ],
            ["Total Bubbles", totalBubbleCount],
            ["Buy Bubbles", buyBubbleCount],
            ["Sell Bubbles", sellBubbleCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}