Perfected FlowScript
footprint scalping
Footprint Scalping V2 is indexed as 236_footprint_scalping.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
16.6 KB
Lines
386
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Buy
line 322:9
Trigger
(showShapes) && (extremeBuy)
Value
smoothDelta
Deps
extremeBuy:var, showShapes:input
Extreme Sell
line 332:9
Trigger
(showShapes) && (extremeSell)
Value
smoothDelta
Deps
extremeSell:var, showShapes:input
Buy Cross
line 342:9
Trigger
(showShapes) && (crossUp)
Value
smoothDelta
Deps
crossUp:var, showShapes:input
Sell Cross
line 352:9
Trigger
(showShapes) && (crossDn)
Value
smoothDelta
Deps
crossDn:var, showShapes:input
Buy Absorption
line 366:9
Trigger
(showAbsorption) && (absorptionType == 1)
Value
smoothDelta
Deps
absorptionType:var, showAbsorption:input
Sell Absorption
line 376:9
Trigger
(showAbsorption) && (absorptionType == -1)
Value
smoothDelta
Deps
absorptionType:var, showAbsorption:input
236_footprint_scalping.flowscript
source path: kscripts/perfected/236_footprint_scalping.flowscript · sha256:39b8ca300202213156296019eac2d807a925ac454d50296033349c30de5a654e
//@version=2
// ============================================================================
// Footprint Scalping V2 — Microstructure Scalping Signals with Absorption
// Author: A (@Akshay S Patil) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #scalp, #microstructure, #delta, #absorption, #footprint
//
// Production-quality footprint-chart inspired scalping indicator with
// per-bar volume delta analysis, absorption detection, z-score normalization,
// regime detection, and session-level static tracking.
//
// FORMULA FOUNDATION:
// 1. Per-Bar Delta: Δ = BuyVolume − SellVolume (aggressive buy minus sell)
// per Lee & Ready (1991) tick classification.
// 2. Imbalance Ratio: I = Δ / (Buy + Sell) ∈ [−1, +1]
// per Cont, Kukanov & Stoikov (2014) OFI framework.
// 3. Absorption Detection: |Δ| large AND |price change| small → passive
// absorption (Bouchaud, Farmer & Lillo 2009; Tóth et al. 2011).
// 4. Z-Score Normalization: Z_t = (Δ_t − μ_t) / σ_t for regime-relative
// scalping signals (Zhao & Palomar 2018).
// 5. Regime: Buy aggression (Δ > 0), Sell aggression (Δ < 0), Neutral,
// Extreme (|Z| > 2) per standard normal thresholds.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. Footprint charts visualize multi-
// level OFI at intra-bar level; price impact ∝ OFI / depth.
// DOI: 10.1093/jjfinec/nbt003
// • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
// Order Book", arXiv:1907.06230. Multi-level imbalance improves short-horizon
// price prediction; footprint charts make this visible intra-bar.
// • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Handbook of Financial Markets, 57–160. Liquidity
// memory time: when aggressive volume fails to move price, it reflects
// absorption / passive liquidity replenishment.
// • Tóth et al. (2011), "Anomalous Price Impact and the Critical Nature of
// Liquidity in Financial Markets", Physical Review X 1(2), 021006. Square-
// root impact law: impact ∝ √volume; sublinear absorption signals deep
// liquidity or impending exhaustion.
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", JFE 65(1), 111–130. Extreme |imbalance| predicts return
// reversals; absorption at extremes often precedes reversals.
// DOI: 10.1016/S0304-405X(02)00136-8
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance 46(2), 733–746. Tick-test classification: buy if
// close > open, else sell. 85–93% accuracy.
// DOI: 10.1111/j.1540-6261.1991.tb02683.x
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE TSP. Z-score entry thresholds at ±2σ for statistically rare events.
// ============================================================================
define(
title="Footprint Scalping V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Delta Configuration ---
var deltaLen = input(name="deltaLen", type="number", defaultValue=14.0, label="Delta Smoothing Length", constraints={min: 1.0, max: 50.0, step: 1.0}, group="Delta")
var imbalanceThreshold = input(name="imbalanceThreshold", type="number", defaultValue=0.6, label="Imbalance Threshold", constraints={min: 0.1, max: 0.95, step: 0.05}, group="Delta")
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Plot Raw Delta", group="Delta")
// --- Absorption Detection ---
var absorptionThreshold = input(name="absorptionThreshold", type="number", defaultValue=2.0, label="Absorption Z-Threshold", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Absorption")
var minDeltaPct = input(name="minDeltaPct", type="number", defaultValue=0.3, label="Min Delta % of Volume", constraints={min: 0.05, max: 0.95, step: 0.05}, group="Absorption")
var showAbsorption = input(name="showAbsorption", type="boolean", defaultValue=true, label="Show Absorption Shapes", group="Absorption")
// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=50.0, label="Z-Score Window (bars)", constraints={min: 20.0, max: 200.0, step: 5.0}, group="Z-Score")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Z-Score")
// --- Thresholds & Regime ---
var extremeZ = input(name="extremeZ", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Thresholds")
// --- Display ---
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Smoothed Delta", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Delta Histogram", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var plotStyle = input(name="plotStyle", type="select", defaultValue="Histogram", label="Plot Style", options=["Histogram", "Line"], group="Display")
// --- Colors ---
var buyColor = input(name="buyColor", type="color", defaultValue="#26a69a", label="Buy Aggression Color", group="Colors")
var sellColor = input(name="sellColor", type="color", defaultValue="#ef5350", label="Sell Aggression Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBuyColor = input(name="extremeBuyColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeSellColor = input(name="extremeSellColor", type="color", defaultValue="#ff1744", label="Extreme Sell Color", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#42a5f5", label="Z-Score Color", group="Colors")
var absorptionColor = input(name="absorptionColor", type="color", defaultValue="#d500f9", label="Absorption Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries open = ohlcvTS.open
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)
// NaN guard — prevent execution before data is loaded
if (isnan(close[0]) || !isnum(buySell.buy_volume)) {
return
}
// ------------------------------------------------------------------------------
// Buy/Sell Volume Classification (Lee & Ready 1991 fallback)
// ------------------------------------------------------------------------------
timeseries buyV = isnum(buySell.buy_volume) ? buySell.buy_volume : (close > open ? ohlcvTS.volume : 0)
timeseries sellV = isnum(buySell.sell_volume) ? buySell.sell_volume : (close <= open ? ohlcvTS.volume : 0)
timeseries rawDelta = buyV - sellV
timeseries totalVol = buyV + sellV
// Volume availability check
var volAvailable = isnum(buyV) && isnum(sellV) && totalVol > 0
// ------------------------------------------------------------------------------
// Delta Analysis
// ------------------------------------------------------------------------------
// Imbalance ratio: |delta| / total volume ∈ [0, 1]
// Bar range as context for absorption detection
timeseries barRange = high - low
var rangeSafe = barRange > 0 ? barRange : 1
timeseries imbRatio = volAvailable && totalVol > 0 ? rawDelta / totalVol : 0.0
timeseries absImbRatio = math.abs(imbRatio)
// Smoothed delta (in volume units)
timeseries smoothDelta = sma(rawDelta, deltaLen)
// Smoothed imbalance ratio
timeseries smoothImb = sma(imbRatio, deltaLen)
// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Z_t = (Δ_t − μ_t) / σ_t for statistically significant scalping signals.
timeseries deltaMean = sma(smoothDelta, zWindow)
timeseries deltaStd = stdev(smoothDelta, zWindow)
timeseries deltaZ = (deltaStd > 0) ? (smoothDelta - deltaMean) / deltaStd : 0.0
// ------------------------------------------------------------------------------
// Absorption Detection (Bouchaud et al. 2009; Tóth et al. 2011)
// ------------------------------------------------------------------------------
// Absorption = large delta relative to volume AND minimal price movement.
// Large aggressive flow fails to move price → passive side is absorbing.
// Detection: |deltaZ| > absorptionThreshold AND |imbRatio| > minDeltaPct
// AND price move within bar is small relative to range (or delta is large
// relative to range).
timeseries priceMove = math.abs(close - open)
timeseries priceMovePct = rangeSafe > 0 ? priceMove / rangeSafe : 0.0
var isAbsorption = volAvailable && math.abs(deltaZ) >= absorptionThreshold && absImbRatio >= minDeltaPct && priceMovePct <= 0.3
// Absorption type: 1 = buy absorption (sellers absorbing buys), -1 = sell absorption
var absorptionType = 0
if (isAbsorption) {
if (rawDelta > 0) {
absorptionType = 1 // buy absorption: buyers aggressive but price didn't move up
} else if (rawDelta < 0) {
absorptionType = -1 // sell absorption: sellers aggressive but price didn't move down
}
}
// ------------------------------------------------------------------------------
// Regime Detection (4-tier aggression classification)
// ------------------------------------------------------------------------------
// Buy aggression: smoothDelta > 0
// Sell aggression: smoothDelta < 0
// Extreme: |deltaZ| ≥ extremeZ
var regime = 0 // 0 = neutral, 1 = buy, -1 = sell
var extremeRegime = 0 // 0 = normal, 1 = extreme buy, -1 = extreme sell
if (smoothDelta > 0) {
regime = 1
} else if (smoothDelta < 0) {
regime = -1
}
if (deltaZ >= extremeZ) {
extremeRegime = 1
} else if (deltaZ <= -extremeZ) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks delta extremes, regime transitions, absorption events, and extreme
// aggression counts for context-aware alerting.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDelta = -999999999.0
static sessionLowDelta = 999999999.0
static extremeBuyCount = 0
static extremeSellCount = 0
static absorptionBuyCount = 0
static absorptionSellCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (smoothDelta > sessionHighDelta) {
sessionHighDelta = smoothDelta
}
if (smoothDelta < sessionLowDelta) {
sessionLowDelta = smoothDelta
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBuyCount = extremeBuyCount + 1
} else if (extremeRegime == -1) {
extremeSellCount = extremeSellCount + 1
}
if (absorptionType == 1) {
absorptionBuyCount = absorptionBuyCount + 1
} else if (absorptionType == -1) {
absorptionSellCount = absorptionSellCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=extremeZ, color=opacity(extremeBuyColor, 20), width=1)
hline(value=-extremeZ, color=opacity(extremeSellColor, 20), width=1)
}
// Raw delta line (optional, for diagnostics)
if (showRaw) {
plotLine(
value=rawDelta,
width=1,
colors=[opacity(neutralColor, 40)],
label=["Raw Delta"],
desc=["Unsmoothed buy-sell delta per bar"]
)
}
// Smoothed delta with regime-coded fill area
if (showDelta) {
var deltaColorIdx = extremeRegime == 1 ? 0 : (extremeRegime == -1 ? 1 : (regime == 1 ? 2 : 3))
if (plotStyle == "Histogram") {
plotBar(
value=smoothDelta,
colors=[extremeBuyColor, extremeSellColor, buyColor, sellColor],
colorIndex=deltaColorIdx,
width=2,
label=["Smoothed Delta"],
desc=["Per-bar buy-sell delta, smoothed for scalping (extreme buy/extreme sell/buy/sell)"]
)
} else {
plotLine(
value=smoothDelta,
width=2,
colors=[extremeBuyColor, extremeSellColor, buyColor, sellColor],
colorIndex=deltaColorIdx,
label=["Smoothed Delta"],
desc=["Per-bar buy-sell delta, smoothed (extreme buy/extreme sell/buy/sell)"],
fill=true
)
}
}
// Delta histogram (plotBar) — always shown as secondary if main is line
if (showHistogram && plotStyle == "Line") {
var histColors = [extremeBuyColor, extremeSellColor, buyColor, sellColor]
var histIdx = extremeRegime == 1 ? 0 : (extremeRegime == -1 ? 1 : (regime == 1 ? 2 : 3))
plotBar(
value=smoothDelta,
colors=histColors,
colorIndex=histIdx,
width=1,
label=["Delta Histogram"],
desc=["Volume delta histogram (extreme buy/extreme sell/buy/sell)"]
)
}
// Z-Score line (regime-relative aggression)
if (showZScore && useZScore) {
plotLine(
value=deltaZ,
width=2,
colors=[zScoreColor],
label=["Delta Z-Score"],
desc=["Z-score normalized delta: (Delta − μ) / σ. Values > 2 or < −2 are statistically extreme."]
)
}
// Extreme divergence shapes — statistically rare aggression events
if (showShapes) {
var extremeBuy = deltaZ >= extremeZ && !isnan(deltaZ[1]) && deltaZ[1] < extremeZ
var extremeSell = deltaZ <= -extremeZ && !isnan(deltaZ[1]) && deltaZ[1] > -extremeZ
var crossUp = smoothDelta > 0 && !isnan(smoothDelta[1]) && smoothDelta[1] <= 0
var crossDn = smoothDelta < 0 && !isnan(smoothDelta[1]) && smoothDelta[1] >= 0
if (extremeBuy) {
plotShape(
value=smoothDelta,
shape="triangleup",
color=extremeBuyColor,
width=3,
label=["Extreme Buy"],
desc=["Extreme buy aggression detected — statistically rare positive delta event"]
)
}
if (extremeSell) {
plotShape(
value=smoothDelta,
shape="triangledown",
color=extremeSellColor,
width=3,
label=["Extreme Sell"],
desc=["Extreme sell aggression detected — statistically rare negative delta event"]
)
}
if (crossUp) {
plotShape(
value=smoothDelta,
shape="circle",
color=buyColor,
width=2,
label=["Buy Cross"],
desc=["Smoothed delta crossed above zero — buy aggression emerging"]
)
}
if (crossDn) {
plotShape(
value=smoothDelta,
shape="circle",
color=sellColor,
width=2,
label=["Sell Cross"],
desc=["Smoothed delta crossed below zero — sell aggression emerging"]
)
}
}
// Absorption shapes (Bouchaud et al. 2009; Tóth et al. 2011)
if (showAbsorption) {
if (absorptionType == 1) {
plotShape(
value=smoothDelta,
shape="cross",
color=absorptionColor,
width=3,
label=["Buy Absorption"],
desc=["Buy absorption detected — aggressive buy volume with minimal price movement; potential exhaustion"]
)
}
if (absorptionType == -1) {
plotShape(
value=smoothDelta,
shape="cross",
color=absorptionColor,
width=3,
label=["Sell Absorption"],
desc=["Sell absorption detected — aggressive sell volume with minimal price movement; potential exhaustion"]
)
}
}