MM Flow
FlowScripts

Perfected FlowScript

BAR STATS

BAR STATS — Perfected Edition is indexed as 141_bar_stats.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.8 KB

Lines

528

Native Signal Candidates

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

5/5 guarded

Delta Extreme+

line 446:9

Trigger

(showShapes) && (deltaExtremeHigh)

Value

deltaZ

Deps

deltaExtremeHigh:var, showShapes:input

Delta Extreme-

line 456:9

Trigger

(showShapes) && (deltaExtremeLow)

Value

deltaZ

Deps

deltaExtremeLow:var, showShapes:input

CumDelta Extreme+

line 466:9

Trigger

(showShapes) && (cumDeltaExtremeHigh)

Value

cumDeltaZ

Deps

cumDeltaExtremeHigh:var, showShapes:input

CumDelta Extreme-

line 476:9

Trigger

(showShapes) && (cumDeltaExtremeLow)

Value

cumDeltaZ

Deps

cumDeltaExtremeLow:var, showShapes:input

Liq Cascade

line 486:9

Trigger

(showShapes) && (liqExtremeHigh)

Value

liqZ

Deps

liqExtremeHigh:var, showShapes:input

141_bar_stats.flowscript

source path: kscripts/perfected/141_bar_stats.flowscript · sha256:86a7ab2dbd464fe7c0c2dd12cf004e94525e0c474f35e81c6a76cc9ae012e643

hash verified
//@version=2
// ============================================================================
// BAR STATS — Perfected Edition
// Author: P (@Parzival4567) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #footprints, #bar_statistics, #max_delta, #min_delta, #volume,
//       #open_interest, #funding, #liquidations, #zscore, #heatmap
//
// Production-grade multi-metric bar statistics dashboard. Implements
// footprint-style delta (BVC classification), open interest delta, funding
// rate, liquidation flow, and z-score heat coloring across all metrics.
//
// Academic foundations:
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data"
//     (Journal of Finance 46(2), 733–746). The canonical quote-rule + tick-test
//     algorithm for classifying aggressive buy vs sell volume. Achieved ~85–93%
//     accuracy on NYSE TORQ data. Underpins all volume-delta calculations.
//     Key formula: trade at ask = buyer-initiated (+), at bid = seller-initiated
//     (−), with 5-second lag for quote staleness.
//  2. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//     Activity" (SSRN 1989555). BVC method classifies volume probabilistically
//     using price-change distribution within a bar — more robust in HFT/crypto
//     where tick-rule classifications break down.
//  3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//     (Journal of Financial Econometrics 12(1), 47–88). OFI linearly predicts
//     price changes: ΔP ≈ λ·OFI where λ ∝ 1/depth. Validates delta as the
//     primary driver of short-term price moves.
//  4. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts" (Journal of Finance 50(1),
//     281–300). Establishes OI as containing information about future volatility
//     and market expectations — higher OI = greater information flow.
//  5. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
//     (Review of Financial Studies 22(6), 2201–2238). The liquidity spiral model:
//     when funding liquidity tightens, liquidations increase, market liquidity
//     drops, and volatility rises — creating the correlated bar statistics this
//     script displays.
//  6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint"
//     (IEEE TSP). z̄_t = (z_t − μ_z)/σ_z with entry thresholds at Δ = d×σ_z.
//     Underpins z-score normalization and heat-coloring used here.
// ============================================================================

define(
    title="BAR STATS — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Volume Delta ---
var footprintLen = input(
    name="footprintLen",
    type="number",
    defaultValue=10,
    label="Footprint Lookback (max/min delta window)",
    constraints={min: 2, max: 100, step: 1},
    group="Volume Delta"
)
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Per-Bar Delta",
    group="Volume Delta"
)
var showCumDelta = input(
    name="showCumDelta",
    type="boolean",
    defaultValue=true,
    label="Show Cumulative Delta",
    group="Volume Delta"
)
var showMaxMin = input(
    name="showMaxMin",
    type="boolean",
    defaultValue=true,
    label="Show Max/Min Delta Lines",
    group="Volume Delta"
)

