Perfected FlowScript
FootPrint bar statistics (Fork)
FootPrint Bar Statistics V2 is indexed as 157_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
onchart
Axis
false
Size
17.8 KB
Lines
370
Native Signal Candidates
7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Buy
line 282:9
Trigger
(showExtremeShapes) && (isExtreme && delta > 0 && !isAbsorption)
Value
low - rng * 0.3
Deps
delta:timeseries, isAbsorption:timeseries, isExtreme:var, showExtremeShapes:input
Extreme Sell
line 293:9
Trigger
(showExtremeShapes) && (isExtreme && delta < 0 && !isAbsorption)
Value
high + rng * 0.3
Deps
delta:timeseries, isAbsorption:timeseries, isExtreme:var, showExtremeShapes:input
Absorption (Buy)
line 310:9
Trigger
(showAbsorption && isAbsorption) && (delta > 0)
Value
low - rng * 0.5
Deps
delta:timeseries, isAbsorption:timeseries, showAbsorption:input
Absorption (Sell)
line 320:9
Trigger
(showAbsorption && isAbsorption)
Value
high + rng * 0.5
Deps
isAbsorption:timeseries, showAbsorption:input
Long Liq
line 335:5
Trigger
(liqProxy && longLiqProxy)
Value
low - rng * 0.5
Deps
liqProxy:input, longLiqProxy:timeseries
Short Liq
line 345:5
Trigger
(liqProxy && shortLiqProxy)
Value
high + rng * 0.5
Deps
liqProxy:input, shortLiqProxy:timeseries
Unlabeled shape
line 361:5
Trigger
(showLabels && isImbalanced && !isAbsorption && !longLiqProxy && !shortLiqProxy)
Value
(high + low) / 2.0
Deps
isAbsorption:timeseries, isImbalanced:var, longLiqProxy:timeseries, shortLiqProxy:timeseries, showLabels:input
157_footprint_bar_statistics.flowscript
source path: kscripts/perfected/157_footprint_bar_statistics.flowscript · sha256:9bf6824201f7909acecdc54e260eb1239bc492ee7d281904ca16118ae5488725
//@version=2
// ============================================================================
// FootPrint Bar Statistics — Production-Grade Orderflow Microstructure Indicator
// Author: C (@Crypinfo) — Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, CORE, #volume, #delta, #footprint, #liquidation, #zscore
//
// Per-bar volume, delta (buys − sells), imbalance, absorption, and liquidation
// detection with z-score heat coloring, shape markers for extremes, and
// whale-positioning visual alerts. Transforms raw footprint data into a
// statistically normalized, visually actionable overlay.
//
// FORMULA FOUNDATION:
// 1. Footprint Delta (Δ): BuyVol − SellVol estimated via close-position proxy
// Δ = Volume × (2×closePos − 1) where closePos = (Close − Low) / (High − Low)
// per BVC (Easley, López de Prado & O'Hara 2012) probabilistic classification.
// 2. Delta Percentage: δ = Δ / Volume ∈ [−1, +1]
// per Cont, Kukanov & Stoikov (2014) OFI normalization.
// 3. Z-Score Heat Coloring: z_Δ = (Δ − μ_Δ) / σ_Δ over rolling window.
// per Zhao & Palomar (2018) mean-reversion threshold framework.
// 4. Absorption Detection: |δ| > threshold AND body/range < 0.3 (large delta
// with minimal price movement = passive liquidity absorbing aggressive flow).
// per Bouchaud, Farmer & Lillo (2009) liquidity memory framework.
// 5. Imbalance Ratio: I = |Δ| / Volume; I > 0.6 = strong directional bar.
// per Chordia, Roll & Subrahmanyam (2002) order imbalance predicts returns.
// 6. Liquidation Proxy: deep wick + extreme delta = forced position closure.
// per Brunnermeier & Pedersen (2009) liquidity spiral model.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI linearly predicts short-term
// price changes; Δ/Volume at bar level is the footprint equivalent.
// Key formula: ΔPrice ≈ λ × OFI; slope ∝ 1/depth.
// • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
// Order Book", arXiv:1907.06230. Multi-level imbalance improves out-of-sample
// predictive power. Footprint bars extend this to intra-bar price levels.
// • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
// a High-Frequency World", Rev. Financial Studies 25(5), 1547–1574. BVC
// probabilistic classification of volume direction; foundation for delta
// estimation when tick data is unavailable.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Rev. Financial Studies 22(6), 2201–2238. Liquidity spiral model explains
// liquidation cascades and forced position closure mechanics.
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", J. Financial Economics 65(1), 111–130. Extreme order
// imbalances predict return reversals; validates |δ| threshold logic.
// • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Handbook of Financial Markets. Liquidity memory explains
// absorption: large volume with minimal price movement = deep liquidity.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE Trans. Signal Processing. Z-score normalization: z = (X − μ) / σ.
// ============================================================================
define(title="FootPrint Bar Statistics V2", position="onchart", axis=false)
// -----------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// -----------------------------------------------------------------------------
// --- Delta & Imbalance ---
var deltaLookback = input(name="deltaLookback", type="number", defaultValue=20, label="Delta Z-Score Lookback", constraints={min: 5, max: 100, step: 1}, group="Delta & Imbalance")
var deltaStrong = input(name="deltaStrong", type="number", defaultValue=0.6, label="Strong Delta Threshold", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Delta & Imbalance")
var imbalanceThreshold = input(name="imbalanceThreshold", type="number", defaultValue=0.6, label="Imbalance Ratio Threshold", constraints={min: 0.1, max: 0.95, step: 0.05}, group="Delta & Imbalance")
var showDeltaBar = input(name="showDeltaBar", type="boolean", defaultValue=true, label="Show Delta Bar Chart", group="Delta & Imbalance")
var showDeltaZScore = input(name="showDeltaZScore", type="boolean", defaultValue=true, label="Show Delta Z-Score Line", group="Delta & Imbalance")
// --- Absorption ---
var showAbsorption = input(name="showAbsorption", type="boolean", defaultValue=true, label="Show Absorption Markers", group="Absorption")
var absBodyRatio = input(name="absBodyRatio", type="number", defaultValue=0.3, label="Absorption Body/Range Max", constraints={min: 0.05, max: 0.9, step: 0.05}, group="Absorption")
var absVolPercentile = input(name="absVolPercentile", type="number", defaultValue=80.0, label="Absorption Volume Percentile", constraints={min: 50.0, max: 99.0, step: 1.0}, group="Absorption")
// --- Liquidation ---
var liqProxy = input(name="liqProxy", type="boolean", defaultValue=true, label="Show Liquidation Proxy", group="Liquidation")
var liqWickRatio = input(name="liqWickRatio", type="number", defaultValue=0.6, label="Liquidation Wick Ratio", constraints={min: 0.3, max: 0.9, step: 0.05}, group="Liquidation")
var liqDeltaThreshold = input(name="liqDeltaThreshold", type="number", defaultValue=0.4, label="Liquidation Delta Threshold", constraints={min: 0.1, max: 0.9, step: 0.05}, group="Liquidation")
// --- Volume ---
var volSpikeMult = input(name="volSpikeMult", type="number", defaultValue=1.8, label="Volume Spike Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Volume")
var showVolumeLine = input(name="showVolumeLine", type="boolean", defaultValue=true, label="Show Volume Line", group="Volume")
// --- Display ---
var showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Labels", group="Display")
var showExtremeShapes = input(name="showExtremeShapes", type="boolean", defaultValue=true, label="Show Extreme Delta Shapes", group="Display")
var showZScoreHeat = input(name="showZScoreHeat", type="boolean", defaultValue=true, label="Z-Score Heat Coloring", group="Display")
// --- Colors ---
var colUp = input(name="colUp", type="color", defaultValue="#26a69a", label="Bullish Delta Color", group="Colors")
var colDn = input(name="colDn", type="color", defaultValue="#ef5350", label="Bearish Delta Color", group="Colors")
var colExtremeUp = input(name="colExtremeUp", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var colExtremeDn = input(name="colExtremeDn", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
var colAbsorption = input(name="colAbsorption", type="color", defaultValue="#ff9100", label="Absorption Color", group="Colors")
var colLiqLong = input(name="colLiqLong", type="color", defaultValue="#42a5f5", label="Long Liquidation Color", group="Colors")
var colLiqShort = input(name="colLiqShort", type="color", defaultValue="#ab47bc", label="Short Liquidation Color", group="Colors")
// -----------------------------------------------------------------------------
// Data Sources
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries open = price.open
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume
// NaN guard — prevent execution before data is loaded (Cont et al. 2014 data-integrity best practice)
if (isnan(close[0]) || isnan(volume[0])) {
return
}
// -----------------------------------------------------------------------------
// Footprint Delta Computation (BVC-based probabilistic classification)
// -----------------------------------------------------------------------------
// BVC: allocate bar volume proportionally based on close position within range.
// closePos = 0 → all sell; closePos = 1 → all buy; closePos = 0.5 → balanced.
// Formula: BuyVol = Volume × closePos; SellVol = Volume × (1 − closePos)
// Delta = BuyVol − SellVol = Volume × (2×closePos − 1)
timeseries rng = math.max(high - low, 0.0001)
timeseries closePos = (close - low) / rng
timeseries buyVol = volume * closePos
timeseries sellVol = volume * (1.0 - closePos)
timeseries delta = buyVol - sellVol
timeseries deltaPct = delta / math.max(volume, 1.0)
// -----------------------------------------------------------------------------
// Z-Score Heat Coloring (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// Rolling mean and standard deviation of delta for z-score normalization.
// z = (Δ − μ_Δ) / σ_Δ; values beyond ±2σ are statistically rare (~95% within).
timeseries deltaMean = sma(delta, deltaLookback)
timeseries deltaStd = stdev(delta, deltaLookback)
timeseries deltaZScore = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0.0
// Z-score magnitude for heat coloring: |z| > 2 = extreme, |z| > 1 = elevated.
var zAbs = math.abs(deltaZScore)
var isExtreme = zAbs > 2.0
var isElevated = zAbs > 1.0
// -----------------------------------------------------------------------------
// Volume Spike Detection
// -----------------------------------------------------------------------------
timeseries avgVol = sma(volume, 20)
timeseries volSpike = volume > avgVol * volSpikeMult
// Volume percentile rank for absorption detection (requires rolling window).
timeseries volRank = volume > percentile(volume, 100 - absVolPercentile, 100) ? 1 : 0
// -----------------------------------------------------------------------------
// Imbalance Detection (Chordia et al. 2002)
// -----------------------------------------------------------------------------
// Imbalance ratio: I = |Δ| / Volume. I > threshold = strongly directional bar.
var imbalanceRatio = math.abs(deltaPct)
var isImbalanced = imbalanceRatio > imbalanceThreshold
// -----------------------------------------------------------------------------
// Absorption Detection (Bouchaud, Farmer & Lillo 2009)
// -----------------------------------------------------------------------------
// Absorption = large directional volume with minimal price movement.
// Conditions: (1) volume in top percentile, (2) |delta| > strong threshold,
// (3) body/range < small ratio (price didn't move much despite heavy flow).
timeseries body = math.abs(close - open)
timeseries bodyRatio = body / rng
timeseries isAbsorption = volRank == 1 && math.abs(deltaPct) > deltaStrong && bodyRatio < absBodyRatio
// -----------------------------------------------------------------------------
// Liquidation Proxy (Brunnermeier & Pedersen 2009 liquidity spiral)
// -----------------------------------------------------------------------------
// Deep wick in opposite direction of delta = forced liquidation.
// Long liquidation: deep lower wick + negative delta (longs stopped out).
// Short liquidation: deep upper wick + positive delta (shorts stopped out).
timeseries wickUp = high - math.max(close, open)
timeseries wickDn = math.min(close, open) - low
timeseries longLiqProxy = wickDn > rng * liqWickRatio && deltaPct < -liqDeltaThreshold && volSpike
timeseries shortLiqProxy = wickUp > rng * liqWickRatio && deltaPct > liqDeltaThreshold && volSpike
// -----------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// -----------------------------------------------------------------------------
static sessionDeltaHigh = -999999.0
static sessionDeltaLow = 999999.0
static sessionExtremeUpCount = 0
static sessionExtremeDnCount = 0
static sessionAbsorptionCount = 0
static sessionLiqCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (delta > sessionDeltaHigh) {
sessionDeltaHigh = delta
}
if (delta < sessionDeltaLow) {
sessionDeltaLow = delta
}
if (isExtreme && delta > 0) {
sessionExtremeUpCount = sessionExtremeUpCount + 1
} else if (isExtreme && delta < 0) {
sessionExtremeDnCount = sessionExtremeDnCount + 1
}
if (isAbsorption) {
sessionAbsorptionCount = sessionAbsorptionCount + 1
}
if (longLiqProxy || shortLiqProxy) {
sessionLiqCount = sessionLiqCount + 1
}
}
// -----------------------------------------------------------------------------
// Color Logic: Z-Score Heat (dynamic coloring based on statistical extremity)
// -----------------------------------------------------------------------------
// Base colors modified by z-score intensity.
var barColor = colUp
if (delta < 0) {
barColor = colDn
}
// Heat override: extreme z-scores get brighter colors.
if (showZScoreHeat) {
if (isExtreme && delta > 0) {
barColor = colExtremeUp
} else if (isExtreme && delta < 0) {
barColor = colExtremeDn
} else if (isElevated && delta > 0) {
barColor = opacity(colExtremeUp, 70)
} else if (isElevated && delta < 0) {
barColor = opacity(colExtremeDn, 70)
}
}
// -----------------------------------------------------------------------------
// Plots — Delta Bar with Z-Score Heat
// -----------------------------------------------------------------------------
if (showDeltaBar) {
plotBar(
value=delta,
colors=[barColor],
width=1,
label=["Delta"],
desc=["Buy minus Sell volume (footprint delta). Z-score heat: brighter = more extreme."]
)
}
// Delta Z-Score line (off-chart secondary signal)
if (showDeltaZScore) {
plotLine(
value=deltaZScore,
width=2,
colors=[colUp, colDn, "#9e9e9e"],
colorIndex=deltaZScore > 1.0 ? 0 : (deltaZScore < -1.0 ? 1 : 2),
label=["Delta Z-Score"],
desc=["Rolling z-score of delta: (Δ − μ) / σ. |z| > 2 = statistically extreme."],
fill=true,
forceOnChart=false
)
}
// Volume total as overlay line (contextual reference)
if (showVolumeLine) {
plotLine(
value=volume,
colors=[opacity("#ffffff", 25)],
width=1,
label=["Volume"],
desc=["Total bar volume for delta context."],
forceOnChart=false
)
}
// -----------------------------------------------------------------------------
// Plots — Extreme Delta Shape Markers
// -----------------------------------------------------------------------------
if (showExtremeShapes) {
// Extreme positive delta marker (aggressive buying climax)
if (isExtreme && delta > 0 && !isAbsorption) {
plotShape(
value=low - rng * 0.3,
shape="triangleup",
colorIndex=colExtremeUp,
width=4,
label=["Extreme Buy"],
desc=["Extreme positive delta z-score (>+2σ): aggressive buying climax."]
)
}
// Extreme negative delta marker (aggressive selling climax)
if (isExtreme && delta < 0 && !isAbsorption) {
plotShape(
value=high + rng * 0.3,
shape="triangledown",
colorIndex=colExtremeDn,
width=4,
label=["Extreme Sell"],
desc=["Extreme negative delta z-score (<−2σ): aggressive selling climax."]
)
}
}
// -----------------------------------------------------------------------------
// Plots — Absorption Markers (Bouchaud et al. 2009)
// -----------------------------------------------------------------------------
if (showAbsorption && isAbsorption) {
if (delta > 0) {
// Passive buyer absorption: aggressive sellers hit hidden buyers.
plotShape(
value=low - rng * 0.5,
shape="circle",
colorIndex=colAbsorption,
width=4,
label=["Absorption (Buy)"],
desc=["Buyer absorption: heavy volume + positive delta + minimal body = hidden buyers absorbing supply."]
)
} else {
// Passive seller absorption: aggressive buyers hit hidden sellers.
plotShape(
value=high + rng * 0.5,
shape="circle",
colorIndex=colAbsorption,
width=4,
label=["Absorption (Sell)"],
desc=["Seller absorption: heavy volume + negative delta + minimal body = hidden sellers absorbing demand."]
)
}
}
// -----------------------------------------------------------------------------
// Plots — Liquidation Markers (Brunnermeier & Pedersen 2009)
// -----------------------------------------------------------------------------
if (liqProxy && longLiqProxy) {
plotShape(
value=low - rng * 0.5,
shape="x",
colorIndex=colLiqLong,
width=4,
label=["Long Liq"],
desc=["Long liquidation proxy: deep lower wick + negative delta + volume spike = forced long closure."]
)
}
if (liqProxy && shortLiqProxy) {
plotShape(
value=high + rng * 0.5,
shape="x",
colorIndex=colLiqShort,
width=4,
label=["Short Liq"],
desc=["Short liquidation proxy: deep upper wick + positive delta + volume spike = forced short closure."]
)
}
// -----------------------------------------------------------------------------
// Plots — Imbalance Marker (Chordia et al. 2002)
// -----------------------------------------------------------------------------
if (showLabels && isImbalanced && !isAbsorption && !longLiqProxy && !shortLiqProxy) {
var imbalLabel = delta > 0 ? "Buy Imbal" : "Sell Imbal"
var imbalColor = delta > 0 ? colUp : colDn
plotShape(
value=(high + low) / 2.0,
shape="diamond",
colorIndex=imbalColor,
width=2,
label=[imbalLabel],
desc=["Strong directional imbalance: |δ| > threshold. One-sided aggressive flow."]
)
}