Perfected FlowScript
Volume Spike Levels
Volume Spike Levels — Perfected Edition is indexed as 173_volume_spike_levels.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
14.6 KB
Lines
455
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Spike (" + spikeIntensity + ")
line 304:5
Trigger
(showSpikeMarkers && isSpike)
Value
spikeMid
Deps
isSpike:var, showSpikeMarkers:input
Unlabeled shape
line 416:5
Trigger
(isLastBar)
Value
high
Deps
isLastBar:builtin
173_volume_spike_levels.flowscript
source path: kscripts/perfected/173_volume_spike_levels.flowscript · sha256:7d93f48ff31ff3e9968cc1715289739b6f22ac3a905e39d1f361b5679c63bcfd
//@version=2
// ============================================================================
// Volume Spike Levels — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #volume, #spike, #zscore, #levels, #microstructure, #orderflow
//
// Production-grade volume spike detector with z-score normalization,
// spike-level tracking, intensity-based color coding, and horizontal
// reference lines at spike mid-prices. Grounded in market microstructure
// research on order flow imbalance, volume-driven price impact, and
// volume profile analysis.
//
// Academic foundations:
// 1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
// Events" (J. Financial Econometrics, 12(1)). Price changes driven
// linearly by Order Flow Imbalance (OFI). OFI = (ΔBidVolume - ΔAskVolume).
// Slope inversely proportional to market depth. Volume spikes indicate
// aggressive order flow that drives short-term price changes.
// 2. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
// in a High-Frequency World" (Rev. Financial Studies, 25(5)). VPIN
// (Volume-Synchronized Probability of Informed Trading) reached
// historically high levels >1 hour before the 2010 Flash Crash. Volume
// bucket analysis reveals informed trading intensity. Bulk Volume
// Classification (BVC) improves volume classification robustness.
// 3. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
// Market Profile" (Wiley, 2nd ed.). Markets are continuous auctions
// seeking equilibrium. Volume clusters at accepted value levels (POC).
// High Volume Nodes (HVN) act as price magnets; volume spikes mark
// significant order flow events that establish or reject value.
// 4. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
// in Supply and Demand" (Handbook of Financial Markets). Square-root
// impact law: large volume may not move price if liquidity is deep
// (absorption). Volume spikes without price movement = absorption;
// with large price movement = initiative activity.
// 5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
// and Market Returns" (J. Financial Economics, 65(1)). Extreme order
// imbalances predict return reversals. Volume spikes at extremes flag
// potential exhaustion points. CVD divergence from price signals shifts
// in order flow pressure.
// 6. Kyle (1985), "Continuous Auctions and Insider Trading" (Econometrica,
// 53(6)). Prices respond linearly to order flow with slope λ (Kyle's
// Lambda). High volume at specific price levels indicates significant
// informed trading. Volume spikes are signatures of aggressive informed
// order flow.
// ============================================================================
define(
title="Volume Spike Levels — Perfected Edition",
position="onchart",
axis=false
)
// === USER INPUTS ===
// --- Spike Detection ---
var spikeMult = input(
name="spikeMult",
type="number",
defaultValue=2.0,
label="Volume Spike Multiplier (× avg)",
constraints={min: 1.0, max: 10.0, step: 0.1},
group="Spike Detection"
)
var lookback = input(
name="lookback",
type="number",
defaultValue=50,
label="Volume SMA Lookback",
constraints={min: 10, max: 200, step: 5},
group="Spike Detection"
)
var useZScore = input(
name="useZScore",
type="boolean",
defaultValue=true,
label="Use Z-Score Normalization",
group="Spike Detection"
)
var zThreshold = input(
name="zThreshold",
type="number",
defaultValue=2.0,
label="Z-Score Threshold",
constraints={min: 0.5, max: 5.0, step: 0.1},
group="Spike Detection"
)
// --- Levels ---
var numLevels = input(
name="numLevels",
type="number",
defaultValue=3,
label="Number of Spike Levels to Track",
constraints={min: 1, max: 5, step: 1},
group="Levels"
)
var levelLookback = input(
name="levelLookback",
type="number",
defaultValue=100,
label="Level Lookback (bars)",
constraints={min: 20, max: 500, step: 10},
group="Levels"
)
var showLevelLines = input(
name="showLevelLines",
type="boolean",
defaultValue=true,
label="Show Spike Level Lines",
group="Levels"
)
// --- Display ---
var showSpikeMarkers = input(
name="showSpikeMarkers",
type="boolean",
defaultValue=true,
label="Show Spike Markers",
group="Display"
)
var showVolumeRatio = input(
name="showVolumeRatio",
type="boolean",
defaultValue=true,
label="Show Volume Ratio Bar",
group="Display"
)
var showZScoreLine = input(
name="showZScoreLine",
type="boolean",
defaultValue=true,
label="Show Z-Score Line (offchart)",
group="Display"
)
// --- Colors ---
var mildColor = input(
name="mildColor",
type="color",
defaultValue="#ffa726",
label="Mild Spike Color (z 1.5-2.5)",
group="Colors"
)
var moderateColor = input(
name="moderateColor",
type="color",
defaultValue="#ff7043",
label="Moderate Spike Color (z 2.5-3.5)",
group="Colors"
)
var extremeColor = input(
name="extremeColor",
type="color",
defaultValue="#ff1744",
label="Extreme Spike Color (z > 3.5)",
group="Colors"
)
var levelColor = input(
name="levelColor",
type="color",
defaultValue="#00e5ff",
label="Level Line Color",
group="Colors"
)
// === DATA SOURCES & NaN GUARD ===
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume
if (isnan(close[0]) || isnan(volume[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// === COMPUTATION ===
// Bar counter
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
}
// Volume statistics
timeseries avgVol = sma(volume, lookback)
timeseries stdVol = stddev(volume, lookback)
timeseries volRatio = avgVol > 0 ? (volume / avgVol) : 1.0
// Z-score normalization
timeseries zScore = (stdVol > 0) ? ((volume - avgVol) / stdVol) : 0.0
// Spike detection (mult-based or z-score-based)
var isSpikeMult = volRatio >= spikeMult
var isSpikeZ = useZScore && zScore >= zThreshold
var isSpike = isSpikeMult || isSpikeZ
// Spike intensity classification
var spikeIntensity = 0 // 0 = none, 1 = mild, 2 = moderate, 3 = extreme
if (useZScore && zScore >= 3.5) {
spikeIntensity = 3
} else if (useZScore && zScore >= 2.5) {
spikeIntensity = 2
} else if (useZScore && zScore >= 1.5) {
spikeIntensity = 1
} else if (!useZScore && volRatio >= spikeMult * 2.0) {
spikeIntensity = 3
} else if (!useZScore && volRatio >= spikeMult * 1.5) {
spikeIntensity = 2
} else if (!useZScore && volRatio >= spikeMult) {
spikeIntensity = 1
}
// Spike mid-price
timeseries spikeMid = (high + low) / 2.0
// Spike color by intensity
var spikeColor = spikeIntensity == 3 ? extremeColor
: (spikeIntensity == 2 ? moderateColor
: (spikeIntensity == 1 ? mildColor : "#9e9e9e"))
// === STATIC STATE: Spike Level Tracking ===
// Track last N spike bars and their mid-prices
static lastSpikeBar1 = 0
static lastSpikeBar2 = 0
static lastSpikeBar3 = 0
static lastSpikeBar4 = 0
static lastSpikeBar5 = 0
static lastSpikePrice1 = 0.0
static lastSpikePrice2 = 0.0
static lastSpikePrice3 = 0.0
static lastSpikePrice4 = 0.0
static lastSpikePrice5 = 0.0
static lastSpikeIntensity1 = 0
static lastSpikeIntensity2 = 0
static lastSpikeIntensity3 = 0
static lastSpikeIntensity4 = 0
static lastSpikeIntensity5 = 0
// --- STATE UPDATE (only on bar close) ---
if (!isLiveUpdate && isSpike) {
// Shift down: 4→5, 3→4, 2→3, 1→2
lastSpikeBar5 = lastSpikeBar4
lastSpikePrice5 = lastSpikePrice4
lastSpikeIntensity5 = lastSpikeIntensity4
lastSpikeBar4 = lastSpikeBar3
lastSpikePrice4 = lastSpikePrice3
lastSpikeIntensity4 = lastSpikeIntensity3
lastSpikeBar3 = lastSpikeBar2
lastSpikePrice3 = lastSpikePrice2
lastSpikeIntensity3 = lastSpikeIntensity2
lastSpikeBar2 = lastSpikeBar1
lastSpikePrice2 = lastSpikePrice1
lastSpikeIntensity2 = lastSpikeIntensity1
// New spike at position 1
lastSpikeBar1 = barCount
lastSpikePrice1 = spikeMid
lastSpikeIntensity1 = spikeIntensity
}
// Level expiration: clear if older than levelLookback
if (!isLiveUpdate) {
if (lastSpikeBar1 > 0 && barCount - lastSpikeBar1 > levelLookback) {
lastSpikeBar1 = 0
lastSpikePrice1 = 0.0
lastSpikeIntensity1 = 0
}
if (lastSpikeBar2 > 0 && barCount - lastSpikeBar2 > levelLookback) {
lastSpikeBar2 = 0
lastSpikePrice2 = 0.0
lastSpikeIntensity2 = 0
}
if (lastSpikeBar3 > 0 && barCount - lastSpikeBar3 > levelLookback) {
lastSpikeBar3 = 0
lastSpikePrice3 = 0.0
lastSpikeIntensity3 = 0
}
if (lastSpikeBar4 > 0 && barCount - lastSpikeBar4 > levelLookback) {
lastSpikeBar4 = 0
lastSpikePrice4 = 0.0
lastSpikeIntensity4 = 0
}
if (lastSpikeBar5 > 0 && barCount - lastSpikeBar5 > levelLookback) {
lastSpikeBar5 = 0
lastSpikePrice5 = 0.0
lastSpikeIntensity5 = 0
}
}
// === EVENT FLAGS ===
var isNewSpike = isSpike && lastSpikeBar1 == barCount
// === PLOTS: SPIKE MARKERS ===
if (showSpikeMarkers && isSpike) {
var markerShape = spikeIntensity == 3 ? "xcross"
: (spikeIntensity == 2 ? "triangleup"
: (spikeIntensity == 1 ? "circle" : "dot"))
var markerWidth = spikeIntensity == 3 ? 4 : (spikeIntensity == 2 ? 3 : 2)
plotShape(
value=spikeMid,
shape=markerShape,
colorIndex=spikeColor,
width=markerWidth,
label=["Spike (" + spikeIntensity + ")"],
desc=["Volume spike detected: vol=" + volRatio + "x avg, z=" + zScore]
)
}
// === PLOTS: SPIKE LEVEL LINES ===
if (showLevelLines && numLevels >= 1 && lastSpikeBar1 > 0) {
var lvl1Col = lastSpikeIntensity1 == 3 ? extremeColor
: (lastSpikeIntensity1 == 2 ? moderateColor
: (lastSpikeIntensity1 == 1 ? mildColor : levelColor))
plotLine(
value=lastSpikePrice1,
width=1,
colors=[lvl1Col],
label=["Spike Level 1"],
desc=["Most recent volume spike mid-price (intensity " + lastSpikeIntensity1 + ")"]
)
}
if (showLevelLines && numLevels >= 2 && lastSpikeBar2 > 0) {
var lvl2Col = lastSpikeIntensity2 == 3 ? extremeColor
: (lastSpikeIntensity2 == 2 ? moderateColor
: (lastSpikeIntensity2 == 1 ? mildColor : levelColor))
plotLine(
value=lastSpikePrice2,
width=1,
colors=[opacity(lvl2Col, 70)],
label=["Spike Level 2"],
desc=["Second most recent volume spike mid-price (intensity " + lastSpikeIntensity2 + ")"]
)
}
if (showLevelLines && numLevels >= 3 && lastSpikeBar3 > 0) {
var lvl3Col = lastSpikeIntensity3 == 3 ? extremeColor
: (lastSpikeIntensity3 == 2 ? moderateColor
: (lastSpikeIntensity3 == 1 ? mildColor : levelColor))
plotLine(
value=lastSpikePrice3,
width=1,
colors=[opacity(lvl3Col, 50)],
label=["Spike Level 3"],
desc=["Third most recent volume spike mid-price (intensity " + lastSpikeIntensity3 + ")"]
)
}
if (showLevelLines && numLevels >= 4 && lastSpikeBar4 > 0) {
var lvl4Col = lastSpikeIntensity4 == 3 ? extremeColor
: (lastSpikeIntensity4 == 2 ? moderateColor
: (lastSpikeIntensity4 == 1 ? mildColor : levelColor))
plotLine(
value=lastSpikePrice4,
width=1,
colors=[opacity(lvl4Col, 40)],
label=["Spike Level 4"],
desc=["Fourth most recent volume spike mid-price"]
)
}
if (showLevelLines && numLevels >= 5 && lastSpikeBar5 > 0) {
var lvl5Col = lastSpikeIntensity5 == 3 ? extremeColor
: (lastSpikeIntensity5 == 2 ? moderateColor
: (lastSpikeIntensity5 == 1 ? mildColor : levelColor))
plotLine(
value=lastSpikePrice5,
width=1,
colors=[opacity(lvl5Col, 30)],
label=["Spike Level 5"],
desc=["Fifth most recent volume spike mid-price"]
)
}
// === PLOTS: VOLUME RATIO BAR (offchart) ===
if (showVolumeRatio) {
var ratioColor = volRatio >= spikeMult * 2.0 ? extremeColor
: (volRatio >= spikeMult * 1.5 ? moderateColor
: (volRatio >= spikeMult ? mildColor : "#26a69a40"))
plotBar(
value=volRatio,
colors=[ratioColor],
width=1,
label=["Vol Ratio"],
desc=["Volume ratio vs SMA(" + lookback + "): current / average"]
)
}
// === PLOTS: Z-SCORE LINE (offchart) ===
if (showZScoreLine) {
var zColor = zScore >= 3.5 ? extremeColor
: (zScore >= 2.5 ? moderateColor
: (zScore >= 1.5 ? mildColor : "#9e9e9e40"))
plotLine(
value=zScore,
width=1,
colors=[zColor],
label=["Vol Z-Score"],
desc=["Volume z-score: (vol - SMA) / StdDev. >2.0 = statistically significant spike."]
)
// Z-score threshold lines
hline(value=zThreshold, color=opacity(mildColor, 50), width=1)
hline(value=0, color="#ffffff20", width=1)
}
// === VOLUME SPIKE LABEL (last bar only) ===
if (isLastBar) {
var spikeLabel = isSpike ? (spikeIntensity == 3 ? "EXTREME SPIKE"
: (spikeIntensity == 2 ? "MODERATE SPIKE"
: (spikeIntensity == 1 ? "MILD SPIKE" : "NO SPIKE"))) : "NO SPIKE"
var spikeLabelColor = spikeIntensity == 3 ? extremeColor
: (spikeIntensity == 2 ? moderateColor
: (spikeIntensity == 1 ? mildColor : "#9e9e9e"))
plotPriceLabel(
price=high,
text=spikeLabel,
type="callout",
color="#ffffff",
backgroundColor=spikeLabelColor,
size=10,
fontWeight=700
)
}
// === VOLUME SPIKE SUMMARY TABLE (last bar only) ===
if (isLastBar) {
var totalSpikes = (lastSpikeBar1 > 0 ? 1 : 0) + (lastSpikeBar2 > 0 ? 1 : 0)
+ (lastSpikeBar3 > 0 ? 1 : 0) + (lastSpikeBar4 > 0 ? 1 : 0) + (lastSpikeBar5 > 0 ? 1 : 0)
plotTable(
data=[
["Volume Spike Levels", useZScore ? "Z-Score Mode" : "Ratio Mode"],
["Current Vol Ratio", volRatio],
["Current Z-Score", zScore],
["Spike Intensity", spikeIntensity == 3 ? "EXTREME" : (spikeIntensity == 2 ? "MODERATE" : (spikeIntensity == 1 ? "MILD" : "NONE"))],
["Active Levels", totalSpikes],
["Avg Volume", avgVol],
["Vol StdDev", stdVol]
],
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
)
}