MM Flow
FlowScripts

Perfected FlowScript

OBV+

OBV+ — Perfected Edition is indexed as 148_obv_plus.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

14.6 KB

Lines

527

Native Signal Candidates

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

8/8 guarded

Bull Div

line 412:9

Trigger

(showAlerts && enableDiv) && (bullDiv)

Value

obvSmooth

Deps

bullDiv:var, enableDiv:input, showAlerts:input

Bear Div

line 422:9

Trigger

(showAlerts && enableDiv) && (bearDiv)

Value

obvSmooth

Deps

bearDiv:var, enableDiv:input, showAlerts:input

Hidden Bull

line 432:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBullDiv)

Value

obvSmooth

Deps

enableDiv:input, hiddenBullDiv:var, showAlerts:input, showHidden:input

Hidden Bear

line 442:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBearDiv)

Value

obvSmooth

Deps

enableDiv:input, hiddenBearDiv:var, showAlerts:input, showHidden:input

Cross Up

line 456:9

Trigger

(showAlerts) && (crossUp)

Value

obvSignal

Deps

crossUp:var, showAlerts:input

Cross Down

line 466:9

Trigger

(showAlerts) && (crossDown)

Value

obvSignal

Deps

crossDown:var, showAlerts:input

Z+ Extreme

line 476:9

Trigger

(showAlerts) && (zExtremeHigh)

Value

obvSmooth

Deps

showAlerts:input, zExtremeHigh:var

Z- Extreme

line 486:9

Trigger

(showAlerts) && (zExtremeLow)

Value

obvSmooth

Deps

showAlerts:input, zExtremeLow:var

148_obv_plus.flowscript

source path: kscripts/perfected/148_obv_plus.flowscript · sha256:bb782f3705b3460d2363436deccf6cd7bf5ec9384aad9f645e185935a1eb060c

hash verified
//@version=2
// ============================================================================
// OBV+ — Perfected Edition
// Author: C (@chaincoder) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #obv, #volume, #divergence, #momentum, #zscore
//
// Production-quality enhanced On Balance Volume. Implements Granville's
// canonical OBV with multiple smoothing options, signal line, full stateful
// divergence detection (regular + hidden), z-score normalization, dynamic
// banding, regime color coding, fill/shape visualization, and a comprehensive
// regime table.
//
// Research papers underpinning this design:
//  1. Granville (1963), "Granville's New Key to Stock Market Profits":
//     original OBV publication. OBV_t = OBV_{t-1} ± Volume_t.
//  2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     OFI framework validates volume-direction classification; divergence
//     between price and volume pressure signals weakening momentum.
//  3. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand": liquidity memory time explains why volume precedes
//     price; volume accumulation without price = coiled spring.
//  4. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//     Stock Returns": sentiment-driven volume flows create persistent
//     divergences from fundamental price trends.
// ============================================================================

define(
    title="OBV+ — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- OBV Settings ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=14,
    label="OBV Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="OBV Settings"
)
var smoothType = input(
    name="smoothType",
    type="select",
    defaultValue="EMA",
    label="Smoothing Type",
    options=["EMA", "SMA", "WMA"],
    group="OBV Settings"
)

// --- Signal Line ---
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal Line Length",
    constraints={min: 2, max: 50, step: 1},
    group="Signal"
)
var signalType = input(
    name="signalType",
    type="select",
    defaultValue="SMA",
    label="Signal Type",
    options=["SMA", "EMA"],
    group="Signal"
)

// --- Z-Score ---
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Panel",
    group="Z-Score"
)

// --- Divergence ---
var enableDiv = input(
    name="enableDiv",
    type="boolean",
    defaultValue=true,
    label="Enable Divergence Detection",
    group="Divergence"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=10,
    label="Divergence Lookback",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)
var showHidden = input(
    name="showHidden",
    type="boolean",
    defaultValue=true,
    label="Show Hidden Divergence",
    group="Divergence"
)

// --- Bands ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Reference Bands",
    group="Bands"
)
var bandColor = input(
    name="bandColor",
    type="color",
    defaultValue="#ff5252",
    label="Band Color",
    group="Bands"
)