// --- Open Interest ---
var showOI = input(
    name="showOI",
    type="boolean",
    defaultValue=true,
    label="Show Open Interest Delta",
    group="Open Interest"
)
var oiSmoothLen = input(
    name="oiSmoothLen",
    type="number",
    defaultValue=5,
    label="OI Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Open Interest"
)

// --- Funding Rate ---
var showFunding = input(
    name="showFunding",
    type="boolean",
    defaultValue=true,
    label="Show Funding Rate",
    group="Funding"
)
var fundingSmoothLen = input(
    name="fundingSmoothLen",
    type="number",
    defaultValue=3,
    label="Funding Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Funding"
)

// --- Liquidations ---
var showLiq = input(
    name="showLiq",
    type="boolean",
    defaultValue=true,
    label="Show Liquidations",
    group="Liquidations"
)
var liqLookback = input(
    name="liqLookback",
    type="number",
    defaultValue=20,
    label="Liquidation Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Liquidations"
)

// --- Z-Score & Heat ---
var zScoreLookback = input(
    name="zScoreLookback",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score & Heat"
)
var showZScoreHeat = input(
    name="showZScoreHeat",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Heat Coloring",
    group="Z-Score & Heat"
)
var zExtreme = input(
    name="zExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 5.0, step: 0.5},
    group="Z-Score & Heat"
)

// --- Display ---
var showZero = input(
    name="showZero",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shape Markers",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table (last bar)",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var heatHighColor = input(
    name="heatHighColor",
    type="color",
    defaultValue="#00e676",
    label="Heat — High Z-Score",
    group="Colors"
)
var heatLowColor = input(
    name="heatLowColor",
    type="color",
    defaultValue="#ff5252",
    label="Heat — Low Z-Score",
    group="Colors"
)
var oiColor = input(
    name="oiColor",
    type="color",
    defaultValue="#ab47bc",
    label="OI Color",
    group="Colors"
)
var fundingColor = input(
    name="fundingColor",
    type="color",
    defaultValue="#ffd700",
    label="Funding Color",
    group="Colors"
)
var liqColor = input(
    name="liqColor",
    type="color",
    defaultValue="#ff9100",
    label="Liquidation Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0])) {
    return
}

// Open interest (best-effort; falls back to zero if unavailable)
timeseries oiRaw = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = isnan(oiRaw.close) ? 0.0 : oiRaw.close

// Funding rate (best-effort; falls back to zero if unavailable)
timeseries fundRaw = funding_rate(symbol=currentSymbol, exchange=currentExchange)
timeseries fund = isnan(fundRaw) ? 0.0 : fundRaw

// Liquidations (best-effort; falls back to zero if unavailable)
timeseries liqRaw = liquidations(symbol=currentSymbol, exchange=currentExchange)
timeseries liq = isnan(liqRaw) ? 0.0 : liqRaw

// ---------------------------------------------------------------------------
// 3. PER-BAR VOLUME DELTA (BVC-style midpoint classification)
// ---------------------------------------------------------------------------
// Per Easley, López de Prado & O'Hara (2012) BVC method: classify volume by
// bar midpoint. Close >= mid → buyer-initiated; close < mid → seller-initiated.
timeseries mid = (h + l) / 2.0
timeseries buyV = (c >= mid) ? v : 0.0
timeseries sellV = (c < mid) ? v : 0.0
timeseries delta = buyV - sellV

// Max / min delta over footprint window
timeseries deltaMax = highest(delta, footprintLen)
timeseries deltaMin = lowest(delta, footprintLen)

// ---------------------------------------------------------------------------
// 4. CUMULATIVE DELTA (static tracking)
// ---------------------------------------------------------------------------
static cumDelta = 0.0
if (!isLiveUpdate) {
    cumDelta = nz(cumDelta) + delta
}

// ---------------------------------------------------------------------------
// 5. OPEN INTEREST DELTA
// ---------------------------------------------------------------------------
timeseries oiDelta = oi - nz(oi[1])
timeseries oiDeltaSmooth = ema(oiDelta, oiSmoothLen)

// ---------------------------------------------------------------------------
// 6. FUNDING RATE (smoothed)
// ---------------------------------------------------------------------------
timeseries fundSmooth = ema(fund, fundingSmoothLen)

// ---------------------------------------------------------------------------
// 7. LIQUIDATION Z-SCORE
// ---------------------------------------------------------------------------
timeseries liqMean = sma(liq, liqLookback)
timeseries liqStd = stddev(liq, liqLookback)
timeseries liqZ = (liqStd > 0) ? (liq - liqMean) / liqStd : 0.0

// ---------------------------------------------------------------------------
// 8. Z-SCORE NORMALIZATION FOR DELTA
// ---------------------------------------------------------------------------
timeseries deltaMean = sma(delta, zScoreLookback)
timeseries deltaStd = stddev(delta, zScoreLookback)
timeseries deltaZ = (deltaStd > 0) ? (delta - deltaMean) / deltaStd : 0.0

timeseries cumDeltaMean = sma(cumDelta, zScoreLookback)
timeseries cumDeltaStd = stddev(cumDelta, zScoreLookback)
timeseries cumDeltaZ = (cumDeltaStd > 0) ? (cumDelta - cumDeltaMean) / cumDeltaStd : 0.0

// ---------------------------------------------------------------------------
// 9. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime based on cumulative delta z-score and liquidation z-score.
// Bullish: cumDeltaZ > 0.5 and liqZ < 1 (buying pressure, no extreme liqs)
// Bearish: cumDeltaZ < -0.5 and liqZ < 1 (selling pressure, no extreme liqs)
// Exhaustion: |liqZ| > 2 (liquidation cascade — contrarian)
var regimeBull = cumDeltaZ > 0.5 && liqZ < 1.0
var regimeBear = cumDeltaZ < -0.5 && liqZ < 1.0
var regimeExhaust = math.abs(liqZ) > 2.0
var regimeNeutral = !regimeBull && !regimeBear && !regimeExhaust

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : (regimeExhaust ? "#ff9100" : "#9e9e9e"))

