MM Flow
FlowScripts

Perfected FlowScript

Footprint Statistic Bar

Footprint Statistic Bar V2 is indexed as 045_footprint_statistic_bar.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

15.7 KB

Lines

374

Native Signal Candidates

5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

5/5 guarded

Whale Buy Vol

line 326:9

Trigger

(showShapes) && (isWhaleVolBuy)

Value

l

Deps

isWhaleVolBuy:var, showShapes:input

Whale Sell Vol

line 336:9

Trigger

(showShapes) && (isWhaleVolSell)

Value

h

Deps

isWhaleVolSell:var, showShapes:input

Extreme Delta Buy

line 346:9

Trigger

(showShapes) && (isExtremeDeltaBuy)

Value

l

Deps

isExtremeDeltaBuy:var, showShapes:input

Extreme Delta Sell

line 356:9

Trigger

(showShapes) && (isExtremeDeltaSell)

Value

h

Deps

isExtremeDeltaSell:var, showShapes:input

V

line 372:5

Trigger

(showLabels)

Value

dispV

Deps

showLabels:input

045_footprint_statistic_bar.flowscript

source path: kscripts/perfected/045_footprint_statistic_bar.flowscript · sha256:c4188e25deab4522166da72555aa3fc84bdcdae71abd067beb2f79e32f741740

hash verified
//@version=2
// ============================================================================
// Footprint Statistic Bar V2 — Production-Quality Per-Bar Orderflow Analytics
// Author: D (@Denethh) | Perfected by: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #volume, #orderflow, #session, #delta, #footprint
//
// Multi-metric footprint display combining per-bar volume, volume delta,
// buy/sell split, liquidation tracking, and z-score heat coloring with
// session-level cumulative statistics and whale-detection shape markers.
//
// FORMULA FOUNDATION:
// 1. Volume Delta: ΔV = V_buy − V_sell per bar (Lee-Ready 1991 tick-rule
//    fallback when direct taker feed is unavailable).
// 2. Z-Score Standardization: z_t = (x_t − μ_t) / σ_t over rolling window W.
//    Per Zhao & Palomar (2018); thresholds at ±1σ, ±2σ for event triggers.
// 3. VPIN Framework: Easley, López de Prado & O'Hara (2012) — volume-
//    synchronized probability of informed trading; extreme |z| flags toxic flow.
// 4. Market Profile Session Analysis: Steidlmayer & Hawkins (2003) — session-
//    based volume accumulation with daily reset for contextual tracking.
// 5. Cont, Kukanov & Stoikov (2014): linear price-impact model validates
//    per-bar delta as primary driver of short-term price changes.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI linearly predicts price changes;
//    cumulative OFI (CVD) captures sustained pressure.
//    DOI: https://doi.org/10.1093/jjfinec/nbt003
//  • MarketDelta LLC (2007), "Footprint Chart Documentation". Bid volume (left),
//    ask volume (right) at each price level; Delta = Ask − Bid per bar.
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity"
//    (VPIN). J. Portfolio Management 38(2), 1–15.
//    VPIN = Σ|V_buy − V_sell| / ΣV_total over volume buckets; elevated VPIN
//    flags informed trading / adverse selection.
//    DOI: 10.3905/jpm.2012.38.2.106
//  • Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with Market
//    Profile". Session-based volume analysis; Value Area, POC, excess volume.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    z-score event triggers: z̄_t = (z_t − μ_z) / σ_z; entry at ±1σ or ±2σ.
// ============================================================================

