Perfected FlowScript
Volume Suite • [Leviathan]
Volume Suite [Leviathan] — Perfected is indexed as 026_volume_suite_leviathan.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.8 KB
Lines
545
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Delta Extreme Buy
line 464:13
Trigger
(showShapes) && (!isnan(deltaSmooth) && !isnan(deltaSmooth[1])) && (deltaHighCross)
Value
deltaSmooth
Deps
deltaHighCross:var, deltaSmooth:var, showShapes:input
Delta Extreme Sell
line 474:13
Trigger
(showShapes) && (!isnan(deltaSmooth) && !isnan(deltaSmooth[1])) && (deltaLowCross)
Value
deltaSmooth
Deps
deltaLowCross:var, deltaSmooth:var, showShapes:input
RVOL Spike
line 491:13
Trigger
(showShapes) && (!isnan(rvolSmooth) && !isnan(rvolSmooth[1])) && (rvolHighCross)
Value
rvolSmooth
Deps
rvolHighCross:var, rvolSmooth:var, showShapes:input
RVOL Low
line 501:13
Trigger
(showShapes) && (!isnan(rvolSmooth) && !isnan(rvolSmooth[1])) && (rvolLowCross)
Value
rvolSmooth
Deps
rvolLowCross:var, rvolSmooth:var, showShapes:input
026_volume_suite_leviathan.flowscript
source path: kscripts/perfected/026_volume_suite_leviathan.flowscript · sha256:58a548c2e438ee079e5e4ffc986a7eecb8fe0a257369c9f2c0b3a1079b63542d
//@version=2
// ============================================================================
// Volume Suite [Leviathan] — Perfected Edition
// Author: Leviathan (@Leviathan) | Perfected by: kScript Perfection Engineer
// Tags: CORE, ADVANCED, #volumesuite, #leviathan, #volume, #delta, #cvd, #obv
//
// Production-quality multi-metric volume dashboard displaying Volume Delta, CVD,
// Buy & Sell Volume, Relative Volume, Cumulative Relative Volume, and OBV — all
// simultaneously in a unified visual. Each metric has threshold-based coloring,
// toggle switches, and optional shapes for extreme events. Includes cumulative
// measure anchoring, session tracking, and regime detection.
//
// FORMULA FOUNDATION:
// 1. Volume Delta = Buy Volume − Sell Volume per Lee & Ready (1991) tick
// classification; BVC refinement per Easley, López de Prado & O'Hara (2012).
// 2. CVD = Cumulative Volume Delta (running sum) per Cont, Kukanov & Stoikov
// (2014); long-memory properties justify cumulative over per-bar (Lillo &
// Farmer 2004).
// 3. Relative Volume = Current Volume / SMA(Volume, lookback) per Steidlmayer
// (1986/2003) Market Profile "excess volume" concept.
// 4. OBV = Σ(sgn(ΔPrice) × Volume) per Granville (1963); volume precedes price.
//
// RESEARCH BASIS:
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// JF 46(2), 733–746. Foundational trade classification; ~85–93% accuracy.
// • Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
// Activity", SSRN. BVC method improves robustness in HFT environments.
// • Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
// OFI linearly predicts price changes; validates delta as a signal.
// • Lillo & Farmer (2004), SNDE 8(3), 1–35. Order flow long-memory justifies
// cumulative measures (CVD, CumRV) as more informative than per-bar.
// • Steidlmayer & Hawkins (1986/2003), "Steidlmayer on Markets: Trading with
// Market Profile". Value Area, POC, and excess volume concepts.
// • Chordia, Roll & Subrahmanyam (2002), JFE 65(1), 111–130. Extreme order
// imbalances predict return reversals; supports threshold-based alerts.
// • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand", Handbook of Financial Markets. Square-root impact law
// and liquidity memory inform absorption/exhaustion detection.
// ============================================================================
define(
title="Volume Suite [Leviathan] — Perfected",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// 1. USER INPUTS — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Lookback & Smoothing ---
var rvolLen = input(
name="rvolLen",
type="number",
defaultValue=20,
label="RVOL / SMA Lookback",
constraints={min: 5, max: 100, step: 1},
group="Lookback"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="EMA Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Lookback"
)
var cvdReset = input(
name="cvdReset",
type="boolean",
defaultValue=false,
label="Reset CVD on New Session",
group="Lookback"
)
// --- Thresholds ---
var deltaHighThresh = input(
name="deltaHighThresh",
type="number",
defaultValue=1.0,
label="Delta High Threshold (× avg)",
constraints={min: 0.5, max: 10.0, step: 0.1},
group="Thresholds"
)
var deltaLowThresh = input(
name="deltaLowThresh",
type="number",
defaultValue=-1.0,
label="Delta Low Threshold (× avg)",
constraints={min: -10.0, max: -0.5, step: 0.1},
group="Thresholds"
)
var rvolHighThresh = input(
name="rvolHighThresh",
type="number",
defaultValue=2.0,
label="RVOL High Threshold (× avg)",
constraints={min: 1.0, max: 10.0, step: 0.1},
group="Thresholds"
)
var rvolLowThresh = input(
name="rvolLowThresh",
type="number",
defaultValue=0.5,
label="RVOL Low Threshold (× avg)",
constraints={min: 0.1, max: 1.0, step: 0.1},
group="Thresholds"
)
// --- Display Toggles ---
var showDelta = input(
name="showDelta",
type="boolean",
defaultValue=true,
label="Show Volume Delta",
group="Display"
)
var showCvd = input(
name="showCvd",
type="boolean",
defaultValue=true,
label="Show CVD",
group="Display"
)
var showBuySell = input(
name="showBuySell",
type="boolean",
defaultValue=true,
label="Show Buy & Sell Volume",
group="Display"
)
var showRvol = input(
name="showRvol",
type="boolean",
defaultValue=true,
label="Show Relative Volume",
group="Display"
)
var showCumRvol = input(
name="showCumRvol",
type="boolean",
defaultValue=true,
label="Show Cumulative RVOL",
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-Event Shapes",
group="Display"
)
var showGuides = input(
name="showGuides",
type="boolean",
defaultValue=true,
label="Show Guide Lines",
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bullish / Buy Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bearish / Sell Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var extremeColor = input(
name="extremeColor",
type="color",
defaultValue="#ffca28",
label="Extreme Event Color",
group="Colors"
)
var rvolColor = input(
name="rvolColor",
type="color",
defaultValue="#42a5f5",
label="RVOL Color",
group="Colors"
)
var obvColor = input(
name="obvColor",
type="color",
defaultValue="#ab47bc",
label="OBV Color",
group="Colors"
)
// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
// NaN guard — prevent execution before data is loaded (Lee & Ready 1991 data-integrity)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// 3. BASE METRIC COMPUTATION
// ------------------------------------------------------------------------------
// Trade classification with Lee-Ready (1991) tick-test fallback
var buyVol = isnum(taker.buy) ? taker.buy : (px > bars.open ? bars.volume : 0)
var sellVol = isnum(taker.sell) ? taker.sell : (px <= bars.open ? bars.volume : 0)
// Volume delta (buy − sell)
var delta = buyVol - sellVol
var deltaSmooth = ema(delta, smoothLen)
// CVD — cumulative volume delta (static for session persistence)
static cvd = 0.0
var cvdDelta = buyVol - sellVol
if (isnan(cvd)) {
cvd = 0.0
}
// Session reset logic
static sessionStartBar = 0
var currentBar = bar_index[0]
if (!isnan(currentBar) && currentBar != sessionStartBar) {
sessionStartBar = currentBar
}
if (cvdReset && !isLiveUpdate && currentBar == sessionStartBar) {
cvd = 0.0
} else {
cvd = cvd + cvdDelta
}
var cvdSmooth = ema(cvd, smoothLen)
// Relative Volume = current / SMA(volume)
var avgVol = sma(bars.volume, rvolLen)
var rvol = avgVol > 0 ? bars.volume / avgVol : 1.0
var rvolSmooth = ema(rvol, smoothLen)
// Cumulative Relative Volume (static for session persistence)
static cumRvol = 0.0
if (isnan(cumRvol)) {
cumRvol = 0.0
}
if (cvdReset && !isLiveUpdate && currentBar == sessionStartBar) {
cumRvol = 0.0
} else {
cumRvol = cumRvol + rvol
}
var cumRvolSmooth = ema(cumRvol, smoothLen)
// OBV = Σ(sgn(ΔPrice) × Volume)
static obv = 0.0
if (isnan(obv)) {
obv = 0.0
}
var priceChange = px - px[1]
var obvDelta = priceChange > 0 ? bars.volume : (priceChange < 0 ? -bars.volume : 0)
if (cvdReset && !isLiveUpdate && currentBar == sessionStartBar) {
obv = 0.0
} else {
obv = obv + obvDelta
}
var obvSmooth = ema(obv, smoothLen)
// ------------------------------------------------------------------------------
// 4. REGIME DETECTION
// ------------------------------------------------------------------------------
// Bullish volume regime: delta > 0 AND volume above average
// Bearish volume regime: delta < 0 AND volume above average
// Neutral: everything else (low volume or mixed delta)
var regimeBull = delta > 0 && bars.volume > avgVol
var regimeBear = delta < 0 && bars.volume > avgVol
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// ------------------------------------------------------------------------------
// 5. STATIC SESSION TRACKING
// ------------------------------------------------------------------------------
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0
static sessionHighCvd = -999999.0
static sessionLowCvd = 999999.0
static sessionHighRvol = -999999.0
static sessionLowRvol = 999999.0
static extremeDeltaCount = 0
static lastBarIndex = 0
if (!isnan(currentBar) && currentBar != lastBarIndex) {
lastBarIndex = currentBar
if (delta > sessionHighDelta) {
sessionHighDelta = delta
}
if (delta < sessionLowDelta) {
sessionLowDelta = delta
}
if (cvd > sessionHighCvd) {
sessionHighCvd = cvd
}
if (cvd < sessionLowCvd) {
sessionLowCvd = cvd
}
if (rvol > sessionHighRvol) {
sessionHighRvol = rvol
}
if (rvol < sessionLowRvol) {
sessionLowRvol = rvol
}
// Extreme delta event: |delta| > threshold × avgVol
var deltaAbsThresh = avgVol * deltaHighThresh
if (math.abs(delta) > deltaAbsThresh) {
extremeDeltaCount = extremeDeltaCount + 1
}
}
// ------------------------------------------------------------------------------
// 6. PLOTTING — Multi-Metric Dashboard
// ------------------------------------------------------------------------------
// --- Guide lines ---
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=1, color=transparency(neutralColor, 30), width=1)
hline(value=rvolHighThresh, color=transparency(rvolColor, 30), width=1)
hline(value=rvolLowThresh, color=transparency(rvolColor, 30), width=1)
}
// --- Volume Delta (plotBar) ---
if (showDelta) {
var deltaColorIdx = deltaSmooth >= 0 ? 0 : 1
plotBar(
value=deltaSmooth,
colors=[bullColor, bearColor],
colorIndex=deltaColorIdx,
width=1,
label=["Volume Delta"],
desc=["Volume delta (buy − sell) per bar: green=buy-heavy, red=sell-heavy"]
)
}
// --- CVD (plotLine with regime fill) ---
if (showCvd) {
plotLine(
value=cvdSmooth,
width=2,
colors=[regimeColor],
label=["CVD"],
desc=["Cumulative volume delta: running sum of delta (regime-colored). Green=accumulating buy pressure, red=accumulating sell pressure"],
fill=true
)
// Zero reference
plotLine(
value=[cvdSmooth, 0],
width=1,
colors=[transparency(regimeColor, 10), transparency(regimeColor, 10)],
colorIndex=0,
fill=true,
label=["CVD", "Zero"],
desc=["Fill between CVD and zero reference"]
)
}
// --- Buy & Sell Volume (plotBar) ---
if (showBuySell) {
plotBar(
value=buyVol,
colors=[transparency(bullColor, 60)],
width=1,
label=["Buy Volume"],
desc=["Buy-initiated volume per bar (taker buy or tick-test proxy)"]
)
plotBar(
value=-sellVol,
colors=[transparency(bearColor, 60)],
width=1,
label=["Sell Volume"],
desc=["Sell-initiated volume per bar (negative for visual separation)"]
)
}
// --- Relative Volume (histogram-style bar) ---
if (showRvol) {
var rvolColorIdx = rvolSmooth >= rvolHighThresh ? 0 : (rvolSmooth <= rvolLowThresh ? 1 : 2)
plotBar(
value=rvolSmooth - 1.0,
colors=[transparency(bullColor, 50), transparency(bearColor, 50), transparency(rvolColor, 50)],
colorIndex=rvolColorIdx,
width=1,
label=["RVOL"],
desc=["Relative volume vs. SMA(20): centered at 0 (positive=above average, negative=below average)"]
)
plotLine(
value=rvolSmooth,
width=1,
colors=[transparency(rvolColor, 60)],
label=["RVOL Line"],
desc=["Smoothed relative volume line (1.0 = average)"]
)
}
// --- Cumulative Relative Volume (plotLine) ---
if (showCumRvol) {
plotLine(
value=cumRvolSmooth,
width=2,
colors=[transparency(rvolColor, 70)],
label=["Cum RVOL"],
desc=["Cumulative relative volume: running sum of RVOL. Rising = sustained above-average volume"]
)
}
// --- OBV (plotLine) ---
if (showObv) {
plotLine(
value=obvSmooth,
width=2,
colors=[transparency(obvColor, 70)],
label=["OBV"],
desc=["On-balance volume: cumulative volume flow (Granville 1963). Rising = buying pressure, falling = selling pressure"]
)
}
// ------------------------------------------------------------------------------
// 7. EXTREME EVENT SHAPES
// ------------------------------------------------------------------------------
if (showShapes) {
// Delta extreme shapes
if (!isnan(deltaSmooth) && !isnan(deltaSmooth[1])) {
var deltaHighCross = deltaSmooth >= deltaHighThresh * avgVol && deltaSmooth[1] < deltaHighThresh * avgVol
var deltaLowCross = deltaSmooth <= deltaLowThresh * avgVol && deltaSmooth[1] > deltaLowThresh * avgVol
if (deltaHighCross) {
plotShape(
value=deltaSmooth,
shape="triangleup",
color=extremeColor,
width=2,
label=["Delta Extreme Buy"],
desc=["Volume delta crossed extreme buy threshold — aggressive buying detected"]
)
}
if (deltaLowCross) {
plotShape(
value=deltaSmooth,
shape="triangledown",
color=extremeColor,
width=2,
label=["Delta Extreme Sell"],
desc=["Volume delta crossed extreme sell threshold — aggressive selling detected"]
)
}
}
// RVOL extreme shapes
if (!isnan(rvolSmooth) && !isnan(rvolSmooth[1])) {
var rvolHighCross = rvolSmooth >= rvolHighThresh && rvolSmooth[1] < rvolHighThresh
var rvolLowCross = rvolSmooth <= rvolLowThresh && rvolSmooth[1] > rvolLowThresh
if (rvolHighCross) {
plotShape(
value=rvolSmooth,
shape="circle",
color=extremeColor,
width=2,
label=["RVOL Spike"],
desc=["Relative volume spiked above " + rvolHighThresh + "× average — volume anomaly detected"]
)
}
if (rvolLowCross) {
plotShape(
value=rvolSmooth,
shape="xcross",
color=extremeColor,
width=2,
label=["RVOL Low"],
desc=["Relative volume dropped below " + rvolLowThresh + "× average — low participation warning"]
)
}
}
}
// ------------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH VOLUME" : (regimeBear ? "BEARISH VOLUME" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["Volume Suite — Perfected", regimeText],
["Volume Delta", deltaSmooth[0]],
["CVD", cvdSmooth[0]],
["Relative Volume", rvolSmooth[0]],
["Cum RVOL", cumRvolSmooth[0]],
["OBV", obvSmooth[0]],
["Session High Δ", sessionHighDelta],
["Session Low Δ", sessionLowDelta],
["Extreme Events", extremeDeltaCount]
],
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
)
}