MM Flow
FlowScripts

Perfected FlowScript

FootPrint bar statistics (ali almanzly)

FootPrint Bar Statistics — Perfected Edition is indexed as 279_footprint_bar_statistics_ali_almanzly.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

15.2 KB

Lines

474

Native Signal Candidates

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

6/6 guarded

Absorption

line 370:9

Trigger

(showAbsorption) && (isAbsorption)

Value

delta

Deps

isAbsorption:var, showAbsorption:input

Exhaustion

line 380:9

Trigger

(showAbsorption) && (isExhaustion)

Value

delta

Deps

isExhaustion:var, showAbsorption:input

Whale Buy

line 394:9

Trigger

(showWhale) && (whaleBuy)

Value

delta

Deps

showWhale:input, whaleBuy:var

Whale Sell

line 404:9

Trigger

(showWhale) && (whaleSell)

Value

delta

Deps

showWhale:input, whaleSell:var

Buy Imbalance

line 417:5

Trigger

(extremeBuyImb)

Value

delta

Deps

extremeBuyImb:var

Sell Imbalance

line 427:5

Trigger

(extremeSellImb)

Value

delta

Deps

extremeSellImb:var

279_footprint_bar_statistics_ali_almanzly.flowscript

source path: kscripts/perfected/279_footprint_bar_statistics_ali_almanzly.flowscript · sha256:bb3c33f04c67cab0b947b334c861f410392feb4a635a691cd90ea58663ff59aa

hash verified
//@version=2

// ============================================================================
// FootPrint Bar Statistics (Ali Almanzly) — Perfected Edition
// Author: A (@ali abdulkarem) | Perfected by kScript_Perfection_Engineer
// Index: 279
// Tags: ADVANCED, CORE, #volume, #delta, #footprint, #liquidation, #orderflow
//
// Production-quality footprint bar statistics implementing per-bar volume,
// delta (buys − sells), absorption/exhaustion detection, imbalance z-score
// heat coloring, and whale-position marking with comprehensive state tracking.
// Inspired by MarketDelta footprint charts and Ali Almanzly's original
// color-theme concept with yellow high-volume boxes and dark-blue negative
// delta highlighting.
//
// Academic foundation:
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//     foundational algorithm for trade classification. ~85–93% accuracy.
//     DOI: 10.1111/j.1540-6261.1991.tb02683.x
//
//  2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events": linear relationship between OFI and price changes.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
//     Trading Activity" (BVC): probabilistic volume classification for
//     high-frequency environments. SSRN: 1989555
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns": extreme imbalances predict return reversals.
//     DOI: 10.1016/S0304-405X(02)00136-8
//
//  5. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand": liquidity memory and absorption/exhaustion
//     theory. arXiv: 0809.0822
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading": linear
//     price impact model. λ = price impact per unit of order flow.
//     DOI: 10.2307/1913210
//
//  7. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
//     Market Profile": auction market theory, volume profile, POC, value
//     area concepts underlying footprint chart interpretation.
// ============================================================================