// ---------------------------------------------------------------------------
// 10. EXTREME SHAPE MARKERS (static tracking to avoid repaint)
// ---------------------------------------------------------------------------
static lastDeltaZ = 0.0
static lastCumDeltaZ = 0.0
static lastLiqZ = 0.0

var deltaExtremeHigh = false
var deltaExtremeLow = false
var cumDeltaExtremeHigh = false
var cumDeltaExtremeLow = false
var liqExtremeHigh = false

if (!isLiveUpdate) {
    deltaExtremeHigh = deltaZ > zExtreme && lastDeltaZ <= zExtreme
    deltaExtremeLow = deltaZ < -zExtreme && lastDeltaZ >= -zExtreme
    cumDeltaExtremeHigh = cumDeltaZ > zExtreme && lastCumDeltaZ <= zExtreme
    cumDeltaExtremeLow = cumDeltaZ < -zExtreme && lastCumDeltaZ >= -zExtreme
    liqExtremeHigh = liqZ > zExtreme && lastLiqZ <= zExtreme

    lastDeltaZ = deltaZ
    lastCumDeltaZ = cumDeltaZ
    lastLiqZ = liqZ
}

// ---------------------------------------------------------------------------
// 11. PLOTTING
// ---------------------------------------------------------------------------

// --- Zero Line ---
if (showZero) {
    hline(value=0, color="#ffffff20", width=1)
}

// --- Delta Z-Score Heat Bar (primary visualization) ---
if (showZScoreHeat) {
    var heatColor = deltaZ >= 0 ? heatHighColor : heatLowColor
    var heatIntensity = math.min(math.abs(deltaZ) / zExtreme, 1.0)
    var heatAlpha = 30 + math.floor(heatIntensity * 50)
    plotBar(
        value=deltaZ,
        colors=[transparency(heatColor, 100 - heatAlpha)],
        width=1,
        label=["Delta Z-Score"],
        desc=["Per-bar volume delta z-score (BVC classification). " + deltaZ]
    )
}

