BankNifty - OBV
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gokoffline

//@version=5

indicator(title="BankNifty - OBV", shorttitle="BankNifty - OBV", format=format.volume)

vol_ticker  = input.symbol("NSE:BANKNIFTY1!",title="Volume Symbol")
src         = input.source(close            ,title="Source")
anchor_res  = input.timeframe("1D"          ,title="Session")
res         = timeframe.period 


int i           = na
float _high1    = na
float _low1     = na
float v_high    = na
float v_low     = na
float v_close   = na
float sopen     = na
//float obv_out   = na
float cum_obv   = na


t               = time(anchor_res, session.regular) 
is_first        = na(t[1])  and not na(t)  or t[1]  < t

i       := is_first ?1:i[1]+1


float _volume = request.security(vol_ticker,res,volume)


//if barstate.isfirst 
//    obv_out:=0
//else
//    obv_out := src>src[1]?obv_out[1]+_volume:src<src[1]?obv_out[1]-_volume:obv_out[1]

obv_out=ta.cum(math.sign(ta.change(src)) * _volume)


sopen  := is_first?request.security(syminfo.tickerid, anchor_res, open[1]   ):sopen[1] //d_open //da00ff


// Color
high_color  = sopen   != sopen[1] ? na : color.new(#0e8f14,15)
low_color   = sopen   != sopen[1] ? na : color.new(color.red,15)
close_color = sopen   != sopen[1] ? na : color.new(color.black,15)
//obv_color   = sopen   != sopen[1] ? na : color.new(#3A6CA8,15)
obv_color   = color.new(#3A6CA8,15)

plot(obv_out, color=obv_color, title="OnBalanceVolume")


if is_first
    _high1    := obv_out
    _low1     := obv_out
    v_high   := _high1[1]
    v_low    := _low1 [1]
    v_close  := obv_out[1] 
else
    _high1    := obv_out > _high1[1]? obv_out:_high1[1]
    _low1     := obv_out < _low1[1] ? obv_out:_low1[1]
    v_high   := v_high [1]
    v_low    := v_low  [1] 
    v_close  := v_close[1] 
    

plot(v_high  ,color=high_color)
plot(v_low   ,color=low_color)
plot(v_close ,color=close_color)


// Plot Avg

cum_obv := is_first?obv_out:obv_out+cum_obv[1]
plot(cum_obv/i,color=color.orange,linewidth=2)

plot(0,color=color.maroon)


//end