MM Flow
FlowScripts

Perfected FlowScript

ITC Bubbles

ITC Bubbles V2 is indexed as 083_itc_bubbles.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.4 KB

Lines

401

Native Signal Candidates

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

5/5 guarded

Volume Bubble

line 301:5

Trigger

(volZ > minZ)

Value

plotVal

Deps

minZ:input, volZ:timeseries

Extreme Buy

line 314:9

Trigger

(showShapes) && (regimeExtremeBuy)

Value

low

Deps

regimeExtremeBuy:var, showShapes:input

Extreme Sell

line 324:9

Trigger

(showShapes) && (regimeExtremeSell)

Value

high

Deps

regimeExtremeSell:var, showShapes:input

Absorption

line 338:9

Trigger

(showAbsorption) && (isAbsorption)

Value

close

Deps

isAbsorption:var, showAbsorption:input

Exhaustion

line 348:9

Trigger

(showAbsorption) && (isExhaustion)

Value

close

Deps

isExhaustion:var, showAbsorption:input

083_itc_bubbles.flowscript

source path: kscripts/perfected/083_itc_bubbles.flowscript · sha256:d68094fccd6786cc00c38c6ae58188b17d8c16dc00b1e38012854be9e5f0f491

hash verified
//@version=2
// ============================================================================
// ITC Bubbles V2 — Production-Quality Volume-Z-Score Bubble Visualization
// Author: P (@PatrikHaim) | Perfected by: kScript Perfection Engineer
// Tags: VISUAL, #volume, #bubbles, #zscore, #impact, #absorption, #exhaustion
//
// On-chart bubble visualization where bubble size scales with volume z-score,
// opacity increases with extremity, and color reflects a multi-regime
// classification of market condition. Integrates volume-based price impact
// theory with Bouchaud-Farmer-Lillo square-root impact law and VPIN-style
// volume-bucket toxicity detection.
//
// FORMULA FOUNDATION:
// 1. Volume Z-Score: z_vol = (V_t - μ_V) / σ_V over rolling lookback
//    per standard Gaussian normalization; extreme volumes flagged at |z| > 2.
// 2. Bubble Size: size = clamp(z_vol × multiplier, minSize, maxSize)
//    scaling visualizes the magnitude of the volume anomaly.
// 3. Bubble Opacity: α = baseOpacity + (|z_vol| / maxZ) × (1 - baseOpacity)
//    so extreme events become more visually prominent.
// 4. Regime Classification by Price + Volume alignment:
//    Extreme Buy:  up bar + z_vol > +2  (aggressive accumulation)
//    Buy:          up bar + z_vol > +1  (normal accumulation)
//    Neutral:      |z_vol| ≤ 1          (balanced volume)
//    Sell:         down bar + z_vol > +1 (normal distribution)
//    Extreme Sell: down bar + z_vol > +2 (aggressive liquidation)
//
// RESEARCH BASIS:
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    J. Finance 46(2), 733–746. Tick-test classification of buyer-initiated
//    vs. seller-initiated trades; foundational for volume-direction indicators.
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World", Rev. Financial Studies 25(5), 1457–1493.
//    VPIN volume-bucket approach; elevated buy-sell imbalance flags toxic
//    flow and anticipates market stress (demonstrated before 2010 Flash Crash).
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand", Handbook of Financial Markets. Square-root impact
//    law: large volume without proportional price move = absorption; large
//    volume with price continuation = exhaustion.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme order
//    imbalances predict return reversals; volume spikes at extremes signal
//    potential turning points.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Price changes linearly driven by
//    net order flow; volume z-score magnitude correlates with price impact.
// ============================================================================

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

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

