MM Flow
FlowScripts

Perfected FlowScript

Liquidation Bubbles [BackQuant] (Fork)

Liquidation Bubbles V2 — BackQuant Fork is indexed as 258_liquidation_bubbles_backquant_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

13.5 KB

Lines

385

Native Signal Candidates

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

3/3 guarded

Liquidation Bubble

line 270:5

Trigger

(showBubbles && significantLiq)

Value

bubblePos

Deps

showBubbles:input, significantLiq:var

Extreme Buy Liq

line 282:5

Trigger

(showShapes && extremeBuyLiq)

Value

high

Deps

extremeBuyLiq:var, showShapes:input

Extreme Sell Liq

line 292:5

Trigger

(showShapes && extremeSellLiq)

Value

low

Deps

extremeSellLiq:var, showShapes:input

258_liquidation_bubbles_backquant_fork.flowscript

source path: kscripts/perfected/258_liquidation_bubbles_backquant_fork.flowscript · sha256:11836a739a2b4afcab082ec5bbbbd50e64f072826b6b8193306918488bebf797

hash verified
//@version=2
// ============================================================================
// Liquidation Bubbles V2 — BackQuant Fork | Perfected Edition
// Author: J (@Jeet9999) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, ONCHART, #liquidations, #zscore, #regime, #bubbles
//
// On-chart bubbles visualizing liquidation activity with statistical rigor.
// Computes z-score normalized liquidation volume over a rolling window,
// detects liquidation regime (long squeeze vs. short squeeze), scales bubble
// size and opacity by extremity, and emits color-coded shape markers for
// statistically significant liquidation events. Static state tracks cumulative
// liquidation pressure and regime persistence for context-aware alerting.
//
// Academic foundation (exact papers & formulas):
//  1. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//     Review of Financial Studies, 22(6), 2201–2238.
//     [Formula] Liquidity spiral: margin calls → forced selling → price drops
//     → more margin calls. Negative feedback loop between market liquidity
//     (asset ease of trading) and funding liquidity (traders' ease of financing).
//     DOI: https://doi.org/10.1093/rfs/hhn098
//
//  2. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//     a High-Frequency World", Review of Financial Studies, 25(5), 1457–1493.
//     [Formula] VPIN = Σ|V_buy − V_sell| / ΣV_bucket over equal-volume buckets.
//     Elevated VPIN precedes market stress. Informs the z-score normalization
//     and extreme-event threshold design for liquidation bubbles.
//     DOI: https://doi.org/10.1093/rfs/hhs053
//
//  3. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//     IEEE Transactions on Signal Processing, 66(2), 573–587.
//     [Formula] z_t = (x_t − μ_t) / σ_t; entry at |z| > Δ where Δ is typically
//     1.5–2.5σ. Directly underpins the z-score normalization and bubble-sizing
//     logic used in this indicator.
//     URL: https://palomar.home.ece.ust.hk/papers/2018/ZhaoPalomar-TSP2018.pdf
//
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] Δp_t = λ·OFI_t + ε_t. Order flow imbalance (OFI) is the primary
//     driver of short-term price changes. Liquidation cascades are extreme OFI
//     events where λ spikes due to depleted depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme |Imbalance| predicts return reversals. Liquidation cascades
//     create extreme imbalance that often precedes mean-reversion bounces.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ establishes the linear price-impact coefficient. During liquidation
//     spirals, λ increases as liquidity providers withdraw, amplifying impact.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(
    title="Liquidation Bubbles V2 — BackQuant Fork",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var mode = input(
    name="mode",
    type="select",
    defaultValue="Total",
    label="Liquidation Mode",
    options=["Total", "Delta", "BuySell"],
    group="Computation"
)
var lookback = input(
    name="lookback",
    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="Z-Score Bubble Threshold",
    constraints={min: 0.5, max: 4.0, step: 0.25},
    group="Computation"
)
var extremeZ = input(
    name="extremeZ",
    type="number",
    defaultValue=2.5,
    label="Extreme Z-Score Threshold",
    constraints={min: 2.0, max: 5.0, step: 0.25},
    group="Computation"
)
var sizeMult = input(
    name="sizeMult",
    type="number",
    defaultValue=3.0,
    label="Bubble Size Multiplier",
    constraints={min: 1.0, max: 10.0, step: 0.5},
    group="Computation"
)
var opacityMult = input(
    name="opacityMult",
    type="number",
    defaultValue=0.7,
    label="Opacity Multiplier",
    constraints={min: 0.1, max: 1.0, step: 0.1},
    group="Computation"
)