// --- Display ---
var showObvLine = input(
    name="showObvLine",
    type="boolean",
    defaultValue=true,
    label="Show OBV Line",
    group="Display"
)
var showSignalLine = input(
    name="showSignalLine",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show OBV/Signal Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#ffffff",
    label="OBV Line Color",
    group="Colors"
)
var divBullColor = input(
    name="divBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Divergence Color",
    group="Colors"
)
var divBearColor = input(
    name="divBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Divergence Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries v = bars.volume

if (isnan(c[0]) || isnan(v[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. OBV COMPUTATION
// -----------------------------------------------------------------------------
// Granville's formula: add volume on up close, subtract on down close
timeseries upBar = c > nz(c[1])
timeseries downBar = c < nz(c[1])
timeseries dirVol = (upBar ? v : 0.0) - (downBar ? v : 0.0)

static obv = 0.0
obv = nz(obv) + dirVol

// --- Smoothing ---
timeseries obvSmooth = smoothType == "EMA" ? ema(obv, smoothLen)
    : smoothType == "SMA" ? sma(obv, smoothLen)
    : wma(obv, smoothLen)

// --- Signal Line ---
timeseries obvSignal = signalType == "SMA" ? sma(obvSmooth, signalLen) : ema(obvSmooth, signalLen)

// --- Momentum Histogram ---
timeseries hist = obvSmooth - obvSignal

// -----------------------------------------------------------------------------
// 4. Z-SCORE
// -----------------------------------------------------------------------------
timeseries obvMean = sma(obv, zLen)
timeseries obvStd = stdev(obv, zLen)
timeseries obvZ = (obv - obvMean) / max(obvStd, 1e-9)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
var regimeBull = obvSmooth > obvSignal && obvZ > 0
var regimeBear = obvSmooth < obvSignal && obvZ < 0
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

// -----------------------------------------------------------------------------
// 6. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
static prevObvHigh = -1.0
static prevPxHigh = -1.0
static prevObvLow = -1.0
static prevPxLow = -1.0
static prevObvHighLow = -1.0
static prevPxHighLow = -1.0
static prevObvLowHigh = -1.0
static prevPxLowHigh = -1.0

var bearDiv = false
var bullDiv = false
var hiddenBearDiv = false
var hiddenBullDiv = false

if (prevObvHigh < 0) {
    prevObvHigh = obvSmooth[0]
    prevPxHigh = bars.high[0]
    prevObvLow = obvSmooth[0]
    prevPxLow = bars.low[0]
    prevObvHighLow = obvSmooth[0]
    prevPxHighLow = bars.high[0]
    prevObvLowHigh = obvSmooth[0]
    prevPxLowHigh = bars.low[0]
}

if (!isLiveUpdate && enableDiv) {
    // Regular bearish divergence: price higher high, OBV lower high
    if (bars.high[0] > prevPxHigh) {
        if (obvSmooth[0] < prevObvHigh) {
            bearDiv = true
        }
        prevPxHigh = bars.high[0]
        prevObvHigh = obvSmooth[0]
    }

    // Regular bullish divergence: price lower low, OBV higher low
    if (bars.low[0] < prevPxLow) {
        if (obvSmooth[0] > prevObvLow) {
            bullDiv = true
        }
        prevPxLow = bars.low[0]
        prevObvLow = obvSmooth[0]
    }

    // Hidden divergence
    if (showHidden) {
        // Hidden bullish: price higher low, OBV lower low
        if (bars.low[0] > prevPxLow && bars.high[0] < prevPxHigh) {
            if (obvSmooth[0] < prevObvLow) {
                hiddenBullDiv = true
            }
        }
        // Hidden bearish: price lower high, OBV higher high
        if (bars.high[0] < prevPxHigh && bars.low[0] > prevPxLow) {
            if (obvSmooth[0] > prevObvHigh) {
                hiddenBearDiv = true
            }
        }
    }
}

// -----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = obvSmooth > obvSignal && obvSmooth[1] <= obvSignal[1]
var crossDown = obvSmooth < obvSignal && obvSmooth[1] >= obvSignal[1]
var zExtremeHigh = obvZ > 2.0 && obvZ[1] <= 2.0
var zExtremeLow = obvZ < -2.0 && obvZ[1] >= -2.0
var zStretchHigh = obvZ > 3.0 && obvZ[1] <= 3.0
var zStretchLow = obvZ < -3.0 && obvZ[1] >= -3.0

// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero Line ---
hline(value=0, color="#ffffff20", width=1)

// --- Reference Bands ---
if (showBands) {
    hline(value=2.0, color=bandColor, width=1)
    hline(value=-2.0, color=bandColor, width=1)
}

// --- OBV Line (regime-colored) ---
if (showObvLine) {
    plotLine(
        value=obvSmooth,
        width=2,
        colors=[regimeColor],
        label=["OBV+"],
        desc=["Smoothed On Balance Volume (" + smoothType + " " + smoothLen + ")"]
    )
}

// --- Raw OBV (faint) ---
plotLine(
    value=obv,
    width=1,
    colors=[transparency(lineColor, 80)],
    label=["OBV Raw"],
    desc=["Raw cumulative OBV"]
)

// --- Signal Line ---
if (showSignalLine) {
    plotLine(
        value=obvSignal,
        width=1,
        colors=["#ffffff"],
        label=["Signal"],
        desc=["Signal line of smoothed OBV (" + signalType + " " + signalLen + ")"]
    )
}

// --- Fill between OBV and Signal ---
if (showFill && showObvLine && showSignalLine) {
    var fillBull = obvSmooth > obvSignal
    plotLine(
        value=[obvSmooth, obvSignal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["OBV", "Signal"],
        desc=["Fill between OBV+ and signal line"]
    )
}

// --- Momentum Histogram ---
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["OBV Momentum"],
        desc=["Histogram of OBV+ minus signal"]
    )
}

// --- Z-Score Panel ---
if (showZScore) {
    plotLine(
        value=obvZ,
        width=2,
        colors=[transparency(bullColor, 50)],
        label=["OBV Z-Score"],
        desc=["OBV z-score over " + zLen + " bars"]
    )
}

// --- Divergence Shapes ---
if (showAlerts && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=obvSmooth,
            shape="triangleup",
            colorIndex=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, OBV higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=obvSmooth,
            shape="triangledown",
            colorIndex=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, OBV lower high"]
        )
    }
    if (showHidden && hiddenBullDiv) {
        plotShape(
            value=obvSmooth,
            shape="arrowup",
            colorIndex=divBullColor,
            width=1,
            label=["Hidden Bull"],
            desc=["Hidden bullish divergence: price higher low, OBV lower low"]
        )
    }
    if (showHidden && hiddenBearDiv) {
        plotShape(
            value=obvSmooth,
            shape="arrowdown",
            colorIndex=divBearColor,
            width=1,
            label=["Hidden Bear"],
            desc=["Hidden bearish divergence: price lower high, OBV higher high"]
        )
    }
}

// --- Alert Shapes ---
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=obvSignal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["OBV+ crossed above signal"]
        )
    }
    if (crossDown) {
        plotShape(
            value=obvSignal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["OBV+ crossed below signal"]
        )
    }
    if (zExtremeHigh) {
        plotShape(
            value=obvSmooth,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["Z+ Extreme"],
            desc=["OBV Z-Score crossed above +2σ"]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=obvSmooth,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["Z- Extreme"],
            desc=["OBV Z-Score crossed below -2σ"]
        )
    }
}

// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH PRESSURE" : (regimeBear ? "BEARISH PRESSURE" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

    plotTable(
        data=[
            ["OBV+ — Perfected", regimeText],
            ["OBV Smooth", obvSmooth[0]],
            ["Signal", obvSignal[0]],
            ["Momentum", hist[0]],
            ["Z-Score", obvZ[0]],
            ["Smoothing", smoothType + "(" + smoothLen + ")"],
            ["Signal", signalType + "(" + signalLen + ")"]
        ],
        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
    )
}