Auto anchored VWAP Highest/Lowest Last 'n' bars 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Badshah.E.Alam

//@version=5
indicator("Auto anchored VWAP Highest/Lowest Last 'n' bars ", overlay=true,max_labels_count = 500,max_lines_count = 500, max_bars_back = 3000)

len = input.int(100,'bars to look for Highest/Lowest ',maxval = 3000)
src = input.source(hlc3,'source')

hiOffset = - ta.highestbars(src,len)
loOffset = - ta.lowestbars(src,len)

htf=''
//function to calculate and store the vwap values 
f_avwap(src, date) =>
    float[]    array_sumSrc = array.new_float( date,na)
    float[]    array_sumVol = array.new_float( date,na)
    float[]    array_final = array.new_float( date,na)
    int[]    bar_finaltime = array.new_int( date,na)
    if date>0 and array.size(array_sumSrc)>0
        for i=date-1 to 0 
            sumSrc = src[i] * volume[i]
            sumVol = volume[i]
            array.set(array_sumSrc,i,sumSrc + sumSrc[1+i])
            array.set(array_sumVol,i,sumVol + sumVol[1+i])
            // sumSrc :=  sumSrc + sumSrc[1+i]
            // sumVol :=  sumVol + sumVol[1+i]
            finalVal=array.sum(array_sumSrc) / array.sum(array_sumVol)
            array.set(array_final,i,finalVal)
            array.set(bar_finaltime,i,time_close)
    [array_final,bar_finaltime]        

// get vwap from highest from last 'n' bars 
ath_dt = bar_index-bar_index[hiOffset]
[final_val,barTime]=request.security(syminfo.tickerid,htf,f_avwap(src, ath_dt))


// get vwap from lowest from last 'n' bars 
atl_dt = bar_index-bar_index[loOffset]
[final_vallo,barTimelo]=request.security(syminfo.tickerid,htf,f_avwap(src, atl_dt))

alertML=input.string('touch Low Auto VWAP',title ='Auto VWAP lowest touch Alert message',group = 'Alert Message')
alertMH=input.string('touch High Auto VWAP',title ='Auto VWAP highest touch Alert message',group = 'Alert Message')
//plotting the vwap
if barstate.islast//confirmedhistory
    if array.size(final_val)>0
        for i=array.size(final_val)-1 to 0 
            line.new(bar_index[i+1],array.get(final_val,i),bar_index[i],array.get(final_val,i),color=color.red)   
            if ta.crossover(close,     array.get(final_val,i))
                alert(alertMH,freq = alert.freq_once_per_bar_close)
                //label.new(bar_index,close,'TH')
    if array.size(final_vallo)>0
        for i=array.size(final_vallo)-1 to 0 
            line.new(bar_index[i+1],array.get(final_vallo,i),bar_index[i],array.get(final_vallo,i),color=color.lime)        
            if ta.crossunder(close,     array.get(final_vallo,i))
                alert(alertML,freq = alert.freq_once_per_bar_close)
                //label.new(bar_index,close,'TL')
