MM Flow
FlowScripts

Perfected FlowScript

OBV Bollinger Bands

OBV Bollinger Bands V2 is indexed as 226_obv_bollinger_bands.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.0 KB

Lines

451

Native Signal Candidates

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

6/6 guarded

OBV Above Upper

line 345:9

Trigger

(showShapes) && (obvAboveUpper)

Value

upper

Deps

obvAboveUpper:var, showShapes:input

OBV Below Lower

line 355:9

Trigger

(showShapes) && (obvBelowLower)

Value

lower

Deps

obvBelowLower:var, showShapes:input

OBV Cross Up

line 365:9

Trigger

(showShapes) && (obvCrossUp)

Value

basis

Deps

obvCrossUp:var, showShapes:input

OBV Cross Down

line 375:9

Trigger

(showShapes) && (obvCrossDown)

Value

basis

Deps

obvCrossDown:var, showShapes:input

%B OB Entry

line 389:9

Trigger

(showPbShapes && showPercentB) && (pbEnterOverbought)

Value

0.8

Deps

pbEnterOverbought:var, showPbShapes:input, showPercentB:input

%B OS Entry

line 399:9

Trigger

(showPbShapes && showPercentB) && (pbEnterOversold)

Value

0.2

Deps

pbEnterOversold:var, showPbShapes:input, showPercentB:input

226_obv_bollinger_bands.flowscript

source path: kscripts/perfected/226_obv_bollinger_bands.flowscript · sha256:6a1e3e1a9b4b7a0201e39dcd31582c80771f4342f2071e56d6fb1e438f62b49d

hash verified
//@version=2
// ============================================================================
// OBV Bollinger Bands V2 — Volume-Momentum Envelope with %B Oscillator
// Author: B (@buyanyjeansnecessary) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #Bollinger, #Bands, #OBV, #BBands
//
// Production-quality academically-grounded Bollinger Band envelope analysis
// applied to On-Balance Volume (OBV). Implements canonical OBV cumulative
// flow, volatility-normalized bands, %B oscillator, band fill, regime
// detection, color-coded visualization, and extreme-event shape alerts.
//
// Research papers underpinning this design:
//  1. Bollinger, J. (2001), "Bollinger on Bollinger Bands", McGraw-Hill.
//     [Formula] Upper Band = SMA(20) + 2σ; Lower Band = SMA(20) − 2σ;
//     %B = (Close − Lower) / (Upper − Lower). The definitive BB text.
//
//  2. Lee, C. M. C. & Ready, M. J. (1991), "Inferring Trade Direction from
//     Intraday Data", J. Finance 46(2):733-746. Foundational Lee-Ready
//     algorithm (85–93% accuracy) for buy/sell classification underlying OBV.
//
//  3. Ellis, K., Michaely, R. & O'Hara, M. (2000), "The Accuracy of Trade
//     Classification Rules", JFQA 35(4):529-551. Validates classification
//     accuracy bounds (~81% in modern electronic markets), informing the
//     accuracy bounds of OBV-based signals.
//
//  4. Granville (1963), "Granville's New Key to Stock Market Profits".
//     Original OBV formulation: OBV_t = OBV_{t−1} + Volume_t × sign(ΔClose_t).
//     Granville's premise that volume precedes price underpins the BB-OBV
//     combination — volume extremes flagged by band penetration precede
//     price turning points.
//
//  5. Chordia, Roll & Subrahmanyam (2002), JFE 65(1), 111–130. Order
//     imbalance predicts return reversals. OBV extremes (band penetrations)
//     flag extreme imbalance, supporting mean-reversion interpretation.
//
//  6. Poterba & Summers (1988), "Mean Reversion in Stock Prices", JFE 22(1),
//     27–59. Negative autocorrelation at medium horizons; supports dynamic
//     band width calibration to rolling volatility of OBV.
// ============================================================================

