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

//@version=5

indicator('Automatic Moving Average', overlay=true, max_bars_back=201)

// input
start = 20
lookback = input(20, "Sensitivity", tooltip="Low (High Sensitivity), High (Low Sensitivity).\n\nAdjust according to timeframe and asset.")
resp = 1
smoothing = input(5, "Smoothing")
source = input(close, "Source")


// global
var ix = -1
var mal = array.new_int(0)


// functions
avg(source, len) =>
    sum = 0.0
    for i = 0 to len-1
        sum += source[i]
    sum/len

bull = close > open

wick_touch(x) =>
    bull ? ((close <= x and x <= high) or (low <= x and x <= open)) : ((open <= x and x <= high) or (low <= x and x <= close))

body_touch(x) =>
    bull ? (open < x and x < close) : (close < x and x < open)

touches(t) =>
    touches = 0
    for i = 0 to lookback-1
        touches += t[i] ? 1 : 0
    touches


// local
ix := ix+1
prev_mal = ix >= 1 ? array.get(mal, ix-1) : start

cma = avg(source, prev_mal)
cma_p1 = avg(source, prev_mal+1)
cma_m1 = avg(source, prev_mal-1)

d = touches(wick_touch(cma))
d_p1 = touches(wick_touch(cma_p1))
d_m1 = touches(wick_touch(cma_m1))

d_b = touches(body_touch(cma))
d_p1_b = touches(body_touch(cma_p1))
d_m1_b = touches(body_touch(cma_m1))

any_body_touch = d_b > 0 or d_p1_b > 0 or d_m1_b > 0
no_wick_touch = d <= 0 and d_p1 <= 0 and d_m1 <= 0
wick_maximized = d >= d_p1 and d >= d_m1 ? prev_mal : (d_p1 >= d and d_p1 >= d_m1 ? prev_mal+resp : (d_m1 >= d and d_m1 >= d_p1 ? prev_mal-resp : na))

uptrend = cma > cma[1]
downtrend = cma < cma[1]
against_trend = (uptrend and close < cma) or (downtrend and close > cma)

new_mal = no_wick_touch or against_trend ? prev_mal-resp : (any_body_touch ? prev_mal+resp : wick_maximized)
next_mal = na(new_mal) ? prev_mal : new_mal

array.push(mal, next_mal < 2 ? 2 : (next_mal > 200 ? 200 : next_mal))


// graph
scma = ta.ema(cma, smoothing)
plot(scma, "Automatic MA")