define(
    title="FootPrint Bar Statistics — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Computation ---
var deltaLookback = input(
    name="deltaLookback",
    type="number",
    defaultValue=20,
    label="Delta Z-Score Lookback",
    constraints={min: 10, max: 100, step: 5},
    group="Computation"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Average Lookback",
    constraints={min: 10, max: 100, step: 5},
    group="Computation"
)
var imbalanceThreshold = input(
    name="imbalanceThreshold",
    type="number",
    defaultValue=2.0,
    label="Imbalance Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.5},
    group="Computation"
)
var absorptionThreshold = input(
    name="absorptionThreshold",
    type="number",
    defaultValue=1.5,
    label="Absorption Volume Threshold (x avg)",
    constraints={min: 1.0, max: 5.0, step: 0.5},
    group="Computation"
)
var whaleThresh = input(
    name="whaleThresh",
    type="number",
    defaultValue=3.0,
    label="Whale Volume Threshold (x avg)",
    constraints={min: 1.5, max: 10.0, step: 0.5},
    group="Computation"
)

// --- Display ---
var showVolume = input(
    name="showVolume",
    type="boolean",
    defaultValue=true,
    label="Show Volume Bars",
    group="Display"
)
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Delta Line",
    group="Display"
)
var showCumDelta = input(
    name="showCumDelta",
    type="boolean",
    defaultValue=true,
    label="Show Cumulative Delta",
    group="Display"
)
var showImbalance = input(
    name="showImbalance",
    type="boolean",
    defaultValue=true,
    label="Show Imbalance Z-Score",
    group="Display"
)
var showAbsorption = input(
    name="showAbsorption",
    type="boolean",
    defaultValue=true,
    label="Show Absorption Shapes",
    group="Display"
)
var showWhale = input(
    name="showWhale",
    type="boolean",
    defaultValue=true,
    label="Show Whale Markers",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Statistics Table",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutColor = input(
    name="neutColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var whaleColor = input(
    name="whaleColor",
    type="color",
    defaultValue="#ffca28",
    label="Whale Color (Yellow)",
    group="Colors"
)
var absorpColor = input(
    name="absorpColor",
    type="color",
    defaultValue="#7c4dff",
    label="Absorption Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume

// Attempt to fetch taker volume for direct delta
timeseries takerVol = source("taker_volume", currentSymbol, currentExchange)

if (isnan(close[0]) || isnan(volume[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. VOLUME DELTA COMPUTATION
// -----------------------------------------------------------------------------
// Approximate buy/sell classification via bar strength (BVC-inspired)
// When taker volume is available, prefer direct feed
timeseries range = high - low
timeseries barPos = (range > 0) ? (close - low) / range : 0.5

// Buy volume estimate: volume × bar position (close near high = more buys)
// Sell volume estimate: volume × (1 - bar position)
timeseries buyVol = isnum(takerVol.buy) ? takerVol.buy : volume * barPos
timeseries sellVol = isnum(takerVol.sell) ? takerVol.sell : volume * (1 - barPos)

// Per-bar delta = buy - sell
timeseries delta = buyVol - sellVol

// Rolling delta z-score for statistical context
timeseries deltaMean = sma(delta, deltaLookback)
timeseries deltaStd = stddev(delta, deltaLookback)
timeseries deltaZ = (deltaStd > 0) ? (delta - deltaMean) / deltaStd : 0

// -----------------------------------------------------------------------------
// 4. CUMULATIVE DELTA (CVD) via static state
// -----------------------------------------------------------------------------
static cumDelta = 0.0
if (!isnan(delta[0])) {
    cumDelta = cumDelta + delta[0]
}

// Rolling CVD z-score for trend context
timeseries cvdMean = sma(cumDelta, deltaLookback)
timeseries cvdStd = stddev(cumDelta, deltaLookback)
timeseries cvdZ = (cvdStd > 0) ? (cumDelta - cvdMean) / cvdStd : 0

// -----------------------------------------------------------------------------
// 5. IMBALANCE DETECTION
// -----------------------------------------------------------------------------
// Per-bar imbalance ratio: (buy - sell) / total volume
timeseries imbalance = (volume > 0) ? delta / volume : 0

// Rolling imbalance z-score
timeseries imbMean = sma(imbalance, deltaLookback)
timeseries imbStd = stddev(imbalance, deltaLookback)
timeseries imbZ = (imbStd > 0) ? (imbalance - imbMean) / imbStd : 0

// Imbalance regime flags
var extremeBuyImb = imbZ > imbalanceThreshold
var extremeSellImb = imbZ < -imbalanceThreshold
var normalImb = !extremeBuyImb && !extremeSellImb

// -----------------------------------------------------------------------------
// 6. ABSORPTION & EXHAUSTION DETECTION
// -----------------------------------------------------------------------------
// Per Bouchaud-Farmer-Lillo (2009): when large volume fails to move price
// (absorption) or when volume spikes with fading follow-through (exhaustion)

timeseries avgVol = sma(volume, volLookback)
timeseries volRatio = (avgVol > 0) ? volume / avgVol : 1.0

// Price change magnitude
timeseries barChange = math.abs(close - close[1])
timeseries avgChange = sma(barChange, volLookback)

// Absorption: high volume, small price change (liquidity replenishment)
var isAbsorption = volRatio > absorptionThreshold && barChange < avgChange

// Exhaustion: high volume, large price change but delta disagrees with direction
// (e.g., price up but negative delta = selling into strength)
var isExhaustion = volRatio > absorptionThreshold && barChange > avgChange * 2 &&
                   ((close > close[1] && delta < 0) || (close < close[1] && delta > 0))

// -----------------------------------------------------------------------------
// 7. WHALE DETECTION
// -----------------------------------------------------------------------------
// High volume bars with significant delta
var isWhaleVol = volume > avgVol * whaleThresh
var whaleBuy = isWhaleVol && delta > 0
var whaleSell = isWhaleVol && delta < 0

// -----------------------------------------------------------------------------
// 8. STATIC TRACKING
// -----------------------------------------------------------------------------
static totalVolume = 0.0
static totalBuyVol = 0.0
static totalSellVol = 0.0
static maxDelta = 0.0
static minDelta = 0.0
static maxCumDelta = 0.0
static minCumDelta = 0.0
static whaleCount = 0
static absorpCount = 0

if (!isnan(volume[0])) {
    totalVolume = totalVolume + volume[0]
    totalBuyVol = totalBuyVol + buyVol[0]
    totalSellVol = totalSellVol + sellVol[0]
}
if (!isnan(delta[0])) {
    if (delta[0] > maxDelta) { maxDelta = delta[0] }
    if (delta[0] < minDelta) { minDelta = delta[0] }
}
if (cumDelta > maxCumDelta) { maxCumDelta = cumDelta }
if (cumDelta < minCumDelta) { minCumDelta = cumDelta }
if (isWhaleVol) { whaleCount = whaleCount + 1 }
if (isAbsorption) { absorpCount = absorpCount + 1 }

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Volume Bars (color-coded by close direction) ---
if (showVolume) {
    var volBull = close >= close[1]
    plotBar(
        value=volume,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=volBull ? 0 : 1,
        width=1,
        label=["Volume"],
        desc=["Total bar volume; color-coded by close direction"]
    )
}

// --- Delta Line (z-score heat coloring) ---
if (showDelta) {
    // Color by delta z-score: hot green for extreme buy, hot red for extreme sell
    var deltaColorIdx = deltaZ > 2 ? 0 : (deltaZ < -2 ? 1 : 2)
    plotLine(
        value=delta,
        width=2,
        colors=[bullColor, bearColor, neutColor],
        colorIndex=deltaColorIdx,
        label=["Delta"],
        desc=["Net buy-sell delta per bar (z-score colored)"]
    )
}

// --- Cumulative Delta Line ---
if (showCumDelta) {
    var cvdColor = cumDelta > 0 ? bullColor : bearColor
    plotLine(
        value=cumDelta,
        width=2,
        colors=[cvdColor],
        label=["CVD"],
        desc=["Cumulative volume delta since first bar"]
    )
}

// --- Imbalance Z-Score Line ---
if (showImbalance) {
    var imbColorIdx = imbZ > imbalanceThreshold ? 0 : (imbZ < -imbalanceThreshold ? 1 : 2)
    plotLine(
        value=imbZ,
        width=2,
        colors=[bullColor, bearColor, neutColor],
        colorIndex=imbColorIdx,
        label=["Imb Z-Score"],
        desc=["Imbalance z-score: rolling statistical significance of buy/sell skew"]
    )
    hline(value=0, color="#ffffff40", width=1)
    hline(value=imbalanceThreshold, color=transparency(bullColor, 50), width=1)
    hline(value=-imbalanceThreshold, color=transparency(bearColor, 50), width=1)
}

// --- Absorption Shapes ---
if (showAbsorption) {
    if (isAbsorption) {
        plotShape(
            value=delta,
            shape="square",
            colorIndex=absorpColor,
            width=2,
            label=["Absorption"],
            desc=["High volume with small price change: passive liquidity absorbing aggressive flow"]
        )
    }
    if (isExhaustion) {
        plotShape(
            value=delta,
            shape="diamond",
            colorIndex=absorpColor,
            width=2,
            label=["Exhaustion"],
            desc=["Volume spike with delta disagreeing from price direction: potential reversal"]
        )
    }
}

// --- Whale Shapes ---
if (showWhale) {
    if (whaleBuy) {
        plotShape(
            value=delta,
            shape="circle",
            colorIndex=whaleColor,
            width=4,
            label=["Whale Buy"],
            desc=["High volume positive delta: large aggressive buying detected"]
        )
    }
    if (whaleSell) {
        plotShape(
            value=delta,
            shape="circle",
            colorIndex=absorpColor,
            width=4,
            label=["Whale Sell"],
            desc=["High volume negative delta: large aggressive selling detected"]
        )
    }
}

// --- Extreme Imbalance Shapes (triangle up/down) ---
if (extremeBuyImb) {
    plotShape(
        value=delta,
        shape="triangleup",
        colorIndex=bullColor,
        width=2,
        label=["Buy Imbalance"],
        desc=["Extreme buy imbalance: z-score > " + imbalanceThreshold]
    )
}
if (extremeSellImb) {
    plotShape(
        value=delta,
        shape="triangledown",
        colorIndex=bearColor,
        width=2,
        label=["Sell Imbalance"],
        desc=["Extreme sell imbalance: z-score < -" + imbalanceThreshold]
    )
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
    var netDeltaPct = (totalVolume > 0) ? ((totalBuyVol - totalSellVol) / totalVolume) * 100 : 0
    var cvdRegime = cumDelta > 0 ? "BULLISH" : (cumDelta < 0 ? "BEARISH" : "NEUTRAL")
    var cvdRegimeColor = cumDelta > 0 ? bullColor : (cumDelta < 0 ? bearColor : neutColor)

    plotTable(
        data=[
            ["FootPrint Stats — Perfected", cvdRegime],
            ["Current Delta", delta[0]],
            ["Delta Z-Score", deltaZ[0]],
            ["Cumulative Delta", cumDelta],
            ["Imbalance Z", imbZ[0]],
            ["Volume", volume[0]],
            ["Avg Volume", avgVol[0]],
            ["Vol Ratio", volRatio[0]],
            ["Whale Count", whaleCount],
            ["Absorption Count", absorpCount],
            ["Net Delta %", netDeltaPct],
            ["Max Delta", maxDelta],
            ["Min Delta", minDelta]
        ],
        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
    )
}