Trop Bands
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Troptrap

//@version=5
indicator("Trop Bands",overlay=true)
len = input.int(title="Ema length",defval=9)
src = input.source(defval=hlc3)
sns = input.float(title="Sensitivity",defval=0.25 )
innerdi = input.bool(title="Display inner signals", defval=false)
ema = ta.ema(src,len)
uph = 0.0
dnl = 0.0

stup = src[1]<ema and src>ema? src:na
uph := src>ema?ta.highest(len):uph[1]
udiff = uph-ema
upper = fixnan(ta.ema(src+udiff,len))


plot(uph?upper:upper[1],color=color.red, title = "upper")
stdn = src[1]>ema and src<ema? src:na
dnl := src<ema?ta.lowest(len):dnl[1]
ddiff = ema-dnl
lower = fixnan(ta.ema(src-ddiff,len))

plot(dnl?lower:lower[1],color=color.green, title = "lower")


plot(ema, title="ema")


smooth = input(title='Smooth', defval=10)
sma = input(title='SMA', defval=true)
//

bar = (close - open) / open
p = ta.percentile_nearest_rank(bar, 1, 100)
di = 0.0
va = 0.0
h = 0.0
l = 0.0


h := high>high[2]?high:high[2]
l := low<low[2]?low:low[2]
va := h - l
va := sma?ta.sma(va,10):math.avg(va,10)
if va == 0
    va := 1
    va
k = 3 * close / va
p *= k
bp = 1.0
sp = 1.0
bp := close>open?volume:volume/p
sp := close>open?volume/p:volume
di := math.abs(bp)>math.abs(sp)?sp/bp:bp/sp
di := ta.ema(di, smooth)


xtr = di>sns and high>upper?di:di<(-1*sns) and low<lower?di:na
plotshape(xtr>0, location = location.abovebar, style = shape.triangledown, size = size.normal, color=color.red, title = "out of bands upper")
plotshape(xtr<0, location = location.belowbar,style = shape.triangleup, size = size.normal, color=color.green, title = "out of bands lower")


xtrin = di>sns and high<upper?di:di<(-1*sns) and low>lower?di:na

plotshape(innerdi and xtrin>0, location = location.abovebar, style = shape.triangledown, size = size.tiny, color=color.red, title = "inside bands upper")
plotshape(innerdi and xtrin<0, location = location.belowbar,style = shape.triangleup, size = size.tiny, color=color.green, title = "inside bands lower")
