STD Stepped Ehlers Optimal Tracking Filter MTF w/ Alerts [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('STD Step Ehlers Optimal Tracking Filter MTF w/ Alerts [Loxx]', 
     shorttitle = "STDSEOTFMTFA [Loxx]", 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204
redcolor = #D2042D 
 
_filt(src, len, filt)=>
    price = src
    filtdev = filt * ta.stdev(src, len)
    price := math.abs(price - price[1]) < filtdev ? price[1] : price
    price

_otf(src)=>
    value1 = 0., value2 = 0., lambda = 0., value3 = 0.
    value1 := 0.2 * (src - nz(src[1])) + 0.8 * nz(value1[1])
    value2 := 0.1 * (high - low) + 0.8 * nz(value2[1])
    lambda := math.abs(value1 / value2)
    alpha = (-lambda * lambda + math.sqrt(lambda * lambda * lambda * lambda + 16 * lambda * lambda)) / 8
    value3 := alpha * src + (1 - alpha) * nz(value3[1])
    value3
    
src = input.source(hl2, "Soruce", group=  "Basic Settings")
filterop = input.string("Both", "Filter Options", options = ["Price", "Ehlers OTF", "Both"], group=  "Basic Settings")
len = input.int(15, "Filter Length", group= "Basic Settings", minval = 1)
filtdev = input.float(0.5, "Filter Devaitions", minval = 0, group= "Basic Settings", step = 0.01)
colorbars = input.bool(false, "Color bars?", group= "UI Options")
showSigs = input.bool(false, "Show signals?", group= "UI Options")

price = filterop == "Both" or filterop == "Price" ? _filt(src, len, filtdev) : src
otfout = _otf(price)
out = filterop == "Both" or filterop == "Ehlers OTF" ? _filt(otfout, len, filtdev) : otfout

goLong_pre = ta.crossover(out, out[1])
goShort_pre = ta.crossunder(out, out[1])

contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch

goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)

plot(out,"EOTF", color = contSwitch == 1  ? greencolor : redcolor, linewidth = 3)

barcolor(colorbars ? contSwitch == 1 ? greencolor : redcolor : na)

plotshape(showSigs and goLong, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.belowbar, size = size.small)
plotshape(showSigs and goShort, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.abovebar, size = size.small)

alertcondition(goLong, title="Long", message="Ehlers Step OTF: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Ehlers Step OTF: Short\nSymbol: {{ticker}}\nPrice: {{close}}")