define(
    title="OBV Bollinger Bands V2",
    position="offchart",
    axis=true
)

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

// -- Bollinger Settings --
var bbLen = input(
    name="bbLen",
    type="number",
    defaultValue=20,
    label="Bollinger Length (bars)",
    constraints={min: 5, max: 100, step: 1},
    group="Bollinger Settings"
)
var bbMult = input(
    name="bbMult",
    type="number",
    defaultValue=2.0,
    label="Bollinger StdDev Multiplier",
    constraints={min: 0.5, max: 4.0, step: 0.5},
    group="Bollinger Settings"
)

// -- OBV Settings --
var obvSmooth = input(
    name="obvSmooth",
    type="number",
    defaultValue=1,
    label="OBV EMA Smooth (0 = raw)",
    constraints={min: 0, max: 20, step: 1},
    group="OBV Settings"
)

// -- %B Oscillator --
var showPercentB = input(
    name="showPercentB",
    type="boolean",
    defaultValue=true,
    label="Show %B Oscillator",
    group="%B Oscillator"
)
var pbSmooth = input(
    name="pbSmooth",
    type="number",
    defaultValue=3,
    label="%B EMA Smooth",
    constraints={min: 1, max: 20, step: 1},
    group="%B Oscillator"
)

// -- Display --
var showObv = input(
    name="showObv",
    type="boolean",
    defaultValue=true,
    label="Show OBV Line",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Bollinger Bands",
    group="Display"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fill",
    group="Display"
)
var showObvFill = input(
    name="showObvFill",
    type="boolean",
    defaultValue=true,
    label="Show OBV/Band Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Band Touch Shapes",
    group="Display"
)
var showPbShapes = input(
    name="showPbShapes",
    type="boolean",
    defaultValue=true,
    label="Show %B Extreme Shapes",
    group="Display"
)

// -- Colors --
var basisColor = input(
    name="basisColor",
    type="color",
    defaultValue="#ffffff",
    label="Basis (SMA) Color",
    group="Colors"
)
var upperColor = input(
    name="upperColor",
    type="color",
    defaultValue="#26a69a",
    label="Upper Band Color",
    group="Colors"
)
var lowerColor = input(
    name="lowerColor",
    type="color",
    defaultValue="#ef5350",
    label="Lower Band Color",
    group="Colors"
)
var obvBullColor = input(
    name="obvBullColor",
    type="color",
    defaultValue="#00c853",
    label="OBV Bull Color",
    group="Colors"
)
var obvBearColor = input(
    name="obvBearColor",
    type="color",
    defaultValue="#d50000",
    label="OBV Bear Color",
    group="Colors"
)
var pbColor = input(
    name="pbColor",
    type="color",
    defaultValue="#ffeb3b",
    label="%B Line Color",
    group="Colors"
)

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

timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries volume = ohlcvTS.volume

// Guard: halt until price and volume have loaded to avoid NaN propagation
if (isnan(close[0]) || isnan(volume[0])) {
    return
}

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

// -- 3.1 Build OBV: cumulative volume signed by close direction --
// Granville (1963) original: OBV_t = OBV_{t−1} + Volume_t × sign(ΔClose_t).
// Lee-Ready (1991) provides the trade-direction classification that underpins
// the sign convention: close > prior close → buyer-initiated (+volume);
// close < prior close → seller-initiated (−volume).
timeseries direction = close > close[1] ? 1 : (close < close[1] ? -1 : 0)
static obvState = 0.0

// Guard each increment against NaN to prevent state corruption
if (!isnan(direction[0]) && !isnan(volume[0])) {
    obvState = obvState + direction[0] * volume[0]
}

// Optional EMA smoothing of OBV
timeseries obv = obvSmooth > 0 ? ema(source=obvState, period=obvSmooth) : obvState