define(
    title="Footprint Statistic Bar V2",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Statistics ---
var zLen = input(name="zLen", type="number", defaultValue=50, label="Z-Score Lookback (bars)", constraints={min: 10, max: 200, step: 5}, group="Statistics")
var sessionBars = input(name="sessionBars", type="number", defaultValue=96, label="Session Length (bars)", constraints={min: 10, max: 500, step: 1}, group="Statistics")
var useUsd = input(name="useUsd", type="boolean", defaultValue=false, label="Display in USD (off = coin)", group="Statistics")

// --- Thresholds ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Delta Threshold (σ)", constraints={min: 0.5, max: 3.0, step: 0.5}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Delta Threshold (σ)", constraints={min: -3.0, max: -0.5, step: 0.5}, group="Thresholds")
var whaleThresh = input(name="whaleThresh", type="number", defaultValue=2.0, label="Whale Volume Threshold (σ)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Thresholds")

// --- Display ---
var showVol = input(name="showVol", type="boolean", defaultValue=true, label="Show Volume Bars", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Volume Delta Line", group="Display")
var showDeltaBar = input(name="showDeltaBar", type="boolean", defaultValue=true, label="Show Delta Histogram", group="Display")
var showBuySell = input(name="showBuySell", type="boolean", defaultValue=false, label="Show Buy/Sell Lines", group="Display")
var showLiquidation = input(name="showLiquidation", type="boolean", defaultValue=false, label="Show Liquidation Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Whale Shapes", group="Display")
var showLabels = input(name="showLabels", type="boolean", defaultValue=false, label="Show Bar Labels", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Buy/Delta-Positive Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Sell/Delta-Negative Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Sell Color", group="Colors")
var whaleColor = input(name="whaleColor", type="color", defaultValue="#ffeb3b", label="Whale Volume Color", group="Colors")
var liqColor = input(name="liqColor", type="color", defaultValue="#9c27b0", label="Liquidation Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries c = pxTS.close
timeseries v = pxTS.volume

// Prefer direct taker feed when available; Lee-Ready fallback per Cont et al.
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries liq = source("liquidations", currentSymbol, currentExchange)

// NaN guard — halt until price data is loaded to prevent NaN propagation
// (Cont et al. 2014 data-integrity best practice)
if (isnan(c[0])) {
    return
}

// ------------------------------------------------------------------------------
// Tick-Rule Classification with Taker Feed Priority
// ------------------------------------------------------------------------------
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller.
// When taker.buy/sell is available, prefer direct feed for higher accuracy.
// Formula: buyVol = V × (upW / range) where upW = max(close − open, 0)
//          sellVol = V × (dnW / range) where dnW = max(open − close, 0)
// This is a bar-internal proportional estimate (BVC-like per Easley et al. 2012).

timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)

timeseries buyVol = isnum(taker.buy) ? taker.buy : (range_ > 0 ? v * (upW / range_) : v * 0.5)
timeseries selVol = isnum(taker.sell) ? taker.sell : (range_ > 0 ? v * (dnW / range_) : v * 0.5)
timeseries delta = buyVol - selVol

// Unit conversion: USD if requested, otherwise native coin
timeseries unit = useUsd ? c : 1.0
timeseries dispV = v * unit
timeseries dispD = delta * unit
timeseries dispBuy = buyVol * unit
timeseries dispSell = selVol * unit

// Liquidation data (optional; zero if unavailable)
timeseries liqLong = isnum(liq.long) ? liq.long : 0.0
timeseries liqShort = isnum(liq.short) ? liq.short : 0.0
timeseries liqTotal = liqLong + liqShort
timeseries dispLiq = liqTotal * unit

// ------------------------------------------------------------------------------
// Z-Score Color Grading (Zhao & Palomar 2018; VPIN Easley et al. 2012)
// ------------------------------------------------------------------------------
// Seven-tier sigma heatmap for delta: ±0.5σ, ±1σ, ±2σ bands with distinct colors.
// Volume z-score flags whale events (bars with statistically unusual size).
// All standard deviations guarded against zero to prevent division-by-zero crashes.

timeseries dMean = sma(dispD, zLen)
timeseries dStd = stdev(dispD, zLen)
timeseries dZ = dStd > 0 ? (dispD - dMean) / dStd : 0.0

timeseries vMean = sma(dispV, zLen)
timeseries vStd = stdev(dispV, zLen)
timeseries vZ = vStd > 0 ? (dispV - vMean) / vStd : 0.0

// Seven-tier delta color map (heatmap from extreme bid to extreme ask)
timeseries dCol = dZ > 2.0 ? extremeBidColor :
                    dZ > 1.0 ? bidColor :
                    dZ > 0.5 ? "#80cbc4" :
                    dZ > -0.5 ? neutralColor :
                    dZ > -1.0 ? "#ffab91" :
                    dZ > -2.0 ? askColor : extremeAskColor

// Volume color: heat-yellow for whale events, neutral for normal volume
timeseries vCol = vZ > 2.0 ? opacity(whaleColor, 90) :
                    vZ > 1.0 ? opacity(whaleColor, 70) :
                    vZ > 0.5 ? opacity(whaleColor, 50) :
                    vZ > -0.5 ? neutralColor :
                    vZ > -1.0 ? opacity(whaleColor, 50) :
                    vZ > -2.0 ? opacity(whaleColor, 70) : opacity(whaleColor, 90)

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes:
//   Bullish:   dZ ≥ bullThresh
//   Neutral:   bearThresh < dZ < bullThresh
//   Bearish:   dZ ≤ bearThresh
// Extreme regimes flag potential whale / informed flow events.

var regime = 0         // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

if (dZ >= bullThresh) {
    regime = 1
} else if (dZ <= bearThresh) {
    regime = -1
}

if (dZ >= whaleThresh) {
    extremeRegime = 1
} else if (dZ <= -whaleThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for session tracking, counters, and extreme-event tally.
// Tracks regime transitions, session volume/delta extremes, and whale counts.
// Session resets after sessionBars to maintain recency (Steidlmayer 2003).

static sessVol = 0.0
static sessDelta = 0.0
static sessBuy = 0.0
static sessSell = 0.0
static sessLiq = 0.0
static sessCount = 0
static lastBarIndex = 0
static whaleCount = 0
static extremeBidCount = 0
static extremeAskCount = 0
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex
    sessCount = sessCount + 1

    sessVol = sessVol + dispV
    sessDelta = sessDelta + dispD
    sessBuy = sessBuy + dispBuy
    sessSell = sessSell + dispSell
    sessLiq = sessLiq + dispLiq

    if (dispD > sessionHighDelta) {
        sessionHighDelta = dispD
    }
    if (dispD < sessionLowDelta) {
        sessionLowDelta = dispD
    }

    if (vZ >= whaleThresh || vZ <= -whaleThresh) {
        whaleCount = whaleCount + 1
    }
    if (dZ >= bullThresh) {
        extremeBidCount = extremeBidCount + 1
    } else if (dZ <= bearThresh) {
        extremeAskCount = extremeAskCount + 1
    }

    if (sessCount >= sessionBars) {
        sessVol = 0.0
        sessDelta = 0.0
        sessBuy = 0.0
        sessSell = 0.0
        sessLiq = 0.0
        sessCount = 0
        sessionHighDelta = -999999.0
        sessionLowDelta = 999999.0
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Bar, Line, Histogram, Shape, Fill)
// ------------------------------------------------------------------------------

// 1. Volume bars with z-score heat coloring (volume anomaly detection)
//    Bars are colored by the volume z-score to highlight whale events.
if (showVol) {
    plotBar(
        value=dispV,
        colors=[vCol],
        width=1,
        label=["Footprint Volume"],
        desc=["Per-bar volume with σ-tier heat coloring; whale events highlighted in yellow tones"]
    )
}

// 2. Volume Delta line with regime-coded fill area
//    Fill color changes based on delta regime: bull / bear / neutral.
//    The fill makes dominance visually obvious at a glance.
if (showDelta) {
    plotLine(
        value=dispD,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Volume Delta"],
        desc=["Buy volume − sell volume per bar (USD or coin); fill coded by regime (bull/bear/neutral)"],
        fill=true
    )
}

// 3. Delta histogram (plotBar) — sign-based colouring for delta
//    Positive delta = bidColor, negative delta = askColor.
//    Provides a pulse-style read of per-bar orderflow imbalance.
if (showDeltaBar) {
    plotBar(
        value=dispD,
        colors=[bidColor, askColor],
        width=1,
        label=["Delta Histogram"],
        desc=["Volume delta as bars; positive = buy-heavy, negative = sell-heavy"]
    )
}

// 4. Buy / Sell volume lines (optional, for granular buy/sell decomposition)
if (showBuySell) {
    plotLine(
        value=dispBuy,
        width=1,
        colors=[opacity(bidColor, 60)],
        label=["Buy Volume"],
        desc=["Aggressive buy volume per bar (taker feed or Lee-Ready estimate)"]
    )
    plotLine(
        value=dispSell,
        width=1,
        colors=[opacity(askColor, 60)],
        label=["Sell Volume"],
        desc=["Aggressive sell volume per bar (taker feed or Lee-Ready estimate)"]
    )
}

// 5. Liquidation line (optional, when data is available)
if (showLiquidation && liqTotal > 0) {
    plotLine(
        value=dispLiq,
        width=1,
        colors=[liqColor],
        label=["Liquidations"],
        desc=["Total liquidations (long + short) per bar; purple when available"]
    )
}

// 6. Whale detection shapes — extreme volume events (VPIN informed-flow flag)
//    Circles mark whale volume; triangles mark extreme delta.
if (showShapes) {
    var isWhaleVolBuy = vZ >= whaleThresh && buyVol > selVol
    var isWhaleVolSell = vZ >= whaleThresh && selVol > buyVol
    var isExtremeDeltaBuy = dZ >= whaleThresh
    var isExtremeDeltaSell = dZ <= -whaleThresh

    if (isWhaleVolBuy) {
        plotShape(
            value=l,
            shape="circle",
            colorIndex=whaleColor,
            width=3,
            label=["Whale Buy Vol"],
            desc=["Extreme volume event: buy-side volume z-score exceeds threshold (≥ +2σ)"]
        )
    }
    if (isWhaleVolSell) {
        plotShape(
            value=h,
            shape="circle",
            colorIndex=whaleColor,
            width=3,
            label=["Whale Sell Vol"],
            desc=["Extreme volume event: sell-side volume z-score exceeds threshold (≥ +2σ)"]
        )
    }
    if (isExtremeDeltaBuy) {
        plotShape(
            value=l,
            shape="triangleup",
            colorIndex=extremeBidColor,
            width=4,
            label=["Extreme Delta Buy"],
            desc=["Extreme positive delta: aggressive buy imbalance exceeds +2σ"]
        )
    }
    if (isExtremeDeltaSell) {
        plotShape(
            value=h,
            shape="triangledown",
            colorIndex=extremeAskColor,
            width=4,
            label=["Extreme Delta Sell"],
            desc=["Extreme negative delta: aggressive sell imbalance exceeds −2σ"]
        )
    }
}

// 7. Reference zero line for delta context
hline(value=0, color="#ffffff30", width=1)

// 8. Optional bar labels (volume value)
if (showLabels) {
    plotPriceLabel(price=dispV, text="V", type="label", color="#ffffff", size=9)
}