TimeLy Moving Average - TMA
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © only_fibonacci

//@version=5
indicator(title = "TimeLy Moving Average", shorttitle = "TMA", overlay= true, max_bars_back = 5000)

temporal = input.string(defval = "Daily", title = "Time", options = ["Hourly","Daily","Weekly","Monthly"])
movingAverageType = input.string(defval = "SMA", title = "MA Type", options = ["SMA","WMA"])
source = input.source(defval = close, title = "Source")
tempo = switch temporal
    "Hourly" => timeframe.isintraday and timeframe.multiplier <= 60 ? hour : na 
    "Daily" => timeframe.isminutes or (timeframe.isseconds and timeframe.multiplier >= 6) ? dayofmonth : na 
    "Weekly" => timeframe.isminutes or timeframe.isdaily ? weekofyear : na
    "Monthly"=>  (timeframe.isminutes and timeframe.multiplier >= 10) or timeframe.isdaily ? month : na

timeLy1 =  ta.valuewhen(tempo != tempo[1] ,bar_index,0)
timeLy2 =  ta.valuewhen(tempo != tempo[1] ,bar_index,1)
period = bar_index - timeLy1 > 0 ? bar_index - timeLy1 : 1

ma = switch movingAverageType
    "SMA" => ta.sma(source,period)
    "WMA" => ta.wma(source,period)





plot(not na(ma) and not timeframe.isweekly and not timeframe.ismonthly ? ma : na, title = "TMA", color = color.black)

if bar_index == timeLy1
    label.new(timeLy1 - 1,ma[1],text = temporal + " Average\n" + str.tostring(math.round_to_mintick(ma[1])),color = color.gray, textcolor = color.white, style = label.style_label_lower_left)

var lastLabel = label.new(last_bar_index,close)
if bar_index == last_bar_index and not timeframe.isweekly and not timeframe.ismonthly
    lastLabel := label.new(last_bar_index,ma,text = temporal + " Average\n" + str.tostring(math.round_to_mintick(ma)),color = color.gray, textcolor = color.white, style = label.style_label_lower_left)
    label.delete(lastLabel[1])

