ATR-Adaptive JMA [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("ATR-Adaptive JMA [Loxx]", 
     shorttitle='ATRAJMA [Loxx]', 
     overlay = true, 
     timeframe="", 
     timeframe_gaps = true)
     
import loxx/loxxjuriktools/1

greencolor = #2DD204
redcolor = #D2042D

_corMa(src, work, per)=>
    out = 0.
    v1 = math.pow(ta.stdev(src, per), 2)
    v2 = math.pow(nz(out[1]) - work, 2) 
    c = (v2 < v1 or v2 == 0) ? 0 : 1 - v1 / v2
    out := nz(out[1]) + c * (work - nz(out[1]))
    out

src  = input.source(close, "Source", group = "Basic Settings")
per = input.int(14, "Period", group = "Basic Settings")
phs = input.float(0, "Jurik Phase", group = "Basic Settings")

colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")

atr = ta.atr(per)
_max   = ta.highest(atr, per)   
_min   = ta.lowest(atr, per)           
_coeff = (_min != _max) ? 1-(atr-_min)/(_max-_min) : 0.5

perout = int(per * (_coeff+1.0)/2.0)

out = loxxjuriktools.jurik_filt(src, perout, phs) 
sig = out[1]

goLong_pre =  ta.crossover(out, sig)  
goShort_pre = ta.crossunder(out, sig)

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

colorout =  out > sig ? greencolor : out < sig ? redcolor : color.gray

plot(out, "ATR-Adaptive JMA", color = colorout, linewidth = 3)

barcolor(colorbars ? colorout : na)
