//@version=4
// Copyright (c) 2019-present, Franklin Moormann (cheatcountry)
// Natural Moving Average [CC] script may be freely distributed under the MIT license.
study("Natural Moving Average [CC]", overlay=true)
inp = input(title="Source", type=input.source, defval=close)
res = input(title="Resolution", type=input.resolution, defval="")
rep = input(title="Allow Repainting?", type=input.bool, defval=false)
bar = input(title="Allow Bar Color Change?", type=input.bool, defval=true)
src = security(syminfo.tickerid, res, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]
length = input(title="Length", type=input.integer, defval=40, minval=1)
ln = log(src) * 1000
num = 0.0, denom = 0.0
for i = 0 to length - 1
oi = abs(nz(ln[i]) - nz(ln[i + 1]))
num += oi * (sqrt(i + 1) - sqrt(i))
denom += oi
ratio = denom != 0 ? num / denom : 0
nma = (src * ratio) + (nz(src[1]) * (1 - ratio))
slo = src - nma
sig = slo > 0 ? slo > nz(slo[1]) ? 2 : 1 : slo < 0 ? slo < nz(slo[1]) ? -2 : -1 : 0
alertcondition(crossover(sig, 1), "Strong Buy Signal", "Strong Bullish Change Detected")
alertcondition(crossunder(sig, -1), "Strong Sell Signal", "Strong Bearish Change Detected")
alertcondition(crossover(sig, 0), "Buy Signal", "Bullish Change Detected")
alertcondition(crossunder(sig, 0), "Sell Signal", "Bearish Change Detected")
nmaColor = sig > 1 ? color.green : sig > 0 ? color.lime : sig < -1 ? color.maroon : sig < 0 ? color.red : color.black
barcolor(bar ? nmaColor : na)
plot(nma, color=nmaColor, linewidth=2)