Auto trend overlay
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © alexhyer13

//@version=5
indicator("Auto trend overlay",overlay=true)

length=input.int(title="CMA Length", defval=42)
color_overlay = input.bool(title="Overlay color (must change visual order to front)", defval=1)
plot_cma = input.bool(title="Plot CMA", defval=1)
rate=input.int(title="CMA derive rate", defval=13)

if (length%2==1)
    length+=1

front_half=0.0
second_half=0.0
for i=0 to (length/2)-1
    front_half := front_half+close[i+(length/2)]
    second_half := second_half+close[i]
new_cma = ((front_half/1.5)+(second_half/0.75))/length

front_half:=0.0
second_half:=0.0
for i=0 to (length/2)-1
    front_half := front_half+close[i+(length/2)+rate]
    second_half := second_half+close[i+rate]
old_cma = ((front_half/1.5)+(second_half/0.75))/length

slope = (new_cma-old_cma)/rate

if (plot_cma==0)
    new_cma:=na

bar_color = color.green
if (slope>=0)
    bar_color := color.green
if (slope<0)
    bar_color := color.red

plotcandle(color_overlay ? open : na,color_overlay ? high : na,color_overlay ? low : na,color_overlay ? close : na,color = bar_color,wickcolor = bar_color,bordercolor = bar_color)

plot(new_cma ? new_cma : na, color=color.purple)