MM Flow
FlowScripts

Perfected FlowScript

Relative Volume (Rvol)

Relative Volume (RVOL) V2 is indexed as 019_relative_volume_rvol.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.1 KB

Lines

460

Native Signal Candidates

3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

3/3 guarded

Vol Anomaly+

line 391:9

Trigger

(showShapes) && (isAnomaly && rvolZ > 0)

Value

rvolDisplay

Deps

isAnomaly:var, rvolZ:timeseries, showShapes:input

Vol Anomaly-

line 401:9

Trigger

(showShapes) && (isAnomaly && rvolZ < 0)

Value

rvolDisplay

Deps

isAnomaly:var, rvolZ:timeseries, showShapes:input

High Activity

line 413:9

Trigger

(showShapes) && (!useZScore && regime == 2)

Value

rvolDisplay

Deps

regime:var, showShapes:input, useZScore:input

019_relative_volume_rvol.flowscript

source path: kscripts/perfected/019_relative_volume_rvol.flowscript · sha256:dca556f7e49bde72abf3f24b18786f36b9ad0b80b0151091b581972bcbe702cf

hash verified
//@version=2
// ============================================================================
// Relative Volume (RVOL) V2 — Production-Quality Volume Participation Indicator
// Author: abetrade (@abetrade) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #volume, #rvol, #participation, #zscore, #histogram, #cumulative
//
// Relative Volume compares current bar volume to its historical average
// over a rolling lookback, flagging unusual participation levels. A reading
// above 1.0 indicates above-average participation; sustained readings well
// above 2.0 flag high-conviction moves worth attention. Includes z-score
// normalization, cumulative relative volume (CRV), threshold-based coloring,
// histogram visualization, and anomaly shape markers.
//
// FORMULA FOUNDATION:
// 1. RVOL = Current Volume / SMA(Volume, N)  per McCulloch & Kazakov (2007)
// 2. Z-Score RVOL: Z_RVOL = (RVOL − μ_RVOL) / σ_RVOL  where μ_RVOL ≈ 1.0
// 3. Cumulative Relative Volume (CRV): Σ RVOL_i  — long-memory cumulative
//    measure per Lillo & Farmer (2004) order-flow persistence.
// 4. Threshold Coloring: green when RVOL > 1.0 (above avg), red when < 1.0
//    (below avg), neutral near 1.0. Per Steidlmayer (1986/2003) "excess volume"
//    concept and Market Profile value-area logic.
// 5. Anomaly Detection: |Z_RVOL| > 2.0 triggers diamond shape markers;
//    flags >95% confidence statistical outliers per standard normal theory.
// 6. Histogram: RVOL − 1.0 centered at zero, colored by direction.
//
// RESEARCH BASIS:
//  • McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy and
//    Relative Volume", QFR Research Paper 201, UTS. Developed RVOL as
//    execution timing metric: RVOL = Current Volume / Expected Volume.
//    Used to front-load or back-load execution away from minimum VWAP risk. [^1]
//  • Steidlmayer & Hawkins (1986/2003), "Steidlmayer on Markets: Trading
//    with Market Profile", Wiley. "Excess volume" concept = practitioner
//    foundation for relative volume indicators. Value Area = ~70% of
//    session volume; POC = highest volume price. [^2]
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//    Studies in Nonlinear Dynamics & Econometrics 8(3), 1–35. Order flow
//    has long-memory properties (power-law autocorrelation decay), justifying
//    cumulative measures (CRV) as more informative than per-bar readings. [^3]
//  • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World" (VPIN), Rev. Financial Studies 25(5), 1457–1493.
//    Volume-synchronized imbalance framework; elevated RVOL clusters flag
//    informed trading and adverse selection. [^4]
//  • Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//    Patterns in Stock Returns", J. Financial Economics 16(1), 99–117. Seminal
//    intraday seasonality paper; volume patterns vary by time-of-day,
//    supporting relative (not absolute) volume analysis. [^5]
//  • Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on
//    the NYSE", J. Finance 43(1), 97–112. First introduced VWAP as benchmark;
//    RVOL is the natural volume-normalized extension of VWAP analysis. [^6]
// ============================================================================

