Perfected FlowScript
FootPrint bar statistics
Footprint Bar Statistics V2 is indexed as 009_footprint_bar_statistics.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
13.6 KB
Lines
307
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Whale Bar
line 277:5
Trigger
(showWhaleShapes && whaleDetected)
Value
bars.volume
Deps
showWhaleShapes:input, whaleDetected:var
Liq Cascade
line 289:5
Trigger
(showWhaleShapes && liqCascade)
Value
totalLiq
Deps
liqCascade:var, showWhaleShapes:input
009_footprint_bar_statistics.flowscript
source path: kscripts/perfected/009_footprint_bar_statistics.flowscript · sha256:f2f7880e2a9835925f0c49d6fc36ad971d6d9e5fd930d7573091839af8ad1d1c
//@version=2
// ============================================================================
// Footprint Bar Statistics V2 — Production-Quality Per-Bar Order Flow Dashboard
// Author: L (@leader56) | Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, CORE, #volume, #delta, #footprint, #liquidation, #orderflow
//
// Comprehensive per-bar footprint dashboard showing volume, delta (buys − sells),
// liquidation breakdown, and buy/sell ratio — all with heatmap-style z-score
// color coding, whale detection shape markers, and histogram visualizations.
//
// FORMULA FOUNDATION:
// 1. Volume Delta = BuyVol − SellVol (Lee-Ready 1991 classification).
// 2. Z-Score Normalization: z_t = (x_t − μ_x) / σ_x over rolling window W.
// Heatmap color intensity scales with |z| (Zhao & Palomar 2018 framework).
// 3. Whale Detection: volume > k × SMA(volume, W) where k = user-configurable
// multiplier (default 2.0). Inspired by Steidlmayer's "excess volume" concept.
// 4. Liquidation Cascade: total liquidations z-score > 2σ flags potential
// Brunnermeier & Pedersen (2009) liquidity spiral conditions.
//
// RESEARCH BASIS:
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746. DOI: 10.1111/j.1540-6261.1991.tb02683.x
// Foundational buy/sell classification for delta computation.
// • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
// Order Book", Market Microstructure and Liquidity, 4(3n4), 1950011.
// Multi-level OFI improves price prediction; supports per-bar footprint.
// DOI: 10.1142/S238262661950011X
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Journal of Finance, 65(6), 2201–2238. Liquidity spiral: market liquidity
// and funding liquidity mutually reinforce; margin breaches trigger cascades.
// DOI: 10.1111/j.1540-6261.2009.01485.x
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", J. Financial Economics 65(1), 111–130. Extreme imbalance
// predicts return reversals; supports whale-detection significance.
// DOI: 10.1016/S0304-405X(02)00136-8
// • Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with Market
// Profile". Excess volume (volume significantly above norm) as structural
// signal for high-volume nodes (HVN) and liquidation events.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// Z-score normalization: z̄_t = (z_t − μ_z) / σ_z; thresholds at ±1σ, ±2σ.
// • Amberdata Research (2026), "Leverage & Liquidations: The $31B Deleveraging".
// Liquidation intensity > 5% of OI = cascade trigger; empirical thresholds.
// ============================================================================
define(title="Footprint Bar Statistics V2", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// --- Data Sources ---
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Sources")
var exchange = input(name="exchange", type="string", defaultValue="BINANCE_FUTURES", label="Exchange", group="Data Sources")
// --- Computation ---
var volLen = input(name="volLen", type="number", defaultValue=20, label="Volume Average Length", constraints={min: 5, max: 100, step: 5}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var bigVolMult = input(name="bigVolMult", type="number", defaultValue=2.0, label="Whale Volume Multiplier (vs SMA)", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Computation")
var liqThreshold = input(name="liqThreshold", type="number", defaultValue=2.0, label="Liquidation Z-Score Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")
// --- Display ---
var showVolume = input(name="showVolume", type="boolean", defaultValue=true, label="Show Volume", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Delta", group="Display")
var showLiquidations = input(name="showLiquidations", type="boolean", defaultValue=true, label="Show Liquidations", group="Display")
var showBuySellRatio = input(name="showBuySellRatio", type="boolean", defaultValue=true, label="Show Buy/Sell Ratio", group="Display")
var showWhaleShapes = input(name="showWhaleShapes", type="boolean", defaultValue=true, label="Show Whale Shapes", group="Display")
var showHeatmap = input(name="showHeatmap", type="boolean", defaultValue=true, label="Show Heatmap Z-Score Colors", group="Display")
// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Buy Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Sell Color", group="Colors")
var bigVolColor = input(name="bigVolColor", type="color", defaultValue="#ffeb3b", label="Whale Volume Highlight", group="Colors")
var liqLongColor = input(name="liqLongColor", type="color", defaultValue="#d50000", label="Long Liq Color", group="Colors")
var liqShortColor = input(name="liqShortColor", type="color", defaultValue="#2962ff", label="Short Liq Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff1744", label="Extreme Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=symbol, exchange=exchange)
timeseries taker = source("taker_volume", symbol, exchange)
timeseries liquidations = source("liquidations", symbol, exchange)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(bars.close[0]) || !isnum(taker.buy)) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Per-bar buy/sell volume (Lee-Ready 1991 classification) --
// When taker.buy/sell is available, prefer direct feed. Otherwise tick test.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (bars.close > bars.open ? bars.volume : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (bars.close <= bars.open ? bars.volume : 0)
timeseries delta = buyVol - sellVol
// -- 3.2 Volume analysis --
timeseries avgVol = sma(bars.volume, volLen)
timeseries isBigVol = bars.volume >= avgVol * bigVolMult
// Volume z-score for heatmap coloring
timeseries volMean = sma(bars.volume, zWindow)
timeseries volStd = stdev(bars.volume, zWindow)
timeseries volZ = volStd > 0 ? (bars.volume - volMean) / volStd : 0
// -- 3.3 Delta z-score for heatmap coloring --
timeseries deltaMean = sma(delta, zWindow)
timeseries deltaStd = stdev(delta, zWindow)
timeseries deltaZ = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0
// -- 3.4 Buy/Sell ratio --
// Ratio = buy / sell; normalized to [−1, +1] for visualization
var totalVol = buyVol + sellVol
var buyRatio = totalVol > 0 ? buyVol / totalVol : 0.5
var sellRatio = totalVol > 0 ? sellVol / totalVol : 0.5
var imbalanceRatio = totalVol > 0 ? (buyVol - sellVol) / totalVol : 0.0 // ∈ [−1, +1]
// -- 3.5 Liquidations --
timeseries longLiq = isnum(liquidations.long) ? liquidations.long : 0
timeseries shortLiq = isnum(liquidations.short) ? liquidations.short : 0
timeseries totalLiq = longLiq + shortLiq
// Liquidation z-score (Brunnermeier & Pedersen 2009 cascade detection)
timeseries liqMean = sma(totalLiq, zWindow)
timeseries liqStd = stdev(totalLiq, zWindow)
timeseries liqZ = liqStd > 0 ? (totalLiq - liqMean) / liqStd : 0
// -- 3.6 Regime detection --
var bullishBar = delta > 0
var bearishBar = delta < 0
var neutralBar = delta == 0
var whaleDetected = isBigVol
var liqCascade = liqZ >= liqThreshold
// -- 3.7 Static state tracking (session-level persistence) --
// Tracks per-bar stats, whale counts, and liquidation extremes across the session.
static lastBarIndex = 0
static sessionHighVol = 0.0
static sessionLowVol = 999999999999.0
static sessionHighDelta = -999999999999.0
static sessionLowDelta = 999999999999.0
static whaleCount = 0
static liqCascadeCount = 0
static totalBuyVol = 0.0
static totalSellVol = 0.0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (bars.volume > sessionHighVol) {
sessionHighVol = bars.volume
}
if (bars.volume < sessionLowVol && bars.volume > 0) {
sessionLowVol = bars.volume
}
if (delta > sessionHighDelta) {
sessionHighDelta = delta
}
if (delta < sessionLowDelta) {
sessionLowDelta = delta
}
if (whaleDetected) {
whaleCount = whaleCount + 1
}
if (liqCascade) {
liqCascadeCount = liqCascadeCount + 1
}
if (!isnan(buyVol[0])) {
totalBuyVol = totalBuyVol + buyVol[0]
}
if (!isnan(sellVol[0])) {
totalSellVol = totalSellVol + sellVol[0]
}
}
// ---------------------------------------------------------------------------
// 4. HEATMAP COLOR CODING (z-score based)
// ---------------------------------------------------------------------------
// Color intensity scales with |z| per Zhao & Palomar (2018).
// 0 = neutral, 1 = moderate, 2 = high, 3 = extreme
var absVolZ = math.abs(volZ)
var absDeltaZ = math.abs(deltaZ)
var volColorIdx = absVolZ >= 3.0 ? 3 : (absVolZ >= 2.0 ? 2 : (absVolZ >= 1.0 ? 1 : 0))
var deltaColorIdx = absDeltaZ >= 3.0 ? 3 : (absDeltaZ >= 2.0 ? 2 : (absDeltaZ >= 1.0 ? 1 : 0))
// Volume color: neutral → bull/bear base → whale highlight → extreme
var volColor = neutralColor
if (showHeatmap) {
if (whaleDetected) {
volColor = bigVolColor
} else if (bullishBar) {
volColor = bullColor
} else if (bearishBar) {
volColor = bearColor
}
} else {
volColor = bullishBar ? bullColor : (bearishBar ? bearColor : neutralColor)
}
// Delta color: heatmap intensity by z-score
var deltaBaseColor = bullishBar ? bullColor : (bearishBar ? bearColor : neutralColor)
var deltaHeatColor = showHeatmap ? (absDeltaZ >= 3.0 ? extremeColor : (absDeltaZ >= 2.0 ? bigVolColor : deltaBaseColor)) : deltaBaseColor
// ---------------------------------------------------------------------------
// 5. VISUALIZATION — Multiple types: plotBar, plotLine, plotShape, hline
// ---------------------------------------------------------------------------
// 5.1 Volume bars (with whale detection coloring)
if (showVolume) {
plotBar(
value=bars.volume,
colors=[volColor],
width=1,
label=["Volume"],
desc=["Per-bar volume; yellow when whale-sized (≥" + tostring(bigVolMult) + "× SMA), color-coded by bar direction"]
)
}
// 5.2 Delta histogram/bars (heatmap z-score colored)
if (showDelta) {
plotBar(
value=delta,
colors=[neutralColor, bullColor, bigVolColor, extremeColor, bearColor, bigVolColor, extremeColor],
colorIndex=deltaColorIdx + (bullishBar ? 1 : (bearishBar ? 4 : 0)),
width=1,
label=["Delta"],
desc=["Buy minus sell volume (Lee-Ready 1991). Heatmap color by z-score: |z|>3=extreme, |z|>2=high, |z|>1=moderate"]
)
}
// 5.3 Liquidation bars (long and short)
if (showLiquidations) {
plotBar(
value=longLiq,
colors=[liqLongColor],
width=1,
label=["Long Liq"],
desc=["Long liquidations (Brunnermeier & Pedersen 2009 cascade indicator)"]
)
plotBar(
value=shortLiq,
colors=[liqShortColor],
width=1,
label=["Short Liq"],
desc=["Short liquidations (Brunnermeier & Pedersen 2009 cascade indicator)"]
)
}
// 5.4 Buy/Sell ratio line (imbalance ratio normalized to [−1, +1])
if (showBuySellRatio) {
plotLine(
value=imbalanceRatio * 100.0,
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=imbalanceRatio > 0.1 ? 0 : (imbalanceRatio < -0.1 ? 1 : 2),
label=["Buy/Sell Imbalance %"],
desc=["(BuyVol − SellVol) / TotalVol × 100. +100 = all buy, −100 = all sell"]
)
}
// 5.5 Whale detection shape markers (Steidlmayer excess volume concept)
if (showWhaleShapes && whaleDetected) {
var whaleShape = bullishBar ? "triangleup" : "triangledown"
var whaleColor = bullishBar ? extremeColor : extremeColor
plotShape(
value=bars.volume,
shape=whaleShape,
color=whaleColor,
width=3,
label=["Whale Bar"],
desc=["Volume ≥ " + tostring(bigVolMult) + "× SMA — potential absorption, exhaustion, or liquidation event (Steidlmayer HVN concept)"]
)
}
// 5.6 Liquidation cascade shape markers (Brunnermeier & Pedersen 2009)
if (showWhaleShapes && liqCascade) {
plotShape(
value=totalLiq,
shape="diamond",
color=extremeColor,
width=4,
label=["Liq Cascade"],
desc=["Liquidation z-score ≥ " + tostring(liqThreshold) + "σ — potential liquidity spiral (Brunnermeier & Pedersen 2009)"]
)
}
// 5.7 Zero line
hline(value=0, color="#ffffff30", width=1)
// 5.8 Reference threshold lines
if (showLiquidations) {
hline(value=liqThreshold, color="#ffffff20", width=1)
hline(value=-liqThreshold, color="#ffffff20", width=1)
}