Standard-Deviation Adaptive Smoother MA [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Standard Deviation Adaptive Smoother [Loxx]",
     shorttitle = "STDAS [Loxx]", 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)
    
greencolor = #2DD204
redcolor = #D2042D 

_smoother(float src, len)=>
    wrk = src, wrk2 = src, wrk4 = src
    wrk0 = 0., wrk1 = 0., wrk3 = 0.
    alpha = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
    wrk0 := src + alpha * (nz(wrk[1]) - src)
    wrk1 := (src - wrk) * (1 - alpha) + alpha * nz(wrk1[1])
    wrk2 := wrk0 + wrk1
    wrk3 := (wrk2 - nz(wrk4[1])) * math.pow(1.0 - alpha, 2) + math.pow(alpha, 2) * nz(wrk3[1])
    wrk4 := wrk3 + nz(wrk4[1])
    wrk4
    
_stdPer(src, per, adaptper)=>
    dev = ta.stdev(src, adaptper)
    avg = ta.sma(dev, adaptper)
    period = (dev!=0) ? math.max(per * avg/dev, 2) : math.max(per, 1)
    period := int(period)
    
src = input.source(close, "Source", group = "Basic Settings")
SmtPeriod = input.int(15, "Smoother Period", group = "Basic Settings")
AdaptivePeriod = input.int(25, "Adaptive Period", group = "Basic Settings")
ColorSteps = input.int(50, "Color Period", group = "Basic Settings")

colorbars = input.bool(false, "Color bars?", group = "UI Options")

len = _stdPer(src, SmtPeriod, AdaptivePeriod)
smt = _smoother(src, len)  

min = ta.lowest(smt, ColorSteps) 
max = ta.highest(smt, ColorSteps) 
mid = (max + min) / 2

colorBuffer = color.from_gradient(smt, min, mid, redcolor, greencolor)

plot(smt, color = colorBuffer, linewidth = 5)

barcolor(colorbars ? colorBuffer : na)




