Anchored Moving Averages - Interactive
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FractalTrade15

//@version=5
indicator("Anchored MA", overlay = true)
// --- functions ---
getBarIndexForTime(t) =>
    // Obtain the bar index from the timestamp. The function is adopted from 
    // the script published by TradingView:
    // https://www.tradingview.com/script/SkmMrMe0-CAGR-Custom-Range/
    // Input: 
    //    t  :: timestamp
    // Outup ::  integer, bar index
    var int barindex_t = na
    if time[1] <= t and time >= t and na(barindex_t)
        barindex_t := bar_index
    barindex_t

anchored_ma(start, source) =>
    startBar = ta.barssince(time == start)
    sumClose = ta.cum(source) - ta.cum(source)[startBar + 1]
    barsFromAnchor = math.min(startBar, bar_index)
    ama = sumClose / (barsFromAnchor + 1)


// --- constants ---
int    DEAFAULT_TIME1 = timestamp("2021-09")
int    DEAFAULT_TIME2 = timestamp("2021-10")
int    DEAFAULT_TIME3 = timestamp("2021-11")
int    startTimeInput1 = input.time(title = "Start Time 1", defval = DEAFAULT_TIME1, confirm = true)
int    startTimeInput2 = input.time(title = "Start Time 2", defval = DEAFAULT_TIME2, confirm = true)
int    startTimeInput3 = input.time(title = "Start Time 3", defval = DEAFAULT_TIME3, confirm = true)
srcinput = input(title='Source', defval=hlc3)
bullc = input.color(color.green, title = "Bullish Color")
bearc = input.color(color.red, title = "Bearish Color")


// Initialize time intervals
int    startTime1 = startTimeInput1
int    startTime2 = startTimeInput2
int    startTime3 = startTimeInput3

// Calculate the AMAs
ama1 = anchored_ma(startTime1, srcinput)
ama2 = anchored_ma(startTime2, srcinput)
ama3 = anchored_ma(startTime3, srcinput)

col1 = ama1 > ama1[2]? bullc : bearc
col2 = ama2 > ama2[2]? bullc : bearc
col3 = ama3 > ama3[2]? bullc : bearc

// Plot the AMAs
plot(ama1, color=color.new(color.silver,90), linewidth=6, title="Anchored Moving Average Shadow 1")
plot(ama1, color=col1, linewidth=1, title="Anchored Moving Average 1")

plot(ama2, color=color.new(color.silver,90), linewidth=6, title="Anchored Moving Average Shadow 2")
plot(ama2, color=col2, linewidth=1, title="Anchored Moving Average 2")

plot(ama3, color=color.new(color.silver,90), linewidth=6, title="Anchored Moving Average Shadow 3")
plot(ama3, color=col3, linewidth=1, title="Anchored Moving Average 3")