Perfected FlowScript
Buy Sell Volume Ratio
Buy Sell Volume Ratio V2 is indexed as 060_buy_sell_volume_ratio.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
12.1 KB
Lines
290
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull
line 226:5
Trigger
(showShapes && extremeBull)
Value
extremeDiv
Deps
extremeBull:var, showShapes:input
Extreme Bear
line 236:5
Trigger
(showShapes && extremeBear)
Value
-extremeDiv
Deps
extremeBear:var, showShapes:input
060_buy_sell_volume_ratio.flowscript
source path: kscripts/perfected/060_buy_sell_volume_ratio.flowscript · sha256:543a5d2d245cef7f7fbc567bddab8e485804286fd43795eb0c2923fb0deb7c42
//@version=2
// ============================================================================
// Buy Sell Volume Ratio V2 — Lee-Ready Classification with Z-Score & Regime
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #volume, #buy, #sell, #ratio, #zscore, #regime
//
// This indicator measures aggressive-side dominance per bar by computing the
// buy-to-sell volume ratio, classifying trades via the Lee-Ready (1991) tick
// rule with a taker-volume fallback when available. The raw ratio is smoothed,
// z-score normalised over a rolling window, and colour-coded by regime. Static
// session tracking counts consecutive bars in each regime for context-aware
// alerting, and shape markers flag statistically extreme readings.
//
// Academic foundation (exact papers & formulas):
// 1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746.
// [Formula] Classify as buy if close > open (tick rule), else sell.
// Quote-based classification achieves 85–93% accuracy.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
// 2. Ellis, Michaely & O'Hara (2000), "The Accuracy of Trade Classification
// Rules: Evidence from Nasdaq", Journal of Financial and Quantitative
// Analysis, 35(3), 529–551.
// [Formula] Lee-Ready = 81.1% accuracy; tick rule = 77.7%; quote rule = 76.4%.
// Validates classification accuracy bounds for electronic markets.
// DOI: https://doi.org/10.2307/2676235
//
// 3. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", SIAM Journal on Financial Mathematics, 9(2), 487–533.
// [Formula] Regime segmentation: Sell-heavy (−1 to −1/3), Neutral (−1/3 to 1/3),
// Buy-heavy (1/3 to 1). The 1.0 midline with 0.95–1.05 noise band directly
// implements this three-regime framework.
// DOI: https://doi.org/10.1137/17M1152916
//
// 4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", Journal of Financial Economics, 65(1), 111–130.
// [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
// return reversals. Underpins the z-score standardisation design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
// 5. Korean Derivatives Association (2015), "Order Imbalance and Return
// Predictability". Order imbalance ratio = (buy − sell) / (buy + sell);
// predicts 5-, 10-, 20-minute future returns. The BSVR ratio is structurally
// identical (inverted), validating directional-bias interpretation.
//
// 6. 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}; linear
// price-impact coefficient ∝ 1/depth. Supports volume-imbalance signals.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
// ============================================================================
define(title="Buy Sell Volume Ratio V2", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Computation --
var maLen = input(name="maLen", type="number", defaultValue=5, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var useEma = input(name="useEma", type="boolean", defaultValue=true, label="Use EMA (off = SMA)", group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Regime Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Z-Score Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")
// -- Display --
var showRawRatio = input(name="showRawRatio", type="boolean", defaultValue=true, label="Show Raw Ratio Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Z-Score Bars", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showMid = input(name="showMid", type="boolean", defaultValue=true, label="Show 1.0 Midline", group="Display")
var showBand = input(name="showBand", type="boolean", defaultValue=true, label="Show 0.95 / 1.05 Band", group="Display")
// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var rawColor = input(name="rawColor", type="color", defaultValue="#2962ff", label="Raw Ratio Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = bars.open
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Lee-Ready (1991) tick test with taker-volume fallback --
// When taker.buy/sell is available, prefer the direct feed for higher accuracy.
// Lee-Ready fallback: close > open → buyer-initiated; else seller-initiated.
// We also use the proportional range method (upW/range, dnW/range) for finer
// classification when the bar has a non-zero range.
timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)
// Taker-volume fallback classification
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)
// Guard against NaN on volume classification
if (isnan(buyVol[0]) || isnan(selVol[0])) {
buyVol = v * 0.5
selVol = v * 0.5
}
// -- 3.2 Buy/Sell Volume Ratio (BSVR) --
// BSVR = buy volume / sell volume. 1.0 = equilibrium.
// Guard: if selVol == 0, emit 1.0 to prevent division-by-zero.
timeseries ratio = (selVol > 0) ? (buyVol / selVol) : 1.0
timeseries sm = useEma ? ema(ratio, maLen) : sma(ratio, maLen)
// -- 3.3 Z-score normalisation of the smoothed ratio --
// Z_t = (sm_t − μ_t) / σ_t, where μ_t = SMA(sm, W), σ_t = StDev(sm, W).
// Guard: if σ_t == 0, emit 0 to prevent division-by-zero crashes.
timeseries ratioMean = sma(sm, zWindow)
timeseries ratioStd = stdev(sm, zWindow)
timeseries ratioZ = (ratioStd > 0) ? (sm - ratioMean) / ratioStd : 0
// -- 3.4 Regime detection (configurable thresholds, no magic numbers) --
var bullishRegime = ratioZ > divThreshold
var bearishRegime = ratioZ < -divThreshold
var extremeBull = ratioZ > extremeDiv
var extremeBear = ratioZ < -extremeDiv
var neutralRegime = !bullishRegime && !bearishRegime
// -- 3.5 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0
if (bullishRegime) {
bullBars = bullBars + 1
bearBars = 0
neutralBars = 0
lastRegime = 1
} else if (bearishRegime) {
bearBars = bearBars + 1
bullBars = 0
neutralBars = 0
lastRegime = -1
} else {
neutralBars = neutralBars + 1
bullBars = 0
bearBars = 0
lastRegime = 0
}
// -- 3.6 Zero-line helper for fill areas --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------
// 4.1 Raw BSVR line (plotLine)
if (showRawRatio) {
plotLine(
value=sm,
width=2,
colors=[rawColor],
label=["BSVR"],
desc=["Buy / Sell volume ratio: >1 buyers in control, <1 sellers in control"]
)
}
// 4.2 Z-score line with regime colour coding (plotLine)
if (showZScore) {
timeseries zColor = bullishRegime ? bullColor : (bearishRegime ? bearColor : neutralColor)
plotLine(
value=ratioZ,
width=2,
colors=[zColor],
label=["BSVR Z-Score"],
desc=["Rolling-window z-score of BSVR; mean-reverting around 0"]
)
}
// 4.3 Z-score histogram with fill area (plotLine + fill)
// colorIndex maps: 0 = bullish, 1 = bearish, 2 = neutral
timeseries zColorIdx = bullishRegime ? 0 : (bearishRegime ? 1 : 2)
if (showBars) {
plotLine(
value=([ratioZ, zeroLine]),
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=zColorIdx,
label=["BSVR Z-Score Bars"],
desc=["Z-score histogram colour-coded by regime: bull / bear / neutral"],
fill=true
)
}
// 4.4 Z-score bars (plotBar) — sign-based colouring
if (showBars) {
plotBar(
value=ratioZ,
colors=[bullColor, bearColor, neutralColor],
colorIndex=zColorIdx,
width=1,
label=["BSVR Z-Score"],
desc=["Z-score of BSVR as bars; positive = buy dominance, negative = sell dominance"]
)
}
// 4.5 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
plotShape(
value=extremeDiv,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Extreme Bull"],
desc=["Buy volume massively outpacing sell volume; potential buying climax / absorption"]
)
}
if (showShapes && extremeBear) {
plotShape(
value=-extremeDiv,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Extreme Bear"],
desc=["Sell volume massively outpacing buy volume; potential selling climax / distribution"]
)
}
// 4.6 Reference lines (hline)
if (showMid) {
hline(value=1.0, color="#ffffff80", width=1)
}
if (showBand) {
hline(value=1.05, color="#ffffff30", width=1)
hline(value=0.95, color="#ffffff30", width=1)
}
// 4.7 Z-score reference thresholds
hline(value=0, color="#ffffff40", width=1)
hline(value=divThreshold, color="#ffffff20", width=1)
hline(value=-divThreshold, color="#ffffff20", width=1)
hline(value=extremeDiv, color="#ffffff15", width=1)
hline(value=-extremeDiv, color="#ffffff15", width=1)
// 4.8 Regime summary table (last bar only)
if (isLastBar) {
var regimeText = bullishRegime ? "BULLISH" : (bearishRegime ? "BEARISH" : "NEUTRAL")
var regimeTextColor = bullishRegime ? bullColor : (bearishRegime ? bearColor : neutralColor)
plotTable(
data=[
["BSVR V2 — Regime", regimeText],
["Raw Ratio", sm[0]],
["Z-Score", ratioZ[0]],
["Bull Bars", bullBars],
["Bear Bars", bearBars],
["Midline", "1.0"],
["Noise Band", "0.95 – 1.05"]
],
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
)
}