Color Changing Moving Average
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jessebadry

//@version=5

indicator(title="Color Changing Moving Average", shorttitle="Colored MA", overlay=true)


//inputs
i_lookback   = input.int(2,     "Angle Period", minval = 1)
i_atrPeriod  = input.int(10,    "ATR Period",  minval = 1)
i_angleLevel = input.int(6,     "Angle Level",  minval = 1)

len = input.int(21, minval=1, title="Length")
src = input.source(close, title="Source")
offset = input.int(title="Offset",defval=0, minval=-500, maxval=500)
type=input.bool(true, "Use EMA? (Off=SMA)")


//output
out=type? ta.ema(src, len) : ta.sma(src, len)




//color change

f_angle(_src, _lookback, _atrPeriod) =>
    rad2degree = 180 / 3.141592653589793238462643  //pi 
    ang = rad2degree * math.atan((_src[0] - _src[_lookback]) / ta.atr(_atrPeriod)/_lookback)
    ang

f_ma(type, _src, _len) =>
    float result = 0
    if type=="SMA" // Simple
        result := ta.sma(_src, _len)
    if type=="EMA" // Exponential
        result := ta.ema(_src, _len)

    result

_ma_type = type ? "EMA" : "SMA"

_ma    = f_ma(_ma_type, src, len)
_angle = f_angle(_ma, i_lookback, i_atrPeriod)


color_H = _angle > 0 ? color.lime : _angle < 0 ? color.red : color.gray

//trend color change
colsh= _angle>0 ? #00ff00 : na
colsh2= _angle<0? #ff0000 : na


//no trend color change
colsh3= _angle==0 ? #9598a1 : na
colsh4= _angle==0 ? #9598a1 : na


//plots


//no rsi plot
// plot(rsifil? na : out, color=col, linewidth=3, offset=offset)


//BG line plot
// plot(_angle==0? out:na, color=#9598a1, linewidth=3, offset=offset)


// //trend line plot
plot(out, color=colsh, linewidth=3, offset=offset)
plot(out, color=colsh2, linewidth=3, offset=offset)




