Perfected FlowScript
OBV with Bollinger Bands
OBV with Bollinger Bands — Perfected Edition is indexed as 220_obv_with_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
12.7 KB
Lines
410
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Touch Upper
line 317:9
Trigger
(showShapes) && (touchUpper)
Value
upper
Deps
showShapes:input, touchUpper:var
Touch Lower
line 327:9
Trigger
(showShapes) && (touchLower)
Value
lower
Deps
showShapes:input, touchLower:var
Retest Upper
line 337:9
Trigger
(showShapes) && (retestUpper)
Value
upper
Deps
retestUpper:var, showShapes:input
Retest Lower
line 347:9
Trigger
(showShapes) && (retestLower)
Value
lower
Deps
retestLower:var, showShapes:input
Cross Mid Up
line 357:9
Trigger
(showShapes) && (crossMidUp)
Value
obvMA
Deps
crossMidUp:var, showShapes:input
Cross Mid Dn
line 367:9
Trigger
(showShapes) && (crossMidDn)
Value
obvMA
Deps
crossMidDn:var, showShapes:input
220_obv_with_bollinger_bands.flowscript
source path: kscripts/perfected/220_obv_with_bollinger_bands.flowscript · sha256:faa045a07e9b027e996dcdd00f4ff17fed7c5e2eff3966be5e91e5c2ab0a499d
//@version=2
// ============================================================================
// OBV with Bollinger Bands — Perfected Edition
// Author: E | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, #obv, #bollinger, #volume, #regime, #bands, #fill
//
// Production-quality On-Balance Volume indicator with Bollinger Band
// overlay. OBV captures cumulative volume pressure; BB bands on OBV
// identify statistical extremes where volume exhaustion or acceleration
// signals regime shift. Includes band fill, %B position, regime detection,
// colour coding, and shape-marked band-touch alerts.
//
// Academic foundation:
// 1. Granville (1963), "Granville's New Key to Stock Market Profits":
// canonical OBV formulation. OBV_t = OBV_{t−1} + V_t if close_t > close_{t−1},
// else OBV_t = OBV_{t−1} − V_t if close_t < close_{t−1}, else unchanged.
// Volume precedes price; OBV divergence from price flags early reversals.
// 2. Bollinger (2001), "Bollinger on Bollinger Bands": BB = SMA ± k·σ,
// k = 2 standard deviations captures ~95% of normal distribution.
// %B = (price − lower) / (upper − lower), mapping position within bands
// to a 0–1 scale. Applied here to OBV instead of price.
// 3. Lee & Swaminathan (2000), "Price Momentum and Trading Volume",
// Journal of Finance, 55(5), 2017–2069. Volume momentum predicts
// return continuation; OBV at BB extremes flags volume-momentum
// exhaustion. DOI: https://doi.org/10.1111/0022-1082.00280
// 4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
// and Market Returns", Journal of Financial Economics, 65(1), 111–130.
// Extreme |Imbalance| predicts return reversals; OBV BB extremes are
// an indirect volume-imbalance proxy. DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// 5. Murphy (1999), "Technical Analysis of the Financial Markets":
// divergence between price and volume indicators as leading reversal
// signal. OBV outside BBs = statistical anomaly in volume flow.
// ============================================================================
define(
title="OBV with Bollinger Bands — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- OBV Settings ---
var obvSrc = input(
name="obvSrc",
type="select",
defaultValue="close",
label="OBV Source",
options=["close", "hlc3", "ohlc4"],
group="OBV Settings"
)
// --- Bollinger Bands ---
var bbLen = input(
name="bbLen",
type="number",
defaultValue=20,
label="Bollinger Length",
constraints={min: 5, max: 100, step: 1},
group="Bollinger Bands"
)
var bbMult = input(
name="bbMult",
type="number",
defaultValue=2.0,
label="StdDev Multiplier",
constraints={min: 0.5, max: 4.0, step: 0.1},
group="Bollinger Bands"
)
// --- Display ---
var showOBV = input(
name="showOBV",
type="boolean",
defaultValue=true,
label="Show OBV Line",
group="Display"
)
var showBB = input(
name="showBB",
type="boolean",
defaultValue=true,
label="Show Bollinger Bands",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Band Fill",
group="Display"
)
var showPctB = input(
name="showPctB",
type="boolean",
defaultValue=true,
label="Show %B Oscillator",
group="Display"
)
var showRegime = input(
name="showRegime",
type="boolean",
defaultValue=true,
label="Show Regime Colouring",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Band-Touch Shapes",
group="Display"
)
var showHist = input(
name="showHist",
type="boolean",
defaultValue=true,
label="Show Volume Momentum Histogram",
group="Display"
)
// --- Colors ---
var obvColor = input(
name="obvColor",
type="color",
defaultValue="#ffffff",
label="OBV Color",
group="Colors"
)
var upColor = input(
name="upColor",
type="color",
defaultValue="#26a69a",
label="Upper / Bull Color",
group="Colors"
)
var dnColor = input(
name="dnColor",
type="color",
defaultValue="#ef5350",
label="Lower / Bear Color",
group="Colors"
)
var midColor = input(
name="midColor",
type="color",
defaultValue="#ff9800",
label="Middle Band Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(currentSymbol, currentExchange)
if (isnan(bars.close[0]) || isnan(bars.volume[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 OBV source selection --
timeseries src = obvSrc == "close" ? bars.close : (obvSrc == "hlc3" ? (bars.high + bars.low + bars.close) / 3 : (bars.open + bars.high + bars.low + bars.close) / 4)
// -- 3.2 On-Balance Volume (cumulative, tracked via static) --
// Granville (1963): add volume on up-close, subtract on down-close.
// static persists across bars for true cumulative tracking.
static obv = 0.0
timeseries srcChg = src - src[1]
timeseries obvChg = srcChg > 0 ? bars.volume : (srcChg < 0 ? -bars.volume : 0)
if (!isnan(obvChg[0])) {
obv = obv + obvChg[0]
}
// -- 3.3 Bollinger Bands on OBV --
// Bollinger (2001): BB = SMA ± k·σ, k = 2 captures ~95% of distribution.
timeseries obvMA = sma(source=obv, period=bbLen)
timeseries obvStd = stddev(source=obv, period=bbLen)
timeseries upper = obvMA + bbMult * obvStd
timeseries lower = obvMA - bbMult * obvStd
// -- 3.4 %B position within bands (0 = lower, 1 = upper, 0.5 = middle) --
// %B = (OBV − lower) / (upper − lower). Guards against division by zero.
timeseries bandWidth = math.max(upper - lower, 1e-9)
timeseries pctB = (obv - lower) / bandWidth
// -- 3.5 Z-score of OBV relative to its BB (how many σ from mean) --
timeseries obvZ = (obvStd > 0) ? (obv - obvMA) / obvStd : 0
// -- 3.6 Regime detection --
// Regime classification based on %B position and OBV direction:
// Bullish: %B > 0.8 AND OBV rising (volume accumulation above upper band)
// Bearish: %B < 0.2 AND OBV falling (volume distribution below lower band)
// Neutral: everything else
var regimeBull = pctB > 0.8 && obv > obv[1]
var regimeBear = pctB < 0.2 && obv < obv[1]
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : "#9e9e9e")
// -- 3.7 Band-touch detection (static for stateful tracking) --
static prevPctB = 0.5
static wasAbove = false
static wasBelow = false
var touchUpper = pctB >= 1.0 && prevPctB < 1.0
var touchLower = pctB <= 0.0 && prevPctB > 0.0
var retestUpper = pctB > 0.9 && pctB < 1.0 && wasAbove
var retestLower = pctB < 0.1 && pctB > 0.0 && wasBelow
wasAbove = pctB >= 1.0
wasBelow = pctB <= 0.0
prevPctB = pctB[0]
// -- 3.8 OBV momentum histogram (rate of change) --
timeseries obvMom = obv - obv[1]
// ---------------------------------------------------------------------------
// 4. ALERT CONDITIONS
// ---------------------------------------------------------------------------
var crossUpper = obv > upper && obv[1] <= upper[1]
var crossLower = obv < lower && obv[1] >= lower[1]
var crossMidUp = obv > obvMA && obv[1] <= obvMA[1]
var crossMidDn = obv < obvMA && obv[1] >= obvMA[1]
// ---------------------------------------------------------------------------
// 5. VISUALIZATION
// ---------------------------------------------------------------------------
// 5.1 Band fill (upper / lower area)
if (showFill && showBB) {
plotLine(
value=[upper, lower],
width=1,
colors=[transparency(upColor, 15), transparency(dnColor, 15)],
colorIndex=0,
fill=true,
label=["Upper Band", "Lower Band"],
desc=["Bollinger band fill area on OBV"]
)
}
// 5.2 Bollinger band lines
if (showBB) {
plotLine(
value=upper,
width=1,
colors=[transparency(upColor, 50)],
label=["Upper BB"],
desc=["Upper Bollinger Band (SMA + " + bbMult + "·σ) on OBV"]
)
plotLine(
value=lower,
width=1,
colors=[transparency(dnColor, 50)],
label=["Lower BB"],
desc=["Lower Bollinger Band (SMA − " + bbMult + "·σ) on OBV"]
)
plotLine(
value=obvMA,
width=1,
colors=[midColor],
label=["OBV SMA"],
desc=["SMA of OBV (" + bbLen + ") — middle Bollinger band"]
)
}
// 5.3 OBV line (regime-coloured when enabled)
if (showOBV) {
var obvLineColor = showRegime ? regimeColor : obvColor
plotLine(
value=obv,
width=2,
colors=[obvLineColor],
label=["OBV"],
desc=["On-Balance Volume (Granville cumulative)"]
)
}
// 5.4 %B oscillator (0–1 scale, offchart-friendly)
if (showPctB) {
var pctBColor = pctB > 0.8 ? upColor : (pctB < 0.2 ? dnColor : "#9e9e9e")
plotLine(
value=pctB,
width=1,
colors=[pctBColor],
label=["%B"],
desc=["Percent B: OBV position within Bollinger Bands (0=lower, 1=upper)"]
)
hline(value=0.8, color=transparency(upColor, 60), width=1)
hline(value=0.5, color="#ffffff20", width=1)
hline(value=0.2, color=transparency(dnColor, 60), width=1)
}
// 5.5 Volume momentum histogram
if (showHist) {
var histBull = obvMom >= 0
plotBar(
value=obvMom,
colors=[transparency(upColor, 60), transparency(dnColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["OBV Momentum"],
desc=["OBV rate of change (volume momentum)"]
)
}
// 5.6 Band-touch and retest shapes
if (showShapes) {
if (touchUpper) {
plotShape(
value=upper,
shape="triangledown",
colorIndex=dnColor,
width=2,
label=["Touch Upper"],
desc=["OBV touched upper Bollinger Band — volume exhaustion / distribution zone"]
)
}
if (touchLower) {
plotShape(
value=lower,
shape="triangleup",
colorIndex=upColor,
width=2,
label=["Touch Lower"],
desc=["OBV touched lower Bollinger Band — volume capitulation / accumulation zone"]
)
}
if (retestUpper) {
plotShape(
value=upper,
shape="arrowdown",
colorIndex=dnColor,
width=1,
label=["Retest Upper"],
desc=["OBV retesting upper band from inside — potential rejection"]
)
}
if (retestLower) {
plotShape(
value=lower,
shape="arrowup",
colorIndex=upColor,
width=1,
label=["Retest Lower"],
desc=["OBV retesting lower band from inside — potential bounce"]
)
}
if (crossMidUp) {
plotShape(
value=obvMA,
shape="circle",
colorIndex=upColor,
width=2,
label=["Cross Mid Up"],
desc=["OBV crossed above middle band — volume accumulation turning positive"]
)
}
if (crossMidDn) {
plotShape(
value=obvMA,
shape="circle",
colorIndex=dnColor,
width=2,
label=["Cross Mid Dn"],
desc=["OBV crossed below middle band — volume distribution turning negative"]
)
}
}
// ---------------------------------------------------------------------------
// 6. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : "#9e9e9e")
var bandWidthPct = (bandWidth > 0) ? (bandWidth / math.max(math.abs(obvMA), 1e-9)) * 100 : 0
plotTable(
data=[
["OBV BB — Perfected", regimeText],
["OBV", obv[0]],
["OBV SMA", obvMA[0]],
["Upper BB", upper[0]],
["Lower BB", lower[0]],
["%B", pctB[0]],
["Z-Score", obvZ[0]],
["Band Width %", bandWidthPct]
],
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
)
}