EMA Gradient
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © m_b_round

//@version=5
indicator("EMA Gradient", precision=5, overlay=true)

emaLength = input.int(200, "EMA Length", group="EMA Inputs")
emaSource = input.source(close, "Source", group="EMA Inputs")

sampleLength = input.int(10, "Linreg length", group="Linear Regression")
showLine = input.bool(true, "Show best fit line", group="Linear Regression")
linregColor = input.color(color.purple, "Best fit line colour", group="Linear Regression")

gradientThreshold = input.float(75, "Gradient Threshold", group="Gradient Comparison")
gradientComparison = input.int(200, "Gradient Lookback", group="Gradient Comparison")

emaLine = ta.ema(emaSource, emaLength)
gradient = (ta.linreg(emaLine,sampleLength,-10) - ta.linreg(emaLine,sampleLength,10)) / 20 

var line li = na
if showLine
    line.delete(li)
    // Use sampleLength as the plot length of the line to show how many data points it refers to.
    li := line.new(bar_index-sampleLength, ta.linreg(emaLine, sampleLength, sampleLength), bar_index, ta.linreg(emaLine, sampleLength, 0), xloc=xloc.bar_index, color=linregColor, style=line.style_dashed, width=2)


percRank = ta.percentrank(math.abs(gradient), gradientComparison)
plot(percRank, "Percentage Rank", display=display.data_window)

plot(emaLine, color= percRank >= gradientThreshold ? gradient > 0 ? color.green :  color.red : color.yellow)
plot(gradient/close*100, "Gradient (%)", display=display.data_window)
// plot(ta.atr(emaLength) / close * 100, "ATRP", display=display.data_window)