define(
    title="Relative Volume (RVOL) V2",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- RVOL Calculation ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="RVOL Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="RVOL Settings"
)
var useZScore = input(
    name="useZScore",
    type="boolean",
    defaultValue=false,
    label="Use Z-Score Normalization",
    group="RVOL Settings"
)
var zScoreLookback = input(
    name="zScoreLookback",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 500, step: 5},
    group="RVOL Settings"
)

// --- Display Mode ---
var displayMode = input(
    name="displayMode",
    type="select",
    defaultValue="Line + Histogram",
    label="Display Mode",
    options=["Line", "Histogram", "Line + Histogram", "Z-Score Only"],
    group="Display"
)
var showCRV = input(
    name="showCRV",
    type="boolean",
    defaultValue=false,
    label="Show Cumulative RVOL (CRV)",
    group="Display"
)

// --- Thresholds ---
var aboveAvgThresh = input(
    name="aboveAvgThresh",
    type="number",
    defaultValue=1.0,
    label="Above-Average Threshold",
    constraints={min: 0.5, max: 3.0, step: 0.1},
    group="Thresholds"
)
var highActivityThresh = input(
    name="highActivityThresh",
    type="number",
    defaultValue=2.0,
    label="High Activity Threshold",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Thresholds"
)
var anomalyThresh = input(
    name="anomalyThresh",
    type="number",
    defaultValue=2.0,
    label="Anomaly Z-Score Threshold (σ)",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Above Average Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Below Average Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="At Average Color",
    group="Colors"
)
var highActivityColor = input(
    name="highActivityColor",
    type="color",
    defaultValue="#ffca28",
    label="High Activity Color",
    group="Colors"
)
var anomalyColor = input(
    name="anomalyColor",
    type="color",
    defaultValue="#ff1744",
    label="Anomaly Color",
    group="Colors"
)

// --- Display Toggles ---
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Anomaly Shapes",
    group="Display"
)
var showStatsTable = input(
    name="showStatsTable",
    type="boolean",
    defaultValue=true,
    label="Show Session Statistics Table",
    group="Display"
)

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries vol = bars.volume

if (isnan(vol[0])) {
    return
}

// Volume availability guard (Cont et al. 2014 data-integrity best practice)
var volAvailable = vol[0] > 0 && !isnan(vol[0])

// ------------------------------------------------------------------------------
// RVOL Core Computation (McCulloch & Kazakov 2007)
// ------------------------------------------------------------------------------
// RVOL = Current Volume / SMA(Volume, N)
// Properly guards against zero-division and missing data.

timeseries avgVol = sma(source=vol, period=lookback)
timeseries rvolRaw = avgVol > 0 ? vol[0] / avgVol : 1.0
timeseries rvolSmooth = ema(source=rvolRaw, period=smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization (optional)
// ------------------------------------------------------------------------------
// Z_RVOL = (RVOL − μ_RVOL) / σ_RVOL over zScoreLookback window.
// Per standard statistical process control; Z > 2 flags ~95% confidence outliers.

timeseries rvolMean = sma(source=rvolRaw, period=zScoreLookback)
timeseries rvolStd = stddev(source=rvolRaw, period=zScoreLookback)
timeseries rvolZ = useZScore && rvolStd > 0 ? (rvolRaw - rvolMean) / rvolStd : 0.0

// Display value: either raw/smoothed RVOL or z-score normalized
timeseries rvolDisplay = useZScore ? rvolZ : rvolSmooth

// ------------------------------------------------------------------------------
// Cumulative Relative Volume (CRV) — Long-Memory Measure
// ------------------------------------------------------------------------------
// CRV = Σ RVOL_i from session start. Per Lillo & Farmer (2004), order flow
// has long-memory properties; cumulative measures capture sustained pressure
// that drives trends. CRV divergences from price flag potential reversals.

static crv = 0.0
static lastBarIndexCRV = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndexCRV && volAvailable) {
    lastBarIndexCRV = currentBarIndex
    crv = crv + rvolRaw[0]
}

