MM Flow
FlowScripts

Perfected FlowScript

Volume Zone Oscillator

Volume Zone Oscillator Pro is indexed as 094_volume_zone_oscillator.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

13.8 KB

Lines

450

Native Signal Candidates

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

6/6 guarded

Buy Zone Entry

line 357:9

Trigger

(showShapes) && (zoneCrossUp)

Value

vzo

Deps

showShapes:input, zoneCrossUp:var

Sell Zone Entry

line 367:9

Trigger

(showShapes) && (zoneCrossDown)

Value

vzo

Deps

showShapes:input, zoneCrossDown:var

Neutral from Sell

line 377:9

Trigger

(showShapes) && (neutralCrossUp)

Value

vzo

Deps

neutralCrossUp:var, showShapes:input

Neutral from Buy

line 387:9

Trigger

(showShapes) && (neutralCrossDown)

Value

vzo

Deps

neutralCrossDown:var, showShapes:input

Extreme Buy

line 399:9

Trigger

(showShapes) && (inExtremeBuy)

Value

extremeLevel

Deps

inExtremeBuy:var, showShapes:input

Extreme Sell

line 409:9

Trigger

(showShapes) && (inExtremeSell)

Value

-extremeLevel

Deps

inExtremeSell:var, showShapes:input

094_volume_zone_oscillator.flowscript

source path: kscripts/perfected/094_volume_zone_oscillator.flowscript · sha256:3e0eb527980159eb6ab0277ffca69b5ccfa0c1342e709ef6f82945a25a12a6d9

hash verified
//@version=2

// ============================================================================
// Volume Zone Oscillator Pro — Volume-Weighted Momentum with Regime Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, VOLUME, #vzo, #zone, #regime, #momentum
//
// Computes a signed-volume oscillator normalized to ±100, with threshold-based
// regime coloring, zone-change shape alerts, histogram fill, and cumulative
// state tracking. The VZO distinguishes between buyer-dominated zones,
// seller-dominated zones, and neutral chop by combining volume direction with
// momentum persistence.
//
// Academic foundation (exact papers & formulas):
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Tick-test classification:
//     close > open → buyer-initiated; close < open → seller-initiated.
//     Accuracy 85–93%. Underpins the signed-volume calculation.
//     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 = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}
//     Price changes driven linearly by order-flow imbalance.
//     Validates volume-zone momentum as a predictive signal.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme signed imbalances predict return reversals. Motivates the
//     overbought/oversold zone threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  4. Steidlmayer & Hawkins (2003), "Steidlmayer on Markets: Trading with
//     Market Profile". Volume-based market analysis framework. Value Area
//     (70% of volume) and extreme zones (top/bottom 15%) map to the VZO
//     zone-threshold concept.
//
//  5. Wilder (1978), "New Concepts in Technical Trading Systems". Canonical
//     RSI formulation (RSI = 100 − 100/(1+RS)) inspires the bounded ±100
//     oscillator design and the zone-based interpretation framework.
//
//  6. Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//     Activity". Probabilistic bucket-based classification; volume direction is
//     more robust in aggregate than trade-by-trade. Validates signed-volume
//     aggregation at the bar level.
// ============================================================================

define(title="Volume Zone Oscillator Pro", position="offchart", axis=true)

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

// -- Computation --
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=14,
    label="Smoothing Length",
    constraints={min: 2, max: 50, step: 1},
    group="Computation"
)
var avgLen = input(
    name="avgLen",
    type="number",
    defaultValue=14,
    label="Average (Signal) Length",
    constraints={min: 2, max: 50, step: 1},
    group="Computation"
)
var useEMA = input(
    name="useEMA",
    type="boolean",
    defaultValue=true,
    label="Use EMA Smoothing (off = SMA)",
    group="Computation"
)

// -- Zone Thresholds --
var zoneBuyLevel = input(
    name="zoneBuyLevel",
    type="number",
    defaultValue=40,
    label="Strong Buying Zone Threshold",
    constraints={min: 20, max: 70, step: 5},
    group="Zone Thresholds"
)
var zoneSellLevel = input(
    name="zoneSellLevel",
    type="number",
    defaultValue=40,
    label="Strong Selling Zone Threshold",
    constraints={min: 20, max: 70, step: 5},
    group="Zone Thresholds"
)
var extremeLevel = input(
    name="extremeLevel",
    type="number",
    defaultValue=60,
    label="Extreme Zone Threshold",
    constraints={min: 40, max: 90, step: 5},
    group="Zone Thresholds"
)