// -- Display --
var showBubbles = input(
    name="showBubbles",
    type="boolean",
    defaultValue=true,
    label="Show Liquidation Bubbles",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Event Shapes",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showCumulative = input(
    name="showCumulative",
    type="boolean",
    defaultValue=false,
    label="Show Cumulative Liquidation Pressure",
    group="Display"
)

// -- Colors --
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Buy Liquidation Color",
    group="Colors"
)
var downColor = input(
    name="downColor",
    type="color",
    defaultValue="#ef5350",
    label="Sell Liquidation Color",
    group="Colors"
)
var deltaColor = input(
    name="deltaColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Neutral/Delta Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#d500f9",
    label="Extreme Event Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries liq = source("liquidations", currentSymbol, currentExchange)

// Guard: halt until external liquidation feed has loaded to avoid NaN propagation
if (isnan(ohlcvTS.close[0]) || isnan(liq.close)) {
    return
}

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

// -- 3.1 Mode-specific liquidation value --
// Total = raw liquidation volume; Delta = long - short imbalance;
// BuySell = buy-side liquidations only (short squeeze proxy)
timeseries liqValue = mode == "Total" ? liq.close : (mode == "Delta" ? (liq.close - liq.open) : liq.close)

// -- 3.2 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (L_t − μ_t) / σ_t, where μ_t = SMA(L, W), σ_t = StDev(L, W).
// Per Zhao & Palomar (2018), z-scores measure distance from equilibrium in
// units of standard deviations, with thresholds typically set at 1.5–2.5σ.
timeseries meanL = sma(source=liqValue, period=lookback)
timeseries stdL = stdev(source=liqValue, period=lookback)
timeseries zLiq = (stdL > 0) ? (liqValue - meanL) / stdL : 0

// -- 3.3 Bubble size scaled by absolute z-score above threshold --
// Bubble size = max(0, |z| − threshold) × sizeMult, clamped to prevent overflow
timeseries bubbleSizeRaw = math.max(0, math.abs(zLiq) - zThreshold) * sizeMult
timeseries bubbleSize = math.min(bubbleSizeRaw, 10.0)

// -- 3.4 Bubble position (above bar for extreme buy liq, below for sell liq) --
// Note: In liquidation terminology, "buy liquidation" = short sellers being
// liquidated (price driven up); "sell liquidation" = long sellers being
// liquidated (price driven down). We map zLiq > threshold → low (below bar
// for sell liquidations) and zLiq < -threshold → high (above bar for buy
// liquidations) based on the sign convention of the liquidation feed.
timeseries bubblePos = math.abs(zLiq) > zThreshold ? (zLiq > 0 ? low : high) : na

// -- 3.5 Color coding by regime --
// colorIndex: 0 = extreme buy liquidation (short squeeze), 1 = extreme sell
// liquidation (long squeeze), 2 = neutral / below threshold
timeseries liqRegimeColor = math.abs(zLiq) > zThreshold ? (zLiq > 0 ? downColor : upColor) : deltaColor

// -- 3.6 Regime detection (configurable thresholds, no magic numbers) --
var extremeBuyLiq = zLiq > extremeZ
var extremeSellLiq = zLiq < -extremeZ
var significantLiq = math.abs(zLiq) > zThreshold
var neutralLiq = !significantLiq

// -- 3.7 Cumulative liquidation pressure via static state --
// Tracks total accumulated liquidation volume and consecutive extreme bars.
static cumLiqBuy = 0.0
static cumLiqSell = 0.0
static extremeBuyBars = 0
static extremeSellBars = 0
static lastRegime = 0

if (!isnan(liqValue)) {
    if (zLiq > 0) {
        cumLiqBuy = cumLiqBuy + liqValue
    } else if (zLiq < 0) {
        cumLiqSell = cumLiqSell + liqValue
    }
}

if (extremeBuyLiq) {
    extremeBuyBars = extremeBuyBars + 1
    extremeSellBars = 0
    lastRegime = 1
} else if (extremeSellLiq) {
    extremeSellBars = extremeSellBars + 1
    extremeBuyBars = 0
    lastRegime = -1
} else {
    extremeBuyBars = 0
    extremeSellBars = 0
    lastRegime = 0
}

// -- 3.8 Zero-line helper for histogram fill --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill
// ---------------------------------------------------------------------------

// 4.1 Liquidation bubbles (plotShape with size = width)
if (showBubbles && significantLiq) {
    plotShape(
        value=bubblePos,
        shape="circle",
        colorIndex=liqRegimeColor,
        width=bubbleSize,
        label=["Liquidation Bubble"],
        desc=["Size scaled by z-score; extreme liquidation events only"]
    )
}

// 4.2 Extreme liquidation shapes (plotShape) — star markers for 2.5σ+ events
if (showShapes && extremeBuyLiq) {
    plotShape(
        value=high,
        shape="star",
        colorIndex=extremeColor,
        width=3,
        label=["Extreme Buy Liq"],
        desc=["Extreme buy liquidation (short squeeze) — z > " + extremeZ]
    )
}
if (showShapes && extremeSellLiq) {
    plotShape(
        value=low,
        shape="star",
        colorIndex=extremeColor,
        width=3,
        label=["Extreme Sell Liq"],
        desc=["Extreme sell liquidation (long squeeze) — z < -" + extremeZ]
    )
}

// 4.3 Z-score histogram (plotLine with colorIndex regime coding + fill)
// colorIndex maps: 0 = extreme buy liq, 1 = extreme sell liq, 2 = neutral
timeseries histColorIdx = extremeBuyLiq ? 0 : (extremeSellLiq ? 1 : 2)
if (showHistogram) {
    plotLine(
        value=([zLiq, zeroLine]),
        width=2,
        colors=[downColor, upColor, deltaColor],
        colorIndex=histColorIdx,
        label=["Z-Score"],
        desc=["Z-score normalized liquidation volume; filled histogram by regime"],
        fill=true
    )
}

// 4.4 Z-score bars (plotBar) — sign-based colouring
if (showHistogram) {
    var barBull = zLiq > 0
    plotBar(
        value=zLiq,
        colors=[downColor, upColor],
        colorIndex=barBull ? 0 : 1,
        width=1,
        label=["Z-Score Bar"],
        desc=["Z-score as bars — positive = sell liq, negative = buy liq"]
    )
}

// 4.5 Optional cumulative liquidation pressure (true cumulative from static state)
if (showCumulative) {
    plotLine(
        value=cumLiqBuy,
        width=1,
        colors=[upColor],
        label=["Cum Buy Liq"],
        desc=["Cumulative buy liquidation pressure (static tracked)"]
    )
    plotLine(
        value=cumLiqSell,
        width=1,
        colors=[downColor],
        label=["Cum Sell Liq"],
        desc=["Cumulative sell liquidation pressure (static tracked)"]
    )
}

// 4.6 Reference threshold lines (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=zThreshold, color=transparency(downColor, 60), width=1)
hline(value=-zThreshold, color=transparency(upColor, 60), width=1)
hline(value=extremeZ, color=transparency(extremeColor, 40), width=1)
hline(value=-extremeZ, color=transparency(extremeColor, 40), width=1)

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = extremeBuyLiq ? "BUY LIQ SPIKE" : (extremeSellLiq ? "SELL LIQ SPIKE" : (significantLiq ? "SIGNIFICANT" : "NEUTRAL"))
    var regimeTextColor = extremeBuyLiq ? downColor : (extremeSellLiq ? upColor : deltaColor)

    plotTable(
        data=[
            ["Liquidation Bubbles V2", regimeText],
            ["Z-Score", zLiq[0]],
            ["Liq Volume", liqValue[0]],
            ["Cum Buy Liq", cumLiqBuy],
            ["Cum Sell Liq", cumLiqSell],
            ["Extreme Buy Bars", extremeBuyBars],
            ["Extreme Sell Bars", extremeSellBars]
        ],
        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
    )
}