// --- Per-Bar Delta ---
if (showDelta) {
    plotLine(
        value=delta,
        width=1,
        colors=[transparency(bullColor, 40)],
        label=["Delta"],
        desc=["Per-bar volume delta (buyV − sellV) via BVC midpoint classification"]
    )
}

// --- Cumulative Delta ---
if (showCumDelta) {
    plotLine(
        value=cumDelta,
        width=2,
        colors=[regimeColor],
        label=["Cumulative Delta"],
        desc=["Running total of per-bar delta. Regime-colored."]
    )
}

// --- Max / Min Delta ---
if (showMaxMin) {
    plotLine(
        value=deltaMax,
        width=1,
        colors=[transparency(bullColor, 60)],
        label=["Max Delta"],
        desc=["Maximum delta over " + footprintLen + "-bar lookback window"]
    )
    plotLine(
        value=deltaMin,
        width=1,
        colors=[transparency(bearColor, 60)],
        label=["Min Delta"],
        desc=["Minimum delta over " + footprintLen + "-bar lookback window"]
    )
}

// --- OI Delta ---
if (showOI) {
    plotLine(
        value=oiDeltaSmooth,
        width=1,
        colors=[transparency(oiColor, 50)],
        label=["OI Delta"],
        desc=["Open interest change (smoothed). Rising = new positions entering."]
    )
}

// --- Funding Rate ---
if (showFunding) {
    plotLine(
        value=fundSmooth,
        width=1,
        colors=[transparency(fundingColor, 50)],
        label=["Funding"],
        desc=["Smoothed funding rate. Positive = longs pay shorts."]
    )
}

// --- Liquidation Z-Score ---
if (showLiq) {
    plotLine(
        value=liqZ,
        width=2,
        colors=[transparency(liqColor, 40)],
        label=["Liq Z-Score"],
        desc=["Liquidation z-score over " + liqLookback + " bars. >2 = extreme."]
    )
}

// --- Extreme Shape Markers ---
if (showShapes) {
    if (deltaExtremeHigh) {
        plotShape(
            value=deltaZ,
            shape="triangleup",
            colorIndex=heatHighColor,
            width=2,
            label=["Delta Extreme+"],
            desc=["Delta z-score crossed above +" + zExtreme + " — extreme buying pressure"]
        )
    }
    if (deltaExtremeLow) {
        plotShape(
            value=deltaZ,
            shape="triangledown",
            colorIndex=heatLowColor,
            width=2,
            label=["Delta Extreme-"],
            desc=["Delta z-score crossed below -" + zExtreme + " — extreme selling pressure"]
        )
    }
    if (cumDeltaExtremeHigh) {
        plotShape(
            value=cumDeltaZ,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["CumDelta Extreme+"],
            desc=["Cumulative delta z-score crossed above +" + zExtreme]
        )
    }
    if (cumDeltaExtremeLow) {
        plotShape(
            value=cumDeltaZ,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["CumDelta Extreme-"],
            desc=["Cumulative delta z-score crossed below -" + zExtreme]
        )
    }
    if (liqExtremeHigh) {
        plotShape(
            value=liqZ,
            shape="xcross",
            colorIndex=liqColor,
            width=2,
            label=["Liq Cascade"],
            desc=["Liquidation z-score crossed above +" + zExtreme + " — potential cascade"]
        )
    }
}

// ---------------------------------------------------------------------------
// 12. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeExhaust ? "EXHAUSTION" : (regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL"))
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : (regimeExhaust ? "#ff9100" : "#9e9e9e"))

    plotTable(
        data=[
            ["BAR STATS — Perfected", regimeText],
            ["Delta Z", deltaZ[0]],
            ["CumDelta Z", cumDeltaZ[0]],
            ["OI Delta", oiDeltaSmooth[0]],
            ["Funding", fundSmooth[0]],
            ["Liq Z", liqZ[0]],
            ["Max Delta", deltaMax[0]],
            ["Min Delta", deltaMin[0]]
        ],
        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
    )
}