Perfected FlowScript
B/S V
B/S V — Buy/Sell Volume Pressure — Perfected Edition is indexed as 320_b_s_v.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.0 KB
Lines
388
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Buy
line 290:9
Trigger
(showShapes) && (buyPenetrate)
Value
dynUpper
Deps
buyPenetrate:var, showShapes:input
Extreme Sell
line 300:9
Trigger
(showShapes) && (sellPenetrate)
Value
dynLower
Deps
sellPenetrate:var, showShapes:input
Cross Up
line 314:9
Trigger
(showAlerts) && (crossUp)
Value
0
Deps
crossUp:var, showAlerts:input
Cross Down
line 324:9
Trigger
(showAlerts) && (crossDown)
Value
0
Deps
crossDown:var, showAlerts:input
Buy Revert
line 334:9
Trigger
(showAlerts) && (buyRevert)
Value
dynUpper
Deps
buyRevert:var, showAlerts:input
Sell Revert
line 344:9
Trigger
(showAlerts) && (sellRevert)
Value
dynLower
Deps
sellRevert:var, showAlerts:input
320_b_s_v.flowscript
source path: kscripts/perfected/320_b_s_v.flowscript · sha256:b400a4e098b073bd4b6a3fffc79b186e5e3105209fec39165dbbc21192924ef5
//@version=2
// ============================================================================
// B/S V — Buy/Sell Volume Pressure — Perfected Edition
// Author: I (@Iopl147u) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #volume, #buysell, #delta, #pressure, #zscore, #regime
//
// Production-quality buy/sell volume pressure indicator. Classifies each bar
// as buyer- or seller-initiated using a hybrid Lee-Ready (1991) midpoint proxy
// and Bulk Volume Classification (BVC) probabilistic approach, then computes
// net pressure, buy/sell ratio, z-score normalisation, regime detection, and
// visualizes via color-coded histograms, fills, and shape alerts.
//
// Research papers underpinning this design:
// 1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746. Foundational tick-classification
// algorithm (85–93% accuracy): classify as buy if close > quote midpoint,
// else sell. The midpoint proxy is the most robust bar-level estimate.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// 2. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
// Activity", SSRN. BVC uses a probabilistic approach based on the
// distribution of price changes within a bar, superior to tick-rule in HFT.
// URL: https://ssrn.com/abstract=1989555
// 3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// JFE, 12(1), 47–88. [Formula] OFI_t linearly predicts Δp_t. Net aggressive
// order flow (delta) is the primary driver of short-term price changes.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
// 4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", JFE, 65(1), 111–130. Extreme |Imbalance| predicts
// return reversals. Directly motivates the pressure-threshold design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// 5. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
// 53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
// Kyle's λ establishes the linear price-impact coefficient.
// DOI: https://doi.org/10.2307/1913210
// 6. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
// SNDE, 8(3), 1–35. Order flow has long-memory properties (power-law
// autocorrelation decay). Cumulative measures capture sustained pressure.
// URL: https://arxiv.org/abs/cond-mat/0311053
// 7. Hasbrouck (2007), "Empirical Market Microstructure", OUP. Definitive
// text on trade classification, price impact, and VAR models of price
// discovery. Supports the econometric foundations of B/S pressure.
// ============================================================================
define(
title="B/S V — Buy/Sell Volume Pressure — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Classification --
var len = input(name="len", type="number", defaultValue=14, label="Smoothing Window", constraints={min: 2, max: 50, step: 1}, group="Classification")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 5}, group="Classification")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Pressure EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Classification")
// -- Thresholds --
var thr = input(name="thr", type="number", defaultValue=0.0, label="Pressure Threshold (raw)", constraints={min: -1000.0, max: 1000.0, step: 10.0}, group="Thresholds")
var zUpper = input(name="zUpper", type="number", defaultValue=2.0, label="Z Upper Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var zLower = input(name="zLower", type="number", defaultValue=-2.0, label="Z Lower Threshold (σ)", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var useDynamic = input(name="useDynamic", type="boolean", defaultValue=false, label="Dynamic Thresholds (vol-adjusted)", group="Thresholds")
var volMultiplier = input(name="volMultiplier", type="number", defaultValue=1.0, label="Volatility Multiplier", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
// -- Display --
var showCum = input(name="showCum", type="boolean", defaultValue=true, label="Show Cumulative Pressure", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Per-Bar Buy/Sell", group="Display")
var showZ = input(name="showZ", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showHist = input(name="showHist", type="boolean", defaultValue=true, label="Show Pressure Histogram", group="Display")
var showShapes= input(name="showShapes",type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showAlerts= input(name="showAlerts",type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")
// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Net Buy Pressure", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Net Sell Pressure", group="Colors")
var cumColor = input(name="cumColor", type="color", defaultValue="#ff9800", label="Cumulative Line", group="Colors")
var bullDivColor = input(name="bullDivColor", type="color", defaultValue="#00e676", label="Bullish Alert Color", group="Colors")
var bearDivColor = input(name="bearDivColor", type="color", defaultValue="#ff5252", label="Bearish Alert Color", group="Colors")
var neutralC = input(name="neutralC", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCE & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries vol = bars.volume
timeseries rng = bars.high - bars.low
if (isnan(vol[0]) || isnan(rng[0]) || isnan(bars.close[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Buy/Sell volume classification (hybrid Lee-Ready + BVC) --
// Per Lee & Ready (1991), close vs. midpoint is the most robust bar-level
// classification proxy. We use a fractional allocation: the closer the close
// is to the high, the greater the buy proportion; closer to low → sell.
// Per Easley et al (2012), BVC improves on tick rules in aggregate buckets.
timeseries midPt = (bars.high + bars.low) / 2.0
timeseries closeN = rng > 0 ? (bars.close - midPt) / rng : 0.0
// Buy fraction: 0.5 baseline + position bias (0.5 to 1.0 range)
timeseries buyFrac = math.max(0.0, math.min(1.0, 0.5 + closeN))
timeseries sellFrac = 1.0 - buyFrac
timeseries buyVol = vol * buyFrac
timeseries selVol = vol * sellFrac
// -- 3.2 Net pressure and smoothing --
timeseries netVol = buyVol - selVol
timeseries smooth = ema(netVol, smoothLen)
// -- 3.3 True cumulative pressure (static state) --
// Per Lillo & Farmer (2004), order flow has long memory. Cumulative measures
// capture sustained pressure that drives trends.
static cumPressure = 0.0
if (!isnan(netVol[0])) {
cumPressure = cumPressure + netVol[0]
}
// -- 3.4 Buy/Sell ratio --
// Ratio > 1 indicates buy dominance; < 1 indicates sell dominance.
timeseries bsRatio = selVol > 0 ? buyVol / selVol : 1.0
timeseries bsRatioSm = ema(bsRatio, smoothLen)
// -- 3.5 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (Pressure_t − μ_t) / σ_t. Per Chordia et al (2002), extreme
// imbalances predict return reversals.
timeseries pressMean = sma(smooth, zWindow)
timeseries pressStd = stddev(smooth, zWindow)
timeseries zScore = (pressStd > 0) ? (smooth - pressMean) / pressStd : 0.0
timeseries zSmooth = ema(zScore, smoothLen)
// -- 3.6 Dynamic thresholds (volatility-adjusted) --
// Adjust z-score bands by rolling standard deviation of the pressure.
timeseries zVol = stddev(zSmooth, zWindow)
var dynUpper = useDynamic ? zUpper + zVol * volMultiplier : zUpper
var dynLower = useDynamic ? zLower - zVol * volMultiplier : zLower
// Guard: ensure bands never invert
if (dynUpper <= dynLower) {
dynUpper = 2.0
dynLower = -2.0
}
// -- 3.7 Regime detection --
// Extreme buy pressure: z > upper threshold → potential reversal (overbought)
// Extreme sell pressure: z < lower threshold → potential reversal (oversold)
// Bullish: smooth > 0 and above threshold
// Bearish: smooth < 0 and below threshold
var extremeBuy = zSmooth > dynUpper
var extremeSell = zSmooth < dynLower
var bullishRegime = smooth > 0 && zSmooth > 0
var bearishRegime = smooth < 0 && zSmooth < 0
var neutralRegime = !extremeBuy && !extremeSell
var regimeColor = bullishRegime ? upColor : (bearishRegime ? dnColor : neutralC)
// ---------------------------------------------------------------------------
// 4. STATIC REGIME TRACKING
// ---------------------------------------------------------------------------
// Track consecutive bars in each regime for context-aware alerting.
static bullBars = 0
static bearBars = 0
static lastRegime = 0
if (bullishRegime) {
bullBars = bullBars + 1
bearBars = 0
lastRegime = 1
} else if (bearishRegime) {
bearBars = bearBars + 1
bullBars = 0
lastRegime = -1
} else {
bullBars = 0
bearBars = 0
lastRegime = 0
}
// ---------------------------------------------------------------------------
// 5. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// First-occurrence extreme alerts
var buyPenetrate = zSmooth > dynUpper && zSmooth[1] <= dynUpper[1]
var sellPenetrate = zSmooth < dynLower && zSmooth[1] >= dynLower[1]
// Reversion (exit from extreme zone)
var buyRevert = zSmooth < dynUpper && zSmooth[1] >= dynUpper[1]
var sellRevert = zSmooth > dynLower && zSmooth[1] <= dynLower[1]
// Cross of zero line
var crossUp = smooth > 0 && smooth[1] <= 0
var crossDown = smooth < 0 && smooth[1] >= 0
// ---------------------------------------------------------------------------
// 6. VISUALIZATION
// ---------------------------------------------------------------------------
// 6.1 Zero line
hline(value=0, color="#ffffff20", width=1)
// 6.2 Z-score reference lines
if (showZ) {
hline(value=dynUpper, color=transparency(upColor, 60), width=1)
hline(value=dynLower, color=transparency(dnColor, 60), width=1)
}
// 6.3 Smoothed net pressure (regime-colored, with fill)
plotLine(
value=smooth,
width=2,
colors=[regimeColor],
label=["Net B/S Pressure"],
desc=["EMA-smoothed net buy/sell volume pressure (" + smoothLen + "-period)"]
)
// 6.4 Pressure fill (smooth vs zero line, color-coded)
plotLine(
value=[smooth, 0],
width=1,
colors=[transparency(upColor, 25), transparency(dnColor, 25)],
colorIndex=bullishRegime ? 0 : 1,
fill=true,
label=["Pressure", "Zero"],
desc=["Fill between net pressure and zero line (color-coded by regime)"]
)
// 6.5 Z-score line
if (showZ) {
plotLine(
value=zSmooth,
width=1,
colors=[regimeColor],
label=["Z-Score (Smoothed)"],
desc=["Z-score of pressure vs " + zWindow + "-period distribution (EMA-smoothed)"]
)
}
// 6.6 Pressure histogram (color-coded bars)
if (showHist) {
var histBull = smooth >= 0
plotBar(
value=smooth,
colors=[transparency(upColor, 60), transparency(dnColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Pressure Histogram"],
desc=["Net buy/sell pressure as histogram"]
)
}
// 6.7 Cumulative pressure line
if (showCum) {
plotLine(
value=cumPressure,
width=1,
colors=[cumColor],
label=["Cumulative Pressure"],
desc=["True cumulative buy/sell pressure from first bar (long-memory tracking)"]
)
}
// 6.8 Per-bar buy/sell lines
if (showBars) {
plotLine(
value=[buyVol, selVol],
width=1,
colors=[transparency(upColor, 40), transparency(dnColor, 40)],
label=["Buy Vol", "Sell Vol"],
desc=["Per-bar estimated buy volume (fractional Lee-Ready)", "Per-bar estimated sell volume (fractional Lee-Ready)"]
)
}
// 6.9 Buy/Sell ratio line
plotLine(
value=bsRatioSm,
width=1,
colors=[bsRatioSm > 1.0 ? upColor : (bsRatioSm < 1.0 ? dnColor : neutralC)],
label=["Buy/Sell Ratio"],
desc=["Buy/sell volume ratio (smoothed). >1 = buy dominant; <1 = sell dominant"]
)
// 6.10 Extreme shapes (first penetration)
if (showShapes) {
if (buyPenetrate) {
plotShape(
value=dynUpper,
shape="triangledown",
colorIndex=bearDivColor,
width=3,
label=["Extreme Buy"],
desc=["Extreme buy pressure detected (z > " + dynUpper + ") — potential overbought / distribution"]
)
}
if (sellPenetrate) {
plotShape(
value=dynLower,
shape="triangleup",
colorIndex=bullDivColor,
width=3,
label=["Extreme Sell"],
desc=["Extreme sell pressure detected (z < " + dynLower + ") — potential oversold / accumulation"]
)
}
}
// 6.11 Alert shapes (crossovers, reversion)
if (showAlerts) {
if (crossUp) {
plotShape(
value=0,
shape="circle",
colorIndex=upColor,
width=2,
label=["Cross Up"],
desc=["Net pressure crossed above zero — buying pressure now dominant"]
)
}
if (crossDown) {
plotShape(
value=0,
shape="circle",
colorIndex=dnColor,
width=2,
label=["Cross Down"],
desc=["Net pressure crossed below zero — selling pressure now dominant"]
)
}
if (buyRevert) {
plotShape(
value=dynUpper,
shape="xcross",
colorIndex=upColor,
width=2,
label=["Buy Revert"],
desc=["Extreme buy pressure reverting — mean reversion toward neutral underway"]
)
}
if (sellRevert) {
plotShape(
value=dynLower,
shape="xcross",
colorIndex=dnColor,
width=2,
label=["Sell Revert"],
desc=["Extreme sell pressure reverting — mean reversion toward neutral underway"]
)
}
}
// ---------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = bullishRegime ? "BULLISH (BUY DOMINANT)" : (bearishRegime ? "BEARISH (SELL DOMINANT)" : "NEUTRAL")
var regimeTextColor = bullishRegime ? upColor : (bearishRegime ? dnColor : neutralC)
var upperText = useDynamic ? "Dynamic Upper: " + dynUpper : "Static Upper: " + zUpper
var lowerText = useDynamic ? "Dynamic Lower: " + dynLower : "Static Lower: " + zLower
plotTable(
data=[
["B/S V — Perfected", regimeText],
["Net Pressure", smooth[0]],
["Z-Score", zSmooth[0]],
["Buy/Sell Ratio", bsRatioSm[0]],
["Cumulative", cumPressure],
[upperText, lowerText],
["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
)
}