MM Flow
FlowScripts

Perfected FlowScript

Volume Ratio Overlay • [Leviathan]

Volume Ratio Overlay V2 is indexed as 051_volume_ratio_overlay_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

13.1 KB

Lines

308

Native Signal Candidates

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

3/3 guarded

Divergence

line 232:9

Trigger

(showDots) && (!isnan(dotY))

Value

dotY

Deps

dotY:timeseries, showDots:input

Extreme Buy Ratio

line 282:5

Trigger

(showShapes && ratioExtremeBull)

Value

smoothedRatio

Deps

ratioExtremeBull:var, showShapes:input

Extreme Sell Ratio

line 292:5

Trigger

(showShapes && ratioExtremeBear)

Value

smoothedRatio

Deps

ratioExtremeBear:var, showShapes:input

051_volume_ratio_overlay_leviathan.flowscript

source path: kscripts/perfected/051_volume_ratio_overlay_leviathan.flowscript · sha256:f5deb8c89469e32a7e71d67773cded49e0036dccfda9c2215314426b0afa1dd8

hash verified
//@version=2

// ============================================================================
// Volume Ratio Overlay V2 — Buy/Sell Volume Ratio Regime Indicator
// Author: Leviathan (@Leviathan) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #volume, #delta, #ratio, #leviathan
//
// Candle-body overlay visualizing buy / sell volume ratio as a proportional
// overlay, plus a standalone volume-ratio oscillator with regime detection,
// histogram, and extreme-ratio shape alerts. When the ratio diverges from
// price direction (e.g., price rising but sell volume dominant), the overlay
// darkens and the oscillator flags potential exhaustion.
//
// Academic foundation (exact papers & formulas):
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.
//     [Formula] Tick test: close > open → buyer-initiated; else seller-initiated.
//     Achieved 85–93% accuracy on NYSE TORQ data. Foundational for all buy/sell
//     volume classification.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Σ(E_bid^i − E_ask^i); price change ∝ OFI / depth.
//     Validates that order flow imbalance drives short-term price changes; the
//     divergence signals in this script flag when price moves against the flow.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//     Activity" (BVC). Probabilistic volume classification in aggregate buckets
//     based on price distribution within a bar; more robust than tick-test in
//     HFT/crypto environments.
//     DOI: SSRN 1989555
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates the extreme-ratio alert design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ establishes the linear price-impact coefficient that underpins
//     every delta-based trading signal.
//     DOI: https://doi.org/10.2307/1913210
//
//  6. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow autocorrelations decay as a power law; cumulative measures
//     capture sustained pressure. Justifies static session tracking of ratio
//     regimes and cumulative buy/sell imbalance.
//     DOI: https://arxiv.org/abs/cond-mat/0311053
// ============================================================================

