Perfected FlowScript
VSA Better Volume
VSA Better Volume V2 is indexed as 209_vsa_better_volume.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
18.9 KB
Lines
444
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Buying Climax
line 350:9
Trigger
(showShapes) && (buyingClimax)
Value
vol
Deps
buyingClimax:timeseries, showShapes:input
Selling Climax
line 362:9
Trigger
(showShapes) && (sellingClimax)
Value
vol
Deps
sellingClimax:timeseries, showShapes:input
Absorption
line 374:9
Trigger
(showShapes) && (absorption)
Value
vol
Deps
absorption:timeseries, showShapes:input
Churn
line 386:9
Trigger
(showShapes) && (churn)
Value
vol
Deps
churn:timeseries, showShapes:input
Climax Churn
line 398:9
Trigger
(showShapes) && (climaxChurn)
Value
vol
Deps
climaxChurn:timeseries, showShapes:input
Vol Anomaly
line 410:9
Trigger
(showShapes) && (volAnomaly and !buyingClimax and !sellingClimax and !climaxChurn)
Value
vol
Deps
buyingClimax:timeseries, climaxChurn:timeseries, sellingClimax:timeseries, showShapes:input, volAnomaly:timeseries
Bull Conviction
line 422:9
Trigger
(showShapes) && (bullishConviction and !buyingClimax)
Value
vol * 0.5
Deps
bullishConviction:timeseries, buyingClimax:timeseries, showShapes:input
Bear Conviction
line 434:9
Trigger
(showShapes) && (bearishConviction and !sellingClimax)
Value
vol * 0.5
Deps
bearishConviction:timeseries, sellingClimax:timeseries, showShapes:input
209_vsa_better_volume.flowscript
source path: kscripts/perfected/209_vsa_better_volume.flowscript · sha256:e6080337762babac785eda757bf205434199cf179a9e1aa849cece6d44373d39
//@version=2
// ============================================================================
// VSA Better Volume V2 — Production-Quality Volume Spread Analysis
// Author: T (@taiwoso21) | Perfected by: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #Volume, #VSA, #spread, #anomaly, #wyckoff, #microstructure
//
// Volume Spread Analysis (VSA) indicator classifying volume bars into six
// signal types with z-score anomaly detection, spread analysis, and regime
// detection. Based on Wyckoff's "Effort vs Result" and Steidlmayer's Market
// Profile, enhanced with modern microstructure research.
//
// FORMULA FOUNDATION:
// 1. Six Signal Types (Wyckoff/Steidlmayer tradition):
// • Buying Climax: climax + upBar + wideRange (distribution at highs)
// • Selling Climax: climax + downBar + wideRange (accumulation at lows)
// • Absorption/Churn: highVol + narrowRange (effort without result)
// • Climax Churn: climax + narrowRange (both climax + churn)
// • Low Volume: vol < volMA × lowMult (disinterest, congestion)
// • Normal: everything else
// 2. Z-Score Volume Anomaly: z_t = (vol_t − μ_vol) / σ_vol per Zhao & Palomar (2018).
// Flags statistically extreme volume events that deviate from recent norms.
// 3. Spread Analysis: bodyRatio = |close − open| / (high − low). Close position
// within the bar reveals who won the battle (close near high = bulls won).
// 4. Volume-Price Divergence: high volume + small spread = absorption per
// Bouchaud, Farmer & Lillo (2009) liquidity memory framework.
// 5. Wyckoff Law of "Effort vs Result": volume (effort) should confirm price
// movement (result). Divergence signals turning points.
//
// RESEARCH BASIS:
// • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Handbook of Financial Markets. "Liquidity memory time"
// explains why large volume may not move price (absorption); temporary
// liquidity depletion creates sublinear impact. Directly motivates the
// absorption/churn detection logic.
// • Steidlmayer & Hawkins (1986/2003), "Steidlmayer on Markets: Trading with
// Market Profile". Auction market theory; Value Area (~70% of volume),
// POC = price magnet; climax volume at extremes = potential rejection.
// • Wyckoff (1930s), "The Richard D. Wyckoff Method of Trading and Investing
// in Stocks". Law of "Effort vs Result": volume should confirm price.
// Divergence between effort and result signals turning points.
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", J. Financial Economics 65(1), 111–130. Extreme volume
// imbalances predict return reversals; directly supports climax detection.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE Trans. Signal Processing. z-score event triggers at Δ = d × σ_z
// for anomaly detection and statistical significance.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. Volume without price movement
// signals deep liquidity absorption rather than directional commitment.
// ============================================================================
define(
title="VSA Better Volume V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Volume Classification ---
var volMaLen = input(name="volMaLen", type="number", defaultValue=20, label="Volume MA Length", constraints={min: 5, max: 100, step: 1}, group="Volume")
var rangeMaLen = input(name="rangeMaLen", type="number", defaultValue=20, label="Range MA Length", constraints={min: 5, max: 100, step: 1}, group="Volume")
var highVolMult = input(name="highVolMult", type="number", defaultValue=1.5, label="High Volume Threshold (x MA)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Volume")
var lowVolMult = input(name="lowVolMult", type="number", defaultValue=0.5, label="Low Volume Threshold (x MA)", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Volume")
var climaxMult = input(name="climaxMult", type="number", defaultValue=2.0, label="Climax Threshold (x MA)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Volume")
// --- Z-Score & Anomaly ---
var volZWindow = input(name="volZWindow", type="number", defaultValue=50, label="Volume Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Anomaly")
var spreadZWindow = input(name="spreadZWindow", type="number", defaultValue=50, label="Spread Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Anomaly")
var anomalyThresh = input(name="anomalyThresh", type="number", defaultValue=2.0, label="Anomaly Threshold (sigma)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Anomaly")
// --- Spread Analysis ---
var bodyWeight = input(name="bodyWeight", type="number", defaultValue=0.7, label="Body/Spread Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Spread")
var showSpreadLine = input(name="showSpreadLine", type="boolean", defaultValue=true, label="Show Spread Ratio Line", group="Spread")
// --- Display ---
var showVolMA = input(name="showVolMA", type="boolean", defaultValue=true, label="Show Volume MA", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Volume Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Signal Shapes", group="Display")
var showClassified = input(name="showClassified", type="boolean", defaultValue=true, label="Show Classified Volume", group="Display")
var showAnomalyBand = input(name="showAnomalyBand", type="boolean", defaultValue=true, label="Show Anomaly Bands", group="Display")
// --- Colors ---
var climaxColor = input(name="climaxColor", type="color", defaultValue="#ef5350", label="Buying Climax Color", group="Colors")
var climaxSellColor = input(name="climaxSellColor", type="color", defaultValue="#ffffff", label="Selling Climax Color", group="Colors")
var absorbColor = input(name="absorbColor", type="color", defaultValue="#26a69a", label="Absorption Color", group="Colors")
var churnColor = input(name="churnColor", type="color", defaultValue="#9c27b0", label="Churn Color", group="Colors")
var lowVolColor = input(name="lowVolColor", type="color", defaultValue="#ffeb3b", label="Low Volume Color", group="Colors")
var normalColor = input(name="normalColor", type="color", defaultValue="#2962ff", label="Normal Color", group="Colors")
var anomalyColor = input(name="anomalyColor", type="color", defaultValue="#ff9100", label="Anomaly Color", group="Colors")
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Up Volume Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Down Volume Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Volume Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(currentSymbol, currentExchange)
// NaN guard — prevent execution before data is loaded
if (isnan(bars.close[0])) {
return
}
// ------------------------------------------------------------------------------
// Volume Classification (Wyckoff/Steidlmayer six-type framework)
// ------------------------------------------------------------------------------
timeseries vol = bars.volume
timeseries volMA = sma(source=vol, period=volMaLen)
timeseries range = bars.high - bars.low
timeseries rangeMA = sma(source=range, period=rangeMaLen)
timeseries upBar = bars.close >= bars.open
// Volume classification thresholds
timeseries highVol = vol > volMA * highVolMult
timeseries lowVol = vol < volMA * lowVolMult
timeseries climax = vol > volMA * climaxMult
timeseries wideRange = range > rangeMA
timeseries narrowRange = range < rangeMA
// Six signal types (Wyckoff/Steidlmayer)
timeseries buyingClimax = climax and upBar and wideRange
timeseries sellingClimax = climax and not upBar and wideRange
timeseries absorption = highVol and narrowRange and upBar
timeseries churn = highVol and narrowRange and not upBar
timeseries climaxChurn = climax and narrowRange
// ------------------------------------------------------------------------------
// Z-Score Volume Anomaly Detection (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z_t = (vol_t − μ_vol) / σ_vol flags statistically extreme volume events.
timeseries volMean = sma(vol, volZWindow)
timeseries volStd = stdev(vol, volZWindow)
timeseries volZ = (volStd > 0) ? (vol - volMean) / volStd : 0.0
// Spread z-score: how unusual is today's spread relative to recent history
timeseries spreadMean = sma(range, spreadZWindow)
timeseries spreadStd = stdev(range, spreadZWindow)
timeseries spreadZ = (spreadStd > 0) ? (range - spreadMean) / spreadStd : 0.0
// Volume anomaly: volume is extreme but spread is compressed = absorption signal
// Volume anomaly: volume is extreme with wide spread = climax signal
timeseries volAnomaly = volZ > anomalyThresh
timeseries spreadAnomaly = spreadZ > anomalyThresh
timeseries absorptionAnomaly = volAnomaly and spreadZ < 0 // high volume, compressed spread
// ------------------------------------------------------------------------------
// Spread Analysis (Body-to-Range Ratio & Close Position)
// ------------------------------------------------------------------------------
// Body ratio reveals how much of the bar's range was "decisive" (body vs wicks).
// Close position reveals who won the intra-bar battle.
timeseries body = math.abs(bars.close - bars.open)
timeseries bodyRatio = range > 0 ? body / range : 0.0
timeseries closePos = range > 0 ? (bars.close - bars.low) / range : 0.5
// Spread regime: wide spread + small body = indecision (doji-like)
// wide spread + large body + close near high = bullish conviction
// wide spread + large body + close near low = bearish conviction
timeseries bullishConviction = bodyRatio > 0.6 and closePos > 0.7 and upBar
timeseries bearishConviction = bodyRatio > 0.6 and closePos < 0.3 and not upBar
timeseries indecision = bodyRatio < 0.3 and range > rangeMA
// ------------------------------------------------------------------------------
// Regime Detection & Scoring
// ------------------------------------------------------------------------------
// Composite VSA score combining volume anomaly, spread regime, and conviction.
// Positive = bullish pressure structure; negative = bearish pressure structure.
timeseries vsaScore = 0.0
if (buyingClimax) {
vsaScore = vsaScore + 2.0
} else if (sellingClimax) {
vsaScore = vsaScore - 2.0
} else if (absorption) {
vsaScore = vsaScore + 1.0
} else if (churn) {
vsaScore = vsaScore - 1.0
} else if (climaxChurn) {
vsaScore = vsaScore + (upBar ? 1.5 : -1.5)
} else if (lowVol) {
vsaScore = vsaScore + (upBar ? 0.3 : -0.3)
}
// Add volume z-score contribution (normalized to ±1 range)
vsaScore = vsaScore + (volZ > 2.0 ? 1.0 : (volZ < -2.0 ? -1.0 : volZ / 2.0))
// Smooth the score for regime stability
timeseries vsaScoreSmooth = ema(vsaScore, 3)
// Regime classification
timeseries bullRegime = vsaScoreSmooth > 1.0
timeseries bearRegime = vsaScoreSmooth < -1.0
timeseries neutralRegime = !bullRegime and !bearRegime
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks signal type counts, anomaly events, and session extremes.
static buyingClimaxCount = 0
static sellingClimaxCount = 0
static absorptionCount = 0
static churnCount = 0
static climaxChurnCount = 0
static lowVolCount = 0
static normalCount = 0
static anomalyCount = 0
static lastBarIndex = 0
static sessionHighVol = 0.0
static sessionHighVolZ = -999999.0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (buyingClimax) {
buyingClimaxCount = buyingClimaxCount + 1
} else if (sellingClimax) {
sellingClimaxCount = sellingClimaxCount + 1
} else if (absorption) {
absorptionCount = absorptionCount + 1
} else if (churn) {
churnCount = churnCount + 1
} else if (climaxChurn) {
climaxChurnCount = climaxChurnCount + 1
} else if (lowVol) {
lowVolCount = lowVolCount + 1
} else {
normalCount = normalCount + 1
}
if (volAnomaly) {
anomalyCount = anomalyCount + 1
}
if (vol > sessionHighVol) {
sessionHighVol = vol
}
if (volZ > sessionHighVolZ) {
sessionHighVolZ = volZ
}
}
// ------------------------------------------------------------------------------
// Color Assignment — Regime-coded for plotLine and plotBar
// ------------------------------------------------------------------------------
// Signal color mapping for classified volume
timeseries signalColor = normalColor
if (buyingClimax) {
signalColor = climaxColor
} else if (sellingClimax) {
signalColor = climaxSellColor
} else if (absorption) {
signalColor = absorbColor
} else if (churn) {
signalColor = churnColor
} else if (climaxChurn) {
signalColor = churnColor
} else if (lowVol) {
signalColor = lowVolColor
}
// Color index for multi-color plotLine (0=bull, 1=bear, 2=neutral, 3=anomaly)
timeseries colorIdx = neutralRegime ? 2 : (bullRegime ? 0 : 1)
if (volAnomaly) {
colorIdx = 3
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, HLine, Fill)
// ------------------------------------------------------------------------------
// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
// Anomaly bands (±2σ reference)
if (showAnomalyBand) {
hline(value=anomalyThresh, color=opacity(anomalyColor, 20), width=1)
hline(value=-anomalyThresh, color=opacity(anomalyColor, 20), width=1)
hline(value=0, color="#ffffff20", width=1)
}
// 1. Classified Volume Bars (plotBar) — the core VSA display
if (showClassified) {
plotBar(
value=vol,
colors=[signalColor, signalColor],
width=1,
label=["Volume (VSA)"],
desc=["Volume classified by VSA type: climax=red/white, absorption=green, churn=purple, low=yellow, normal=blue"]
)
}
// 2. Volume MA line (reference)
if (showVolMA) {
plotLine(
value=volMA,
width=1,
colors=["#ffffff"],
label=["Volume MA"],
desc=["Volume moving average — reference for volume classification thresholds"]
)
}
// 3. Volume Z-Score line (statistical anomaly detection)
if (showZScore) {
plotLine(
value=volZ,
width=2,
colors=[upColor, dnColor, neutralColor, anomalyColor],
colorIndex=colorIdx,
label=["Volume Z-Score"],
desc=["Volume z-score: ±2σ = significant, ±3σ = extreme; colored by regime and anomaly"]
)
}
// 4. VSA Score line (composite pressure)
plotLine(
value=vsaScoreSmooth,
width=2,
colors=[upColor, dnColor, neutralColor],
colorIndex=bullRegime ? 0 : (bearRegime ? 1 : 2),
label=["VSA Score"],
desc=["Composite VSA score: volume type + z-score + spread regime. Positive=bullish pressure structure."],
fill=true
)
// 5. Spread ratio line (body-to-range)
if (showSpreadLine) {
plotLine(
value=bodyRatio,
width=1,
colors=["#9e9e9e"],
label=["Body/Range Ratio"],
desc=["Body-to-range ratio: >0.6 = decisive, <0.3 = indecision/wicks dominate"]
)
}
// 6. Signal shapes (Wyckoff/Steidlmayer event markers)
if (showShapes) {
// Buying climax shape — potential distribution at highs
if (buyingClimax) {
plotShape(
value=vol,
shape="diamond",
color=climaxColor,
width=4,
label=["Buying Climax"],
desc=["Buying climax: extreme volume + wide range + up close — potential distribution at highs (Wyckoff)"]
)
}
// Selling climax shape — potential accumulation at lows
if (sellingClimax) {
plotShape(
value=vol,
shape="diamond",
color=climaxSellColor,
width=4,
label=["Selling Climax"],
desc=["Selling climax: extreme volume + wide range + down close — potential accumulation at lows (Wyckoff)"]
)
}
// Absorption shape — effort without result
if (absorption) {
plotShape(
value=vol,
shape="triangleup",
color=absorbColor,
width=3,
label=["Absorption"],
desc=["Absorption: high volume + narrow range + up close — hidden demand absorbing supply (Bouchaud et al. 2009)"]
)
}
// Churn shape — distribution/rotation
if (churn) {
plotShape(
value=vol,
shape="triangledown",
color=churnColor,
width=3,
label=["Churn"],
desc=["Churn: high volume + narrow range + down close — hidden supply absorbing demand"]
)
}
// Climax churn shape — maximum effort, minimal result
if (climaxChurn) {
plotShape(
value=vol,
shape="square",
color=churnColor,
width=4,
label=["Climax Churn"],
desc=["Climax churn: extreme volume + narrow range — both climax AND churn; highest probability turning point"]
)
}
// Volume anomaly shape — statistical extreme
if (volAnomaly and !buyingClimax and !sellingClimax and !climaxChurn) {
plotShape(
value=vol,
shape="circle",
color=anomalyColor,
width=2,
label=["Vol Anomaly"],
desc=["Volume anomaly: z-score exceeds threshold — statistically unusual volume event"]
)
}
// Bullish conviction shape — strong body, close near high
if (bullishConviction and !buyingClimax) {
plotShape(
value=vol * 0.5,
shape="triangleup",
color=upColor,
width=2,
label=["Bull Conviction"],
desc=["Bullish conviction: large body + close near high — buyers in control"]
)
}
// Bearish conviction shape — strong body, close near low
if (bearishConviction and !sellingClimax) {
plotShape(
value=vol * 0.5,
shape="triangledown",
color=dnColor,
width=2,
label=["Bear Conviction"],
desc=["Bearish conviction: large body + close near low — sellers in control"]
)
}
}