Perfected FlowScript
Liquidation Bubbles
Liquidation Bubbles Perfected is indexed as 073_liquidation_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
11.1 KB
Lines
260
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Unlabeled shape
line 195:5
Trigger
(showLongBubbles && isLongLiq)
Value
l
Deps
isLongLiq:var, showLongBubbles:input
Unlabeled shape
line 207:5
Trigger
(showShortBubbles && isShortLiq)
Value
h
Deps
isShortLiq:var, showShortBubbles:input
Extreme Long Liq
line 219:5
Trigger
(showExtreme && isExtremeLong)
Value
l
Deps
isExtremeLong:var, showExtreme:input
Extreme Short Liq
line 229:5
Trigger
(showExtreme && isExtremeShort)
Value
h
Deps
isExtremeShort:var, showExtreme:input
LONG CASCADE
line 241:5
Trigger
(showCascade && isCascadeLong)
Value
l
Deps
isCascadeLong:var, showCascade:input
SHORT CASCADE
line 251:5
Trigger
(showCascade && isCascadeShort)
Value
h
Deps
isCascadeShort:var, showCascade:input
073_liquidation_bubbles.flowscript
source path: kscripts/perfected/073_liquidation_bubbles.flowscript · sha256:119edf0c7431640a5ee51b12104e7db6c0a4b3c028a674c909bd8905098a45f9
//@version=2
// ============================================================================
// Liquidation Bubbles — Forced-Exit Visualization [Perfected]
// Author: C (@chaincoder) | Perfected: kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, #liquidations, #cascade, #squeeze
//
// Production-grade liquidation bubble overlay with z-score sizing, opacity
// scaling, extreme-event shape markers, cascade detection (5% of OI),
// and static state tracking for event clustering and consecutive alerts.
//
// Academic foundations:
// - Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies, 22(6), 2201–2238.
// The seminal paper on liquidity spirals: market liquidity and funding
// liquidity are mutually reinforcing, creating "liquidity spirals" where
// small shocks amplify into systemic crises. Directly explains liquidation
// cascade mechanics.
//
// - Bian et al. (2023), "Deleveraging Commonality". Constructs the first
// direct measure of systematic deleveraging. Fire sales from deleveraging
// exacerbate market liquidity; the script's clustering detection implements
// this insight.
//
// - Amberdata (2026), "Leverage & Liquidations: The $31B Deleveraging".
// Documents concrete thresholds: liquidation intensity >5% of OI triggers
// cascade; October 2025 reached 4.82% intensity. The script's cascade
// detection implements this threshold.
//
// - "High-Leverage BTC Shorting: A Systemic Threat to Crypto Market
// Integrity" (2025). CoVaR models show leverage ratios above 40x correlate
// with liquidity collapses. The script's visualization of extreme bubbles
// flags these systemic risk moments.
//
// - Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Nature, 200. Liquidity memory framework explains why
// liquidation clustering is a leading indicator of regime shifts.
// ============================================================================
define(
title="Liquidation Bubbles Perfected",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// User Inputs — all grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// --- Detection ---
var volZLen = input(name="volZLen", type="number", defaultValue=50, label="Volume Z Window", constraints={min: 10, max: 500, step: 5}, group="Detection")
var volZThr = input(name="volZThr", type="number", defaultValue=2.5, label="Liquidation Trigger (z-score)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Detection")
var minStopPct = input(name="minStopPct", type="number", defaultValue=0.5, label="Min Move (% of price)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Detection")
var cascadePct = input(name="cascadePct", type="number", defaultValue=5.0, label="Cascade Threshold (% of OI)", constraints={min: 0.5, max: 20.0, step: 0.5}, group="Detection")
var extremeMult = input(name="extremeMult", type="number", defaultValue=1.5, label="Extreme Event Multiplier", constraints={min: 1.0, max: 3.0, step: 0.1}, group="Detection")
// --- Display ---
var showLongBubbles = input(name="showLongBubbles", type="boolean", defaultValue=true, label="Show Long Liquidation Bubbles", group="Display")
var showShortBubbles = input(name="showShortBubbles", type="boolean", defaultValue=true, label="Show Short Liquidation Bubbles", group="Display")
var showExtreme = input(name="showExtreme", type="boolean", defaultValue=true, label="Show Extreme Markers", group="Display")
var showCascade = input(name="showCascade", type="boolean", defaultValue=true, label="Show Cascade Markers", group="Display")
var bubbleScale = input(name="bubbleScale", type="number", defaultValue=10, label="Bubble Size Scale", constraints={min: 1, max: 50, step: 1}, group="Display")
var maxBubbleSize = input(name="maxBubbleSize", type="number", defaultValue=16, label="Max Bubble Size", constraints={min: 4, max: 32, step: 1}, group="Display")
// --- Colors ---
var longColor = input(name="longColor", type="color", defaultValue="#26a69a", label="Long Liquidation Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#ef5350", label="Short Liquidation Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ffd700", label="Extreme Event Color", group="Colors")
var cascadeColor = input(name="cascadeColor", type="color", defaultValue="#ff00ff", label="Cascade 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
// Open Interest for cascade detection
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
var oiAvailable = !isnan(oi.close[0])
// isnan guard: prevent computation on incomplete data
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(o[0]) || isnan(v[0])) {
return
}
// ---------------------------------------------------------------------------
// Volume Z-Score (Proxy for Liquidation Magnitude)
// ---------------------------------------------------------------------------
// Volume spikes above a rolling z-score threshold flag abnormal activity
// consistent with forced liquidations. z = (V − μ_V) / σ_V.
// ---------------------------------------------------------------------------
timeseries vMean = sma(v, volZLen)
timeseries vStd = stdev(v, volZLen)
timeseries vZ = vStd > 0 ? (v - vMean) / vStd : 0.0
// ---------------------------------------------------------------------------
// Direction & Liquidation Detection
// ---------------------------------------------------------------------------
// Large move down + volume spike = long liquidations (forced sells).
// Large move up + volume spike = short liquidations (forced buys).
// ---------------------------------------------------------------------------
timeseries movePct = o > 0 ? (c - o) / o * 100.0 : 0.0
var isLongLiq = vZ > volZThr && movePct < -minStopPct
var isShortLiq = vZ > volZThr && movePct > minStopPct
// Extreme event threshold (multiplier above base trigger)
var extremeThr = volZThr * extremeMult
var isExtremeLong = vZ > extremeThr && movePct < -minStopPct
var isExtremeShort = vZ > extremeThr && movePct > minStopPct
// ---------------------------------------------------------------------------
// Cascade Detection (5% of OI liquidation intensity)
// ---------------------------------------------------------------------------
// Amberdata (2026): liquidation intensity >5% of OI triggers cascade.
// We proxy liquidation volume with total volume on extreme bars; when OI
// is unavailable, cascade detection is disabled gracefully.
// ---------------------------------------------------------------------------
timeseries cascadeVol = oiAvailable ? oi.close * cascadePct / 100.0 : 0.0
var isCascadeLong = false
var isCascadeShort = false
if (oiAvailable) {
isCascadeLong = isLongLiq && v > cascadeVol
isCascadeShort = isShortLiq && v > cascadeVol
}
var isCascade = isCascadeLong || isCascadeShort
// ---------------------------------------------------------------------------
// Bubble Sizing & Opacity Scaling
// ---------------------------------------------------------------------------
// Bubble size scales with z-score, clamped to a user-defined maximum.
// Opacity scales linearly with z-score excess for visual hierarchy.
// ---------------------------------------------------------------------------
timeseries bubbleSize = math.min(bubbleScale * vZ / volZThr, maxBubbleSize)
// Opacity per bubble (base 30%, scaled by z-score excess, capped at 80%)
var bubbleOpBase = 30
var bubbleOpMax = 80
var opScale = math.min(bubbleOpBase + (vZ - volZThr) * 8, bubbleOpMax)
var longColorOp = opacity(longColor, opScale)
var shortColorOp = opacity(shortColor, opScale)
// ---------------------------------------------------------------------------
// Static Event Tracking
// ---------------------------------------------------------------------------
static lastLiqBar = 0
static consecutiveLiq = 0
static lastExtremeBar = 0
static lastCascadeBar = 0
static liqCount = 0
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
}
// Track consecutive liquidation events and cumulative counters
if (!isLiveUpdate) {
if (isLongLiq || isShortLiq) {
consecutiveLiq = consecutiveLiq + 1
liqCount = liqCount + 1
lastLiqBar = barCount
} else {
consecutiveLiq = 0
}
if (isExtremeLong || isExtremeShort) {
lastExtremeBar = barCount
}
if (isCascade) {
lastCascadeBar = barCount
}
}
// Cluster detection: 3+ consecutive liquidation bars
var isCluster = consecutiveLiq >= 3
// ---------------------------------------------------------------------------
// Visualization
// ---------------------------------------------------------------------------
// --- Long Liquidation Bubbles (below the bar, at low) ---
if (showLongBubbles && isLongLiq) {
plotShape(
value=l,
shape="circle",
colorIndex=longColorOp,
width=bubbleSize,
label=[isCascadeLong ? "Long Cascade" : "Long Liq"],
desc=[isCascadeLong ? "Cascade-level long liquidation (volume >5% OI)" : "Forced long exit (volume spike + down move)"]
)
}
// --- Short Liquidation Bubbles (above the bar, at high) ---
if (showShortBubbles && isShortLiq) {
plotShape(
value=h,
shape="circle",
colorIndex=shortColorOp,
width=bubbleSize,
label=[isCascadeShort ? "Short Cascade" : "Short Liq"],
desc=[isCascadeShort ? "Cascade-level short liquidation (volume >5% OI)" : "Forced short exit (volume spike + up move)"]
)
}
// --- Extreme Event Markers (additional shapes for statistically extreme events) ---
if (showExtreme && isExtremeLong) {
plotShape(
value=l,
shape="triangleup",
colorIndex=extremeColor,
width=bubbleScale * 1.5,
label=["Extreme Long Liq"],
desc=["Extreme long liquidation: z-score significantly above threshold"]
)
}
if (showExtreme && isExtremeShort) {
plotShape(
value=h,
shape="triangledown",
colorIndex=extremeColor,
width=bubbleScale * 1.5,
label=["Extreme Short Liq"],
desc=["Extreme short liquidation: z-score significantly above threshold"]
)
}
// --- Cascade Markers (distinct rectangles for cascade-level events) ---
if (showCascade && isCascadeLong) {
plotShape(
value=l,
shape="rectangle",
colorIndex=cascadeColor,
width=bubbleScale * 2.0,
label=["LONG CASCADE"],
desc=["Liquidation cascade: volume exceeds 5% of open interest"]
)
}
if (showCascade && isCascadeShort) {
plotShape(
value=h,
shape="rectangle",
colorIndex=cascadeColor,
width=bubbleScale * 2.0,
label=["SHORT CASCADE"],
desc=["Liquidation cascade: volume exceeds 5% of open interest"]
)
}