Automated Anchored VWAP
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kurtsmock

//@version=5
indicator("Automated Anchored VWAP", shorttitle="aaVWAP", overlay=true)
vw_g1   = "Pivots Settings"
vw_g2   = "Tracking Settings"
s_piv   = input(true,       "Show Pivots",          group=vw_g1)
_lb     = input.int(10,     "Left Bars Lookback",   group=vw_g1)
_rb     = input.int(10,     "Right Bars Lookahead", group=vw_g1)
brks    = input(true,       "Break Early",          group=vw_g2, tooltip = "Stops plotting the Pivot Low when price falls beneath.\nStops plotting the Pivot High when price breaks above.")

c_ph    = ta.pivothigh(_lb, _rb)
c_pl    = ta.pivotlow(_lb, _rb)
_lh     = ta.valuewhen(c_ph, c_ph, 0) < ta.valuewhen(c_ph[1], c_ph[1], 0)
_hh     = ta.valuewhen(c_ph, c_ph, 0) > ta.valuewhen(c_ph[1], c_ph[1], 0)
_ll     = ta.valuewhen(c_pl[1], c_pl[1], 0) > ta.valuewhen(c_pl, c_pl, 0)
_hl     = ta.valuewhen(c_pl[1], c_pl[1], 0) < ta.valuewhen(c_pl, c_pl, 0)

var h_vol = 0.0
var h_src = 0.0
if _hh or _lh
    h_vol := 0
    h_src := 0
    for i=0 to _rb 
        h_vol := h_vol + volume[i]
        h_src := h_src + (hlc3[i] * volume[i]) 

h_sumSrc   = hlc3 * volume
h_sumVol   = volume
h_sumSrc  := _hh or _lh ? h_src : h_sumSrc + h_sumSrc[1]
h_sumVol  := _hh or _lh ? h_vol : h_sumVol + h_sumVol[1]
h_aVWAP    = h_sumSrc / h_sumVol

var l_vol = 0.0
var l_src = 0.0
if _ll or _hl
    l_vol := 0
    l_src := 0
    for i=0 to _rb 
        l_vol := l_vol + volume[i]
        l_src := l_src + (hlc3[i] * volume[i]) 

l_sumSrc   = hlc3 * volume
l_sumVol   = volume
l_sumSrc  := _ll or _hl ? l_src : l_sumSrc + l_sumSrc[1]
l_sumVol  := _ll or _hl ? l_vol : l_sumVol + l_sumVol[1]
l_aVWAP    = l_sumSrc / l_sumVol

h_breaks = brks ? low >h_aVWAP : false
l_breaks = brks ? high<l_aVWAP : false
plot(_hh or _lh or h_breaks ? na : h_aVWAP, color=color.new(color.green,0), style=plot.style_linebr)
plot(_ll or _hl or l_breaks ? na : l_aVWAP, color=color.new(color.red,0),   style=plot.style_linebr)

// Pivot Plotshapes
plotshape(s_piv ? _hh : na, 'Higher High', style=shape.square, location=location.abovebar, color=color.new(color.green, 50), text='[HH]', offset=-_rb, size=size.auto)
plotshape(s_piv ? _lh : na, 'Higher Low',  style=shape.square, location=location.abovebar, color=color.new(color.red, 50),   text='[LH]', offset=-_rb, size=size.auto)
plotshape(s_piv ? _ll : na, 'Lower Low',   style=shape.square, location=location.belowbar, color=color.new(color.red, 50),   text='[LL]', offset=-_rb, size=size.auto)
plotshape(s_piv ? _hl : na, 'Lower High',  style=shape.square, location=location.belowbar, color=color.new(color.green, 50), text='[HL]', offset=-_rb, size=size.auto)
