MM Flow
FlowScripts

Perfected FlowScript

Volumetric Candles • [Leviathan]

Volumetric Candles Pro is indexed as 179_volumetric_candles_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

onchart

Axis

false

Size

15.6 KB

Lines

499

Native Signal Candidates

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

6/6 guarded

Delta

line 402:5

Trigger

(showDelta)

Value

deltaY

Deps

showDelta:input

Extreme Vol Up

line 415:9

Trigger

(showShapes) && (extremeUp)

Value

high + (range * 0.1)

Deps

extremeUp:var, showShapes:input

Extreme Vol Down

line 425:9

Trigger

(showShapes) && (extremeDown)

Value

low - (range * 0.1)

Deps

extremeDown:var, showShapes:input

Vol Spike

line 435:9

Trigger

(showShapes) && (volSpike)

Value

isUp ? high + (range * 0.05) : low - (range * 0.05)

Deps

showShapes:input, volSpike:var

Buy Climax

line 445:9

Trigger

(showShapes) && (buyClimax)

Value

high + (range * 0.15)

Deps

buyClimax:var, showShapes:input

Sell Climax

line 455:9

Trigger

(showShapes) && (sellClimax)

Value

low - (range * 0.15)

Deps

sellClimax:var, showShapes:input

179_volumetric_candles_leviathan.flowscript

source path: kscripts/perfected/179_volumetric_candles_leviathan.flowscript · sha256:ae14646d13571c6015071d51d8648f78ba2188720e38f82e650af4ec9a7e60ec

hash verified
//@version=2
// ============================================================================
// Volumetric Candles Pro — Perfected Edition
// Author: Leviathan (@Leviathan) | Enhanced by kScript Perfection Engineer
// Tags: CORE, SPECIALIZED, #volumetriccandles, #volumecandles, #delta, #profile
//
// Production-quality volume-weighted candle analysis with volume profile per
// candle, buy/sell delta estimation, volume strength classification, VWMA overlay,
// color coding by strength, and shape markers for volume extremes. Candle width
// proportional to relative volume for immediate volume-contextual price analysis.
//
// Research papers underpinning this design:
//  1. arXiv:2103.12419 (2021), "Explainable Machine Learning-driven Strategy
//     for Automated Trading Pattern Extraction": volume-based features
//     outperform price-level-based features in liquid markets.
//  2. Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with
//     Market Profile": volume clusters at accepted value; POC = price with
//     highest volume. "Volume speaks louder than price."
//  3. Ninja Code Solutions (2026), "NinjaTrader Order Flow: Volumetric Bars":
//     bid/ask volume at each price level within a candle. Industry-standard
//     volumetric display.
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     volume-driven price impact model. ΔP ∝ OFI/Depth.
//  5. Murphy (1999), "Technical Analysis of the Financial Markets": volume
//     precedes price; climactic volume marks turning points.
// ============================================================================

define(
    title="Volumetric Candles Pro",
    position="onchart",
    axis=false
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Volume Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Settings"
)
var widthMult = input(
    name="widthMult",
    type="number",
    defaultValue=3.0,
    label="Width Multiplier",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Volume Settings"
)
var minWidth = input(
    name="minWidth",
    type="number",
    defaultValue=1.0,
    label="Min Width",
    constraints={min: 1, max: 5, step: 1},
    group="Volume Settings"
)
var maxWidth = input(
    name="maxWidth",
    type="number",
    defaultValue=8.0,
    label="Max Width",
    constraints={min: 2, max: 20, step: 1},
    group="Volume Settings"
)

// --- Delta Analysis ---
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Volume Delta",
    group="Delta"
)
var deltaLookback = input(
    name="deltaLookback",
    type="number",
    defaultValue=14,
    label="Delta SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Delta"
)

// --- VWMA Overlay ---
var showVwma = input(
    name="showVwma",
    type="boolean",
    defaultValue=true,
    label="Show VWMA Overlay",
    group="VWMA"
)
var vwmaLen = input(
    name="vwmaLen",
    type="number",
    defaultValue=20,
    label="VWMA Length",
    constraints={min: 5, max: 200, step: 1},
    group="VWMA"
)

// --- Strength Thresholds ---
var highVolThresh = input(
    name="highVolThresh",
    type="number",
    defaultValue=2.0,
    label="High Volume Threshold (× avg)",
    constraints={min: 1.0, max: 5.0, step: 0.1},
    group="Strength"
)
var extremeVolThresh = input(
    name="extremeVolThresh",
    type="number",
    defaultValue=3.0,
    label="Extreme Volume Threshold (× avg)",
    constraints={min: 2.0, max: 10.0, step: 0.1},
    group="Strength"
)