// -- Display --
var showVZO = input(
    name="showVZO",
    type="boolean",
    defaultValue=true,
    label="Show VZO Line",
    group="Display"
)
var showAvg = input(
    name="showAvg",
    type="boolean",
    defaultValue=true,
    label="Show Signal Average",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Zone Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show VZO/Average Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Zone-Change Shapes",
    group="Display"
)
var showZoneBands = input(
    name="showZoneBands",
    type="boolean",
    defaultValue=true,
    label="Show Zone Band Lines",
    group="Display"
)

// -- Colors --
var buyZoneColor = input(
    name="buyZoneColor",
    type="color",
    defaultValue="#00c853",
    label="Buying Zone Color",
    group="Colors"
)
var sellZoneColor = input(
    name="sellZoneColor",
    type="color",
    defaultValue="#d50000",
    label="Selling Zone Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var avgColor = input(
    name="avgColor",
    type="color",
    defaultValue="#ff9800",
    label="Signal Line Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries open = bars.open
timeseries vol = bars.volume

// Guard: halt until all OHLCV data have loaded
if (isnan(close[0]) || isnan(open[0]) || isnan(vol[0])) {
    return
}

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

// -- 3.1 Signed volume (Lee-Ready 1991 tick test at bar level) --
// Positive when close > open (buyer-initiated), negative when close < open.
var isUpBar = close > open
var isDnBar = close < open
var signedVol = isUpBar ? vol : (isDnBar ? -vol : 0)

// -- 3.2 Smooth signed and absolute volume --
var smoothSigned = useEMA ? ema(source=signedVol, period=smoothLen) : sma(source=signedVol, period=smoothLen)
var smoothTotal = useEMA ? ema(source=vol, period=smoothLen) : sma(source=vol, period=smoothLen)

// -- 3.3 VZO = 100 × signed / total (bounded ±100 oscillator) --
// Per the Wilder (1978) bounded-oscillator convention.
var vzo = smoothTotal > 0 ? 100.0 * smoothSigned / smoothTotal : 0

// -- 3.4 VZO signal average (smoother reference line) --
var vzoAvg = useEMA ? ema(source=vzo, period=avgLen) : sma(source=vzo, period=avgLen)

// -- 3.5 Momentum (VZO minus average) --
var vzoMomentum = vzo - vzoAvg

// -- 3.6 Zone regime detection --
// Zone classifications per Steidlmayer / Market Profile framework adapted to VZO:
//   Strong Buy:  VZO > +zoneBuyLevel
//   Weak Buy:    0 < VZO ≤ +zoneBuyLevel
//   Neutral:     −zoneSellLevel ≤ VZO ≤ +zoneBuyLevel
//   Weak Sell:   −zoneSellLevel ≤ VZO < 0
//   Strong Sell: VZO < −zoneSellLevel
//   Extreme:     |VZO| > extremeLevel

var inBuyZone = vzo > zoneBuyLevel
var inSellZone = vzo < -zoneSellLevel
var inNeutral = !inBuyZone && !inSellZone
var inExtremeBuy = vzo > extremeLevel
var inExtremeSell = vzo < -extremeLevel
var inWeakBuy = vzo > 0 && vzo <= zoneBuyLevel
var inWeakSell = vzo < 0 && vzo >= -zoneSellLevel

// -- 3.7 Zone state tracking via static variables --
// Detects zone transitions (crossings) for shape alerts.
static prevZone = 0
static buyZoneBars = 0
static sellZoneBars = 0
static neutralBars = 0

var zoneCrossUp = false
var zoneCrossDown = false
var neutralCrossUp = false
var neutralCrossDown = false

var currZone = inBuyZone ? 1 : (inSellZone ? -1 : 0)

if (currZone == 1) {
    buyZoneBars = buyZoneBars + 1
    sellZoneBars = 0
    neutralBars = 0
    if (prevZone != 1) {
        zoneCrossUp = true
    }
} else if (currZone == -1) {
    sellZoneBars = sellZoneBars + 1
    buyZoneBars = 0
    neutralBars = 0
    if (prevZone != -1) {
        zoneCrossDown = true
    }
} else {
    neutralBars = neutralBars + 1
    buyZoneBars = 0
    sellZoneBars = 0
    if (prevZone == 1) {
        neutralCrossDown = true
    } else if (prevZone == -1) {
        neutralCrossUp = true
    }
}
prevZone = currZone

// -- 3.8 Zero-line helper --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 Zero line and zone band hlines
hline(value=0, color="#ffffff30", width=1)

if (showZoneBands) {
    hline(value=zoneBuyLevel, color=transparency(buyZoneColor, 50), width=1)
    hline(value=-zoneSellLevel, color=transparency(sellZoneColor, 50), width=1)
    hline(value=extremeLevel, color=transparency(buyZoneColor, 40), width=1)
    hline(value=-extremeLevel, color=transparency(sellZoneColor, 40), width=1)
}

// 4.2 VZO line with zone-based color coding
var vzoColor = inBuyZone ? buyZoneColor : (inSellZone ? sellZoneColor : neutralColor)
if (showVZO) {
    plotLine(
        value=vzo,
        width=2,
        colors=[vzoColor],
        label=["VZO"],
        desc=["Volume Zone Oscillator: signed volume momentum normalised to ±100"]
    )
}

// 4.3 Signal average line
if (showAvg) {
    plotLine(
        value=vzoAvg,
        width=1,
        colors=[avgColor],
        label=["VZO Signal"],
        desc=["Smoothed average of VZO (" + avgLen + ")"]
    )
}

// 4.4 VZO vs Signal fill
if (showFill) {
    var fillBull = vzo > vzoAvg
    plotLine(
        value=[vzo, vzoAvg],
        width=1,
        colors=[transparency(buyZoneColor, 20), transparency(sellZoneColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["VZO", "Signal"],
        desc=["Fill between VZO and signal average"]
    )
}

// 4.5 Zone histogram (plotBar with colorIndex)
if (showHistogram) {
    var histColorIdx = inBuyZone ? 0 : (inSellZone ? 1 : 2)
    plotBar(
        value=vzo,
        colors=[transparency(buyZoneColor, 60), transparency(sellZoneColor, 60), transparency(neutralColor, 60)],
        colorIndex=histColorIdx,
        width=1,
        label=["VZO Histogram"],
        desc=["Volume Zone Oscillator as histogram; color-coded by zone regime"]
    )

    // Momentum histogram (VZO - average)
    var momentumBull = vzoMomentum >= 0
    plotBar(
        value=vzoMomentum,
        colors=[transparency(buyZoneColor, 40), transparency(sellZoneColor, 40)],
        colorIndex=momentumBull ? 0 : 1,
        width=1,
        label=["VZO Momentum"],
        desc=["VZO minus signal average; momentum histogram"]
    )
}

// 4.6 Zone-change shape alerts
if (showShapes) {
    // Zone crossing shapes
    if (zoneCrossUp) {
        plotShape(
            value=vzo,
            shape="triangleup",
            colorIndex=buyZoneColor,
            width=2,
            label=["Buy Zone Entry"],
            desc=["VZO crossed into strong buying zone (> +" + zoneBuyLevel + ")"]
        )
    }
    if (zoneCrossDown) {
        plotShape(
            value=vzo,
            shape="triangledown",
            colorIndex=sellZoneColor,
            width=2,
            label=["Sell Zone Entry"],
            desc=["VZO crossed into strong selling zone (< −" + zoneSellLevel + ")"]
        )
    }
    if (neutralCrossUp) {
        plotShape(
            value=vzo,
            shape="circle",
            colorIndex=neutralColor,
            width=2,
            label=["Neutral from Sell"],
            desc=["VZO returned to neutral from selling zone"]
        )
    }
    if (neutralCrossDown) {
        plotShape(
            value=vzo,
            shape="circle",
            colorIndex=neutralColor,
            width=2,
            label=["Neutral from Buy"],
            desc=["VZO returned to neutral from buying zone"]
        )
    }

    // Extreme zone shapes
    if (inExtremeBuy) {
        plotShape(
            value=extremeLevel,
            shape="xcross",
            colorIndex=buyZoneColor,
            width=2,
            label=["Extreme Buy"],
            desc=["VZO in extreme buying zone (> +" + extremeLevel + "); potential reversal zone"]
        )
    }
    if (inExtremeSell) {
        plotShape(
            value=-extremeLevel,
            shape="xcross",
            colorIndex=sellZoneColor,
            width=2,
            label=["Extreme Sell"],
            desc=["VZO in extreme selling zone (< −" + extremeLevel + "); potential reversal zone"]
        )
    }
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = inBuyZone ? "BUY ZONE" : (inSellZone ? "SELL ZONE" : "NEUTRAL")
    var regimeTextColor = inBuyZone ? buyZoneColor : (inSellZone ? sellZoneColor : neutralColor)

    plotTable(
        data=[
            ["VZO Pro", regimeText],
            ["VZO", vzo[0]],
            ["Signal", vzoAvg[0]],
            ["Momentum", vzoMomentum[0]],
            ["Buy Zone Bars", buyZoneBars],
            ["Sell Zone Bars", sellZoneBars],
            ["Extreme", inExtremeBuy || inExtremeSell ? "YES" : "NO"]
        ],
        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
    )
}