Perfected FlowScript
Bar Statistics Pro (Fork)
Bar Statistics Pro (Fork) — Perfected is indexed as 283_bar_statistics_pro_fork.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
11.1 KB
Lines
243
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull
line 160:5
Trigger
(showShapes && extremeBull)
Value
extremeZ
Deps
extremeBull:var, showShapes:input
Extreme Bear
line 163:5
Trigger
(showShapes && extremeBear)
Value
-extremeZ
Deps
extremeBear:var, showShapes:input
283_bar_statistics_pro_fork.flowscript
source path: kscripts/perfected/283_bar_statistics_pro_fork.flowscript · sha256:6ea033e03df3751d71cc80cfc0a71246e0307046f3ce745f57b46052f7ed0622
//@version=2
/* ============================================================================
* Bar Statistics Pro (Fork) — Perfected Edition
* Author: M (@mshal8888) | Perfected: kScript_Perfection_Engineer
* Index: 283
* Tags: ADVANCED, CORE, #zscore, #trend, #barstats, #orderflow, #imbalance
*
* Compact per-bar dashboard heat-mapping multiple flow and positioning metrics
* (volume, delta, liquidations, OFI, OI delta, long-short ratio, depth
* imbalance, CVD, OBV) using rolling z-scores for statistical context.
*
* Academic foundation:
* 1. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
* IEEE. [Formula] z_t = (x_t − μ) / σ; entry thresholds at ±1σ or ±2σ.
* Z-score event triggers for mean reversion; positions opened when spread
* diverges from equilibrium. DOI: 10.1109/TSP.2018.2846226
*
* 2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
* Journal of Financial Econometrics, 12(1), 47–88.
* [Formula] OFI_t = Σ(Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0})
* Δp_t ≈ λ·OFI_t where λ ∝ 1/Depth. Multi-level OFI improves prediction.
* DOI: https://doi.org/10.1093/jjfinec/nbt003
*
* 3. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
* a High-Frequency World", Journal of Portfolio Management, 39(2), 55–67.
* [Formula] VPIN = Σ|BuyVol − SellVol| / TotalVol over volume buckets.
* Volume-synchronized buy-sell imbalance anticipates flash crashes.
* DOI: https://doi.org/10.3905/jpm.2012.39.2.055
*
* 4. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
* Stock Returns", Journal of Finance, 61(4), 1645–1680.
* Composite sentiment indices from multiple proxies; extreme readings
* predict return reversals. Underpins the multi-metric alignment logic.
* DOI: https://doi.org/10.1111/j.1540-6261.2006.00885.x
*
* 5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
* Journal of Finance, 46(2), 733–746. Foundational tick-classification
* (85–93% accuracy) used when granular taker data is unavailable.
* DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
* ============================================================================ */
define(title="Bar Statistics Pro (Fork) — Perfected", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Computation --
var lookback = input(name="lookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 5}, group="Computation")
var depth = input(name="depth", type="number", defaultValue=5, label="Orderbook Depth", constraints={min: 1, max: 50, step: 1}, group="Computation")
var extremeZ = input(name="extremeZ", type="number", defaultValue=2.5, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Computation")
var showHeat = input(name="showHeat", type="boolean", defaultValue=true, label="Show Z-Score Heat Lines", group="Display")
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD", group="Display")
var showOBV = input(name="showOBV", type="boolean", defaultValue=true, label="Show OBV", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Divergence Histogram", group="Display")
// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#00e676", label="Positive Z", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ff5252", label="Negative Z", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Z", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#9c27b0", label="CVD Color", group="Colors")
var obvColor = input(name="obvColor", type="color", defaultValue="#ffeb3b", label="OBV Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & isnan GUARD
// ---------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
if (isnan(price.close[0])) {
return
}
timeseries close = price.close
timeseries open = price.open
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)
timeseries bids = isnum(book) ? sumBids(book, depth) : 0
timeseries asks = isnum(book) ? sumAsks(book, depth) : 0
// ---------------------------------------------------------------------------
// 3. BAR STATISTICS COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Bar anatomy (all dimensions of the bar) --
timeseries range = high - low
timeseries body = math.abs(close - open)
timeseries upperWick = high - math.max(close, open)
timeseries lowerWick = math.min(close, open) - low
timeseries bodyRatio = range > 0 ? body / range : 0
timeseries upperWickRatio = range > 0 ? upperWick / range : 0
timeseries lowerWickRatio = range > 0 ? lowerWick / range : 0
// -- 3.2 Volume delta (Lee-Ready fallback) --
timeseries buyVol = range > 0 ? volume * (close - low) / range : volume / 2
timeseries sellVol = volume - buyVol
timeseries delta = buyVol - sellVol
// -- 3.3 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (x_t − μ_t) / σ_t, where μ_t = SMA(x, W), σ_t = StDev(x, W).
timeseries deltaMean = sma(delta, lookback)
timeseries deltaStd = stddev(delta, lookback)
timeseries deltaZ = (deltaStd > 0) ? (delta - deltaMean) / deltaStd : 0
timeseries volMean = sma(volume, lookback)
timeseries volStd = stddev(volume, lookback)
timeseries volZ = (volStd > 0) ? (volume - volMean) / volStd : 0
timeseries ofi = bids - asks
timeseries ofiMean = sma(ofi, lookback)
timeseries ofiStd = stddev(ofi, lookback)
timeseries ofiZ = (ofiStd > 0) ? (ofi - ofiMean) / ofiStd : 0
// -- 3.4 Composite z-score (alignment across all metrics) --
timeseries compositeZ = (deltaZ + volZ + ofiZ) / 3
// -- 3.5 Cumulative series via static for true tracking --
static cvdCum = 0.0
static obvCum = 0.0
if (!isnan(delta[0])) {
cvdCum = cvdCum + delta[0]
}
if (!isnan(volume[0])) {
if (close[0] > close[1]) {
obvCum = obvCum + volume[0]
} else if (close[0] < close[1]) {
obvCum = obvCum - volume[0]
}
}
// -- 3.6 Z-score of cumulative series (rolling-window) --
timeseries cvdMean = sma(cvdCum, lookback)
timeseries cvdStd = stddev(cvdCum, lookback)
timeseries cvdZ = (cvdStd > 0) ? (cvdCum - cvdMean) / cvdStd : 0
timeseries obvMean = sma(obvCum, lookback)
timeseries obvStd = stddev(obvCum, lookback)
timeseries obvZ = (obvStd > 0) ? (obvCum - obvMean) / obvStd : 0
// -- 3.7 Regime detection --
var bullish = compositeZ > 0 && deltaZ > 0 && ofiZ > 0
var bearish = compositeZ < 0 && deltaZ < 0 && ofiZ < 0
var neutral = !bullish && !bearish
var extremeBull = compositeZ > extremeZ || deltaZ > extremeZ || volZ > extremeZ
var extremeBear = compositeZ < -extremeZ || deltaZ < -extremeZ || volZ < -extremeZ
// -- 3.8 Static tracking for regime duration --
static bullBars = 0
static bearBars = 0
static neutralBars = 0
if (bullish) {
bullBars = bullBars + 1
bearBars = 0
neutralBars = 0
} else if (bearish) {
bearBars = bearBars + 1
bullBars = 0
neutralBars = 0
} else {
neutralBars = neutralBars + 1
bullBars = 0
bearBars = 0
}
// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------
// -- 4.1 Z-score heat lines (colorIndex-based regime coloring) --
var heatColorIdx = bullish ? 0 : (bearish ? 1 : 2)
if (showHeat) {
plotLine(value=compositeZ, width=2, colors=[upColor, dnColor, neutralColor], colorIndex=heatColorIdx, label=["Composite Z"], desc=["Composite z-score (delta + volume + OFI) / 3; heat-colored by regime"])
plotLine(value=deltaZ, width=2, colors=[upColor, dnColor, neutralColor], colorIndex=heatColorIdx, label=["Delta Z"], desc=["Volume delta z-score; heat-colored by regime"])
plotLine(value=volZ, width=1, colors=["#2962ff", "#2962ff", "#2962ff"], colorIndex=0, label=["Volume Z"], desc=["Volume z-score"])
plotLine(value=ofiZ, width=1, colors=["#ff9800", "#ff9800", "#ff9800"], colorIndex=0, label=["OFI Z"], desc=["Orderflow imbalance z-score"])
}
// -- 4.2 CVD & OBV (static cumulative) --
if (showCVD) {
plotLine(value=cvdZ, width=2, colors=[cvdColor], label=["CVD Z"], desc=["Cumulative volume delta z-score (static-tracked)"])
}
if (showOBV) {
plotLine(value=obvZ, width=2, colors=[obvColor], label=["OBV Z"], desc=["On-balance volume z-score (static-tracked)"])
}
// -- 4.3 Divergence histogram (composite vs zero) --
if (showHistogram) {
plotLine(value=[compositeZ, 0], width=2, colors=[upColor, dnColor, neutralColor], colorIndex=heatColorIdx, fill=true, label=["Divergence Histogram"], desc=["Composite z-score histogram with regime fill"])
}
// -- 4.4 Extreme shape markers --
if (showShapes && extremeBull) {
plotShape(value=extremeZ, shape="triangleup", colorIndex=upColor, width=3, label=["Extreme Bull"], desc=["All metrics aligned bullish with extreme z-score > " + extremeZ])
}
if (showShapes && extremeBear) {
plotShape(value=-extremeZ, shape="triangledown", colorIndex=dnColor, width=3, label=["Extreme Bear"], desc=["All metrics aligned bearish with extreme z-score < -" + extremeZ])
}
// -- 4.5 Reference thresholds --
hline(value=0, color="#ffffff20", width=1)
hline(value=extremeZ, color="#00e67615", width=1)
hline(value=-extremeZ, color="#ff525215", width=1)
hline(value=2, color="#ff525220", width=1)
hline(value=-2, color="#00e67620", width=1)
// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = bullish ? "BULLISH" : (bearish ? "BEARISH" : "NEUTRAL")
var regimeTextColor = bullish ? upColor : (bearish ? dnColor : neutralColor)
plotTable(
data=[
["Bar Stats Pro", regimeText],
["Delta Z", deltaZ[0]],
["Volume Z", volZ[0]],
["OFI Z", ofiZ[0]],
["Composite Z", compositeZ[0]],
["CVD Z", cvdZ[0]],
["OBV Z", obvZ[0]],
["Bull Bars", bullBars],
["Bear Bars", bearBars]
],
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
)
}