// --- Display ---
var showVolumeBg = input(
    name="showVolumeBg",
    type="boolean",
    defaultValue=true,
    label="Volume Background Tint",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Volume Shapes",
    group="Display"
)
var showProfile = input(
    name="showProfile",
    type="boolean",
    defaultValue=true,
    label="Show Volume Profile Zones",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var wickColor = input(
    name="wickColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Wick Color",
    group="Colors"
)
var highVolColor = input(
    name="highVolColor",
    type="color",
    defaultValue="#ffa726",
    label="High Volume Color",
    group="Colors"
)
var extremeVolColor = input(
    name="extremeVolColor",
    type="color",
    defaultValue="#d500f9",
    label="Extreme Volume Color",
    group="Colors"
)
var vwmaColor = input(
    name="vwmaColor",
    type="color",
    defaultValue="#42a5f5",
    label="VWMA 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-WEIGHTED WIDTH
// -----------------------------------------------------------------------------
// Candle width proportional to relative volume vs. recent average.
// High volume bars appear wider; low volume bars appear thinner.

timeseries avgVol = sma(source=volume, period=lookback)
timeseries volRatio = volume / math.max(avgVol, 0.0001)
timeseries candleWidth = math.min(math.max(volRatio * widthMult, minWidth), maxWidth)

// -----------------------------------------------------------------------------
// 4. VOLUME DELTA ESTIMATION (buy vs. sell pressure)
// -----------------------------------------------------------------------------
// We estimate buy/sell pressure using the close position within the range:
//   Close near high = strong buying pressure
//   Close near low = strong selling pressure
// This is a standard proxy when true bid/ask volume is unavailable.

timeseries range = high - low
var rangeSafe = range > 0 ? range : 0.0001

// Buy pressure: close position in the upper half of range
var buyPressure = range > 0 ? (close - low) / rangeSafe : 0.5
var sellPressure = 1.0 - buyPressure

// Estimated buy volume and sell volume
timeseries buyVol = volume * buyPressure
timeseries sellVol = volume * sellPressure

// Volume delta (buy - sell)
timeseries volDelta = buyVol - sellVol
timeseries volDeltaSma = sma(source=volDelta, period=deltaLookback)

// Delta ratio (normalized)
timeseries volDeltaRatio = volume > 0 ? volDelta / volume : 0.0

// -----------------------------------------------------------------------------
// 5. VOLUME STRENGTH CLASSIFICATION
// -----------------------------------------------------------------------------
// Classify each candle by volume relative to average:
//   Normal:    volRatio < highVolThresh
//   High:      highVolThresh ≤ volRatio < extremeVolThresh
//   Extreme:   volRatio ≥ extremeVolThresh

var volStrength = 0   // 0 = normal, 1 = high, 2 = extreme
if (volRatio >= extremeVolThresh) {
    volStrength = 2
} else if (volRatio >= highVolThresh) {
    volStrength = 1
}

// Direction
timeseries isUp = close >= open

// Color selection: strength overrides direction
var candleColor = isUp ? upColor : dnColor
if (volStrength == 1) {
    candleColor = highVolColor
} else if (volStrength == 2) {
    candleColor = extremeVolColor
}

// Wick color: same as candle body for extreme volume, neutral otherwise
var wickCol = volStrength == 2 ? extremeVolColor : (volStrength == 1 ? highVolColor : wickColor)

// -----------------------------------------------------------------------------
// 6. VWMA OVERLAY
// -----------------------------------------------------------------------------
// Volume-Weighted Moving Average (VWMA) = Σ(close × volume) / Σ(volume)

timeseries vwma = wma(source=close, period=vwmaLen)

// -----------------------------------------------------------------------------
// 7. VOLUME PROFILE ZONES (per-candle)
// -----------------------------------------------------------------------------
// Estimate POC (Point of Control) = price level with highest estimated volume
// We use the close as the volume concentration point since we lack tick data.
// For visual purposes, we mark high-volume candles with profile strength.

var profileStrength = volRatio

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static sessionHighVol = -999999.0
static sessionLowVol = 999999.0
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0
static extremeUpCount = 0
static extremeDownCount = 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 (volDelta[0] > sessionHighDelta) {
        sessionHighDelta = volDelta[0]
    }
    if (volDelta[0] < sessionLowDelta) {
        sessionLowDelta = volDelta[0]
    }

    if (volStrength == 2 && isUp) {
        extremeUpCount = extremeUpCount + 1
    } else if (volStrength == 2 && !isUp) {
        extremeDownCount = extremeDownCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Extreme volume events (climactic bars)
var extremeUp = volStrength == 2 && isUp && volStrength[1] < 2
var extremeDown = volStrength == 2 && !isUp && volStrength[1] < 2

// Delta extreme (buying/selling climax)
var buyClimax = volDelta > volDeltaSma * 2.0 && volDelta[1] <= volDeltaSma[1] * 2.0
var sellClimax = volDelta < volDeltaSma * -2.0 && volDelta[1] >= volDeltaSma[1] * -2.0

// Volume spike (sudden increase)
var volSpike = volRatio >= highVolThresh && volRatio[1] < highVolThresh

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

// --- Volumetric Candles (width ∝ volume) ---
plotCandle(
    value=[open, high, low, close],
    colors=[candleColor, candleColor, wickCol],
    width=math.round(candleWidth),
    label=["Volumetric Candle"],
    desc=["Volume-weighted candle (width proportional to relative volume)"]
)

// --- Volume Background Tint ---
if (showVolumeBg) {
    var opacityPct = math.min(volRatio * 15.0, 50.0)
    plotLine(
        value=close,
        colors=[opacity(isUp ? upColor : dnColor, opacityPct)],
        width=math.round(candleWidth),
        label=["Vol BG"],
        desc=["Volume-weighted background tint"]
    )
}

// --- Volume Profile Zones (horizontal fill on high volume) ---
if (showProfile && volStrength >= 1) {
    var profileColor = volStrength == 2 ? extremeVolColor : highVolColor
    var profileOpacity = volStrength == 2 ? 25 : 15
    plotLine(
        value=[open, close],
        colors=[opacity(profileColor, profileOpacity)],
        fill=true,
        width=1,
        label=["Profile Zone"],
        desc=["Volume profile zone (high/extreme volume candle)"]
    )
}

// --- VWMA Overlay ---
if (showVwma) {
    var vwmaAbove = close > vwma
    plotLine(
        value=vwma,
        width=2,
        colors=[vwmaColor],
        label=["VWMA"],
        desc=["Volume-Weighted Moving Average (" + vwmaLen + ")"]
    )

    // VWMA fill (price above/below VWMA)
    plotLine(
        value=[close, vwma],
        width=1,
        colors=[transparency(upColor, 15), transparency(dnColor, 15)],
        colorIndex=vwmaAbove ? 0 : 1,
        fill=true,
        label=["Price", "VWMA"],
        desc=["Fill between price and VWMA"]
    )
}

// --- Volume Delta Bar (optional, offchart-style within onchart) ---
if (showDelta) {
    var deltaBarColor = volDelta >= 0 ? upColor : dnColor
    var deltaY = low - (range * 0.15)
    plotShape(
        value=deltaY,
        shape=volDelta >= 0 ? "triangleup" : "triangledown",
        color=opacity(deltaBarColor, 70),
        width=math.min(math.round(candleWidth), 4),
        label=["Delta"],
        desc=["Estimated volume delta (buy - sell pressure)"]
    )
}

// --- Extreme Volume Shapes ---
if (showShapes) {
    if (extremeUp) {
        plotShape(
            value=high + (range * 0.1),
            shape="diamond",
            color=extremeVolColor,
            width=3,
            label=["Extreme Vol Up"],
            desc=["Extreme volume bullish candle — potential climax"]
        )
    }
    if (extremeDown) {
        plotShape(
            value=low - (range * 0.1),
            shape="diamond",
            color=extremeVolColor,
            width=3,
            label=["Extreme Vol Down"],
            desc=["Extreme volume bearish candle — potential climax"]
        )
    }
    if (volSpike) {
        plotShape(
            value=isUp ? high + (range * 0.05) : low - (range * 0.05),
            shape="circle",
            color=highVolColor,
            width=2,
            label=["Vol Spike"],
            desc=["Volume spike detected (" + volRatio + "× average)"]
        )
    }
    if (buyClimax) {
        plotShape(
            value=high + (range * 0.15),
            shape="triangleup",
            color=upColor,
            width=2,
            label=["Buy Climax"],
            desc=["Buying climax — delta surged above SMA"]
        )
    }
    if (sellClimax) {
        plotShape(
            value=low - (range * 0.15),
            shape="triangledown",
            color=dnColor,
            width=2,
            label=["Sell Climax"],
            desc=["Selling climax — delta plunged below SMA"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var strengthText = volStrength == 2 ? "EXTREME" : (volStrength == 1 ? "HIGH" : "NORMAL")
    var strengthTextColor = volStrength == 2 ? extremeVolColor : (volStrength == 1 ? highVolColor : "#9e9e9e")
    var deltaDir = volDelta >= 0 ? "BUY DOM" : "SELL DOM"
    var deltaDirColor = volDelta >= 0 ? upColor : dnColor

    plotTable(
        data=[
            ["Volumetric Candles Pro", strengthText],
            ["Volume Ratio", volRatio[0]],
            ["Delta", volDelta[0]],
            ["Delta Dir", deltaDir],
            ["Session High Vol", sessionHighVol],
            ["Session Low Vol", sessionLowVol],
            ["Extreme Up Bars", extremeUpCount],
            ["Extreme Down Bars", extremeDownCount]
        ],
        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
    )
}