Perfected FlowScript
Volume x MA
Volume x MA — Perfected Edition is indexed as 288_volume_x_ma.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
onchart
Axis
false
Size
15.2 KB
Lines
487
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Vol Spike
line 405:9
Trigger
(showSpikes) && (isSpike)
Value
volume
Deps
isSpike:var, showSpikes:input
Vol Exhaustion
line 415:9
Trigger
(showSpikes) && (isExhaustion)
Value
volume
Deps
isExhaustion:var, showSpikes:input
Vol Accel
line 426:9
Trigger
(showSpikes) && (fastMA > midMA && fastMA[1] <= midMA[1])
Value
volume
Deps
fastMA:timeseries, midMA:timeseries, showSpikes:input
Vol Decel
line 437:9
Trigger
(showSpikes) && (fastMA < midMA && fastMA[1] >= midMA[1])
Value
volume
Deps
fastMA:timeseries, midMA:timeseries, showSpikes:input
288_volume_x_ma.flowscript
source path: kscripts/perfected/288_volume_x_ma.flowscript · sha256:1e3b42d0e66e1ad38e7f83c0660176cb523f233e7bb0ee66b0eb04a6cd329bc6
//@version=2
// ============================================================================
// Volume x MA — Perfected Edition
// Author: RoronoaZoro (@RoronoaZoro) | Enhanced by kScript Perfection Engineer
// Index: 288
// Tags: CORE, #volume, #moving_average, #ribbon, #microstructure
//
// Production-quality volume-weighted moving average overlay with multiple
// volume MA ribbon, color-coded volume bars, z-score spike detection, volume
// delta approximation, and static session tracking. Grounded in market
// microstructure research on trade classification, order flow imbalance, and
// volume-driven price impact.
//
// Research papers underpinning this design:
// 1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
// foundational algorithm for classifying trades as buyer-initiated or
// seller-initiated (~85–93% accuracy). Underpins volume color-coding logic. [^1]
// 2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// established linear relationship between order flow imbalance and short-
// term price changes; volume participation magnitude correlates with price
// impact. [^2]
// 3. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes":
// liquidity memory time explains why volume spikes may or may not move
// price (absorption vs. exhaustion). [^3]
// 4. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading":
// BVC method for probabilistic volume classification in aggregate buckets;
// supports volume delta approximation without tick data. [^4]
// 5. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential MA":
// comparative WMA/EMA study showing WMA responds faster but produces more
// whipsaws; combined approaches yield robust decisions. [^5]
// 6. Steidlmayer & Hawkins (1986/2003), "Steidlmayer on Markets": volume
// clusters at accepted value; volume profile reveals market structure. [^6]
// ============================================================================
define(
title="Volume x MA — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Volume MA Ribbon ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=10,
label="Fast Volume MA Length",
constraints={min: 2, max: 100, step: 1},
group="Volume MA Ribbon"
)
var midLen = input(
name="midLen",
type="number",
defaultValue=20,
label="Medium Volume MA Length",
constraints={min: 2, max: 100, step: 1},
group="Volume MA Ribbon"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=50,
label="Slow Volume MA Length",
constraints={min: 2, max: 200, step: 1},
group="Volume MA Ribbon"
)
var fastType = input(
name="fastType",
type="select",
defaultValue="EMA",
label="Fast MA Type",
options=["SMA", "EMA", "WMA"],
group="Volume MA Ribbon"
)
var midType = input(
name="midType",
type="select",
defaultValue="EMA",
label="Medium MA Type",
options=["SMA", "EMA", "WMA"],
group="Volume MA Ribbon"
)
var slowType = input(
name="slowType",
type="select",
defaultValue="SMA",
label="Slow MA Type",
options=["SMA", "EMA", "WMA"],
group="Volume MA Ribbon"
)
// --- Volume Delta ---
var showDelta = input(
name="showDelta",
type="boolean",
defaultValue=true,
label="Show Volume Delta Approximation",
group="Volume Delta"
)
var deltaSmooth = input(
name="deltaSmooth",
type="number",
defaultValue=5,
label="Delta Smoothing Length",
constraints={min: 1, max: 50, step: 1},
group="Volume Delta"
)
// --- Spike Detection ---
var showSpikes = input(
name="showSpikes",
type="boolean",
defaultValue=true,
label="Show Volume Spike Shapes",
group="Spike Detection"
)
var spikeZscore = input(
name="spikeZscore",
type="number",
defaultValue=2.0,
label="Spike Z-Score Threshold",
constraints={min: 1.0, max: 5.0, step: 0.1},
group="Spike Detection"
)
var spikeLookback = input(
name="spikeLookback",
type="number",
defaultValue=50,
label="Spike Lookback",
constraints={min: 10, max: 500, step: 1},
group="Spike Detection"
)
// --- Display ---
var showBars = input(
name="showBars",
type="boolean",
defaultValue=true,
label="Show Volume Bars",
group="Display"
)
var showRibbon = input(
name="showRibbon",
type="boolean",
defaultValue=true,
label="Show MA Ribbon Fill",
group="Display"
)
var showIndividual = input(
name="showIndividual",
type="boolean",
defaultValue=true,
label="Show Individual MA Lines",
group="Display"
)
var showVolumeRatio = input(
name="showVolumeRatio",
type="boolean",
defaultValue=false,
label="Show Volume Ratio Line",
group="Display"
)
// --- Colors ---
var bullBarColor = input(
name="bullBarColor",
type="color",
defaultValue="#2962ff",
label="Bullish Volume Color",
group="Colors"
)
var bearBarColor = input(
name="bearBarColor",
type="color",
defaultValue="#ffffff",
label="Bearish Volume Color",
group="Colors"
)
var fastColor = input(
name="fastColor",
type="color",
defaultValue="#ffeb3b",
label="Fast MA Color",
group="Colors"
)
var midColor = input(
name="midColor",
type="color",
defaultValue="#ff9800",
label="Medium MA Color",
group="Colors"
)
var slowColor = input(
name="slowColor",
type="color",
defaultValue="#f44336",
label="Slow MA Color",
group="Colors"
)
var spikeColor = input(
name="spikeColor",
type="color",
defaultValue="#e91e63",
label="Spike Marker Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries open = price.open
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume
if (isnan(close[0]) || isnan(volume[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. VOLUME DELTA APPROXIMATION
// -----------------------------------------------------------------------------
// Per Lee & Ready (1991) and Easley, López de Prado & O'Hara (2012), we
// approximate buy-initiated vs sell-initiated volume using the bar's close
// position relative to its range (Bulk Volume Classification proxy).
// Buy-initiated ≈ volume × (close − low) / (high − low)
// Sell-initiated ≈ volume × (high − close) / (high − low)
timeseries range = high - low
var buyVol = range > 0 ? volume * (close - low) / range : volume / 2
var sellVol = range > 0 ? volume * (high - close) / range : volume / 2
// Volume delta (buy − sell) — positive = aggressive buying, negative = aggressive selling
timeseries volDelta = buyVol - sellVol
timeseries volDeltaSmooth = ema(source=volDelta, period=deltaSmooth)
// -----------------------------------------------------------------------------
// 4. MULTIPLE VOLUME MAs (RIBBON)
// -----------------------------------------------------------------------------
// Per Manasa & Reddy (2025), combining WMA and EMA leverages both responsiveness
// and stability. We offer three ribbon bands with user-selectable MA types.
function computeMA(src, len, maType) {
if (maType == "SMA") {
return sma(source=src, period=len)
} else if (maType == "EMA") {
return ema(source=src, period=len)
} else {
return wma(source=src, period=len)
}
}
timeseries fastMA = computeMA(volume, fastLen, fastType)
timeseries midMA = computeMA(volume, midLen, midType)
timeseries slowMA = computeMA(volume, slowLen, slowType)
// Volume ratio: current volume vs medium MA (participation level)
timeseries volRatio = midMA > 0 ? volume / midMA : 1.0
// -----------------------------------------------------------------------------
// 5. Z-SCORE SPIKE DETECTION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018), z-score normalization for statistical context.
// We compute rolling z-score of volume relative to its medium MA.
timeseries volMean = sma(source=volume, period=spikeLookback)
timeseries volStd = stddev(source=volume, period=spikeLookback)
timeseries volZscore = volStd > 0 ? (volume - volMean) / volStd : 0
var isSpike = volZscore > spikeZscore
var isExhaustion = volZscore < -spikeZscore
// Volume trend classification using ribbon alignment
var ribbonBull = fastMA > midMA && midMA > slowMA
var ribbonBear = fastMA < midMA && midMA < slowMA
var ribbonExpanding = fastMA > fastMA[1] && midMA > midMA[1]
// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static sessionHighVol = -1.0
static sessionLowVol = 999999999.0
static spikeCount = 0
static exhaustionCount = 0
static aboveAvgCount = 0
static belowAvgCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (volume[0] > sessionHighVol) {
sessionHighVol = volume[0]
}
if (volume[0] < sessionLowVol) {
sessionLowVol = volume[0]
}
if (isSpike) {
spikeCount = spikeCount + 1
}
if (isExhaustion) {
exhaustionCount = exhaustionCount + 1
}
if (volume[0] > midMA[0]) {
aboveAvgCount = aboveAvgCount + 1
} else {
belowAvgCount = belowAvgCount + 1
}
}
// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------
// --- Volume Bars (bullish/bearish color-coded) ---
if (showBars) {
var isBull = close >= open
plotBar(
value=volume,
colors=[bullBarColor, bearBarColor],
colorIndex=isBull ? 0 : 1,
width=1,
label=["Volume"],
desc=["Volume bars — blue = bullish close, white = bearish close"]
)
}
// --- Volume Delta (smoothed) as secondary bar/histogram overlay ---
if (showDelta) {
var deltaBull = volDeltaSmooth >= 0
plotBar(
value=volDeltaSmooth,
colors=[transparency(bullBarColor, 70), transparency(bearBarColor, 70)],
colorIndex=deltaBull ? 0 : 1,
width=1,
label=["Vol Delta"],
desc=["Approximated volume delta (buy − sell volume) — positive = buying pressure"]
)
}
// --- MA Ribbon Fill ---
if (showRibbon) {
var ribbonTop = math.max(fastMA, midMA)
var ribbonBot = math.min(fastMA, midMA)
var ribbonBullColor = fastMA > midMA ? fastColor : midColor
var ribbonBearColor = fastMA < midMA ? bearBarColor : slowColor
plotLine(
value=[ribbonTop, ribbonBot],
width=1,
colors=[transparency(ribbonBullColor, 30), transparency(ribbonBearColor, 30)],
colorIndex=fastMA > midMA ? 0 : 1,
fill=true,
label=["Ribbon Top", "Ribbon Bot"],
desc=["Volume MA ribbon fill between fast and medium moving averages"]
)
}
// --- Individual MA Lines ---
if (showIndividual) {
plotLine(
value=fastMA,
width=2,
colors=[fastColor],
label=["Fast Vol MA"],
desc=["Fast volume MA (" + fastType + " " + fastLen + ")"]
)
plotLine(
value=midMA,
width=2,
colors=[midColor],
label=["Mid Vol MA"],
desc=["Medium volume MA (" + midType + " " + midLen + ")"]
)
plotLine(
value=slowMA,
width=2,
colors=[slowColor],
label=["Slow Vol MA"],
desc=["Slow volume MA (" + slowType + " " + slowLen + ")"]
)
}
// --- Volume Ratio Line ---
if (showVolumeRatio) {
plotLine(
value=volRatio,
width=1,
colors=[midColor],
label=["Vol Ratio"],
desc=["Current volume / medium MA ratio (1.0 = average participation)"]
)
}
// --- Spike & Exhaustion Shapes ---
if (showSpikes) {
if (isSpike) {
plotShape(
value=volume,
shape="diamond",
colorIndex=spikeColor,
width=3,
label=["Vol Spike"],
desc=["Volume spike detected (z-score > " + spikeZscore + ") — above-average participation"]
)
}
if (isExhaustion) {
plotShape(
value=volume,
shape="circle",
colorIndex=transparency(bearBarColor, 50),
width=2,
label=["Vol Exhaustion"],
desc=["Volume exhaustion (z-score < −" + spikeZscore + ") — below-average participation"]
)
}
// Fast MA cross above mid MA (volume acceleration)
if (fastMA > midMA && fastMA[1] <= midMA[1]) {
plotShape(
value=volume,
shape="triangleup",
colorIndex=fastColor,
width=2,
label=["Vol Accel"],
desc=["Fast volume MA crossed above medium MA — volume acceleration signal"]
)
}
// Fast MA cross below mid MA (volume deceleration)
if (fastMA < midMA && fastMA[1] >= midMA[1]) {
plotShape(
value=volume,
shape="triangledown",
colorIndex=slowColor,
width=2,
label=["Vol Decel"],
desc=["Fast volume MA crossed below medium MA — volume deceleration signal"]
)
}
}
// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var ribbonState = ribbonBull ? "EXPANDING (Bull)" : (ribbonBear ? "CONTRACTING (Bear)" : "MIXED")
var ribbonColor = ribbonBull ? fastColor : (ribbonBear ? slowColor : midColor)
var deltaText = volDeltaSmooth >= 0 ? "Buying Pressure" : "Selling Pressure"
var deltaTextColor = volDeltaSmooth >= 0 ? bullBarColor : bearBarColor
plotTable(
data=[
["Volume x MA — Perfected", ribbonState],
["Volume", volume[0]],
["Fast MA", fastMA[0]],
["Mid MA", midMA[0]],
["Slow MA", slowMA[0]],
["Vol Delta", volDeltaSmooth[0]],
[deltaText, ""],
["Vol Z-Score", volZscore[0]],
["Vol Ratio", volRatio[0]],
["Session High Vol", sessionHighVol],
["Session Low Vol", sessionLowVol],
["Spike Count", spikeCount],
["Above Avg Count", aboveAvgCount],
["Below Avg Count", belowAvgCount]
],
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
)
}