// -- 3.2 Bollinger Bands around OBV --
// Per Bollinger (2001): bands at ±kσ around SMA(W).
timeseries basis = sma(source=obv, period=bbLen)
timeseries dev = stdev(source=obv, period=bbLen)
timeseries upper = basis + bbMult * dev
timeseries lower = basis - bbMult * dev

// -- 3.3 %B and BandWidth diagnostics --
// %B = (OBV − Lower) / (Upper − Lower). Measures where OBV sits within
// its band envelope, 0 = lower band, 0.5 = middle, 1 = upper band.
// Guard against division by zero when bands collapse (dev = 0).
timeseries bandRange = upper - lower
timeseries percentB = bandRange > 0 ? (obv - lower) / bandRange : 0.5
timeseries percentBSmooth = ema(source=percentB, period=pbSmooth)

// BandWidth = (Upper − Lower) / Basis. Measures volatility squeeze/expansion.
// Low BandWidth = possible squeeze; expanding = breakout brewing.
timeseries bandWidth = basis != 0 ? bandRange / math.abs(basis) : 0

// -- 3.4 Regime detection from %B --
// %B > 0.8 → OBV near upper band → volume momentum bullish extreme
// %B < 0.2 → OBV near lower band → volume momentum bearish extreme
// %B crossing 0.5 → momentum shift through the mean
var obvAboveUpper = obv > upper
var obvBelowLower = obv < lower
var obvAboveBasis = obv > basis
var pbOverbought = percentBSmooth > 0.8
var pbOversold = percentBSmooth < 0.2
var pbBull = percentBSmooth > 0.5
var pbBear = percentBSmooth < 0.5

// -- 3.5 Regime state tracking via static variables --
// Tracks consecutive bars above/below bands for context-aware alerting.
static lastObvRegime = 0
static aboveUpperBars = 0
static belowLowerBars = 0

if (obvAboveUpper) {
    aboveUpperBars = aboveUpperBars + 1
    belowLowerBars = 0
    lastObvRegime = 1
} else if (obvBelowLower) {
    belowLowerBars = belowLowerBars + 1
    aboveUpperBars = 0
    lastObvRegime = -1
} else {
    aboveUpperBars = 0
    belowLowerBars = 0
    lastObvRegime = 0
}

// -- 3.6 Crossover / crossunder of OBV and basis --
var obvCrossUp = obv > basis && obv[1] <= basis[1]
var obvCrossDown = obv < basis && obv[1] >= basis[1]

// -- 3.7 %B extreme penetrations --
var pbEnterOverbought = percentBSmooth > 0.8 && percentBSmooth[1] <= 0.8
var pbEnterOversold = percentBSmooth < 0.2 && percentBSmooth[1] >= 0.2
var pbExitOverbought = percentBSmooth < 0.8 && percentBSmooth[1] >= 0.8
var pbExitOversold = percentBSmooth > 0.2 && percentBSmooth[1] <= 0.2

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

// 4.1 Bollinger Bands (plotLine with fill)
if (showBands) {
    plotLine(
        value=[upper, basis, lower],
        width=[1, 2, 1],
        colors=[upperColor, basisColor, lowerColor],
        label=["Upper Band", "Basis (SMA)", "Lower Band"],
        desc=["OBV + " + bbMult + " sigma", "OBV SMA (" + bbLen + ")", "OBV - " + bbMult + " sigma"]
    )
}

// 4.2 Band fill (between upper and lower)
if (showBandFill) {
    plotLine(
        value=[upper, lower],
        width=1,
        colors=[transparency(upperColor, 10), transparency(lowerColor, 10)],
        fill=true,
        label=["Upper Band", "Lower Band"],
        desc=["Bollinger Band envelope fill"]
    )
}

// 4.3 OBV line (regime-colored)
if (showObv) {
    var obvColor = obvAboveBasis ? obvBullColor : obvBearColor
    plotLine(
        value=obv,
        width=2,
        colors=[obvColor],
        label=["OBV"],
        desc=["On-Balance Volume (regime-colored); cumulative signed volume per Granville (1963)"]
    )
}

