Day Trader's Anchored Moving Averages [wbburgin]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbburgin

//@version=5
indicator("Day Trader's Anchored Moving Averages [wbburgin]",overlay=true)
source = input.source(close,"Source",group="General")
highlighting = input.bool(true,"Highlighting",group="General")

enable1 = input.bool(true,title="Moving Average #1",inline="A",group="General")
length1 = input.int(50, title="", minval=1,inline="A",group="General")
col1 = input.color(color.red,"",inline="A",group="General")

enable2 = input.bool(true,title="Moving Average #2",inline="B",group="General")
length2 = input.int(100, title="", minval=1,inline="B",group="General")
col2 = input.color(color.yellow,"",inline="B",group="General")

enable3 = input.bool(true,title="Moving Average #3",inline="C",group="General")
length3 = input.int(200, title="", minval=1,inline="C",group="General")
col3 = input.color(color.white,"",inline="C",group="General")

period = input.string("Day",options=["Day","Month"],title="Anchor Change Period",group="General")

anchor_reset = period == "Day" ? ta.change(dayofmonth) : ta.change(month)

anchored_ma(source,length,anchor_reset_period) =>
    sum = 0.
    ma = 0.

    if anchor_reset_period
        sum := 0.0
        ma := source

    num = math.min(ta.barssince(anchor_reset_period),length)
    ma := num > 0 ? math.sum(source,num) / num : source
    ma

ma1 = anchored_ma(source,length1,anchor_reset)
ma2 = anchored_ma(source,length2,anchor_reset)
ma3 = anchored_ma(source,length3,anchor_reset)

map1=plot(not enable1 ? na : ma1,color=col1,title="Anchored MA 1")
map2=plot(not enable2 ? na : ma2,color=col2,title="Anchored MA 2")
map3=plot(not enable3 ? na : ma3,color=col3,title="Anchored MA 3")
hl2p=plot(hl2,color=na,title="HL2 (for highlighting)")

fill(map1,hl2p,color=not highlighting ? na : color.new(col1,88))
fill(map2,hl2p,color=not highlighting ? na : color.new(col2,88))
fill(map3,hl2p,color=not highlighting ? na : color.new(col3,88))