Selective Moving Average: Demo
// 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("Selective Moving Average: Demo",shorttitle = "Selective Moving Average [wbburgin]",overlay=true)

selective_ma(bool condition, float source, simple int length, string ma_type) =>
    selective_data = condition ? source : na
    sum_selective_data = 0.0
    count = 0
    for i = 0 to length - 1
        if not na(selective_data[i])
            sum_selective_data := sum_selective_data + selective_data[i]
            count := count + 1
    
    selma = 0.
    if count > 0
        if ma_type == "SMA"
            selma := sum_selective_data / count
        if ma_type == "EMA"
            selma := ta.ema(sum_selective_data / count, length)
        if ma_type == "RMA"
            selma := ta.rma(sum_selective_data / count, length)
        if ma_type == "WMA"
            selma := ta.wma(sum_selective_data / count, length)
        if ma_type == "VWMA"
            selma := ta.vwma(sum_selective_data / count, length)
    
    selma

src = input.source(close,"Source")
condition_str = input.string("Source Within 1 Standard Deviation","Condition",options=["Source Within 1 Standard Deviation","Source Within 2 Standard Deviations","Positive Volume","Negative Volume","RSI > 50","RSI < 50","Candlestick > Body"],
  tooltip="Condition that you want the moving average to take into account. Future updates will include external conditions.")
length = input.int(200,"Length")
ma_type = input.string("SMA","Average Type",options=["SMA","EMA","RMA","WMA","VWMA"])
condition_length = input.int(14,"Condition Length",tooltip = "If your condition is an indicator and has a length, add it here.")

within_stdev(source,length,standevs)=>
    ma = ta.sma(source,length)
    dev = ta.stdev(source,length)
    condition = source > ma - (standevs * dev) and source < ma + (standevs * dev) ? true : false
    condition

condition = switch
    condition_str == "Source Within 1 Standard Deviation" => within_stdev(src,length,1)
    condition_str == "Source Within 2 Standard Deviations"=> within_stdev(src,length,2)
    condition_str == "Positive Volume" => volume > volume[1]
    condition_str == "Negative Volume" => volume < volume[1]
    condition_str == "RSI > 50" => ta.rsi(src,condition_length) > 50
    condition_str == "RSI < 50" => ta.rsi(src,condition_length) < 50
    condition_str == "Candlestick > Body" => high - math.max(close,open) + math.min(close,open) - low > math.abs(close-open)

selma = selective_ma(condition,src,length,ma_type) > 0 ? selective_ma(condition,src,length,ma_type) : na

plot(selma,color=color.yellow,title="Selective Moving Average",style=plot.style_linebr)