// ------------------------------------------------------------------------------
// Threshold-Based Regime Detection
// ------------------------------------------------------------------------------
// Regime classification for color coding:
//   High Activity: RVOL ≥ highActivityThresh (yellow)
//   Above Average: RVOL ≥ aboveAvgThresh (green)
//   Below Average: RVOL < 1.0 (red)
//   Near Average: otherwise (neutral)

var regime = 0  // 0 = neutral, 1 = above avg, 2 = high activity, -1 = below avg

if (rvolRaw[0] >= highActivityThresh) {
    regime = 2
} else if (rvolRaw[0] >= aboveAvgThresh) {
    regime = 1
} else if (rvolRaw[0] < 1.0) {
    regime = -1
}

// Z-score anomaly detection (|Z| > anomalyThresh)
var isAnomaly = useZScore && abs(rvolZ) >= anomalyThresh

// ------------------------------------------------------------------------------
// Histogram Value (RVOL − 1.0, centered at zero)
// ------------------------------------------------------------------------------
timeseries hist = rvolRaw[0] - 1.0

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks cumulative session statistics, anomaly counts, and volume extremes.

static sessionTotalVol = 0.0
static sessionBarCount = 0
static aboveAvgCount = 0
static belowAvgCount = 0
static highActivityCount = 0
static maxRVOL = 0.0
static minRVOL = 999999.0
static maxZ = 0.0
static anomalyCount = 0
static lastBarIndexStatic = 0

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndexStatic && volAvailable) {
    lastBarIndexStatic = currentBarIndex
    sessionTotalVol = sessionTotalVol + vol[0]
    sessionBarCount = sessionBarCount + 1

    if (rvolRaw[0] > maxRVOL) {
        maxRVOL = rvolRaw[0]
    }
    if (rvolRaw[0] < minRVOL) {
        minRVOL = rvolRaw[0]
    }

    if (regime == 1) {
        aboveAvgCount = aboveAvgCount + 1
    } else if (regime == -1) {
        belowAvgCount = belowAvgCount + 1
    } else if (regime == 2) {
        highActivityCount = highActivityCount + 1
    }

    if (useZScore && abs(rvolZ) > maxZ) {
        maxZ = abs(rvolZ)
    }
    if (isAnomaly) {
        anomalyCount = anomalyCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multi-Mode Visualization (Line, Histogram, Shapes, Fill, HLine)
// ------------------------------------------------------------------------------

// --- Reference Lines ---
// Baseline at 1.0 (average volume) and threshold lines.
if (!useZScore) {
    hline(value=1.0, color="#ffffff40", width=1)
    hline(value=highActivityThresh, color=opacity(highActivityColor, 30), width=1)
    hline(value=aboveAvgThresh, color=opacity(bullColor, 20), width=1)
} else {
    hline(value=0, color="#ffffff40", width=1)
    hline(value=anomalyThresh, color=opacity(anomalyColor, 20), width=1)
    hline(value=-anomalyThresh, color=opacity(anomalyColor, 20), width=1)
    hline(value=1, color=opacity(bullColor, 15), width=1)
    hline(value=-1, color=opacity(bearColor, 15), width=1)
}

// --- Line Plot ---
// Color-coded by regime: green=above avg, red=below, yellow=high activity.
if (displayMode == "Line" || displayMode == "Line + Histogram") {
    var lineColor = regime == 2 ? highActivityColor : (regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor))
    var lineColorFinal = isAnomaly ? anomalyColor : lineColor

    plotLine(
        value=rvolDisplay,
        width=2,
        colors=[lineColorFinal],
        label=["RVOL"],
        desc=[useZScore ? "RVOL Z-Score (" + zScoreLookback + ")" : "Relative Volume (" + lookback + "/" + smoothLen + ")"]
    )
}

// --- Histogram Plot ---
// Centered at zero (RVOL − 1.0). Color by direction: green=positive, red=negative.
// Width modulated by regime intensity.
if (displayMode == "Histogram" || displayMode == "Line + Histogram") {
    var histColor = hist >= 0 ? bullColor : bearColor
    var histColorFinal = regime == 2 ? highActivityColor : histColor

    plotBar(
        value=hist,
        colors=[histColorFinal],
        width=1,
        label=["RVOL Hist"],
        desc=["RVOL histogram (RVOL − 1.0) | current=" + rvolRaw[0]]
    )
}

// --- Z-Score Only Plot ---
if (displayMode == "Z-Score Only") {
    plotLine(
        value=rvolZ,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=rvolZ > 0.5 ? 0 : (rvolZ < -0.5 ? 1 : 2),
        label=["RVOL Z"],
        desc=["RVOL Z-Score (" + zScoreLookback + ") | μ=" + rvolMean + " | σ=" + rvolStd]
    )
}

// --- Cumulative Relative Volume (CRV) Line ---
if (showCRV) {
    plotLine(
        value=crv,
        width=1,
        colors=[neutralColor],
        label=["CRV"],
        desc=["Cumulative Relative Volume — long-memory order flow measure"]
    )
}

// --- Anomaly Shape Markers (>2σ events) ---
// Diamond shapes flag statistical outliers per VPIN/Easley et al. framework.
if (showShapes) {
    if (isAnomaly && rvolZ > 0) {
        plotShape(
            value=rvolDisplay,
            shape="diamond",
            color=anomalyColor,
            width=4,
            label=["Vol Anomaly+"],
            desc=["Volume anomaly: Z=" + rvolZ + " | RVOL=" + rvolRaw[0] + " | abnormal participation spike"]
        )
    }
    if (isAnomaly && rvolZ < 0) {
        plotShape(
            value=rvolDisplay,
            shape="diamond",
            color=anomalyColor,
            width=4,
            label=["Vol Anomaly-"],
            desc=["Volume anomaly: Z=" + rvolZ + " | RVOL=" + rvolRaw[0] + " | abnormal participation collapse"]
        )
    }

    // High activity threshold shapes (non-Z-score mode)
    if (!useZScore && regime == 2) {
        plotShape(
            value=rvolDisplay,
            shape="triangleup",
            color=highActivityColor,
            width=3,
            label=["High Activity"],
            desc=["High activity: RVOL=" + rvolRaw[0] + " | above " + highActivityThresh + "x average"]
        )
    }
}

// ------------------------------------------------------------------------------
// Session Statistics Table (last bar only)
// ------------------------------------------------------------------------------
if (showStatsTable && isLastBar) {
    var avgSessionVol = sessionBarCount > 0 ? sessionTotalVol / sessionBarCount : 0.0
    var abovePct = sessionBarCount > 0 ? (aboveAvgCount / sessionBarCount * 100.0) : 0.0
    var belowPct = sessionBarCount > 0 ? (belowAvgCount / sessionBarCount * 100.0) : 0.0
    var highPct = sessionBarCount > 0 ? (highActivityCount / sessionBarCount * 100.0) : 0.0

    plotTable(
        data=[
            ["RVOL V2", "Session Stats"],
            ["Current RVOL", rvolRaw[0]],
            ["Smoothed RVOL", rvolSmooth[0]],
            [useZScore ? "RVOL Z-Score" : "Z-Score (off)", useZScore ? rvolZ[0] : "N/A"],
            ["Max RVOL", maxRVOL],
            ["Min RVOL", minRVOL == 999999.0 ? "N/A" : minRVOL],
            ["Above Avg %", abovePct],
            ["Below Avg %", belowPct],
            ["High Activity %", highPct],
            ["Anomaly Count", anomalyCount],
            ["CRV", crv]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=opacity("#0f172a", 40),
        headerBackgroundColor=opacity("#1e293b", 40),
        borderColor=opacity("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}