// --- Bubble Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=50,
    label="Volume Z-Score Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Bubble Settings"
)
var sizeMult = input(
    name="sizeMult",
    type="number",
    defaultValue=3.0,
    label="Bubble Size Multiplier",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Bubble Settings"
)
var minSize = input(
    name="minSize",
    type="number",
    defaultValue=3.0,
    label="Minimum Bubble Size",
    constraints={min: 1.0, max: 10.0, step: 1.0},
    group="Bubble Settings"
)
var maxSize = input(
    name="maxSize",
    type="number",
    defaultValue=20.0,
    label="Maximum Bubble Size",
    constraints={min: 5.0, max: 40.0, step: 1.0},
    group="Bubble Settings"
)
var minZ = input(
    name="minZ",
    type="number",
    defaultValue=1.0,
    label="Min Z-Score to Show Bubble",
    constraints={min: 0.0, max: 3.0, step: 0.1},
    group="Bubble Settings"
)

// --- Display ---
var showLabels = input(
    name="showLabels",
    type="boolean",
    defaultValue=false,
    label="Show Bubble Size Labels",
    group="Display"
)
var showContextLines = input(
    name="showContextLines",
    type="boolean",
    defaultValue=true,
    label="Show Volume Context Lines",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Event Shapes",
    group="Display"
)
var showAbsorption = input(
    name="showAbsorption",
    type="boolean",
    defaultValue=true,
    label="Show Absorption/Exhaustion Flags",
    group="Display"
)

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

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvData.close
timeseries open = ohlcvData.open
timeseries high = ohlcvData.high
timeseries low = ohlcvData.low
timeseries vol = ohlcvData.volume