define(
    title="Volume Ratio Overlay V2",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var ratioWindow = input(name="ratioWindow", type="number", defaultValue=20, label="Volume Ratio SMA Window", constraints={min: 5, max: 100, step: 5}, group="Computation")
var smoothLen   = input(name="smoothLen",   type="number", defaultValue=5,  label="Ratio EMA Smooth", constraints={min: 1, max: 50, step: 1}, group="Computation")
var divThresh   = input(name="divThresh",   type="number", defaultValue=0.6, label="Divergence Threshold (opposing share)", constraints={min: 0.1, max: 0.95, step: 0.05}, group="Computation")
var bullRatio   = input(name="bullRatio",   type="number", defaultValue=1.5, label="Bullish Ratio Threshold (>1 = buy heavy)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Computation")
var bearRatio   = input(name="bearRatio",   type="number", defaultValue=0.67, label="Bearish Ratio Threshold (<1 = sell heavy)", constraints={min: 0.1, max: 0.99, step: 0.01}, group="Computation")
var extremeRatio = input(name="extremeRatio", type="number", defaultValue=2.5, label="Extreme Ratio Threshold", constraints={min: 1.5, max: 10.0, step: 0.1}, group="Computation")

// -- Display --
var showOverlay   = input(name="showOverlay",   type="boolean", defaultValue=true,  label="Show Candle Overlay", group="Display")
var showOscillator = input(name="showOscillator", type="boolean", defaultValue=true,  label="Show Ratio Oscillator", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true,  label="Show Ratio Histogram", group="Display")
var showShapes    = input(name="showShapes",    type="boolean", defaultValue=true,  label="Show Extreme Ratio Shapes", group="Display")
var showDots      = input(name="showDots",      type="boolean", defaultValue=true,  label="Show Divergence Dots", group="Display")
var showVolSMA    = input(name="showVolSMA",    type="boolean", defaultValue=false, label="Show Volume SMA Line", group="Display")

// -- Colors --
var upColor       = input(name="upColor",       type="color", defaultValue="#26a69a", label="Up Candle Body", group="Colors")
var dnColor       = input(name="dnColor",       type="color", defaultValue="#ef5350", label="Down Candle Body", group="Colors")
var overlayCol    = input(name="overlayCol",    type="color", defaultValue="#212121", label="Overlay Color", group="Colors")
var dotColor      = input(name="dotColor",      type="color", defaultValue="#ffeb3b", label="Divergence Dot Color", group="Colors")
var bullCol       = input(name="bullCol",       type="color", defaultValue="#00c853", label="Bullish Ratio Color", group="Colors")
var bearCol       = input(name="bearCol",       type="color", defaultValue="#d50000", label="Bearish Ratio Color", group="Colors")
var neutralCol    = input(name="neutralCol",    type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o    = pxTS.open
timeseries h    = pxTS.high
timeseries l    = pxTS.low
timeseries c    = pxTS.close
timeseries v    = pxTS.volume

// Guard: halt until external feeds have loaded to avoid NaN propagation
if (isnan(pxTS.close[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Tick-rule classification (Lee-Ready 1991 fallback) --
// Lee-Ready: close > open → buyer-initiated; close < open → seller-initiated.
// When taker.buy/sell feeds are available, we prefer the direct feed for accuracy.
timeseries takerVol = source("taker_volume", currentSymbol, currentExchange)

timeseries buyVol = isnum(takerVol.buy) ? takerVol.buy : (c > o ? v : 0)
timeseries sellVol = isnum(takerVol.sell) ? takerVol.sell : (c <= o ? v : 0)

// -- 3.2 Volume ratio (buy/sell) with zero-division guard --
timeseries totalFlow = buyVol + sellVol
timeseries rawRatio = (totalFlow > 0) ? (buyVol / totalFlow) * 2.0 : 1.0
// Normalized: 1.0 = balanced, >1 = buy heavy, <1 = sell heavy
// rawRatio = 2*(buy/total) so buy=total → 2.0, sell=total → 0.0, balanced → 1.0

// Alternative: buy/sell ratio directly
timeseries buySellRatio = (sellVol > 0) ? (buyVol / sellVol) : 1.0

// -- 3.3 Volume SMA / relative volume --
timeseries volSMA = sma(v, ratioWindow)
timeseries volRatio = (volSMA > 0) ? (v / volSMA) : 1.0

// -- 3.4 Smoothed ratio for oscillator --
timeseries smoothedRatio = ema(buySellRatio, smoothLen)

// -- 3.5 Regime detection (configurable thresholds, no magic numbers) --
var ratioBull = smoothedRatio > bullRatio
var ratioBear = smoothedRatio < bearRatio
var ratioNeutral = !ratioBull && !ratioBear
var ratioExtremeBull = smoothedRatio > extremeRatio
var ratioExtremeBear = smoothedRatio < (1.0 / extremeRatio)

// -- 3.6 Divergence flags (price direction contradicts volume delta) --
timeseries bodyCol = c >= o ? upColor : dnColor
timeseries isBullish = c >= o

timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)
timeseries buyShare = range_ > 0 ? upW / range_ : 0.5
timeseries sellShare = range_ > 0 ? dnW / range_ : 0.5

timeseries bullDiv = isBullish && sellShare > divThresh
timeseries bearDiv = !isBullish && buyShare > divThresh

// -- 3.7 Static state tracking — session-level persistence (Lillo & Farmer 2004) --
// Tracks cumulative buy/sell flow, regime duration, and session extremes.
static cumBuyVol = 0.0
static cumSellVol = 0.0
static ratioBullBars = 0
static ratioBearBars = 0
static lastRegime = 0
static sessionHighRatio = 0.0
static sessionLowRatio = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (!isnan(buyVol[0])) {
        cumBuyVol = cumBuyVol + buyVol[0]
    }
    if (!isnan(sellVol[0])) {
        cumSellVol = cumSellVol + sellVol[0]
    }

    if (smoothedRatio > sessionHighRatio) {
        sessionHighRatio = smoothedRatio
    }
    if (smoothedRatio < sessionLowRatio && smoothedRatio > 0) {
        sessionLowRatio = smoothedRatio
    }

    if (ratioBull) {
        ratioBullBars = ratioBullBars + 1
        ratioBearBars = 0
        lastRegime = 1
    } else if (ratioBear) {
        ratioBearBars = ratioBearBars + 1
        ratioBullBars = 0
        lastRegime = -1
    } else {
        ratioBullBars = 0
        ratioBearBars = 0
        lastRegime = 0
    }

    if (ratioExtremeBull) {
        extremeBullCount = extremeBullCount + 1
    }
    if (ratioExtremeBear) {
        extremeBearCount = extremeBearCount + 1
    }
}

// Cumulative session ratio (static-tracked)
timeseries cumRatio = (cumSellVol > 0) ? (cumBuyVol / cumSellVol) : 1.0

// -- 3.8 Zero-line and reference levels for oscillator --
timeseries zeroLine = 1.0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Candle overlay (original Leviathan visual)
if (showOverlay) {
    plotCandle(
        value=pxTS,
        colors=[upColor, dnColor, bodyCol, overlayCol],
        label=["Open", "High", "Low", "Close"],
        desc=["Volume-Ratio overlay body with buy/sell classification"]
    )
}

// 4.2 Divergence dots (original Leviathan feature)
if (showDots) {
    timeseries dotY = bullDiv ? h : (bearDiv ? l : na)
    if (!isnan(dotY)) {
        plotShape(
            value=dotY,
            shape="circle",
            colorIndex=dotColor,
            width=3,
            label=["Divergence"],
            desc=["Opposing share exceeds divergence threshold (Lee-Ready classified)"]
        )
    }
}

// 4.3 Ratio oscillator with regime-coded fill area
// colorIndex: 0 = bullish, 1 = bearish, 2 = neutral
timeseries ratioColorIdx = ratioBull ? 0 : (ratioBear ? 1 : 2)
if (showOscillator) {
    plotLine(
        value=([smoothedRatio, zeroLine]),
        width=2,
        colors=[bullCol, bearCol, neutralCol],
        colorIndex=ratioColorIdx,
        label=["Volume Ratio"],
        desc=["Buy/Sell volume ratio EMA-smoothed; >1 = buy heavy, <1 = sell heavy, 1 = balanced"],
        fill=true
    )
}

// 4.4 Ratio histogram (bars colored by direction vs 1.0)
if (showHistogram) {
    plotBar(
        value=smoothedRatio - zeroLine,
        colors=[bullCol, bearCol],
        width=1,
        label=["Ratio Histogram"],
        desc=["Volume ratio centered at 1.0; positive = buy heavy, negative = sell heavy"]
    )
}

// 4.5 Volume SMA line (optional diagnostic)
if (showVolSMA) {
    plotLine(
        value=volSMA,
        width=1,
        colors=[opacity(neutralCol, 50)],
        label=["Volume SMA"],
        desc=["Rolling volume SMA; context for relative volume spikes"]
    )
}

// 4.6 Extreme ratio shapes (plotShape)
if (showShapes && ratioExtremeBull) {
    plotShape(
        value=smoothedRatio,
        shape="triangleup",
        color=bullCol,
        width=3,
        label=["Extreme Buy Ratio"],
        desc=["Buy volume massively exceeds sell volume; potential absorption / exhaustion zone"]
    )
}
if (showShapes && ratioExtremeBear) {
    plotShape(
        value=smoothedRatio,
        shape="triangledown",
        color=bearCol,
        width=3,
        label=["Extreme Sell Ratio"],
        desc=["Sell volume massively exceeds buy volume; potential absorption / distribution zone"]
    )
}

// 4.7 Reference thresholds (hline)
hline(value=1.0, color="#ffffff30", width=1)
hline(value=bullRatio, color=opacity(bullCol, 30), width=1)
hline(value=bearRatio, color=opacity(bearCol, 30), width=1)
hline(value=extremeRatio, color=opacity(bullCol, 20), width=1)
hline(value=1.0 / extremeRatio, color=opacity(bearCol, 20), width=1)