Perfected FlowScript
Liquidation Bubbles • [Leviathan]
Liquidation Bubbles V2 — Leviathan is indexed as 107_liquidation_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
12.5 KB
Lines
397
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Long Liq
line 298:5
Trigger
(showBubbles && longZ > zThreshold)
Value
low
Deps
longZ:timeseries, showBubbles:input, zThreshold:input
Short Liq
line 310:5
Trigger
(showBubbles && shortZ > zThreshold)
Value
high
Deps
shortZ:timeseries, showBubbles:input, zThreshold:input
Unlabeled shape
line 323:5
Trigger
(showLabels && longZ > labelZThreshold)
Value
low
Deps
labelZThreshold:input, longZ:timeseries, showLabels:input
Unlabeled shape
line 335:5
Trigger
(showLabels && shortZ > labelZThreshold)
Value
high
Deps
labelZThreshold:input, shortZ:timeseries, showLabels:input
Long Cascade
line 348:5
Trigger
(showShapes && longCascade)
Value
low
Deps
longCascade:var, showShapes:input
Short Cascade
line 358:5
Trigger
(showShapes && shortCascade)
Value
high
Deps
shortCascade:var, showShapes:input
107_liquidation_bubbles_leviathan.flowscript
source path: kscripts/perfected/107_liquidation_bubbles_leviathan.flowscript · sha256:751039e58cadec374750bb2cb7193a26271fc537f368cbc112d8cbfa5216d513
//@version=2
// ============================================================================
// Liquidation Bubbles V2 — Leviathan
// Author: Leviathan (@Leviathan) | Perfected: kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, #liquidations, #liquidationbubbles, #liqs, #cascade
//
// Visualises liquidation events directly on the price chart as bubbles,
// with size and opacity reflecting the magnitude of each liquidation relative
// to recent history. Long liquidations (longs forced to sell) appear as bubbles
// below the bar; short liquidations (shorts forced to buy) appear above.
// Z-score normalisation filters for statistically significant events, while
// cascade detection flags consecutive extreme liquidation bars that may
// trigger liquidity spirals.
//
// 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: market liquidity ↔ funding liquidity
// reinforcement; margin threshold breaches trigger cascades.
// DOI: https://doi.org/10.1093/rfs/hhn098
//
// 2. Bian, Da, He, Lou, Shive & Zhang (2023), "Deleveraging Commonality",
// Journal of Financial Economics, 147, 103-465.
// Fire sales propagate across assets; systematic deleveraging risk.
// Liquidation intensity > 5% of OI = cascade trigger.
// DOI: https://doi.org/10.1016/j.jfineco.2022.103465
//
// 3. Amberdata Research (2026), "Leverage & Liquidations: The $31B Deleveraging".
// Documents that liquidation intensity exceeding 5% of open interest
// triggers forced-selling cascades. October 2025 cascade reached 4.82%
// intensity. DOI: internal report
//
// 4. He & Manela (2022), "Fundamentals of Perpetual Futures".
// No-arbitrage perpetual futures pricing; past-return momentum explains
// the futures-spot gap with R² > 50%. Deviations are highly correlated
// across currencies, supporting systemic liquidation cascade analysis.
//
// 5. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
// in a High-Frequency World" (VPIN). Review of Financial Studies, 25(5),
// 1457–1493. VPIN framework validates volume-bucket approach to extreme
// flow detection. DOI: https://doi.org/10.1093/rfs/hhs053
//
// 6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// [Formula] z̄_t = (z_t − μ_z) / σ_z; entry/exit at Δ = d·σ_z (d=1,2).
// Directly underpins the z-score normalisation and cascade threshold design.
// ============================================================================
define(
title="Liquidation Bubbles V2 — Leviathan",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- 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 Threshold to Show",
constraints={min: 0.5, max: 4.0, step: 0.5},
group="Computation"
)
var labelZThreshold = input(
name="labelZThreshold",
type="number",
defaultValue=2.5,
label="Z-Score for Value Label",
constraints={min: 1.0, max: 5.0, step: 0.5},
group="Computation"
)
var cascadeThresh = input(
name="cascadeThresh",
type="number",
defaultValue=2.0,
label="Cascade Threshold (σ)",
constraints={min: 1.0, max: 4.0, step: 0.5},
group="Computation"
)
var cascadeBars = input(
name="cascadeBars",
type="number",
defaultValue=3,
label="Cascade Consecutive Bars",
constraints={min: 2, max: 10, step: 1},
group="Computation"
)
// --- Display ---
var showBubbles = input(
name="showBubbles",
type="boolean",
defaultValue=true,
label="Show Bubbles",
group="Display"
)
var showLabels = input(
name="showLabels",
type="boolean",
defaultValue=true,
label="Show Value Labels",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Cascade Shapes",
group="Display"
)
var showLiqZLine = input(
name="showLiqZLine",
type="boolean",
defaultValue=false,
label="Show Liquidation Z Line",
group="Display"
)
var showPressureHist = input(
name="showPressureHist",
type="boolean",
defaultValue=true,
label="Show Liquidation Pressure Histogram",
group="Display"
)
// --- Sizing ---
var sizeMult = input(
name="sizeMult",
type="number",
defaultValue=4.0,
label="Bubble Size Multiplier",
constraints={min: 1.0, max: 10.0, step: 0.5},
group="Sizing"
)
var maxSize = input(
name="maxSize",
type="number",
defaultValue=30,
label="Max Bubble Size",
constraints={min: 5, max: 50, step: 5},
group="Sizing"
)
var opacityBase = input(
name="opacityBase",
type="number",
defaultValue=60,
label="Base Opacity (%)",
constraints={min: 20, max: 100, step: 10},
group="Sizing"
)
var opacityExtreme = input(
name="opacityExtreme",
type="number",
defaultValue=90,
label="Extreme Opacity (%)",
constraints={min: 40, max: 100, step: 10},
group="Sizing"
)
// --- Colors ---
var longColor = input(
name="longColor",
type="color",
defaultValue="#ef5350",
label="Long Liquidation Color",
group="Colors"
)
var shortColor = input(
name="shortColor",
type="color",
defaultValue="#26a69a",
label="Short Liquidation Color",
group="Colors"
)
var cascadeColor = input(
name="cascadeColor",
type="color",
defaultValue="#ff9100",
label="Cascade Color",
group="Colors"
)
var labelColor = input(
name="labelColor",
type="color",
defaultValue="#ffffff",
label="Label Text Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#78909c",
label="Neutral Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries high = pxTS.high
timeseries low = pxTS.low
timeseries close = pxTS.close
timeseries liquidations = source("liquidations", currentSymbol, currentExchange)
// Guard: halt until price and liquidation data have loaded
if (isnan(close[0]) || !isnum(liquidations.buy_longs)) {
return
}
// -----------------------------------------------------------------------------
// 3. COMPUTATION
// -----------------------------------------------------------------------------
// -- 3.1 Long and short liquidation volumes --
timeseries longLiqs = liquidations.buy_longs
timeseries shortLiqs = liquidations.sell_shorts
timeseries totalLiqs = longLiqs + shortLiqs
// -- 3.2 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (Liq_t − μ_t) / σ_t over rolling lookback window.
timeseries longMean = sma(longLiqs, lookback)
timeseries longStd = stdev(longLiqs, lookback)
timeseries longZ = (longStd > 0) ? (longLiqs - longMean) / longStd : 0
timeseries shortMean = sma(shortLiqs, lookback)
timeseries shortStd = stdev(shortLiqs, lookback)
timeseries shortZ = (shortStd > 0) ? (shortLiqs - shortMean) / shortStd : 0
// Total liquidation z-score (combined pressure)
timeseries totalMean = sma(totalLiqs, lookback)
timeseries totalStd = stdev(totalLiqs, lookback)
timeseries totalZ = (totalStd > 0) ? (totalLiqs - totalMean) / totalStd : 0
// -- 3.3 Bubble sizing — scales with z-score, capped at maxSize --
timeseries longSize = longZ > zThreshold ? math.min(longZ * sizeMult, maxSize) : 0
timeseries shortSize = shortZ > zThreshold ? math.min(shortZ * sizeMult, maxSize) : 0
// -- 3.4 Opacity scaling — higher z = more visually prominent --
var longOpacity = longZ > labelZThreshold ? opacityExtreme : opacityBase
var shortOpacity = shortZ > labelZThreshold ? opacityExtreme : opacityBase
// -- 3.5 Cascade detection (stateful via static variables) --
// A cascade is defined as consecutive bars exceeding the cascade threshold.
// Per Brunnermeier & Pedersen (2009) and Amberdata (2026), liquidation cascades
// trigger when intensity exceeds critical levels over sustained periods.
static longCascadeCount = 0
static shortCascadeCount = 0
static lastBarIdx = 0
var currentBarIdx = bar_index[0]
var isLongExtreme = longZ > cascadeThresh
var isShortExtreme = shortZ > cascadeThresh
if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
lastBarIdx = currentBarIdx
if (isLongExtreme) {
longCascadeCount = longCascadeCount + 1
} else {
longCascadeCount = 0
}
if (isShortExtreme) {
shortCascadeCount = shortCascadeCount + 1
} else {
shortCascadeCount = 0
}
}
var longCascade = longCascadeCount >= cascadeBars
var shortCascade = shortCascadeCount >= cascadeBars
// -- 3.6 Zero-line helper --
timeseries zeroLine = 0
// -----------------------------------------------------------------------------
// 4. VISUALIZATION
// -----------------------------------------------------------------------------
// --- 4.1 Long liquidation bubbles (below the bar) ---
if (showBubbles && longZ > zThreshold) {
plotShape(
value=low,
shape="circle",
color=opacity(longColor, longOpacity),
width=longSize,
label=["Long Liq"],
desc=["Long liquidation bubble (z=" + longZ + "); size ∝ magnitude"]
)
}
// --- 4.2 Short liquidation bubbles (above the bar) ---
if (showBubbles && shortZ > zThreshold) {
plotShape(
value=high,
shape="circle",
color=opacity(shortColor, shortOpacity),
width=shortSize,
label=["Short Liq"],
desc=["Short liquidation bubble (z=" + shortZ + "); size ∝ magnitude"]
)
}
// --- 4.3 Value labels for large liquidation events ---
if (showLabels && longZ > labelZThreshold) {
var totalUsd = longLiqs * close
plotPriceLabel(
price=low,
text=("L $" + (totalUsd / 1000.0) + "K"),
type="flag",
color=labelColor,
backgroundColor=longColor,
size=8,
fontWeight=700
)
}
if (showLabels && shortZ > labelZThreshold) {
var totalUsd2 = shortLiqs * close
plotPriceLabel(
price=high,
text=("S $" + (totalUsd2 / 1000.0) + "K"),
type="flag",
color=labelColor,
backgroundColor=shortColor,
size=8,
fontWeight=700
)
}
// --- 4.4 Cascade detection shapes (diamonds for sustained extreme events) ---
if (showShapes && longCascade) {
plotShape(
value=low,
shape="diamond",
color=cascadeColor,
width=5,
label=["Long Cascade"],
desc=["Long liquidation cascade (" + cascadeBars + "+ consecutive bars > " + cascadeThresh + "σ); potential liquidity spiral / forced-selling event"]
)
}
if (showShapes && shortCascade) {
plotShape(
value=high,
shape="diamond",
color=cascadeColor,
width=5,
label=["Short Cascade"],
desc=["Short liquidation cascade (" + cascadeBars + "+ consecutive bars > " + cascadeThresh + "σ); potential liquidity spiral / forced-buying event"]
)
}
// --- 4.5 Optional liquidation z-score line (plotLine) ---
if (showLiqZLine) {
var liqRegime = totalZ > zThreshold ? 1 : (totalZ < -zThreshold ? -1 : 0)
plotLine(
value=totalZ,
width=1,
colors=[shortColor, longColor, neutralColor],
colorIndex=liqRegime == 1 ? 0 : (liqRegime == -1 ? 1 : 2),
label=["Total Liq Z"],
desc=["Combined liquidation z-score; context for bubble events"]
)
}
// --- 4.6 Liquidation pressure histogram (plotBar) ---
if (showPressureHist) {
var pressureColor = totalZ > zThreshold ? longColor : (totalZ < -zThreshold ? shortColor : neutralColor)
plotBar(
value=totalZ,
colors=[pressureColor, pressureColor],
width=1,
label=["Liq Pressure"],
desc=["Total liquidation pressure z-score; bars above threshold = significant event"]
)
}
// --- 4.7 Reference thresholds (hline) ---
hline(value=0, color="#ffffff30", width=1)
hline(value=zThreshold, color=opacity(longColor, 20), width=1)
hline(value=cascadeThresh, color=opacity(cascadeColor, 20), width=1)