// 4.4 OBV / Band fill (between OBV and basis)
if (showObvFill) {
    var obvFillBull = obv > basis
    plotLine(
        value=[obv, basis],
        width=1,
        colors=[transparency(obvBullColor, 20), transparency(obvBearColor, 20)],
        colorIndex=obvFillBull ? 0 : 1,
        fill=true,
        label=["OBV", "Basis"],
        desc=["Fill between OBV and basis SMA"]
    )
}

// 4.5 %B Oscillator
if (showPercentB) {
    plotLine(
        value=percentBSmooth,
        width=2,
        colors=[pbColor],
        label=["%B"],
        desc=["Percent B: (OBV - Lower) / (Upper - Lower); 0.5 = middle band"]
    )
}

// 4.6 Band touch shapes (plotShape)
if (showShapes) {
    if (obvAboveUpper) {
        plotShape(
            value=upper,
            shape="triangleup",
            colorIndex=upperColor,
            width=2,
            label=["OBV Above Upper"],
            desc=["OBV penetrated upper band: extreme bullish volume momentum"]
        )
    }
    if (obvBelowLower) {
        plotShape(
            value=lower,
            shape="triangledown",
            colorIndex=lowerColor,
            width=2,
            label=["OBV Below Lower"],
            desc=["OBV penetrated lower band: extreme bearish volume momentum"]
        )
    }
    if (obvCrossUp) {
        plotShape(
            value=basis,
            shape="circle",
            colorIndex=obvBullColor,
            width=2,
            label=["OBV Cross Up"],
            desc=["OBV crossed above basis SMA: momentum shift bullish"]
        )
    }
    if (obvCrossDown) {
        plotShape(
            value=basis,
            shape="circle",
            colorIndex=obvBearColor,
            width=2,
            label=["OBV Cross Down"],
            desc=["OBV crossed below basis SMA: momentum shift bearish"]
        )
    }
}

// 4.7 %B extreme shapes
if (showPbShapes && showPercentB) {
    if (pbEnterOverbought) {
        plotShape(
            value=0.8,
            shape="xcross",
            colorIndex=obvBullColor,
            width=2,
            label=["%B OB Entry"],
            desc=["Percent B entered overbought zone (>0.8): volume momentum extreme"]
        )
    }
    if (pbEnterOversold) {
        plotShape(
            value=0.2,
            shape="xcross",
            colorIndex=obvBearColor,
            width=2,
            label=["%B OS Entry"],
            desc=["Percent B entered oversold zone (<0.2): volume momentum extreme"]
        )
    }
}

// 4.8 Reference lines (hline)
hline(value=0.5, color="#ffffff30", width=1)
if (showPercentB) {
    hline(value=0.8, color=transparency(upperColor, 40), width=1)
    hline(value=0.2, color=transparency(lowerColor, 40), width=1)
    hline(value=1.0, color=transparency(upperColor, 20), width=1)
    hline(value=0.0, color=transparency(lowerColor, 20), width=1)
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = obvAboveUpper ? "ABOVE UPPER" : (obvBelowLower ? "BELOW LOWER" : (obvAboveBasis ? "ABOVE BASIS" : "BELOW BASIS"))
    var regimeTextColor = obvAboveUpper ? upperColor : (obvBelowLower ? lowerColor : (obvAboveBasis ? obvBullColor : obvBearColor))

    plotTable(
        data=[
            ["OBV BB V2 — Regime", regimeText],
            ["OBV", obv[0]],
            ["Basis", basis[0]],
            ["Upper Band", upper[0]],
            ["Lower Band", lower[0]],
            ["%B", percentBSmooth[0]],
            ["BandWidth", bandWidth[0]],
            ["Above Upper (bars)", aboveUpperBars],
            ["Below Lower (bars)", belowLowerBars]
        ],
        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
    )
}