Historical Average
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262

//@version=5
indicator("Historical Average", overlay = true)

source = input.source(close, "Source")
select = input.string("SMA", "Select", ["SMA","LWMA","EMA","DEMA","TEMA","QEMA"])

simple_moving_average(source)=>
    var float sum = na
    var int count = na
    if close == close
        count := nz(count[1]) + 1
        sum := nz(sum[1]) + source 
    sum/count

linear_weighted_moving_average(source)=>
    var float sum = na
    var int count = na
    if close == close
        count := nz(count[1]) + 1
        sum := nz(sum[1]) + (source * count)
    sum/count/count

exponential_moving_average(source)=>
    var float ema = 0.0
    var int count = 0
    if open == open
        count := nz(count[1]) + 1
        ema := (1.0 - 2.0 / (count + 1.0)) * nz(ema[1]) + 2.0 / (count + 1.0) * source
    ema

double_exponential_moving_average(source)=>
    var float ema1 = 0.0
    var float ema2 = 0.0
    var int count = 0
    if close == close
        count := nz(count[1]) + 1
        ema1 := (1.0 - 2.0 / (count + 1.0)) * nz(ema1[1]) + 2.0 / (count + 1.0) * source
        ema2 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema2[1]) + 2.0 / (count + 1.0) * ema1
    2 * ema1 - ema2

triple_exponential_moving_average(source)=>
    var float ema1 = 0.0
    var float ema2 = 0.0
    var float ema3 = 0.0
    var int count = 0
    if close == close
        count := nz(count[1]) + 1
        ema1 := (1.0 - 2.0 / (count + 1.0)) * nz(ema1[1]) + 2.0 / (count + 1.0) * source
        ema2 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema2[1]) + 2.0 / (count + 1.0) * ema1
        ema3 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema3[1]) + 2.0 / (count + 1.0) * ema2
    3 * ema1 - 3 * ema2 + ema3  

quadruple_exponential_moving_average(source)=>
    var float ema1 = 0.0
    var float ema2 = 0.0
    var float ema3 = 0.0
    var float ema4 = 0.0
    var int count = 0
    if close == close
        count := nz(count[1]) + 1
        ema1 := (1.0 - 2.0 / (count + 1.0)) * nz(ema1[1]) + 2.0 / (count + 1.0) * source
        ema2 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema2[1]) + 2.0 / (count + 1.0) * ema1
        ema3 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema3[1]) + 2.0 / (count + 1.0) * ema2
        ema4 :=(1.0 - 2.0 / (count + 1.0)) * nz(ema4[1]) + 2.0 / (count + 1.0) * ema3
    4 * ema1 - 6 * ema2 + 4 * ema3 - ema4

ma(source, select)=>
    switch select
        "SMA"  => simple_moving_average(source)
        "LWMA" => linear_weighted_moving_average(source)
        "EMA"  => exponential_moving_average(source)
        "DEMA" => double_exponential_moving_average(source)
        "TEMA" => triple_exponential_moving_average(source)
        "QEMA" => quadruple_exponential_moving_average(source)

average = ma(source, select)

plot(average, "Average")

