Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-obv

$ 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.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

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.

02

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.
03

Basic OBV Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My On-Balance Volume (OBV)", overlay=false)

// Calculate OBV using the built-in function
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
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)
$ ✓ Compiled successfully
04

Volume Drives Price

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.

05

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.

  • Bullish Divergence: Price makes a lower low, but OBV makes a higher low.
  • Bearish Divergence: Price makes a higher high, but OBV makes a lower high.
//@version=5
strategy("OBV Divergence Strategy", overlay=true)

obvValue = ta.obv(close, volume)

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

bullishDiv = close < close[1] and close[1] < close[2] and obvValue > obvValue[1] and obvValue[1] > obvValue[2]
bearishDiv = close > close[1] and close[1] > close[2] and obvValue < obvValue[1] and obvValue[1] < obvValue[2]

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)

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.

  • Uptrend Confirmation: Price is making higher highs and higher lows, and OBV is also making higher highs and higher lows.
  • Downtrend Confirmation: Price is making lower highs and lower lows, and OBV is also making lower highs and lower lows.
//@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)

priceMALength = input.int(50, title="Price MA Length", minval=1)
priceMA = ta.sma(close, priceMALength)

longConfirm = close > priceMA and obvValue > obvMA
shortConfirm = close < priceMA and obvValue < obvMA

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

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

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.

  • Bullish Breakout: OBV breaks above its recent resistance level before price does.
  • Bearish Breakout: OBV breaks below its recent support level before price does.
//@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)

obvHighest = ta.highest(obvValue, 20)
obvLowest = ta.lowest(obvValue, 20)

bullishObvBreakout = obvValue > obvHighest[1] and obvValue[1] <= obvHighest[1]
bearishObvBreakout = obvValue < obvLowest[1] and obvValue[1] >= obvLowest[1]

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.")
06

Optimizing OBV Performance

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

  • Focus on Divergence: OBV's greatest strength lies in identifying divergences. These signals often provide early warnings of trend reversals.
  • Smooth with Moving Averages: While OBV itself is cumulative, applying a moving average to OBV (the signal line) can help smooth out noise and make crossovers more reliable.
  • Combine with Price Action: Always confirm OBV signals with price action. A bullish OBV divergence is stronger if price also shows a bullish reversal pattern.
  • Context is Key: Analyze OBV in the context of the overall market trend.
  • Timeframe Consideration: The effectiveness of OBV can vary across different timeframes.
  • Volume Thresholds (Advanced): For very active markets, you might consider setting a minimum volume threshold for bars to be included in OBV calculations.
07

Volume is Conviction

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).

08

Common OBV Pitfalls

  • Lag: Despite being a cumulative indicator, OBV can still lag price action, especially during sharp reversals.
  • False Signals: OBV can sometimes generate false signals, especially in choppy or range-bound markets.
  • Scalability Issues: Because OBV is cumulative, its absolute value can be very large. Its absolute value doesn't matter; what matters is its trend and divergence.
  • No Overbought/Oversold Levels: Unlike oscillators like RSI, OBV does not have fixed overbought/oversold zones.
  • Gaps and News Events: Large price gaps or sudden news events can cause significant jumps or drops in OBV.
  • Not a Standalone Indicator: OBV is a powerful tool but should never be used in isolation.
09

Conclusion

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 strategies and gain a clearer understanding of market conviction.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy