Perfected FlowScript
VSA Multi
VSA Multi — Perfected Edition is indexed as 319_vsa_multi.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.7 KB
Lines
379
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Accumulation
line 283:9
Trigger
(showShapes) && (accAlert)
Value
scoreSm
Deps
accAlert:var, showShapes:input
Distribution
line 293:9
Trigger
(showShapes) && (distAlert)
Value
scoreSm
Deps
distAlert:var, showShapes:input
Climactic Up
line 303:9
Trigger
(showShapes) && (exhUpAlert)
Value
scoreSm
Deps
exhUpAlert:var, showShapes:input
Climactic Down
line 313:9
Trigger
(showShapes) && (exhDownAlert)
Value
scoreSm
Deps
exhDownAlert:var, showShapes:input
Vol Spike
line 327:9
Trigger
(showAlerts) && (volAnomalyAlert && volAnomalyHigh)
Value
volZ
Deps
showAlerts:input, volAnomalyAlert:var, volAnomalyHigh:var
Vol Dry
line 337:9
Trigger
(showAlerts) && (volAnomalyAlert && volAnomalyLow)
Value
volZ
Deps
showAlerts:input, volAnomalyAlert:var, volAnomalyLow:var
319_vsa_multi.flowscript
source path: kscripts/perfected/319_vsa_multi.flowscript · sha256:650c3e900ae7a4dbcbcd9ff857b7f191a34bcd4c3548a8f591387b0eeae5dff5
//@version=2
// ============================================================================
// VSA Multi — Perfected Edition
// Author: I (@Iopl147u) | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, #vsa, #volume, #spread, #accumulation, #distribution, #exhaustion
//
// Production-quality Volume Spread Analysis (VSA) multi-factor indicator.
// Analyzes the relationship between volume, price spread (range), and close
// position to detect accumulation, distribution, exhaustion, and no-demand
// patterns. Implements z-score normalization for volume anomaly detection,
// spread analysis with dynamic thresholds, regime tracking via static state,
// and comprehensive color-coded fills, histograms, and shape alerts.
//
// Research papers underpinning this design:
// 1. 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}
// Cumulative OFI (CVD) linearly predicts short-term price changes:
// Δp_t = λ·OFI_t + ε_t. Validates volume-based price impact.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
// 2. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
// Market Profile" (2nd ed.), Wiley. Foundational auction-market theory:
// Value Area (~70% of volume), Point of Control (POC), Initial Balance,
// Responsive vs. Initiative Activity. Directly supports VSA spread analysis.
// 3. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Handbook of Financial Markets, Elsevier.
// "Liquidity memory time" explains the square-root impact law: large
// volume that fails to move price = absorption (liquidity replenishment).
// Volume spikes with follow-through fade = exhaustion (depletion).
// 4. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746. Foundational tick-classification
// (85–93% accuracy). Close > midpoint → buyer-initiated; else sell.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// 5. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
// Activity", SSRN. Bulk Volume Classification (BVC) uses probabilistic
// price-change distribution for robust buy/sell classification in HFT.
// URL: https://ssrn.com/abstract=1989555
// 6. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", JFE, 65(1), 111–130. Extreme |Imbalance| predicts
// return reversals. Directly motivates the volume-anomaly-threshold design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// 7. 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
// ============================================================================
define(
title="VSA Multi — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- VSA Settings --
var len = input(name="len", type="number", defaultValue=20, label="VSA Window", constraints={min: 5, max: 100, step: 1}, group="VSA Settings")
var highVol = input(name="highVol", type="number", defaultValue=1.5, label="High Volume Threshold (× avg)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="VSA Settings")
var narrowSp = input(name="narrowSp", type="number", defaultValue=0.7, label="Narrow Spread Threshold (× avg)", constraints={min: 0.2, max: 1.0, step: 0.1}, group="VSA Settings")
var wideSp = input(name="wideSp", type="number", defaultValue=1.3, label="Wide Spread Threshold (× avg)", constraints={min: 1.0, max: 3.0, step: 0.1}, group="VSA Settings")
var closeTh = input(name="closeTh", type="number", defaultValue=0.6, label="Close Position Threshold", constraints={min: 0.1, max: 0.9, step: 0.05}, group="VSA Settings")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Score EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="VSA Settings")
// -- Thresholds --
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Volume Z-Score Window", constraints={min: 10, max: 200, step: 5}, group="Thresholds")
var accTh = input(name="accTh", type="number", defaultValue=2.0, label="Accumulation Z Threshold", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Thresholds")
var distTh = input(name="distTh", type="number", defaultValue=2.0, label="Distribution Z Threshold", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Thresholds")
// -- Display --
var showScore = input(name="showScore", type="boolean", defaultValue=true, label="Show VSA Score", group="Display")
var showScoreFill = input(name="showScoreFill", type="boolean", defaultValue=true, label="Show Score Fill", 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 Pattern Shapes", group="Display")
var showAlerts = input(name="showAlerts", type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")
var showHist = input(name="showHist", type="boolean", defaultValue=true, label="Show Volume Histogram", group="Display")
// -- Colors --
var accColor = input(name="accColor", type="color", defaultValue="#26a69a", label="Accumulation Color", group="Colors")
var distColor = input(name="distColor", type="color", defaultValue="#ef5350", label="Distribution Color", group="Colors")
var exhColor = input(name="exhColor", type="color", defaultValue="#ff9800", label="Exhaustion Color", group="Colors")
var neutralC = input(name="neutralC", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var volZColor = input(name="volZColor", type="color", defaultValue="#7e57c2", label="Volume Z 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 Volume anomaly detection (z-score normalised) --
// Per Chordia et al (2002), extreme volume imbalances predict return reversals.
// We standardise volume relative to its rolling mean to detect anomalies.
timeseries avgVol = sma(vol, len)
timeseries volMean = sma(vol, zWindow)
timeseries volStd = stddev(vol, zWindow)
timeseries volZ = (volStd > 0) ? (vol - volMean) / volStd : 0.0
timeseries volRatio = avgVol > 0 ? vol / avgVol : 0.0
// -- 3.2 Spread analysis --
// Per Steidlmayer (2003), spread relative to recent average reveals
// initiative vs. responsive activity (wide = initiative/climactic; narrow = responsive/absorption).
timeseries avgRange = sma(rng, len)
timeseries rngRatio = avgRange > 0 ? rng / avgRange : 0.0
// -- 3.3 Close position analysis (Lee-Ready midpoint proxy) --
// Close position: 0 = at low (sellers dominant), 1 = at high (buyers dominant).
// Per Lee & Ready (1991), close vs. midpoint is a robust tick-classification proxy.
timeseries midPt = (bars.high + bars.low) / 2.0
timeseries closePos = rng > 0 ? (bars.close - bars.low) / rng : 0.5
// -- 3.4 Volume-Spread classification (multi-factor regime detection) --
// Accumulation: high volume + narrow spread + close near high = smart money absorbing supply
// Distribution: high volume + narrow spread + close near low = smart money distributing
// Climactic up: high volume + wide spread + close near high = buying climax / exhaustion
// Climactic down: high volume + wide spread + close near low = selling climax / exhaustion
// No demand: low volume + any spread + close near low = lack of buying interest
// No supply: low volume + narrow spread + close near high = lack of selling pressure
var regime = "NEUTRAL"
var score = 0.0
var scoreColor = neutralC
if (volRatio >= highVol && rngRatio <= narrowSp && closePos > closeTh) {
regime = "ACCUMULATION"
score = 2.0
scoreColor = accColor
} else if (volRatio >= highVol && rngRatio <= narrowSp && closePos < (1.0 - closeTh)) {
regime = "DISTRIBUTION"
score = -2.0
scoreColor = distColor
} else if (volRatio >= highVol && rngRatio >= wideSp && closePos > closeTh) {
regime = "CLIMACTIC UP"
score = 1.0
scoreColor = exhColor
} else if (volRatio >= highVol && rngRatio >= wideSp && closePos < (1.0 - closeTh)) {
regime = "CLIMACTIC DOWN"
score = -1.0
scoreColor = exhColor
} else if (volRatio < 1.0 && closePos < (1.0 - closeTh)) {
regime = "NO DEMAND"
score = -0.5
scoreColor = neutralC
} else if (volRatio < 1.0 && rngRatio <= narrowSp && closePos > closeTh) {
regime = "NO SUPPLY"
score = 0.5
scoreColor = neutralC
}
// -- 3.5 Smoothed score for panel display --
timeseries scoreSm = ema(score, smoothLen)
// -- 3.6 Volume z-score regime (independent anomaly detection) --
var volAnomalyHigh = volZ > accTh
var volAnomalyLow = volZ < -distTh
var volNeutral = !volAnomalyHigh && !volAnomalyLow
// -- 3.7 Combined regime (VSA + volume anomaly intersection) --
var combinedBull = (regime == "ACCUMULATION" || regime == "NO SUPPLY") && volAnomalyHigh
var combinedBear = (regime == "DISTRIBUTION" || regime == "NO DEMAND") && volAnomalyHigh
var combinedExhaustion = (regime == "CLIMACTIC UP" || regime == "CLIMACTIC DOWN") && volAnomalyHigh
// ---------------------------------------------------------------------------
// 4. STATIC REGIME TRACKING
// ---------------------------------------------------------------------------
// Track consecutive bars in each pattern for context-aware alerting.
static accBars = 0
static distBars = 0
static exhBars = 0
static lastPattern = "NEUTRAL"
if (regime == "ACCUMULATION" || regime == "NO SUPPLY") {
accBars = accBars + 1
distBars = 0
exhBars = 0
lastPattern = "ACCUM"
} else if (regime == "DISTRIBUTION" || regime == "NO DEMAND") {
distBars = distBars + 1
accBars = 0
exhBars = 0
lastPattern = "DIST"
} else if (regime == "CLIMACTIC UP" || regime == "CLIMACTIC DOWN") {
exhBars = exhBars + 1
accBars = 0
distBars = 0
lastPattern = "EXH"
} else {
accBars = 0
distBars = 0
exhBars = 0
lastPattern = "NEUTRAL"
}
// ---------------------------------------------------------------------------
// 5. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// First-occurrence pattern alerts
var accAlert = (regime == "ACCUMULATION" && accBars == 1)
var distAlert = (regime == "DISTRIBUTION" && distBars == 1)
var exhUpAlert = (regime == "CLIMACTIC UP" && exhBars == 1)
var exhDownAlert = (regime == "CLIMACTIC DOWN" && exhBars == 1)
var volAnomalyAlert = (volAnomalyHigh || volAnomalyLow) && volNeutral[1]
// ---------------------------------------------------------------------------
// 6. VISUALIZATION
// ---------------------------------------------------------------------------
// 6.1 Zero line
hline(value=0, color="#ffffff20", width=1)
// 6.2 Volume z-score reference lines
if (showZScore) {
hline(value=accTh, color=transparency(accColor, 60), width=1)
hline(value=-distTh, color=transparency(distColor, 60), width=1)
}
// 6.3 VSA Score line (regime-colored, with fill)
if (showScore) {
var scoreColorIdx = combinedBull ? 0 : (combinedBear ? 1 : (combinedExhaustion ? 2 : 3))
plotLine(
value=scoreSm,
width=2,
colors=[accColor, distColor, exhColor, neutralC],
colorIndex=scoreColorIdx,
label=["VSA Score"],
desc=["Smoothed VSA score — positive = bullish pressure, negative = bearish pressure"]
)
}
// 6.4 Score fill (score vs zero line)
if (showScore && showScoreFill) {
var fillBull = scoreSm >= 0
plotLine(
value=[scoreSm, 0],
width=1,
colors=[transparency(accColor, 25), transparency(distColor, 25)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Score", "Zero"],
desc=["Fill between VSA score and zero line"]
)
}
// 6.5 Volume z-score line
if (showZScore) {
var volZColorIdx = volAnomalyHigh ? 0 : (volAnomalyLow ? 1 : 2)
plotLine(
value=volZ,
width=1,
colors=[transparency(volZColor, 80), transparency(neutralC, 50), transparency(neutralC, 50)],
colorIndex=volZColorIdx,
label=["Volume Z-Score"],
desc=["Volume z-score (" + zWindow + "-period) — detects volume anomalies"]
)
}
// 6.6 Volume histogram (bars)
if (showHist) {
var volHistBull = volRatio >= highVol
plotBar(
value=volRatio,
colors=[transparency(accColor, 50), transparency(neutralC, 30)],
colorIndex=volHistBull ? 0 : 1,
width=1,
label=["Volume Ratio"],
desc=["Volume relative to " + len + "-period average (× avg)"]
)
}
// 6.7 Pattern shapes (first-occurrence only)
if (showShapes) {
if (accAlert) {
plotShape(
value=scoreSm,
shape="triangleup",
colorIndex=accColor,
width=3,
label=["Accumulation"],
desc=["Accumulation detected: high volume + narrow spread + close near high — smart money absorbing supply"]
)
}
if (distAlert) {
plotShape(
value=scoreSm,
shape="triangledown",
colorIndex=distColor,
width=3,
label=["Distribution"],
desc=["Distribution detected: high volume + narrow spread + close near low — smart money distributing"]
)
}
if (exhUpAlert) {
plotShape(
value=scoreSm,
shape="arrowup",
colorIndex=exhColor,
width=2,
label=["Climactic Up"],
desc=["Buying climax: high volume + wide spread + close near high — potential exhaustion"]
)
}
if (exhDownAlert) {
plotShape(
value=scoreSm,
shape="arrowdown",
colorIndex=exhColor,
width=2,
label=["Climactic Down"],
desc=["Selling climax: high volume + wide spread + close near low — potential exhaustion"]
)
}
}
// 6.8 Alert shapes (volume anomaly)
if (showAlerts) {
if (volAnomalyAlert && volAnomalyHigh) {
plotShape(
value=volZ,
shape="circle",
colorIndex=volZColor,
width=2,
label=["Vol Spike"],
desc=["Volume anomaly: z-score > " + accTh + " — significant volume surge detected"]
)
}
if (volAnomalyAlert && volAnomalyLow) {
plotShape(
value=volZ,
shape="circle",
colorIndex=neutralC,
width=2,
label=["Vol Dry"],
desc=["Volume dry-up: z-score < " + (-distTh) + " — unusually low volume detected"]
)
}
}
// ---------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeTextColor = combinedBull ? accColor : (combinedBear ? distColor : (combinedExhaustion ? exhColor : neutralC))
plotTable(
data=[
["VSA Multi — Perfected", regime],
["VSA Score", scoreSm[0]],
["Volume Ratio", volRatio[0]],
["Spread Ratio", rngRatio[0]],
["Close Pos", closePos[0]],
["Volume Z", volZ[0]],
["Acc Bars", accBars],
["Dist Bars", distBars],
["Exh Bars", exhBars]
],
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
)
}