On Balance Volume Deviation
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bkeevil
// Adapted from the OBV indicator code provided by TradingView
// Purpose:     To be a leading indicator of a large price change based on the premise that a large spike in volume will lead to a future change in price.
// Description: Displays a histogram of the deviation of the On Balance Volume (OBV) indicator
//              This is overlayed on an SMA area chart of this deviation. 
// Useage:      When the histogram bars are higher than the area plot, then there is about to be a jump in price. Seems to work better on shorter timeframes.
// Reference:   https://www.investopedia.com/terms/o/onbalancevolume.asp 
// @version=5
indicator(title="On Balance Volume Deviation", shorttitle="OBV-DEV", overlay=false, precision=0, format=format.inherit, timeframe="", timeframe_gaps=true)

COLOR_DEV  = color.new(color.purple,0)
COLOR_SMA  = color.new(color.blue,80)

devLengthInput = input.int(defval=4, title="Deviation Length", minval=1, tooltip="Number of periods for SMA to calculate OBV deviation")
smaLengthInput = input.int(defval=8, title="Smoothing Length", minval=1, tooltip="Number of periods for SMA to smooth deviation histogram")
// cumVol is not used in obv calculations, only to detect the presence of volume data
var cumVol = 0.0
cumVol += nz(volume) // nz replaces NaN numbers with zeros
if barstate.islast and cumVol == 0
    runtime.error("No volume is provided by the data vendor.")

// if close > previousDayClose, add todays volume to the accumulator.
// if close < previousDayClose, subtract todays volume from the accumulator.
obv = ta.cum(math.sign(ta.change(close)) * volume)
dev = ta.dev(obv, devLengthInput)
sma = ta.sma(dev, smaLengthInput)

plot(sma, "Histogram SMA", color=COLOR_SMA, style=plot.style_area)
plot(dev, "OBV Deviation", color=COLOR_DEV, style=plot.style_histogram)
