Pine Script OBV (On-Balance Volume)

Master this powerful volume-based momentum indicator in TradingView's Pine Script that measures buying and selling pressure to confirm trends and anticipate price movements.

Last Updated on: Expertise: Intermediate

What is On-Balance Volume (OBV)?

On-Balance Volume (OBV) is a momentum indicator that relates volume to price change. Developed by Joe Granville, OBV is a cumulative total of volume, adding or subtracting volume based on whether the price closed higher or lower than the previous day. The core idea behind OBV is that volume precedes price. A rising OBV indicates that volume is flowing into an asset, suggesting accumulation (buying pressure), which often precedes price increases. Conversely, a falling OBV indicates distribution (selling pressure), often preceding price declines.

OBV is a leading or confirming indicator, providing insights into whether smart money is accumulating or distributing an asset. It helps traders confirm trend direction, identify potential reversals through divergence, and spot breakout validity.

In Pine Script, OBV is a crucial tool for understanding the underlying strength of price movements and anticipating future trends by observing volume flow.

Components and Calculation

The calculation of On-Balance Volume is quite simple and cumulative:

  1. If the current closing price is higher than the previous closing price, the current day's volume is added to the previous OBV value.
  2. If the current closing price is lower than the previous closing price, the current day's volume is subtracted from the previous OBV value.
  3. If the current closing price is the same as the previous closing price, the OBV value remains unchanged.

`OBV = Previous OBV + Current Volume (if Close > Close[1])`
`OBV = Previous OBV - Current Volume (if Close < Close[1])`
`OBV = Previous OBV (if Close == Close[1])`
The starting OBV value is typically set to zero or the first bar's volume.

Basic OBV Implementation in Pine Script

Pine Script v5 provides a convenient built-in function `ta.obv()` for calculating On-Balance Volume.

//@version=5
indicator("My On-Balance Volume (OBV)", overlay=false) // overlay=false to plot in a separate pane

// Calculate OBV using the built-in function
// ta.obv implicitly uses 'close' for price comparison and 'volume' for calculation
obvValue = ta.obv(close, volume)

// Plot the OBV line
plot(obvValue, title="OBV", color=color.blue, linewidth=2)

// Optional: Add a Moving Average of OBV to act as a signal line
// Common lengths for OBV MA are 10, 20, or 30
obvMALength = input.int(20, title="OBV MA Length", minval=1)
obvMA = ta.sma(obvValue, obvMALength)

// Plot the OBV Moving Average (signal line)
plot(obvMA, title="OBV MA", color=color.orange, linewidth=1)
Volume Drives Price: The core philosophy of OBV is that major price moves are often preceded by significant volume flow. OBV quantifies this accumulation/distribution.

Practical OBV Trading Strategies

1. OBV Divergence (Key Strategy)

Divergence between price and OBV is one of the most powerful signals generated by the indicator, suggesting a weakening trend and potential reversal.

//@version=5
strategy("OBV Divergence Strategy", overlay=true)

obvValue = ta.obv(close, volume)

// Plot OBV in a separate pane
plot(obvValue, "OBV", color.blue, display=display.pane_only)

// Simple divergence detection (conceptual, robust detection requires advanced pivot logic)
// This example looks for recent higher/lower swings in price and OBV.

// Bullish Divergence: Price makes a lower low, OBV makes a higher low
bullishDiv = close < close[1] and close[1] < close[2] and obvValue > obvValue[1] and obvValue[1] > obvValue[2]

// Bearish Divergence: Price makes a higher high, OBV makes a lower high
bearishDiv = close > close[1] and close[1] > close[2] and obvValue < obvValue[1] and obvValue[1] < obvValue[2]

