Top Trend [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Top trend [Loxx]", shorttitle = "TT [Loxx]", overlay = true, timeframe="", timeframe_gaps=true)

typebol = "Bollinger Bands"
typekc = "Keltner Channels"

type = input.string(typebol, "Calculation Type", options = [typebol, typekc], group = "Core Settings")
src = input.source(close, "Source", group = "Core Settings")
MoneyRisk= input.float(1.00, "Money Risk", group ="Core Settings", minval = 0)

Length = input.int(20, "Length", group = typebol)
Deviation = input.int(2, "Deviation", group = typebol)

factor =input.int(3, "Multiplier", minval=1, group = typekc)
periodATR =input.int(7, "ATR Period", minval=1, group =typekc)

UptrendBuffer =0.0
DowntrendBuffer =0.0
trendBB = 0.0
bsmax = 0.0
bsmin = 0.0

[_, smax, _] = ta.bb(src, Length, Deviation)
[_, _, smin] = ta.bb(src, Length, Deviation)

if(src > smax[1]) 
    trendBB:=1

if(src < smin[1])
    trendBB:=-1
    
if(trendBB > 0 and smin <smin[1])
    smin := smin[1]
    
if(trendBB < 0 and smax > smax[1])
    smax := smax[1]
    
bsmax := smax + 0.5 * (MoneyRisk-1) * (smax-smin)
bsmin := smin - 0.5 * (MoneyRisk-1) * (smax-smin)

if(trendBB > 0 and bsmin < bsmin[1]) 
    bsmin := bsmin[1]
    
if(trendBB < 0 and bsmax > bsmax[1]) 
    bsmax := bsmax[1]

if (trendBB > 0) 
    UptrendBuffer := bsmin 

if (trendBB < 0) 
    DowntrendBuffer := bsmax 
    
ttBBout = 0.
ttBBout := nz(ttBBout[1])
ttBBout := DowntrendBuffer > 0 ? DowntrendBuffer : UptrendBuffer > 0 ? UptrendBuffer : ttBBout


up = src - (factor*ta.atr(periodATR))
dn = src + (factor*ta.atr(periodATR))

trendUp = 0.0
trendDown = 0.0


trendKC = 0.0
ttkc = 0.0

trendUp := close[1] > trendUp[1] ? math.max(up, trendUp[1]) : up
trendDown := close[1] < trendDown[1] ? math.min(dn, trendDown[1]) : dn

trendKC := close > trendDown[1] ? 1: close < trendUp[1] ? -1:  nz(trendKC[1], 1)

ttkc := trendKC == 1 ? trendUp + 0.5 * (MoneyRisk-1) * (trendUp-trendDown) : trendDown-  0.5 * (MoneyRisk-1)  * (trendUp-trendDown)


linecolorKC = trendKC == 1 ? color.lime : color.red
linecolorBB = close > ttBBout ? color.lime : color.red


plot(type == typekc ? ttkc : ttBBout , color = type == typekc ? linecolorKC : linecolorBB , linewidth = 2, title = "Top trend")



























