Perfected FlowScript
large liquidation on chart
Large Liquidation on Chart V2 is indexed as 262_large_liquidation_on_chart.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
offchart
Axis
true
Size
14.3 KB
Lines
351
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Long Liq
line 280:9
Trigger
(showShapes) && (longLiq)
Value
hi + (hi * 0.002)
Deps
longLiq:var, showShapes:input
Short Liq
line 290:9
Trigger
(showShapes) && (shortLiq)
Value
lo - (lo * 0.002)
Deps
shortLiq:var, showShapes:input
Extreme Liq
line 300:9
Trigger
(showShapes) && (extremeLiq)
Value
px
Deps
extremeLiq:var, showShapes:input
Cascade
line 310:9
Trigger
(showShapes) && (isCascade)
Value
px + (px * 0.003)
Deps
isCascade:var, showShapes:input
262_large_liquidation_on_chart.flowscript
source path: kscripts/perfected/262_large_liquidation_on_chart.flowscript · sha256:c9b904233eece9c1505cab9d1cfc1416b3f940060d0bc73f05d8904d611ba470
//@version=2
// ============================================================================
// Large Liquidation on Chart V2 — Production-Quality Liquidation Detector
// Author: C (@Chimankpa) | Perfected by: kScript Perfection Engineer
// Index: 262
// Tags: FLOW, #liquidation, #cascade, #deleveraging, #funding, #risk
//
// Detects large liquidation events on-chart by monitoring volume anomalies,
// price-range compression/expansion, and rapid price moves. Implements
// liquidation impact scoring, zone detection, and regime classification.
//
// FORMULA FOUNDATION:
// 1. Liquidation Volume: LV = Volume × (|Close − Open| / Range) — volume
// concentrated in the direction of the bar (high conviction candle).
// 2. Liquidation Impact Score: I = (VolZ × PricePct) / (1 + ATR/Price)
// High impact = volume spike + price within liquidation zone + low vol
// environment (thin books amplify liquidation cascades).
// 3. Liquidation Zone: pricePct ∈ (0.3, 0.7) mid-range — liquidations tend
// to occur in the middle of the prior range before breaking out.
// 4. Cascade Detection: consecutive bars with high liquidation score and
// same-direction price movement.
//
// RESEARCH BASIS:
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies 22(6), 2201–2238. Funding liquidity
// shocks → market liquidity dry-up → liquidation spirals.
// • Green, Hollifield & Schurhoff (2005), "Financial Intermediation and the
// Role of Price in Informing Adjustment". Deleveraging cascades produce
// volume spikes with minimal price recovery (one-sided absorption).
// • Cont & Schaanning (2017), "Fire Sales, Indirect Contagion and Systemic
// Stress Testing". Liquidation commonality across assets during stress.
// • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
// in a High-Frequency World", J. Portfolio Mgmt. VPIN metric for
// toxicity/liquidation probability.
// • Gorton & Metrick (2012), "Securitized Banking and the Run on Repo",
// J. Financial Economics. Deleveraging dynamics and funding-liquidity risk.
// ============================================================================
define(
title="Large Liquidation on Chart V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Liquidation Thresholds ---
var liqThreshold = input(name="liqThreshold", type="number", defaultValue=500000, label="Liquidation USD Threshold", constraints={min: 10000, max: 10000000, step: 10000}, group="Thresholds")
var volMul = input(name="volMul", type="number", defaultValue=3.0, label="Volume Spike Multiplier (σ)", constraints={min: 1.0, max: 10.0, step: 0.1}, group="Thresholds")
var impactMin = input(name="impactMin", type="number", defaultValue=2.0, label="Min Impact Score", constraints={min: 0.5, max: 10.0, step: 0.1}, group="Thresholds")
// --- Lookback ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Lookback", constraints={min: 5, max: 100, step: 1}, group="Lookback")
var rangeLookback = input(name="rangeLookback", type="number", defaultValue=20, label="Range Lookback", constraints={min: 5, max: 100, step: 1}, group="Lookback")
var impactLookback = input(name="impactLookback", type="number", defaultValue=20, label="Impact Lookback", constraints={min: 5, max: 100, step: 1}, group="Lookback")
// --- ATR & Volatility Filter ---
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 50, step: 1}, group="Volatility")
var useATRFilter = input(name="useATRFilter", type="boolean", defaultValue=true, label="Use ATR Impact Filter", group="Volatility")
// --- Display ---
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Liquidation Zones", group="Display")
var showImpact = input(name="showImpact", type="boolean", defaultValue=true, label="Show Impact Score Line", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Liquidation Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Liquidation Shapes", group="Display")
var showLongShort = input(name="showLongShort", type="boolean", defaultValue=true, label="Show Long/Short Split", group="Display")
var showATR = input(name="showATR", type="boolean", defaultValue=false, label="Show ATR Line", group="Display")
// --- Colors ---
var longLiqColor = input(name="longLiqColor", type="color", defaultValue="#ff1744", label="Long Liquidation Color", group="Colors")
var shortLiqColor = input(name="shortLiqColor", type="color", defaultValue="#00e676", label="Short Liquidation Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var zoneColor = input(name="zoneColor", type="color", defaultValue="#ffeb3b", label="Zone Color", group="Colors")
var impactColor = input(name="impactColor", type="color", defaultValue="#ff9800", label="Impact Score Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries op = priceBars.open
timeseries hi = priceBars.high
timeseries lo = priceBars.low
timeseries vol = priceBars.volume
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Range & Volatility
// ------------------------------------------------------------------------------
var rangeHi = highest(hi, rangeLookback)
var rangeLo = lowest(lo, rangeLookback)
var rangeSpan = rangeHi - rangeLo
var rangeSpanSafe = rangeSpan > 0 ? rangeSpan : 0.0001
// Price position within the range (0 = low, 1 = high)
var pricePct = (px - rangeLo) / rangeSpanSafe
// ATR for volatility normalization
var atr = atr(atrLen)
var atrPct = px > 0 ? atr / px : 0.0
// ------------------------------------------------------------------------------
// Volume Anomaly
// ------------------------------------------------------------------------------
var avgVol = sma(vol, volLookback)
var stdVol = stddev(vol, volLookback)
var volZ = stdVol > 0 ? (vol - avgVol) / stdVol : 0.0
var volSpike = volZ >= volMul
// Liquidation volume = volume weighted by directional intensity
// (larger body = more directional conviction)
var barBody = math.abs(px - op)
var barRange = hi - lo
var barRangeSafe = barRange > 0 ? barRange : 0.0001
var dirIntensity = barBody / barRangeSafe
var liqVol = vol * dirIntensity
// ------------------------------------------------------------------------------
// Liquidation Impact Score (Brunnermeier & Pedersen 2009 deleveraging model)
// ------------------------------------------------------------------------------
// Impact = (Volume Z-score × Price Position) / (1 + ATR%)
// High volume + mid-range price + low volatility environment = high impact
var impactRaw = volZ * pricePct
var impactDenom = useATRFilter ? (1.0 + atrPct * 10.0) : 1.0
var impactScore = impactDenom > 0 ? impactRaw / impactDenom : 0.0
// Impact Z-score for normalization
var avgImpact = sma(impactScore, impactLookback)
var stdImpact = stddev(impactScore, impactLookback)
var impactZ = stdImpact > 0 ? (impactScore - avgImpact) / stdImpact : 0.0
// ------------------------------------------------------------------------------
// Liquidation Direction Detection
// ------------------------------------------------------------------------------
// Long liquidation: price drops (close < open) with high volume
// Short liquidation: price rises (close > open) with high volume
var isDown = px < op
var isUp = px > op
var longLiq = volSpike && isDown && impactScore >= impactMin && pricePct > 0.2 && pricePct < 0.8
var shortLiq = volSpike && isUp && impactScore >= impactMin && pricePct > 0.2 && pricePct < 0.8
var extremeLiq = impactZ >= 2.0 && volSpike
// ------------------------------------------------------------------------------
// Cascade Detection (consecutive liquidation events)
// ------------------------------------------------------------------------------
static lastLiqDir = 0 // 1 = long, -1 = short, 0 = none
static cascadeCount = 0
static liqEventCount = 0
static maxImpact = 0.0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
var currentDir = longLiq ? 1 : (shortLiq ? -1 : 0)
if (currentDir != 0 && currentDir == lastLiqDir) {
cascadeCount = cascadeCount + 1
} else if (currentDir != 0) {
cascadeCount = 1
} else {
cascadeCount = 0
}
lastLiqDir = currentDir
if (longLiq || shortLiq) {
liqEventCount = liqEventCount + 1
}
if (impactScore > maxImpact) {
maxImpact = impactScore
}
}
var isCascade = cascadeCount >= 2
// ------------------------------------------------------------------------------
// Regime Detection
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = long-liquidation dominant, -1 = short-liquidation dominant
if (longLiq && !shortLiq) {
regime = 1
} else if (shortLiq && !longLiq) {
regime = -1
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types
// ------------------------------------------------------------------------------
// Zero / threshold lines
hline(value=0, color="#ffffff30", width=1)
if (showZones) {
hline(value=0.7, color=opacity(zoneColor, 30), width=1)
hline(value=0.3, color=opacity(zoneColor, 30), width=1)
}
// Range high/low lines (liquidation zone boundaries)
if (showZones) {
plotLine(
value=rangeHi,
width=1,
colors=[opacity(longLiqColor, 40)],
label=["Range High"],
desc=["Upper liquidation zone boundary (rolling high)"],
forceOnChart=true
)
plotLine(
value=rangeLo,
width=1,
colors=[opacity(shortLiqColor, 40)],
label=["Range Low"],
desc=["Lower liquidation zone boundary (rolling low)"],
forceOnChart=true
)
}
// Impact score line (normalized)
if (showImpact) {
var impactRegimeColor = regime == 1 ? longLiqColor : (regime == -1 ? shortLiqColor : neutralColor)
plotLine(
value=impactScore,
width=2,
colors=[impactColor, longLiqColor, shortLiqColor, neutralColor],
colorIndex=impactScore >= impactMin ? (regime == 1 ? 1 : (regime == -1 ? 2 : 0)) : 3,
label=["Impact Score"],
desc=["Liquidation impact score (vol × price position / ATR)"],
fill=true
)
}
// ATR line (optional, for context)
if (showATR) {
plotLine(
value=atr,
width=1,
colors=[neutralColor],
label=["ATR"],
desc=["Average True Range (volatility context)"]
)
}
// Liquidation histogram (long/short split)
if (showBars) {
if (showLongShort) {
// Separate bars for long and short liquidation
var liqBar = longLiq || shortLiq ? impactScore : 0.0
plotBar(
value=liqBar,
colors=[longLiqColor, shortLiqColor, neutralColor],
colorIndex=longLiq ? 0 : (shortLiq ? 1 : 2),
width=1,
label=["Long Liq", "Short Liq", "Neutral"],
desc=["Long liquidation impact", "Short liquidation impact", "No liquidation"]
)
} else {
// Combined liquidation bars
var liqBar = longLiq || shortLiq ? impactScore : 0.0
plotBar(
value=liqBar,
colors=[longLiqColor, shortLiqColor, neutralColor],
colorIndex=longLiq ? 0 : (shortLiq ? 1 : 2),
width=1,
label=["Liquidation"],
desc=["Liquidation impact histogram"]
)
}
}
// Liquidation shape markers
if (showShapes) {
if (longLiq) {
plotShape(
value=hi + (hi * 0.002),
shape="triangledown",
color=longLiqColor,
width=3,
label=["Long Liq"],
desc=["Long liquidation: high volume + down bar + mid-range (stops hunted)"]
)
}
if (shortLiq) {
plotShape(
value=lo - (lo * 0.002),
shape="triangleup",
color=shortLiqColor,
width=3,
label=["Short Liq"],
desc=["Short liquidation: high volume + up bar + mid-range (stops hunted)"]
)
}
if (extremeLiq) {
plotShape(
value=px,
shape="diamond",
color=zoneColor,
width=4,
label=["Extreme Liq"],
desc=["Extreme liquidation event: impact Z-score ≥ 2σ"]
)
}
if (isCascade) {
plotShape(
value=px + (px * 0.003),
shape="xcross",
color=longLiqColor,
width=2,
label=["Cascade"],
desc=["Liquidation cascade: consecutive same-direction liquidation events"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "LONG LIQ" : (regime == -1 ? "SHORT LIQ" : "NEUTRAL")
var regimeTextColor = regime == 1 ? longLiqColor : (regime == -1 ? shortLiqColor : neutralColor)
plotTable(
data=[
["Liquidation V2", regimeText],
["Impact Score", impactScore],
["Vol Z-Score", volZ],
["ATR %", atrPct * 100],
["Liq Events", liqEventCount],
["Cascade Count", cascadeCount],
["Max Impact", maxImpact]
],
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
)
}