Perfected FlowScript
Aggregated Statistic Bar - BTC Only
Aggregated Statistic Bar — BTC Multi-Venue [Perfected] is indexed as 138_aggregated_statistic_bar_btc_only.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
17.8 KB
Lines
422
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Vol Extreme
line 362:9
Trigger
(showShapes) && (volExtremeUp)
Value
volZSmooth
Deps
showShapes:input, volExtremeUp:var
Vol Extreme
line 372:9
Trigger
(showShapes) && (volExtremeDn)
Value
volZSmooth
Deps
showShapes:input, volExtremeDn:var
Delta Extreme
line 382:9
Trigger
(showShapes) && (dExtremeUp)
Value
dZSmooth
Deps
dExtremeUp:var, showShapes:input
Delta Extreme
line 392:9
Trigger
(showShapes) && (dExtremeDn)
Value
dZSmooth
Deps
dExtremeDn:var, showShapes:input
Session Extreme
line 402:9
Trigger
(showShapes) && (sdExtremeUp)
Value
sdZSmooth
Deps
sdExtremeUp:var, showShapes:input
Session Extreme
line 412:9
Trigger
(showShapes) && (sdExtremeDn)
Value
sdZSmooth
Deps
sdExtremeDn:var, showShapes:input
138_aggregated_statistic_bar_btc_only.flowscript
source path: kscripts/perfected/138_aggregated_statistic_bar_btc_only.flowscript · sha256:a361b37f2ab21b44d029c24e4c0ce3cfafb96d7f23cba76024df27f1aaf9dab6
//@version=2
// ============================================================================
// Aggregated Statistic Bar — BTC Multi-Venue Microstructure [Perfected]
// Author: D (@Denethh) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #statistics, #bar, #aggregated, #agg, #btc
//
// Multi-exchange aggregated bar statistics for BTC: volume, volume delta,
// and session delta (resets daily at 00:00 UTC). Combines data from Binance,
// Bybit, OKX, Hyperliquid perps, and Coinbase spot. Color-coded by z-score
// with configurable intensity thresholds, regime detection, and shape markers
// for extreme deviation events.
//
// FORMULA FOUNDATION:
// 1. Aggregate Volume: Σ Volume_i across N venues [Aleti & Mizrach 2021]
// 2. Volume Delta: Σ(BuyVol_i − SellVol_i) / N [Hasbrouck 2007 trade classification]
// 3. Session Delta: Cumulative Δ reset daily at 00:00 UTC [Cont et al. 2014]
// 4. Z-Score: z = (x − μ) / σ [Zhao & Palomar 2018]
// 5. Heat Coloring: 7-tier color map based on |z| thresholds [0.5, 1.5, 2.5]
//
// RESEARCH BASIS:
// • Aleti, Saketh & Mizrach, Bruce (2021), "Bitcoin Spot and Futures Market
// Microstructure". Cross-venue aggregation improves signal quality; CME leads
// price discovery; spot median trade sizes < $1,300; CME > $18,000.
// • Zhao, S. & Palomar, D. P. (2018), "Mean-Reverting Portfolio With Budget
// Constraint". z = (x − μ) / σ; color intensity scales with deviation magnitude.
// • Hasbrouck (2007), "Empirical Market Microstructure". Multi-metric bar
// statistics as a practical implementation of price-discovery VAR framework.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events".
// Volume delta (buy vs. sell difference) is the primary driver of short-term
// price changes; cumulative session delta captures persistent pressure.
// ============================================================================
define(
title="Aggregated Statistic Bar — BTC Multi-Venue [Perfected]",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Statistical Configuration ---
var lookback = input(name="lookback", type="number", defaultValue=30, label="Statistical Lookback", constraints={min: 5, max: 200, step: 1}, group="Statistics")
var mode = input(name="mode", type="select", defaultValue="Coin", label="Display Mode", options=["Coin", "USD"], group="Statistics")
var smoothLen = input(name="smoothLen", type="number", defaultValue=1, label="Smoothing Length (1 = off)", constraints={min: 1, max: 50, step: 1}, group="Statistics")
var useEmaSmooth = input(name="useEmaSmooth", type="boolean", defaultValue=false, label="Use EMA Smoothing", group="Statistics")
// --- Thresholds & Regime ---
var zMild = input(name="zMild", type="number", defaultValue=0.5, label="Mild Threshold (σ)", constraints={min: 0.1, max: 3.0, step: 0.1}, group="Thresholds")
var zModerate = input(name="zModerate", type="number", defaultValue=1.5, label="Moderate Threshold (σ)", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Thresholds")
var zExtreme = input(name="zExtreme", type="number", defaultValue=2.5, label="Extreme Threshold (σ)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Thresholds")
// --- Display ---
var showVolZ = input(name="showVolZ", type="boolean", defaultValue=true, label="Show Volume Z-Score", group="Display")
var showDeltaZ = input(name="showDeltaZ", type="boolean", defaultValue=true, label="Show Delta Z-Score", group="Display")
var showSessionZ = input(name="showSessionZ", type="boolean", defaultValue=true, label="Show Session Delta Z-Score", 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 showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Metric Labels", group="Display")
// --- Colors ---
var bullL1 = input(name="bullL1", type="color", defaultValue="#1b5e20", label="Bullish Mild", group="Colors")
var bullL2 = input(name="bullL2", type="color", defaultValue="#26a69a", label="Bullish Moderate", group="Colors")
var bullL3 = input(name="bullL3", type="color", defaultValue="#a5d6a7", label="Bullish Extreme", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral", group="Colors")
var bearL1 = input(name="bearL1", type="color", defaultValue="#ffcdd2", label="Bearish Mild", group="Colors")
var bearL2 = input(name="bearL2", type="color", defaultValue="#ef5350", label="Bearish Moderate", group="Colors")
var bearL3 = input(name="bearL3", type="color", defaultValue="#b71c1c", label="Bearish Extreme", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources — multi-venue BTC aggregation (Aleti & Mizrach 2021 completeness)
// ------------------------------------------------------------------------------
timeseries barsBybit = ohlcv(symbol="BTCUSDT", exchange="BYBIT")
timeseries barsBinance = ohlcv(symbol="BTCUSDT", exchange="BINANCE_FUTURES")
timeseries barsOkex = ohlcv(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries barsCB = ohlcv(symbol="BTC-USD", exchange="COINBASE")
timeseries barsHL = ohlcv(symbol="BTC", exchange="HYPERLIQUID_FUTURES")
// NaN guard — prevent execution before all multi-venue data is loaded.
// Critical for BTC-only scripts where venue availability varies by session.
if (isnan(barsBybit.close[0]) || isnan(barsBinance.close[0]) || isnan(barsOkex.close[0]) || isnan(barsCB.close[0]) || isnan(barsHL.close[0])) {
return
}
// ------------------------------------------------------------------------------
// Volume Extraction
// ------------------------------------------------------------------------------
timeseries vBybit = barsBybit.volume
timeseries vBinance = barsBinance.volume
timeseries vOkex = barsOkex.volume
timeseries vCB = barsCB.volume
timeseries vHL = barsHL.volume
// Price reference for USD mode (Bybit as pricing proxy — most liquid BTC perp)
timeseries hBybit = barsBybit.high
timeseries lBybit = barsBybit.low
timeseries cBybit = barsBybit.close
timeseries typBybit = (hBybit + lBybit + cBybit) / 3.0
// ------------------------------------------------------------------------------
// Aggregate Volume (all 5 venues — CRITICAL BUG FIX: added missing Coinbase)
// ------------------------------------------------------------------------------
// The original omitted Coinbase (vCB) from the aggregate, losing ~15–20% of
// spot volume. All five venues are now included per Aleti & Mizrach (2021)
// cross-venue completeness principle.
timeseries aggVol = vBybit + vBinance + vOkex + vCB + vHL
if (mode == "USD") {
aggVol = aggVol * typBybit
}
// Zero-division guard: ensure aggregate volume is non-negative
aggVol = math.max(aggVol, 0.0)
// ------------------------------------------------------------------------------
// Per-Venue Volume Delta (close-vs-mid trade classification proxy)
// ------------------------------------------------------------------------------
// Hasbrouck (2007) trade classification: buy-initiated if close ≥ midpoint.
// Simplified proxy per venue; Lee-Ready (1991) tick-data algorithm would
// require quote-midpoint comparison at the trade level (~85–93% accuracy).
//
// CRITICAL BUG FIX: The original referenced undefined variables cBinance, cOkex,
// cHL. All close prices are now properly extracted from their respective bars.
// Bybit
timeseries midBybit = (barsBybit.high + barsBybit.low) / 2.0
timeseries buyBybit = barsBybit.close >= midBybit ? vBybit : 0.0
timeseries sellBybit = barsBybit.close < midBybit ? vBybit : 0.0
timeseries deltaBybit = buyBybit - sellBybit
// Binance
timeseries midBinance = (barsBinance.high + barsBinance.low) / 2.0
timeseries buyBinance = barsBinance.close >= midBinance ? vBinance : 0.0
timeseries sellBinance = barsBinance.close < midBinance ? vBinance : 0.0
timeseries deltaBinance = buyBinance - sellBinance
// OKX
timeseries midOkex = (barsOkex.high + barsOkex.low) / 2.0
timeseries buyOkex = barsOkex.close >= midOkex ? vOkex : 0.0
timeseries sellOkex = barsOkex.close < midOkex ? vOkex : 0.0
timeseries deltaOkex = buyOkex - sellOkex
// Coinbase
timeseries midCB = (barsCB.high + barsCB.low) / 2.0
timeseries buyCB = barsCB.close >= midCB ? vCB : 0.0
timeseries sellCB = barsCB.close < midCB ? vCB : 0.0
timeseries deltaCB = buyCB - sellCB
// Hyperliquid
timeseries midHL = (barsHL.high + barsHL.low) / 2.0
timeseries buyHL = barsHL.close >= midHL ? vHL : 0.0
timeseries sellHL = barsHL.close < midHL ? vHL : 0.0
timeseries deltaHL = buyHL - sellHL
// Aggregate delta (mean across 5 venues — BUG FIX: added Coinbase deltaCB)
timeseries aggDelta = (deltaBybit + deltaBinance + deltaOkex + deltaCB + deltaHL) / 5.0
// ------------------------------------------------------------------------------
// Session Delta (daily reset at 00:00 UTC — Cont et al. 2014 cumulative pressure)
// ------------------------------------------------------------------------------
// Session delta tracks cumulative buy/sell pressure since midnight UTC.
// Resets daily to isolate intraday flow patterns from interday drift.
timeseries tBybit = barsBybit.time
var dayId = math.floor(tBybit / 86400000)
static sessDelta = 0.0
static lastDay = -1
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0
if (lastDay == -1 || dayId != lastDay) {
lastDay = dayId
sessDelta = aggDelta
sessionHighDelta = aggDelta
sessionLowDelta = aggDelta
} else {
sessDelta = nz(sessDelta) + aggDelta
if (sessDelta > sessionHighDelta) {
sessionHighDelta = sessDelta
}
if (sessDelta < sessionLowDelta) {
sessionLowDelta = sessDelta
}
}
// ------------------------------------------------------------------------------
// Z-Score Computation (Zhao & Palomar 2018) with zero-division guards
// ------------------------------------------------------------------------------
// Volume Z: how many standard deviations is current aggregate volume from
// its recent mean? High positive = unusually high volume (capitulation / FOMO).
// High negative = unusually low volume (consolidation / pre-breakout).
timeseries volMean = sma(aggVol, lookback)
timeseries volStd = stdev(aggVol, lookback)
timeseries volZ = (aggVol - volMean) / max(volStd, 1e-9)
// Delta Z: standardized per-bar buy/sell imbalance.
timeseries dMean = sma(aggDelta, lookback)
timeseries dStd = stdev(aggDelta, lookback)
timeseries dZ = (aggDelta - dMean) / max(dStd, 1e-9)
// Session Delta Z: standardized cumulative flow pressure.
timeseries sdMean = sma(sessDelta, lookback)
timeseries sdStd = stdev(sessDelta, lookback)
timeseries sdZ = (sessDelta - sdMean) / max(sdStd, 1e-9)
// Optional smoothing (EMA per Cont et al. 2014 noise-reduction)
timeseries volZSmooth = smoothLen <= 1 ? volZ : (useEmaSmooth ? ema(volZ, smoothLen) : sma(volZ, smoothLen))
timeseries dZSmooth = smoothLen <= 1 ? dZ : (useEmaSmooth ? ema(dZ, smoothLen) : sma(dZ, smoothLen))
timeseries sdZSmooth = smoothLen <= 1 ? sdZ : (useEmaSmooth ? ema(sdZ, smoothLen) : sma(sdZ, smoothLen))
// ------------------------------------------------------------------------------
// Regime Detection (7-tier heat map for Volume Z; 3-tier for Delta/Session Z)
// ------------------------------------------------------------------------------
// Volume Z regime: 0=extreme bull, 1=moderate bull, 2=mild bull, 3=neutral,
// 4=mild bear, 5=moderate bear, 6=extreme bear
var volRegime = 3
if (volZSmooth > zExtreme) {
volRegime = 0
} else if (volZSmooth > zModerate) {
volRegime = 1
} else if (volZSmooth > zMild) {
volRegime = 2
} else if (volZSmooth < -zExtreme) {
volRegime = 6
} else if (volZSmooth < -zModerate) {
volRegime = 5
} else if (volZSmooth < -zMild) {
volRegime = 4
} else {
volRegime = 3
}
// Delta Z regime: 0=neutral, 1=bull, -1=bear (per Cartea et al. 2018 three-segment)
var dRegime = 0
if (dZSmooth >= zMild) {
dRegime = 1
} else if (dZSmooth <= -zMild) {
dRegime = -1
}
// Session Delta Z regime: 0=neutral, 1=bull, -1=bear
var sdRegime = 0
if (sdZSmooth >= zMild) {
sdRegime = 1
} else if (sdZSmooth <= -zMild) {
sdRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ------------------------------------------------------------------------------
// Tracks session extremes, extreme-event counts, and regime transitions for
// diagnostic and alerting purposes.
static lastBarIndex = 0
static sessionHighVolZ = -999999.0
static sessionLowVolZ = 999999.0
static extremeVolCount = 0
static extremeDeltaCount = 0
static extremeSessionCount = 0
static lastVolRegime = 3
static regimeChangeCount = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (volZSmooth > sessionHighVolZ) {
sessionHighVolZ = volZSmooth
}
if (volZSmooth < sessionLowVolZ) {
sessionLowVolZ = volZSmooth
}
if (math.abs(volZSmooth) > zExtreme) {
extremeVolCount = extremeVolCount + 1
}
if (math.abs(dZSmooth) > zExtreme) {
extremeDeltaCount = extremeDeltaCount + 1
}
if (math.abs(sdZSmooth) > zExtreme) {
extremeSessionCount = extremeSessionCount + 1
}
if (lastVolRegime != volRegime) {
lastVolRegime = volRegime
regimeChangeCount = regimeChangeCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Fill, Shape, HLine)
// ------------------------------------------------------------------------------
// Zero line
hline(value=0, color="#ffffff30", width=1)
// Guide lines at threshold levels
if (showGuides) {
hline(value=zMild, color=opacity(bullL2, 30), width=1)
hline(value=-zMild, color=opacity(bearL2, 30), width=1)
hline(value=zModerate, color=opacity(bullL2, 20), width=1)
hline(value=-zModerate, color=opacity(bearL2, 20), width=1)
hline(value=zExtreme, color=opacity(bullL3, 15), width=1)
hline(value=-zExtreme, color=opacity(bearL3, 15), width=1)
}
// Volume Z — filled line with 7-tier heat coloring
if (showVolZ) {
plotLine(
value=volZSmooth,
width=2,
colors=[bullL3, bullL2, bullL1, neutralColor, bearL1, bearL2, bearL3],
colorIndex=volRegime,
label=["Volume Z"],
desc=["Aggregate volume z-score across 5 venues (BTC). 7-tier heat coloring by deviation magnitude."],
fill=true
)
}
// Delta Z — filled line with 3-tier regime coloring
if (showDeltaZ) {
plotLine(
value=dZSmooth,
width=2,
colors=[bullL2, bearL2, neutralColor],
colorIndex=dRegime == 1 ? 0 : (dRegime == -1 ? 1 : 2),
label=["Delta Z"],
desc=["Aggregate volume delta z-score (buy minus sell) across 5 venues. Positive = buyer dominance."],
fill=true
)
}
// Session Delta Z — filled line with 3-tier regime coloring
if (showSessionZ) {
plotLine(
value=sdZSmooth,
width=2,
colors=[bullL3, bearL3, neutralColor],
colorIndex=sdRegime == 1 ? 0 : (sdRegime == -1 ? 1 : 2),
label=["Session Delta Z"],
desc=["Cumulative session delta z-score (resets daily at 00:00 UTC). Tracks persistent flow pressure."],
fill=true
)
}
// Shape markers for extreme z-score events
if (showShapes) {
var volExtremeUp = volZSmooth >= zExtreme && !isnan(volZSmooth[1]) && volZSmooth[1] < zExtreme
var volExtremeDn = volZSmooth <= -zExtreme && !isnan(volZSmooth[1]) && volZSmooth[1] > -zExtreme
var dExtremeUp = dZSmooth >= zExtreme && !isnan(dZSmooth[1]) && dZSmooth[1] < zExtreme
var dExtremeDn = dZSmooth <= -zExtreme && !isnan(dZSmooth[1]) && dZSmooth[1] > -zExtreme
var sdExtremeUp = sdZSmooth >= zExtreme && !isnan(sdZSmooth[1]) && sdZSmooth[1] < zExtreme
var sdExtremeDn = sdZSmooth <= -zExtreme && !isnan(sdZSmooth[1]) && sdZSmooth[1] > -zExtreme
if (volExtremeUp) {
plotShape(
value=volZSmooth,
shape="triangleup",
color=bullL3,
width=3,
label=["Vol Extreme"],
desc=["Volume z-score crossed into extreme bullish territory (> +2.5σ)"]
)
}
if (volExtremeDn) {
plotShape(
value=volZSmooth,
shape="triangledown",
color=bearL3,
width=3,
label=["Vol Extreme"],
desc=["Volume z-score crossed into extreme bearish territory (< −2.5σ)"]
)
}
if (dExtremeUp) {
plotShape(
value=dZSmooth,
shape="triangleup",
color=bullL2,
width=3,
label=["Delta Extreme"],
desc=["Delta z-score crossed into extreme bullish territory (> +2.5σ)"]
)
}
if (dExtremeDn) {
plotShape(
value=dZSmooth,
shape="triangledown",
color=bearL2,
width=3,
label=["Delta Extreme"],
desc=["Delta z-score crossed into extreme bearish territory (< −2.5σ)"]
)
}
if (sdExtremeUp) {
plotShape(
value=sdZSmooth,
shape="diamond",
color=bullL3,
width=4,
label=["Session Extreme"],
desc=["Session delta z-score crossed into extreme bullish territory (> +2.5σ)"]
)
}
if (sdExtremeDn) {
plotShape(
value=sdZSmooth,
shape="diamond",
color=bearL3,
width=4,
label=["Session Extreme"],
desc=["Session delta z-score crossed into extreme bearish territory (< −2.5σ)"]
)
}
}