// Plot shapes on the chart to indicate divergence
plotshape(bullishDiv, title="Bullish OBV Divergence", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(bearishDiv, title="Bearish OBV Divergence", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

if (bullishDiv)
    strategy.entry("Long Divergence", strategy.long)
if (bearishDiv)
    strategy.entry("Short Divergence", strategy.short)

// Basic exit after a few bars or on opposite signal
strategy.exit("Long Divergence Exit", from_entry="Long Divergence", profit=close*0.02, loss=close*0.01)
strategy.exit("Short Divergence Exit", from_entry="Short Divergence", profit=close*0.02, loss=close*0.01)

2. Trend Confirmation

OBV can confirm the strength and direction of a price trend. If price is trending up and OBV is also trending up, it confirms buying pressure. If price is trending down and OBV is also trending down, it confirms selling pressure.

//@version=5
strategy("OBV Trend Confirmation Strategy", overlay=true)

obvValue = ta.obv(close, volume)
obvMALength = input.int(20, title="OBV MA Length", minval=1)
obvMA = ta.sma(obvValue, obvMALength)

plot(obvValue, "OBV", color.blue, display=display.pane_only)
plot(obvMA, "OBV MA", color.orange, display=display.pane_only)

// Price trend filter (e.g., 50-period SMA)
priceMALength = input.int(50, title="Price MA Length", minval=1)
priceMA = ta.sma(close, priceMALength)

// Conditions for trend confirmation
// Long: Price above MA, and OBV above its MA (or sloping up)
longConfirm = close > priceMA and obvValue > obvMA

// Short: Price below MA, and OBV below its MA (or sloping down)
shortConfirm = close < priceMA and obvValue < obvMA

if (longConfirm)
    strategy.entry("Long Confirm", strategy.long)

if (shortConfirm)
    strategy.entry("Short Confirm", strategy.short)

// Basic exit: trend reversal or OBV MA cross
strategy.close("Long Confirm", when=close < priceMA or obvValue < obvMA)
strategy.close("Short Confirm", when=close > priceMA or obvValue > obvMA)

3. OBV Breakouts (Accumulation/Distribution Breakouts)

Sometimes, OBV will break out of its own trading range before price does. This can act as an early warning signal for an impending price breakout.

//@version=5
indicator("OBV Breakout Detection", overlay=true)

obvValue = ta.obv(close, volume)
obvMALength = input.int(20, title="OBV MA Length", minval=1)
obvMA = ta.sma(obvValue, obvMALength)

plot(obvValue, "OBV", color.blue)
plot(obvMA, "OBV MA", color.orange)

// Identify recent highs/lows on OBV for breakout detection (simplified)
obvHighest = ta.highest(obvValue, 20) // 20-period highest OBV
obvLowest = ta.lowest(obvValue, 20)   // 20-period lowest OBV

// Bullish OBV Breakout: OBV crosses above its recent high
bullishObvBreakout = obvValue > obvHighest[1] and obvValue[1] <= obvHighest[1]

// Bearish OBV Breakout: OBV crosses below its recent low
bearishObvBreakout = obvValue < obvLowest[1] and obvValue[1] >= obvLowest[1]

// Plot alerts/shapes on the price chart
plotshape(bullishObvBreakout, title="Bullish OBV Breakout", location=location.belowbar, color=color.lime, style=shape.arrowup, size=size.small)
plotshape(bearishObvBreakout, title="Bearish OBV Breakout", location=location.abovebar, color=color.maroon, style=shape.arrowdown, size=size.small)

alertcondition(bullishObvBreakout, "OBV Bullish Breakout", "OBV has broken out upwards, anticipate price move.")
alertcondition(bearishObvBreakout, "OBV Bearish Breakout", "OBV has broken out downwards, anticipate price move.")

Optimizing OBV Performance

To get the most from On-Balance Volume in Pine Script:

Volume is Conviction: OBV helps you see if a price move has real conviction (volume backing it) or if it's just noise (low volume).

Common OBV Pitfalls

Conclusion

On-Balance Volume (OBV) is a foundational and highly effective volume-based momentum indicator available in Pine Script for TradingView. By uniquely quantifying buying and selling pressure through cumulative volume, it provides traders with invaluable insights into the market's underlying strength and potential future price movements. While its greatest strength lies in identifying powerful divergences with price, it also excels at confirming existing trends and validating breakouts. By understanding its calculation, thoughtfully utilizing its signals (especially divergence), and integrating it strategically with price action and other technical analysis tools, you can leverage OBV to enhance your trading decisions and gain a clearer understanding of market conviction.