if (isnan(close[0]) || isnan(vol[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. COMPUTATION
// -----------------------------------------------------------------------------

// Bar direction
timeseries isUpBar = close > open
timeseries isDnBar = close < open

// Volume z-score
timeseries volMean = sma(source=vol, period=lookback)
timeseries volStd = stdev(source=vol, period=lookback)
timeseries volZ = volStd > 0 ? (vol - volMean) / volStd : 0

// Absorption / exhaustion detection: large volume with small price move
// Bouchaud et al. (2009): if V is large but |ΔP|/V is small → absorption
// If V is large and |ΔP|/V is large → exhaustion/continuation
timeseries barRange = high - low
timeseries barRangeMean = sma(source=barRange, period=lookback)
timeseries volEfficiency = barRangeMean > 0 ? barRange / barRangeMean : 0
timeseries impactRatio = volEfficiency > 0 ? volZ / volEfficiency : volZ

// Absorption: high volume z, low price efficiency → liquidity absorbing the flow
var isAbsorption = volZ > 2 && volEfficiency < 0.5

// Exhaustion: high volume z, high price efficiency → price moving through liquidity
var isExhaustion = volZ > 2 && volEfficiency > 1.5

// -----------------------------------------------------------------------------
// 4. BUBBLE SIZING & VISUAL PROPERTIES
// -----------------------------------------------------------------------------
// Bubble size scales with z-score, clamped to [minSize, maxSize]
timeseries absZ = math.abs(volZ)
timeseries rawSize = absZ * sizeMult
timeseries bubbleSize = rawSize < minSize ? minSize : (rawSize > maxSize ? maxSize : rawSize)

// Opacity scales with z-score (more extreme = more opaque)
// Base 30% opacity, max 90% at |z| = 4+
timeseries opacityPct = 30 + (absZ / 4.0) * 60
timeseries bubbleOpacity = opacityPct > 90 ? 90 : opacityPct

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Five-tier regime based on bar direction + volume z-score
var regimeExtremeBuy = isUpBar && volZ > 2.0
var regimeBuy = isUpBar && volZ > minZ && volZ <= 2.0
var regimeNeutral = volZ <= minZ && volZ >= -minZ
var regimeSell = isDnBar && volZ > minZ && volZ <= 2.0
var regimeExtremeSell = isDnBar && volZ > 2.0

// Regime color for bubble
var bubbleColor = regimeExtremeBuy ? extremeBuyColor : (regimeBuy ? buyColor : (regimeSell ? sellColor : (regimeExtremeSell ? extremeSellColor : neutralColor)))

// Plot position: buy bubbles at low, sell bubbles at high
var plotVal = isUpBar ? low : high

// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static extremeBuyCount = 0
static extremeSellCount = 0
static absorptionCount = 0
static exhaustionCount = 0
static sessionMaxVolZ = 0.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (absZ > sessionMaxVolZ) {
        sessionMaxVolZ = absZ
    }

    if (regimeExtremeBuy) {
        extremeBuyCount = extremeBuyCount + 1
    } else if (regimeExtremeSell) {
        extremeSellCount = extremeSellCount + 1
    }

    if (isAbsorption) {
        absorptionCount = absorptionCount + 1
    }
    if (isExhaustion) {
        exhaustionCount = exhaustionCount + 1
    }
}

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Volume Context Lines (background) ---
if (showContextLines) {
    plotLine(
        value=volMean,
        width=1,
        colors=[opacity(neutralColor, 30)],
        label=["Volume Mean"],
        desc=["Rolling average volume for context"]
    )
    plotLine(
        value=volMean + volStd,
        width=1,
        colors=[opacity(buyColor, 20)],
        label=["+1σ Volume"],
        desc=["Upper volume standard deviation band"]
    )
    plotLine(
        value=volMean - volStd,
        width=1,
        colors=[opacity(sellColor, 20)],
        label=["-1σ Volume"],
        desc=["Lower volume standard deviation band"]
    )
}

// --- Bubbles (main visualization) ---
if (volZ > minZ) {
    plotShape(
        value=plotVal,
        shape="circle",
        color=opacity(bubbleColor, bubbleOpacity),
        width=bubbleSize,
        label=["Volume Bubble"],
        desc=[("Volume Z: " + volZ + " | Size: " + bubbleSize)]
    )
}

// --- Extreme Event Shape Markers ---
if (showShapes) {
    if (regimeExtremeBuy) {
        plotShape(
            value=low,
            shape="triangleup",
            color=extremeBuyColor,
            width=4,
            label=["Extreme Buy"],
            desc=["Extreme volume accumulation bubble: aggressive buyer-initiated flow"]
        )
    }
    if (regimeExtremeSell) {
        plotShape(
            value=high,
            shape="triangledown",
            color=extremeSellColor,
            width=4,
            label=["Extreme Sell"],
            desc=["Extreme volume distribution bubble: aggressive seller-initiated flow"]
        )
    }
}

// --- Absorption / Exhaustion Flags ---
if (showAbsorption) {
    if (isAbsorption) {
        plotShape(
            value=close,
            shape="diamond",
            color=opacity("#42a5f5", 70),
            width=3,
            label=["Absorption"],
            desc=["High volume + low price efficiency: liquidity absorbing the flow (Bouchaud et al. 2009)"]
        )
    }
    if (isExhaustion) {
        plotShape(
            value=close,
            shape="cross",
            color=opacity("#ffa726", 70),
            width=3,
            label=["Exhaustion"],
            desc=["High volume + high price efficiency: potential exhaustion point (Chordia et al. 2002)"]
        )
    }
}

// --- Labels ---
if (showLabels && volZ > minZ) {
    plotLabel(
        value=plotVal,
        text=("Z=" + volZ),
        color=opacity(bubbleColor, bubbleOpacity),
        fontSize=8,
        label=["Volume Z Label"]
    )
}

// -----------------------------------------------------------------------------
// 8. SESSION TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeExtremeBuy ? "EXTREME BUY" : (regimeBuy ? "BUY" : (regimeSell ? "SELL" : (regimeExtremeSell ? "EXTREME SELL" : "NEUTRAL")))
    var regimeTextColor = regimeExtremeBuy ? extremeBuyColor : (regimeBuy ? buyColor : (regimeSell ? sellColor : (regimeExtremeSell ? extremeSellColor : neutralColor)))

    plotTable(
        data=[
            ["ITC Bubbles — Perfected", regimeText],
            ["Volume Z", volZ[0]],
            ["Bubble Size", bubbleSize[0]],
            ["Session Max |Z|", sessionMaxVolZ],
            ["Extreme Buy Events", extremeBuyCount],
            ["Extreme Sell Events", extremeSellCount],
            ["Absorption Flags", absorptionCount],
            ["Exhaustion Flags", exhaustionCount]
        ],
        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
    )
}