Tracer
Tracer
me/eyops
//@version=5
//text inputs
textVPosition = 'middle'
textHPosition = 'center'
symVPosition = 'top'
symHPosition = 'left'
width = 0
height = 0
c_title = #b2b5be80
s_title = 'large'
a_title = 'center'
c_subtitle = #b2b5be80
s_subtitle = 'normal'
a_subtitle = 'center'
c_bg = color.new(color.blue, 100)
indicator("Lux Algo Signals & Overlays [6.3]", "Lux Algo Signals & Overlays [6.3]",
overlay = true, max_labels_count = 500)
//Import libraries
import ayvaliktrading/EyopsTelegram/1 as LAF
import ayvaliktrading/JoinUsEyopsTelegram/1 as kernels
// Advanced Settings
groupAdvanced = "ADVANCED SETTINGS"
takeProfitBoxes = input.string("Off", "TP/SL Points", options=["Off","On"], inline
= "2", tooltip = "Shows Take Profit and Stop Loss areas",group = groupAdvanced)
takeProfitStopLossDistance = input.int(5,"", minval = 1, maxval = 10, inline = "2",
group=groupAdvanced)
autopilotMode = input.string("Off", "Autopilot Sensivity",["Off","Short-Term",
"Mid-Term", "Long-Term"],tooltip = "Sets automatic settings for signals and
improves their quality" ,inline = "3", group = groupAdvanced)
dashboardLocation = input.string("Bottom Right","Dashboard Location", ["Top
Right","Bottom Right","Bottom Left"], inline = "4",tooltip = "Changes dashboard
positions" ,group = groupAdvanced)
dashboardSize = input.string("Normal","Dashboard Size",
["Tiny","Small","Normal","Large"], inline = "5",tooltip = "Changes the size of the
dashboard" ,group = groupAdvanced)
n = bar_index
// # ============================[BUY/SELL SIGNALS]============================ #
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------}
// # ============================[SESSIONS]============================ #
show_sesa = true
sesa_txt = 'New York'
sesa_ses = '1300-2200'
sesa_css = #ff5d00
sesa_range = true
sesa_tl = false
sesa_avg = false
sesa_vwap = false
sesa_maxmin = false
//Session B
show_sesb = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
sesb_css = #2157f3
sesb_range = true
sesb_tl = false
sesb_avg = false
sesb_vwap = false
sesb_maxmin = false
//Timezones
tz_incr = 0
use_exchange = false
//Ranges Options
bg_transp = 90
show_outline = true
show_txt = true
//Dashboard
show_ses_div = false
show_day_div = false
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
sma
    var   float   y1 = na
    var   float   y2 = na
    var   float   stdev = na
    var   float   r2    = na
          y1 := 4 * sma - 3 * wma
          y2 := 3 * wma - 2 * sma
//Session Vwap
get_vwap(session) =>
    var float num = na
    var float den = na
    [num, den]
//Set line
set_line(session, y1, y2, session_css)=>
    var line tl = na
        box.set_top(bx, max)
        box.set_rightbottom(bx, n, min)
          if show_txt
              label.set_xy(lbl, int(math.avg(t, time)), max)
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//Ranges
if show_sesa and sesa_range and textVPosition    == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title    == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle ==    'normal' and a_subtitle == 'center'
    [max, min] = get_range(is_sesa, sesa_txt,    sesa_css)
    max_sesa := max
    min_sesa := min
//Trendlines
//Mean
if show_sesa and sesa_avg and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center'
    avg = get_avg(is_sesa)
    set_line(is_sesa, avg, avg, sesa_css)
//VWAP
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot max/min
plot(showSessions and sesa_maxmin and textVPosition == 'middle' and textHPosition
== 'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
max_sesa : na, 'Session A Maximum', sesa_css, 1, plot.style_linebr, editable =
false)
plot(showSessions and sesa_maxmin and textVPosition == 'middle' and textHPosition
== 'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
min_sesa : na, 'Session A Minimum', sesa_css, 1, plot.style_linebr, editable =
false)
//Plot Divider A
plotshape(is_sesa and show_ses_div and show_sesa and showSessions, "·"
  , shape.square
  , location.bottom
  , na
  , text = "."
  , textcolor = sesa_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
//Plot Divider B
plotshape(is_sesb and show_ses_div and show_sesb and showSessions, "·"
  , shape.labelup
  , location.bottom
  , na
  , text = "."
  , textcolor = sesb_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
plotshape(is_sesb != is_sesb[1] and show_ses_div and show_sesb and showSessions,
"LDN"
  , shape.labelup
  , location.bottom
  , na
  , text = "❚"
  , textcolor = sesb_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
// # ============================[FUNCTIONS]============================ #
type bar
    float   o   =   open
    float   h   =   high
    float   l   =   low
    float   c   =   close
    float   v   =   volume
    int     i   =   bar_index
bar b = bar.new()
nzV = nz(b.v)
f_calcV() =>
    uV = 0.0
    dV = 0.0
    switch
        (b.c - b.l) > (b.h - b.c)   => uV := nzV
        (b.c - b.l) < (b.h - b.c)   => dV := -nzV
        b.c > b.o => uV := nzV
        b.c < b.o => dV := -nzV
        b.c > nz(b.c[1]) => uV :=   nzV
        b.c < nz(b.c[1]) => dV :=   -nzV
        nz(uV[1]) > 0 => uV := uV   + nzV
        nz(dV[1]) < 0 => dV := dV   - nzV
[uV, dV]
// # ============================[CONSTANT VARIABLES]============================ #
sma4 = ta.sma(close, 4)
sma5 = ta.sma(close, 5)
sma9 = ta.sma(close, 9)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
bullishSignalColor = #59e08a
bearishSignalColor = #ff5959
dashboardRedText = #ee787d
dashboardGreenText = #42bda8
dashboardGreenBackground = #284444
dashboardRedBackground = #49343e
// # ============================[CANDLE COLORING]============================ #
macdFastLength = 12
macdSlowLength = 26
macdSignalLength = 9
// Yellow
yellowLow = #56328f
// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #56328f
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    redHigh := #ff0000
    redMidHigh := #c21637
    redMidLow := #c33252
    redLow := #8e215f
if (candleColorType == 'Contrarian Gradient')
    redHigh := #01d70c
    redMidHigh := #269444
    redMidLow :=#4f966c
    redLow := #425970
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    greenHigh := #ff0000
    greenMidHigh := #c21637
    greenMidLow := #c33252
    greenLow := #8e215f
// Default color
candleBody = yellowLow
if histX > 0
    if histX > histX[1] and histX[1] > 0 and textVPosition == 'middle' and
textHPosition == 'center' and c_title == #b2b5be80 and s_title == 'large' and
a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and
a_subtitle == 'center'
        candleBody := greenLow
if histX < 0
    if histX < histX[1] and histX[1] < 0 and textVPosition == 'middle' and
textHPosition == 'center' and c_title == #b2b5be80 and s_title == 'large' and
a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and
a_subtitle == 'center'
        candleBody := redLow
// Bullish trend
if MacdX > 0 and histX > 0
    candleBody := greenMidLow
    if histX > histX[1] and MacdX[1] > 0 and histX[1] > 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
        candleBody := greenMidHigh
        if histX > histX[2] and MacdX[2] > 0 and histX[2] > 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
            candleBody := greenHigh
// Bearish trend
if MacdX < 0 and histX < 0
    candleBody := redMidLow
    if histX < histX[1] and MacdX[1] < 0 and histX[1] < 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
        candleBody := redMidHigh
        if histX < histX[2] and MacdX[2] < 0 and histX[2] < 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
            candleBody := redHigh
// # ============================[SMART TRAIL]============================ #
[smartTrailLine, fillerLine, smartTrailDirection] = LAF.getSmartTrail(10, 4, 8)
smartTrail1 = plot(smartTrail and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
smartTrailLine : na, "Smart Trail", style = plot.style_line, color =
smartTrailDirection== 'long' ? color.new(#2157f9, 0) : smartTrailDirection ==
'short' ? color.new(#ff1100, 0) : na, editable = false)
smartTrail2 = plot(smartTrail and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
fillerLine : na, "Fib 2", style = plot.style_line, transp = 100, editable = false)
fill(smartTrail1, smartTrail2, color = smartTrailDirection == 'long' ?
color.new(#2157f9, 80) : smartTrailDirection == 'short' ? color.new(#ff1100, 80) :
na, editable = false)
// # ============================[TREND CATCHER]============================ #
[trendCatcherLine, trendCatcherColor] = LAF.getTrendCatcher()
newTrendCatcherColor = trendCatcherColor == color.blue ? #02ff65 : #ff1100
plot(trendCatcher and textVPosition == 'middle' and textHPosition == 'center' and
c_title == #b2b5be80 and s_title == 'large' and a_title == 'center' and c_subtitle
== #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
trendCatcherLine : na, title='Trend Catcher', linewidth=2,
color=newTrendCatcherColor, editable = false)
// # ============================[NEO CLOUD]============================ #
// # ============================[REVERSAL ZONES]============================ #
// # ============================[TREND TRACER]============================ #
[trendTracerLine, trendTracerDirection] = LAF.getTrendTracer()
plot(trendTracer and textVPosition == 'middle' and textHPosition == 'center' and
c_title == #b2b5be80 and s_title == 'large' and a_title == 'center' and c_subtitle
== #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
trendTracerLine : na, title='Trend Tracer', linewidth=2, style=plot.style_cross,
color = trendTracerDirection, editable = false)
// # ============================[DASHBOARD
COMPONENTS|]============================ #
volatilityMetric = LAF.getVolatilityMetric()
volatilityMetric2 = ta.sma(LAF.getVolatilityMetric(), 8)
volatilityText = volatilityMetric < 30 ? 'Stable' : volatilityMetric < 80 ?
'Moderate' : 'Volatile'
volatilityEmoji = volatilityMetric2 > volatilityMetric ? '📉' : '📈'
volatilityCellColor = newTrendCatcherColor == #02ff65 ? dashboardGreenBackground :
dashboardRedBackground
VolatilityTextColor = trendStrengthCellColor == dashboardGreenBackground ?
dashboardGreenText : dashboardRedText
totalVolume = uV + math.abs(dV)
//volumecolor = totalVolume >= 50 ? bullish : bearish
volumeCellColor = dashboardRedBackground
volumeTextColor = totalVolume >= 50 ? dashboardGreenText : dashboardRedText
if (totalVolume >= 50)
     totalVolume := totalVolume*2
     volumeCellColor := dashboardGreenBackground
else
     totalVolume := totalVolume*-2
volumeSentiment = totalVolume
tb = table.new(table_position, 7, 7
  , bgcolor = #1e222d
  , border_color = #373a46
  , border_width = 1
  , frame_color = #373a46
  , frame_width = 1)
if showDashboard
    if barstate.islast
        tb.cell(0, 2, autopilotMode == 'Off' ? "✈️
                                                 Optimal Sensivity" : " Autopilot
Enabled", text_color = color.white, text_size = table_size, text_halign =
text.align_left)
        tb.cell(0, 3, str.tostring(trendIndication) + "Trend Strength", text_color
= color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 4, volatilityEmoji+ " Lux Volatility", text_color = color.white,
text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 5, "🔃 Squeeze", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
        tb.cell(0, 6, "💧 Volume Sentiment", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
indiSet = false
source = hlc3
type = 'SuperSmoother'
length = 100
innermult = 1.0
outermult = 2.415
ChartSet = false
drawchannel = true
displayzone = true
zonetransp = 60
displayline = true
MTFSet = false
enable_mtf = true
mtf_disp_typ = 'On Hover'
mtf_typ = 'Auto'
mtf_lvl1 = 'D'
mtf_lvl2 = 'W'
//
***********************************************************************************
*************************
// Functions Start {
//
***********************************************************************************
*************************
var pi = 2 * math.asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp
//-----------------------
// Ehler SwissArmyKnife Function
//-----------------------
SAK_smoothing(_type, _src, _length) =>
    c0 = 1.0
    c1 = 0.0
    b0 = 1.0
    b1 = 0.0
    b2 = 0.0
    a1 = 0.0
    a2 = 0.0
    alpha = 0.0
    beta = 0.0
    gamma = 0.0
    cycle = 2 * pi / _length
    if _type == 'Ehlers EMA'
        alpha := (math.cos(cycle) + math.sin(cycle) - 1) / math.cos(cycle)
        b0 := alpha
        a1 := 1 - alpha
        a1
    if _type == 'Gaussian'
        beta := 2.415 * (1 - math.cos(cycle))
        alpha := -beta + math.sqrt(beta * beta + 2 * beta)
        c0 := alpha * alpha
        a1 := 2 * (1 - alpha)
        a2 := -(1 - alpha) * (1 - alpha)
        a2
    if _type == 'Butterworth'
        beta := 2.415 * (1 - math.cos(cycle))
        alpha := -beta + math.sqrt(beta * beta + 2 * beta)
        c0 := alpha * alpha / 4
        b1 := 2
        b2 := 1
        a1 := 2 * (1 - alpha)
        a2 := -(1 - alpha) * (1 - alpha)
        a2
    if _type == 'BandStop'
        beta := math.cos(cycle)
        gamma := 1 / math.cos(cycle * 2 * 0.1) // delta default to 0.1. Acceptable
delta -- 0.05<d<0.5
        alpha := gamma - math.sqrt(gamma * gamma - 1)
        c0 := (1 + alpha) / 2
        b1 := -2 * beta
        b2 := 1
        a1 := beta * (1 + alpha)
        a2 := -alpha
        a2
    if _type == 'SMA'
        c1 := 1 / _length
        b0 := 1 / _length
        a1 := 1
        a1
    if _type == 'EMA'
        alpha := 2 / (_length + 1)
        b0 := alpha
        a1 := 1 - alpha
        a1
    if _type == 'RMA'
        alpha := 1 / _length
        b0 := alpha
        a1 := 1 - alpha
        a1
    _Input = _src
    _Output = 0.0
    _Output := c0 * (b0 * _Input + b1 * nz(_Input[1]) + b2 * nz(_Input[2])) + a1 *
nz(_Output[1]) + a2 * nz(_Output[2]) - c1 * nz(_Input[_length])
    _Output
//-----------------------
// SuperSmoother Function
//-----------------------
supersmoother(_src, _length) =>
    s_a1 = math.exp(-math.sqrt(2) * pi / _length)
    s_b1 = 2 * s_a1 * math.cos(math.sqrt(2) * pi / _length)
    s_c3 = -math.pow(s_a1, 2)
    s_c2 = s_b1
    s_c1 = 1 - s_c2 - s_c3
    ss = 0.0
    ss := s_c1 * _src + s_c2 * nz(ss[1], _src[1]) + s_c3 * nz(ss[2], _src[2])
    ss
//-----------------------
// Auto TimeFrame Function
//-----------------------
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
    _resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60.
* 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _resInMinutes
get_tf(_lvl) =>
    y = f_resInMinutes()
    z = timeframe.period
    if mtf_typ == 'Auto'
         if y < 1
              z := _lvl == 1 ? '1' : _lvl == 2 ? '5' : z
              z
         else if y <= 3
              z := _lvl == 1 ? '5' : _lvl == 2 ? '15' : z
              z
         else if y <= 10
              z := _lvl == 1 ? '15' : _lvl == 2 ? '60' : z
              z
         else if y <= 30
              z := _lvl == 1 ? '60' : _lvl == 2 ? '240' : z
              z
         else if y <= 120
              z := _lvl == 1 ? '240' : _lvl == 2 ? 'D' : z
              z
         else if y <= 240
              z := _lvl == 1 ? 'D' : _lvl == 2 ? 'W' : z
              z
         else if y <= 1440
              z := _lvl == 1 ? 'W' : _lvl == 2 ? 'M' : z
              z
         else if y <= 10080
              z := _lvl == 1 ? 'M' : z
              z
         else
              z := z
              z
    else
         z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
         z
//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
    v_condition = 0
    v_meanline = source
    v_meanrange = supersmoother(ta.tr, length)
    if type != 'SuperSmoother'
        v_meanline := SAK_smoothing(type, source, length)
        v_meanline
//-----------------------
// MTF Analysis
//-----------------------
get_stat(_cond) =>
    ret = 'Price at Mean Line\n'
    if _cond == 1
        ret := 'Overbought (Weak)\n'
        ret
    else if _cond == 2
        ret := 'Overbought\n'
        ret
    else if _cond == 3
        ret := 'Overbought (Strong)\n'
        ret
    else if _cond == 4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == 5
        ret := 'Price Above Mean\n'
        ret
    else if _cond == -1
        ret := 'Oversold (Weak)\n'
        ret
    else if _cond == -2
        ret := 'Oversold\n'
        ret
    else if _cond == -3
        ret := 'Oversold (Strong)\n'
        ret
    else if _cond == -4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == -5
        ret := 'Price Below Mean\n'
        ret
    ret
//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
    y = str.tostring(x, '0.00000')
    if x > 10
        y := str.tostring(x, '0.000')
        y
    if x > 1000
        y := str.tostring(x, '0.00')
        y
    y
//
***********************************************************************************
*************************
// Calculate Channel
//
***********************************************************************************
*************************
var tf_0 = timeframe.period
var tf_1 = get_tf(1)
var tf_2 = get_tf(2)
textstylist = table.new(textVPosition + '_' + textHPosition, 1, 3)
[meanline, meanrange, upband1, loband1, upband2, loband2, condition] = get_mrc()
[mtf1_meanline, mtf1_meanrange, mtf1_upband1, mtf1_loband1, mtf1_upband2,
mtf1_loband2, mtf1_condition] = request.security(syminfo.tickerid, tf_1, get_mrc())
[mtf2_meanline, mtf2_meanrange, mtf2_upband1, mtf2_loband1, mtf2_upband2,
mtf2_loband2, mtf2_condition] = request.security(syminfo.tickerid, tf_2, get_mrc())
//
***********************************************************************************
*************************
// Drawing Start {
//
***********************************************************************************
*************************
float p_meanline = drawchannel ? meanline : na
float p_upband1 = drawchannel ? upband1 : na
float p_loband1 = drawchannel ? loband1 : na
float p_upband2 = drawchannel ? upband2 : na
float p_loband2 = drawchannel ? loband2 : na
//-----------------------
// Draw zone
//-----------------------
//---
var color1 = #FF0000
var color2 = #FF4200
var color3 = #FF5D00
var color4 = #FF7400
var color5 = #FF9700
var color6 = #FFAE00
var color7 = #FFC500
var color8 = #FFCD00
//---
float upband2_1 = drawchannel         and displayzone ? upband2 + meanrange * gradsize *
4 : na
float loband2_1 = drawchannel         and displayzone ? loband2 - meanrange * gradsize *
4 : na
float upband2_2 = drawchannel         and displayzone ? upband2 + meanrange * gradsize *
3 : na
float loband2_2 = drawchannel         and displayzone ? loband2 - meanrange * gradsize *
3 : na
float upband2_3 = drawchannel         and displayzone ? upband2 + meanrange * gradsize *
2 : na
float loband2_3 = drawchannel         and displayzone ? loband2 - meanrange * gradsize *
2 : na
float upband2_4 = drawchannel         and displayzone ? upband2 + meanrange * gradsize *
1 : na
float loband2_4 = drawchannel         and displayzone ? loband2 - meanrange * gradsize *
1 : na
float upband2_5 = drawchannel         and displayzone ? upband2 + meanrange * gradsize *
0 : na
float loband2_5 = drawchannel         and displayzone ? loband2 - meanrange * gradsize *
0 : na
float upband2_6 = drawchannel         and displayzone ? upband2 + meanrange * gradsize * -1
: na
float loband2_6 = drawchannel         and displayzone ? loband2 - meanrange * gradsize * -1
: na
float upband2_7 = drawchannel         and displayzone ? upband2 + meanrange * gradsize * -2
: na
float loband2_7 = drawchannel         and displayzone ? loband2 - meanrange * gradsize * -2
: na
float upband2_8 = drawchannel         and displayzone ? upband2 + meanrange * gradsize * -3
: na
float loband2_8 = drawchannel         and displayzone ? loband2 - meanrange * gradsize * -3
: na
float upband2_9 = drawchannel         and displayzone ? upband2 + meanrange * gradsize * -4
: na
float loband2_9 = drawchannel         and displayzone ? loband2 - meanrange * gradsize * -4
: na
kijun_len    = 365
kijun_mult   = 7
spanB_len    = 365
spanB_mult   = 15
offset      = 2
//------------------------------------------------------------------------------
avg(src,length,mult)=>
    atr = ta.atr(length)*mult
    up = hl2 + atr
    dn = hl2 - atr
    upper = 0.,lower = 0.
    upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
    lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
    os = 0,max = 0.,min = 0.
    os := src > upper ? 1 : src < lower ? 0 : os[1]
    spt = os == 1 ? lower : upper
    max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ?
math.max(src,max[1]) : spt
    min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ?
math.min(src,min[1]) : spt
    math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = #2156f300
kijun_css = #ff5e0000
chikou_css = #7b1fa2
plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none, editable =
false)
//box.delete(boxes.shift())
// ==== Overview ====
// ==================
// Fundamental Assumptions:
// (1) There exists a probability density function that describes the relative
likelihood for a price to visit a given value.
// (2) The probability density function for price is a function of time.
// (3) The probability density function can approximate a Gaussian distribution
(shown below).
//                                                                              ___
//                                    .::~!:..                                   |
// :ΞΞΞΞ~!ΞΞΞ!. |
// .ΞJΞΞΞΞ~!ΞΞΞ?J^ |
// :J?ΞΞΞΞΞ~!ΞΞΞΞΞJ^ |
// :J?ΞΞΞΞΞΞ~!ΞΞΞΞΞΞ??. |
// :JΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞ?J^ |
//                            :JΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞ?J^
[ PRICE ]
//                          .:~ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!!~                          |
// :?~^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^Ξ! |
// ~:^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^!Ξ. |
// .Ξ!^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^~Ξ~ |
// .~Ξ~^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^!Ξ: |
// .~Ξ~^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^~!!^. |
// ....::^^!~~^^^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^^^^~!^^::...... |
// ..:::^^^^^^^::::::::::::::ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!::::::::::::^^^^^^^^:::.. |
//
// -------------------------------- [ TIME ] -------------------------------|
// How to use this indicator:
// - The basic usage of WT3D is similar to how one would use the traditional WT
indicator.
// - Divergences can be spotted by finding "trigger waves", which are small waves
that immediately follow a larger wave. These can also be thought of as Lower-Highs
and Higher-Lows in the oscillator.
// - Instead of the SMA-cross in the original WT, the primary mechanism for
identifying potential pivots are the crossovers of the fast/normal speed
oscillators, denoted by the small red/green circles.
// - The larger red/green circles represent points where there could be a potential
trigger wave for a Divergence. Settings related to Divergence detection can be
configured in the "Divergence" section.
// - For overbought/oversold conditions, the 0.5 and -0.5 levels are convenient
since the normal-speed oscillator will only exceed this level ~25% of the time.
// - For less experienced users, focusing on the three oscillators is recommended
since they give critical information from multiple timeframes that can help to
identify trends and spot potential divergences.
// - For more experienced users, this indicator also has many other valuable
features, such as Center of Gravity (CoG) smoothing, Kernel Estimate Crossovers, a
mirrored mode for cycle analysis, and more.
// - Note: Additional resources for learning/using the more advanced features of
this indicator are a work in progress, but in the meantime, I am happy to answer
any questions.
// ================
// ==== Inputs ====
// ================
// Signal Settings
src = close
useMirror = false
useEma = false
emaLength = 3
useCog = false
cogLength = 6
oscillatorLookback =20
quadraticMeanLength = 50
src := useEma ? ta.ema(src, emaLength) : src
src := useCog ? ta.cog(src, cogLength) : src
speedToEmphasize = 'Normal'
emphasisWidth = 2
useKernelMA = false
useKernelEmphasis = false
// Oscillator Settings
offset := 0
showOsc = true
showOsc := showOsc
float f_length = 0.75
float f_smoothing = 0.45
float n_length = 1.0
float n_smoothing = 1.0
float s_length = 1.75
float s_smoothing = 2.5
// Divergence Detection
divThreshold = 30
sizePercent = 40
// Overbought/Oversold Zones (Reversal Zones)
showObOs = false
invertObOsColors = false
// The defaults are colors that Google uses for its Data Science libraries (e.g.
TensorFlow). They are considered to be colorblind-safe.
var color fastBullishColor = color.black
var color normalBullishColor = color.black
var color slowBullishColor = color.black
var color fastBearishColor = color.black
var color normalBearishColor = color.black
var color slowBearishColor =color.black
var color c_bullish = color.black
var color c_bearish = color.black
areaFastTrans =   areaBackgroundTrans
lineFastTrans =   lineBackgroundTrans
areaNormalTrans   = areaBackgroundTrans
lineNormalTrans   = lineBackgroundTrans
areaSlowTrans =   areaForegroundTrans
lineSlowTrans =   lineForegroundTrans
switch speedToEmphasize
    "Slow" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaForegroundTrans
        lineSlowTrans := lineForegroundTrans
    "Normal" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaForegroundTrans
        lineNormalTrans := lineForegroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "Fast" =>
        areaFastTrans := areaForegroundTrans
        lineFastTrans := lineForegroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "None" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
// =================================
// ==== Color Helper Functions =====
// =================================
// ================================
// ==== Main Helper Functions =====
// ================================
// =================================
// ==== Oscillator Calculations ====
// =================================
// =====================================
// ==== Color Gradient Calculations ====
// =====================================
// =========================================
// ==== Plot Parameters and Logic Gates ====
// =========================================
// Speed   Booleans
isSlow =   speedToEmphasize == "Slow"
isNormal   = speedToEmphasize == "Normal"
isFast =   speedToEmphasize == "Fast"
// Series Colors
seriesSlowColor = showOsc or isSlow ? color.new(slowLineGradientFromSource,
lineSlowTrans) : na
seriesNormalColor = showOsc or isNormal ? color.new(normalLineGradientFromSource,
lineNormalTrans) : na
seriesFastColor = showOsc or isFast   ? color.new(fastLineGradientFromSource,
lineFastTrans) : na
seriesSlowMirrorColor = useMirror ?   seriesSlowColor : na
seriesNormalMirrorColor = useMirror   ? seriesNormalColor : na
seriesFastMirrorColor = useMirror ?   seriesFastColor : na
colorAreaEmphasis = switch
    isFast => fastAreaGradientFromSource
    isNormal => normalAreaGradientFromSource
    isSlow => slowAreaGradientFromSource
    => na
// Crossover Signals
bearishCross = ta.crossunder(seriesFast, seriesNormal) and seriesNormal > 0
bullishCross = ta.crossover(seriesFast, seriesNormal) and seriesNormal < 0
slowBearishMedianCross = ta.crossunder(seriesSlow, 0)
slowBullishMedianCross = ta.crossover(seriesSlow, 0)
normalBearishMedianCross = ta.crossunder(seriesNormal, 0)
normalBullishMedianCross = ta.crossover(seriesNormal, 0)
fastBearishMedianCross = ta.crossunder(seriesFast, 0)
fastBullishMedianCross = ta.crossover(seriesFast, 0)
// ===========================
// ==== Kernel Estimators ====
// ===========================
// Gaussian Kernel with a lookback of 3 bars, starting on bar 2 of the chart (tight
fit)
yhat1 = kernels.gaussian(seriesEmphasis, 3, 2)
// Trend Assessment based on the relative position of the medium fit kernel to the
slow oscillator
isBearishKernelTrend = yhat0 < seriesSlow
isBullishKernelTrend = yhat0 > seriesSlow
// Divergence Signals
isBearishDivZone = ta.barssince(bearishCross[1]) < divThreshold
isBullishDivZone = ta.barssince(bullishCross[1]) < divThreshold
// Crossover Detection
isBearishTriggerWave = isSmallerBearishCross and isBearishDivZone and
isBearishKernelTrend
isBullishTriggerWave = isSmallerBullishCross and isBullishDivZone and
isBullishKernelTrend
// =======================
// ==== Plots & Fills ====
var position = 0
length := atrLength
minMult = math.max(sensitivity-4, 1)
maxMult = math.min(sensitivity, 26)
float step    = .5
//Trigger error
if minMult > maxMult
    runtime.error('Minimum factor is greater than maximum factor in the range')
float perfAlpha = 10
fromCluster = 'Best'
//Optimization
maxIter = 250
maxData = 2500
//Style
bearCss = color.red
bullCss = color.teal
showGradient = true
//Dashboard
showDash = true
//dashboardLocation = input.string('Top Right', 'Location', options = ['Top
Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = 'Small'
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
    float upper = hl2
    float lower = hl2
    float output
    float perf = 0
    float factor
    int trend = 0
type vector
    array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
atr = ta.atr(length)
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
factor_array = array.new<float>(0)
data = array.new<float>(0)
//Intialize clusters
var array<vector> factors_clusters = na
var array<vector> perfclusters = na
            idx = dist.indexof(dist.min())
            perfclusters.get(idx).out.push(value)
            factors_clusters.get(idx).out.push(factor_array.get(i))
            i += 1
        //Update centroids
        new_centroids = array.new<float>(0)
        for cluster_ in perfclusters
            new_centroids.push(cluster_.out.avg())
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Signals and trailing stop
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float target_factor = na
var float perf_idx = na
var float perf_ama = na
if not na(perfclusters)
    //Get average factors within target cluster
    target_factor := nz(factors_clusters.get(from).out.avg(), target_factor)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------{
css = os ? bullCss : bearCss
//Candle coloring
//barcolor(showGradient ? color.from_gradient(perf_idx, 0, 1, color.new(css, 80),
css) : na)
//Signals
if showSignals
    if os > os[1] and (signalPresets != "Smart Trail [Filter]" or
smartTrailDirection == 'long') and (signalPresets != "Trend Tracer [Filter]" or
trendTracerDirection==#02ff65) and (signalPresets != "Trend Strength [Filter]" or
trendStrengthMetric >= 25) and (signalPresets != "Trend Catcher [Filter]" or
newTrendCatcherColor == #02ff65) and (signalPresets != "Neo Cloud [Filter]" or
int(lastNeo) >= last5Neo)
        int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :
int(perf_idx*10) < 5 ? 3 : 4
        label.new(n, low-ta.atr(30)/2, signalClassifier ?
str.tostring(signalStrength) : ema50 > ema200 ? "▲+" : "▲"
          , color = bullCss
          , style = label.style_label_up
          , textcolor = color.white
              , yloc=yloc.belowbar
          , size = size.small)
        position := 1
// =======================
// Signal Plots
//plot(position == 1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_cross, linewidth=2, color=c_bearish, offset=-1)
//plot(position == -1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_circles, linewidth=2, color=c_bearish, offset=-1)
//plot(position == 1 and isBearishTriggerWave ? high+5 : na, title="Bearish Trigger
Cross", style=plot.style_cross, linewidth=3, color=c_bearish, offset=-1)
//plot(position == -1 and isBearishTriggerWave ? high+5 : na, title="Bearish
Trigger Cross", style=plot.style_circles, linewidth=3, color=c_bearish, offset=-1)
//plotchar(bearishCross and position == 1, "Long", "✖", location.abovebar, color =
#4774f5, size = size.tiny, editable = false)
//plotchar(bearishCross and position == -1, "Long", "▼", location.abovebar, color =
c_bearish, size = size.tiny)
plotchar(isBearishTriggerWave and position == 1, "Long", "✖", location.abovebar,
color=#4774f5, size = size.tiny, editable = false)
//plotchar(isBearishTriggerWave and position == -1, "Long", "▼", location.abovebar,
color=c_bearish, size = size.small)
// Shit
atrMultiplier = input(2, title="ATR Multiplier")
boxHeightInAtr = atrMultiplier * ta.atr(10)
// Box TP 1
if (takeProfitBoxes == 'On')
    tp1box = box.new(left=bar_index + 1, top=close + midb, right=bar_index + 18,
bottom=close + lowb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 55), text="TP/SL 1 :   "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    bottom_tp1 = box.get_bottom(tp1box)
    box.delete(tp1box[1])
    // Box TP 2
    tp2box = box.new(left=bar_index + 1, top=close+highb, right=bar_index + 18,
bottom=close+midb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 65), text="TP/SL 2 :    "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    top_tp2 = box.get_top(tp2box)
    box.delete(tp2box[1])
    // Empty Box
    newBox = box.new(left=bar_index + 18, top=top_tp2, right=bar_index + 200,
bottom=bottom_tp1, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 50), text=" ",
text_size=size.normal, text_color=color.new(#3666f5, 0))
    box.delete(newBox[1])
    // SL Box
    slBox = box.new(left=bar_index + 3, top=close-lowb, right=bar_index + 18,
bottom=close-midb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 66), text="TP/SL 2 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl = box.get_top(slBox)
    box.delete(slBox[1])
    // SL2 Box
    sl2Box = box.new(left=bar_index + 3, top=close-midb, right=bar_index + 18,
bottom=close-highb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 65), text="TP/SL 1 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl2 = box.get_bottom(sl2Box)
    box.delete(sl2Box[1])
    // Empty Box SL
    Slboxem = box.new(left=bar_index + 18, top=bottom_sl, right=bar_index + 200,
bottom=bottom_sl2, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 50), text=" ",
text_size=size.normal, text_color=color.new(color.red, 0))
    box.delete(Slboxem[1])
//
    // Line tp Bottom
    var line tpb = na
    isLastBar = barstate.islast
    if (isLastBar)
        tpb := line.new(na, bottom_tp1, na, bottom_tp1, color=color.new(#3666f5,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        tp2Line := line.new(na, top_tp2, na, top_tp2, color=color.new(#3666f5, 0),
width=2, style=line.style_dashed)
    // Line SL
    var line slLine = na
    if (isLastBar)
        slLine := line.new(na, bottom_sl, na, bottom_sl, color=color.new(color.red,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        sl2Line := line.new(na, bottom_sl2, na, bottom_sl2,
color=color.new(color.red, 0), width=2, style=line.style_dashed)
###################################################################################
###################################################################################
##################################################
//text inputs
textVPosition = 'middle'
textHPosition = 'center'
symVPosition = 'top'
symHPosition = 'left'
width = 0
height = 0
c_title = #b2b5be80
s_title = 'large'
a_title = 'center'
c_subtitle = #b2b5be80
s_subtitle = 'normal'
a_subtitle = 'center'
c_bg = color.new(color.blue, 100)
//Import libraries
//Import libraries
import ayvaliktrading/EyopsTelegram/1 as LAF
import ayvaliktrading/JoinUsEyopsTelegram/1 as kernels
// Advanced Settings
groupAdvanced = "ADVANCED SETTINGS"
takeProfitBoxes = input.string("Off", "TP/SL Points", options=["Off","On"], inline
= "2", tooltip = "Shows Take Profit and Stop Loss areas",group = groupAdvanced)
takeProfitStopLossDistance = input.int(5,"", minval = 1, maxval = 10, inline = "2",
group=groupAdvanced)
autopilotMode = input.string("Off", "Autopilot Sensivity",["Off","Short-Term",
"Mid-Term", "Long-Term"],tooltip = "Sets automatic settings for signals and
improves their quality" ,inline = "3", group = groupAdvanced)
dashboardLocation = input.string("Bottom Right","Dashboard Location", ["Top
Right","Bottom Right","Bottom Left"], inline = "4",tooltip = "Changes dashboard
positions" ,group = groupAdvanced)
dashboardSize = input.string("Normal","Dashboard Size",
["Tiny","Small","Normal","Large"], inline = "5",tooltip = "Changes the size of the
dashboard" ,group = groupAdvanced)
// # ============================[BUY/SELL SIGNALS]============================ #
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------}
// # ============================[SESSIONS]============================ #
show_sesa = true
sesa_txt = 'New York'
sesa_ses = '1300-2200'
sesa_css = #ff5d00
sesa_range = true
sesa_tl = false
sesa_avg = false
sesa_vwap = false
sesa_maxmin = false
//Session B
show_sesb = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
sesb_css = #2157f3
sesb_range = true
sesb_tl = false
sesb_avg = false
sesb_vwap = false
sesb_maxmin = false
//Timezones
tz_incr = 0
use_exchange = false
//Ranges Options
bg_transp = 90
show_outline = true
show_txt = true
//Dashboard
show_ses_div = false
show_day_div = false
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
sma
    var   float   y1 = na
    var   float   y2 = na
    var   float   stdev = na
    var   float   r2    = na
          y1 := 4 * sma - 3 * wma
          y2 := 3 * wma - 2 * sma
//Session Vwap
get_vwap(session) =>
    var float num = na
    var float den = na
    if session > session[1] and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center'
        num := close * volume
        den := volume
[num, den]
//Set line
set_line(session, y1, y2, session_css)=>
    var line tl = na
          box.set_top(bx, max)
          box.set_rightbottom(bx, n, min)
          if show_txt
              label.set_xy(lbl, int(math.avg(t, time)), max)
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//Ranges
if show_sesa and sesa_range and textVPosition       == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title       == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle ==       'normal' and a_subtitle == 'center'
    [max, min] = get_range(is_sesa, sesa_txt,       sesa_css)
    max_sesa := max
    min_sesa := min
//Trendlines
//Mean
if show_sesa and sesa_avg and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center'
    avg = get_avg(is_sesa)
    set_line(is_sesa, avg, avg, sesa_css)
//VWAP
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot max/min
plot(showSessions and sesa_maxmin and textVPosition == 'middle' and textHPosition
== 'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
max_sesa : na, 'Session A Maximum', sesa_css, 1, plot.style_linebr, editable =
false)
plot(showSessions and sesa_maxmin and textVPosition == 'middle' and textHPosition
== 'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
min_sesa : na, 'Session A Minimum', sesa_css, 1, plot.style_linebr, editable =
false)
//Plot Divider A
plotshape(is_sesa and show_ses_div and show_sesa and showSessions, "·"
  , shape.square
  , location.bottom
  , na
  , text = "."
  , textcolor = sesa_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
//Plot Divider B
plotshape(is_sesb and show_ses_div and show_sesb and showSessions, "·"
  , shape.labelup
  , location.bottom
  , na
  , text = "."
  , textcolor = sesb_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
// # ============================[FUNCTIONS]============================ #
type bar
    float   o   =   open
    float   h   =   high
    float   l   =   low
    float   c   =   close
    float   v   =   volume
    int     i   =   bar_index
bar b = bar.new()
nzV = nz(b.v)
f_calcV() =>
    uV = 0.0
    dV = 0.0
      switch
          (b.c - b.l) > (b.h - b.c)   => uV := nzV
          (b.c - b.l) < (b.h - b.c)   => dV := -nzV
          b.c > b.o => uV := nzV
          b.c < b.o => dV := -nzV
          b.c > nz(b.c[1]) => uV :=   nzV
          b.c < nz(b.c[1]) => dV :=   -nzV
          nz(uV[1]) > 0 => uV := uV   + nzV
          nz(dV[1]) < 0 => dV := dV   - nzV
      [uV, dV]
// # ============================[CONSTANT VARIABLES]============================ #
sma4 = ta.sma(close, 4)
sma5 = ta.sma(close, 5)
sma9 = ta.sma(close, 9)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
bullishSignalColor = #59e08a
bearishSignalColor = #ff5959
dashboardRedText = #ee787d
dashboardGreenText = #42bda8
dashboardGreenBackground = #284444
dashboardRedBackground = #49343e
// # ============================[CANDLE COLORING]============================ #
macdFastLength = 12
macdSlowLength = 26
macdSignalLength = 9
// Yellow
yellowLow = #56328f
// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #56328f
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    redHigh := #ff0000
    redMidHigh := #c21637
    redMidLow := #c33252
    redLow := #8e215f
if (candleColorType == 'Contrarian Gradient')
    redHigh := #01d70c
    redMidHigh := #269444
    redMidLow :=#4f966c
    redLow := #425970
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    greenHigh := #ff0000
    greenMidHigh := #c21637
    greenMidLow := #c33252
    greenLow := #8e215f
// Default color
candleBody = yellowLow
if histX > 0
    if histX > histX[1] and histX[1] > 0 and textVPosition == 'middle' and
textHPosition == 'center' and c_title == #b2b5be80 and s_title == 'large' and
a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and
a_subtitle == 'center'
        candleBody := greenLow
if histX < 0
    if histX < histX[1] and histX[1] < 0 and textVPosition == 'middle' and
textHPosition == 'center' and c_title == #b2b5be80 and s_title == 'large' and
a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and
a_subtitle == 'center'
        candleBody := redLow
// Bullish trend
if MacdX > 0 and histX > 0
    candleBody := greenMidLow
    if histX > histX[1] and MacdX[1] > 0 and histX[1] > 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
        candleBody := greenMidHigh
        if histX > histX[2] and MacdX[2] > 0 and histX[2] > 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
            candleBody := greenHigh
// Bearish trend
if MacdX < 0 and histX < 0
    candleBody := redMidLow
    if histX < histX[1] and MacdX[1] < 0 and histX[1] < 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
        candleBody := redMidHigh
        if histX < histX[2] and MacdX[2] < 0 and histX[2] < 0 and textVPosition ==
'middle' and textHPosition == 'center' and c_title == #b2b5be80 and s_title ==
'large' and a_title == 'center' and c_subtitle == #b2b5be80 and s_subtitle ==
'normal' and a_subtitle == 'center'
            candleBody := redHigh
// # ============================[SMART TRAIL]============================ #
[smartTrailLine, fillerLine, smartTrailDirection] = LAF.getSmartTrail(10, 4, 8)
smartTrail1 = plot(smartTrail and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
smartTrailLine : na, "Smart Trail", style = plot.style_line, color =
smartTrailDirection== 'long' ? color.new(#2157f9, 0) : smartTrailDirection ==
'short' ? color.new(#ff1100, 0) : na, editable = false)
smartTrail2 = plot(smartTrail and textVPosition == 'middle' and textHPosition ==
'center' and c_title == #b2b5be80 and s_title == 'large' and a_title == 'center'
and c_subtitle == #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
fillerLine : na, "Fib 2", style = plot.style_line, transp = 100, editable = false)
fill(smartTrail1, smartTrail2, color = smartTrailDirection == 'long' ?
color.new(#2157f9, 80) : smartTrailDirection == 'short' ? color.new(#ff1100, 80) :
na, editable = false)
// # ============================[TREND CATCHER]============================ #
[trendCatcherLine, trendCatcherColor] = LAF.getTrendCatcher()
newTrendCatcherColor = trendCatcherColor == color.blue ? #02ff65 : #ff1100
plot(trendCatcher and textVPosition == 'middle' and textHPosition == 'center' and
c_title == #b2b5be80 and s_title == 'large' and a_title == 'center' and c_subtitle
== #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
trendCatcherLine : na, title='Trend Catcher', linewidth=2,
color=newTrendCatcherColor, editable = false)
// # ============================[NEO CLOUD]============================ #
// # ============================[REVERSAL ZONES]============================ #
// # ============================[TREND TRACER]============================ #
[trendTracerLine, trendTracerDirection] = LAF.getTrendTracer()
plot(trendTracer and textVPosition == 'middle' and textHPosition == 'center' and
c_title == #b2b5be80 and s_title == 'large' and a_title == 'center' and c_subtitle
== #b2b5be80 and s_subtitle == 'normal' and a_subtitle == 'center' ?
trendTracerLine : na, title='Trend Tracer', linewidth=2, style=plot.style_cross,
color = trendTracerDirection, editable = false)
// # ============================[DASHBOARD
COMPONENTS|]============================ #
totalVolume = uV + math.abs(dV)
//volumecolor = totalVolume >= 50 ? bullish : bearish
volumeCellColor = dashboardRedBackground
volumeTextColor = totalVolume >= 50 ? dashboardGreenText : dashboardRedText
if (totalVolume >= 50)
     totalVolume := totalVolume*2
     volumeCellColor := dashboardGreenBackground
else
     totalVolume := totalVolume*-2
volumeSentiment = totalVolume
tb = table.new(table_position, 7, 7
  , bgcolor = #1e222d
  , border_color = #373a46
  , border_width = 1
  , frame_color = #373a46
  , frame_width = 1)
if showDashboard
    if barstate.islast
        tb.cell(0, 2, autopilotMode == 'Off' ? "✈️
                                                 Optimal Sensivity" : " Autopilot
Enabled", text_color = color.white, text_size = table_size, text_halign =
text.align_left)
        tb.cell(0, 3, str.tostring(trendIndication) + "Trend Strength", text_color
= color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 4, volatilityEmoji+ " Lux Volatility", text_color = color.white,
text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 5, "🔃 Squeeze", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
        tb.cell(0, 6, "💧 Volume Sentiment", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
//
***********************************************************************************
*************************
// REV ZONES
//
***********************************************************************************
*************************
indiSet = false
source = hlc3
type = 'SuperSmoother'
length = 100
innermult = 1.0
outermult = 2.415
ChartSet = false
drawchannel = true
displayzone = true
zonetransp = 60
displayline = true
MTFSet = false
enable_mtf = true
mtf_disp_typ = 'On Hover'
mtf_typ = 'Auto'
mtf_lvl1 = 'D'
mtf_lvl2 = 'W'
//
***********************************************************************************
*************************
// Functions Start {
//
***********************************************************************************
*************************
var pi = 2 * math.asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp
//-----------------------
// Ehler SwissArmyKnife Function
//-----------------------
SAK_smoothing(_type, _src, _length) =>
    c0 = 1.0
    c1 = 0.0
    b0 = 1.0
    b1 = 0.0
    b2 = 0.0
    a1 = 0.0
    a2 = 0.0
    alpha = 0.0
    beta = 0.0
    gamma = 0.0
    cycle = 2 * pi / _length
    _Input = _src
    _Output = 0.0
    _Output := c0 * (b0 * _Input + b1 * nz(_Input[1]) + b2 * nz(_Input[2])) + a1 *
nz(_Output[1]) + a2 * nz(_Output[2]) - c1 * nz(_Input[_length])
    _Output
//-----------------------
// SuperSmoother Function
//-----------------------
supersmoother(_src, _length) =>
    s_a1 = math.exp(-math.sqrt(2) * pi / _length)
    s_b1 = 2 * s_a1 * math.cos(math.sqrt(2) * pi / _length)
    s_c3 = -math.pow(s_a1, 2)
    s_c2 = s_b1
    s_c1 = 1 - s_c2 - s_c3
    ss = 0.0
    ss := s_c1 * _src + s_c2 * nz(ss[1], _src[1]) + s_c3 * nz(ss[2], _src[2])
    ss
//-----------------------
// Auto TimeFrame Function
//-----------------------
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
    _resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60.
* 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _resInMinutes
get_tf(_lvl) =>
    y = f_resInMinutes()
    z = timeframe.period
    if mtf_typ == 'Auto'
        if y < 1
            z := _lvl == 1   ? '1' : _lvl == 2 ? '5' : z
            z
        else if y <= 3
            z := _lvl == 1   ? '5' : _lvl == 2 ? '15' : z
            z
        else if y <= 10
            z := _lvl == 1   ? '15' : _lvl == 2 ? '60' : z
            z
        else if y <= 30
            z := _lvl == 1   ? '60' : _lvl == 2 ? '240' : z
            z
        else if y <= 120
            z := _lvl == 1   ? '240' : _lvl == 2 ? 'D' : z
            z
        else if y <= 240
            z := _lvl == 1   ? 'D' : _lvl == 2 ? 'W' : z
            z
        else if y <= 1440
             z := _lvl == 1 ? 'W' : _lvl == 2 ? 'M' : z
             z
        else if y <= 10080
             z := _lvl == 1 ? 'M' : z
             z
        else
             z := z
             z
    else
        z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
        z
//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
    v_condition = 0
    v_meanline = source
    v_meanrange = supersmoother(ta.tr, length)
    if type != 'SuperSmoother'
        v_meanline := SAK_smoothing(type, source, length)
        v_meanline
//-----------------------
// MTF Analysis
//-----------------------
get_stat(_cond) =>
    ret = 'Price at Mean Line\n'
    if _cond == 1
        ret := 'Overbought (Weak)\n'
        ret
    else if _cond == 2
        ret := 'Overbought\n'
        ret
    else if _cond == 3
        ret := 'Overbought (Strong)\n'
        ret
    else if _cond == 4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == 5
        ret := 'Price Above Mean\n'
        ret
    else if _cond == -1
        ret := 'Oversold (Weak)\n'
        ret
    else if _cond == -2
        ret := 'Oversold\n'
        ret
    else if _cond == -3
        ret := 'Oversold (Strong)\n'
        ret
    else if _cond == -4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == -5
        ret := 'Price Below Mean\n'
        ret
    ret
//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
    y = str.tostring(x, '0.00000')
    if x > 10
        y := str.tostring(x, '0.000')
        y
    if x > 1000
        y := str.tostring(x, '0.00')
        y
    y
//
***********************************************************************************
*************************
// Calculate Channel
//
***********************************************************************************
*************************
var tf_0 = timeframe.period
var tf_1 = get_tf(1)
var tf_2 = get_tf(2)
textstylist = table.new(textVPosition + '_' + textHPosition, 1, 3)
[meanline, meanrange, upband1, loband1, upband2, loband2, condition] = get_mrc()
[mtf1_meanline, mtf1_meanrange, mtf1_upband1, mtf1_loband1, mtf1_upband2,
mtf1_loband2, mtf1_condition] = request.security(syminfo.tickerid, tf_1, get_mrc())
[mtf2_meanline, mtf2_meanrange, mtf2_upband1, mtf2_loband1, mtf2_upband2,
mtf2_loband2, mtf2_condition] = request.security(syminfo.tickerid, tf_2, get_mrc())
//
***********************************************************************************
*************************
// Drawing Start {
//
***********************************************************************************
*************************
float p_meanline = drawchannel ? meanline : na
float p_upband1 = drawchannel ? upband1 : na
float p_loband1 = drawchannel ? loband1 : na
float p_upband2 = drawchannel ? upband2 : na
float p_loband2 = drawchannel ? loband2 : na
//-----------------------
// Draw zone
//-----------------------
//---
var color1 = #FF0000
var color2 = #FF4200
var color3 = #FF5D00
var color4 = #FF7400
var color5 = #FF9700
var color6 = #FFAE00
var color7 = #FFC500
var color8 = #FFCD00
//---
float upband2_1 = drawchannel   and displayzone ? upband2 + meanrange * gradsize *
4 : na
float loband2_1 = drawchannel   and displayzone ? loband2 - meanrange * gradsize *
4 : na
float upband2_2 = drawchannel   and displayzone ? upband2 + meanrange * gradsize *
3 : na
float loband2_2 = drawchannel   and displayzone ? loband2 - meanrange * gradsize *
3 : na
float upband2_3 = drawchannel   and displayzone ? upband2 + meanrange * gradsize *
2 : na
float loband2_3 = drawchannel   and displayzone ? loband2 - meanrange * gradsize *
2 : na
float upband2_4 = drawchannel   and displayzone ? upband2 + meanrange * gradsize *
1 : na
float loband2_4 = drawchannel   and displayzone ? loband2 - meanrange * gradsize *
1 : na
float upband2_5 = drawchannel   and displayzone ? upband2 + meanrange * gradsize *
0 : na
float loband2_5 = drawchannel   and displayzone ? loband2 - meanrange * gradsize *
0 : na
float upband2_6 = drawchannel   and displayzone ? upband2 + meanrange * gradsize * -1
: na
float loband2_6 = drawchannel   and displayzone ? loband2 - meanrange * gradsize * -1
: na
float upband2_7 = drawchannel   and displayzone ? upband2 + meanrange * gradsize * -2
: na
float loband2_7 = drawchannel   and displayzone ? loband2 - meanrange * gradsize * -2
: na
float upband2_8 = drawchannel   and displayzone ? upband2 + meanrange * gradsize * -3
: na
float loband2_8 = drawchannel   and displayzone ? loband2 - meanrange * gradsize * -3
: na
float upband2_9 = drawchannel   and displayzone ? upband2 + meanrange * gradsize * -4
: na
float loband2_9 = drawchannel   and displayzone ? loband2 - meanrange * gradsize * -4
: na
kijun_len     = 365
kijun_mult    = 7
spanB_len     = 365
spanB_mult    = 15
offset      = 2
//------------------------------------------------------------------------------
avg(src,length,mult)=>
    atr = ta.atr(length)*mult
    up = hl2 + atr
    dn = hl2 - atr
    upper = 0.,lower = 0.
    upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
    lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
    os = 0,max = 0.,min = 0.
    os := src > upper ? 1 : src < lower ? 0 : os[1]
    spt = os == 1 ? lower : upper
    max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ?
math.max(src,max[1]) : spt
    min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ?
math.min(src,min[1]) : spt
    math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = #2156f300
kijun_css = #ff5e0000
cloud_a = color.new(#006989, 47)
cloud_b = color.new(#ff5252, 66)
chikou_css = #7b1fa2
plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none, editable =
false)
//box.delete(boxes.shift())
// Fundamental Assumptions:
// (1) There exists a probability density function that describes the relative
likelihood for a price to visit a given value.
// (2) The probability density function for price is a function of time.
// (3) The probability density function can approximate a Gaussian distribution
(shown below).
//                                                                            ___
//                                    .::~!:..                                 |
// :ΞΞΞΞ~!ΞΞΞ!. |
// .ΞJΞΞΞΞ~!ΞΞΞ?J^ |
// :J?ΞΞΞΞΞ~!ΞΞΞΞΞJ^ |
// :J?ΞΞΞΞΞΞ~!ΞΞΞΞΞΞ??. |
// :JΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞ?J^ |
//                            :JΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞ?J^
[ PRICE ]
//                        .:~ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!!~                          |
//                         :?~^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^Ξ!                        |
// ~:^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^!Ξ. |
// .Ξ!^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^~Ξ~ |
// .~Ξ~^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^!Ξ: |
// .~Ξ~^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^~!!^. |
// ....::^^!~~^^^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^^^^~!^^::...... |
// ..:::^^^^^^^::::::::::::::ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!::::::::::::^^^^^^^^:::.. |
//
// -------------------------------- [ TIME ] -------------------------------|
// ================
// ==== Inputs ====
// ================
// Signal Settings
src = close
useMirror = false
useEma = false
emaLength = 3
useCog = false
cogLength = 6
oscillatorLookback =20
quadraticMeanLength = 50
src := useEma ? ta.ema(src, emaLength) : src
src := useCog ? ta.cog(src, cogLength) : src
speedToEmphasize = 'Normal'
emphasisWidth = 2
useKernelMA = false
useKernelEmphasis = false
// Oscillator Settings
offset := 0
showOsc = true
showOsc := showOsc
float f_length = 0.75
float f_smoothing = 0.45
float n_length = 1.0
float n_smoothing = 1.0
float s_length = 1.75
float s_smoothing = 2.5
// Divergence Detection
divThreshold = 30
sizePercent = 40
// The defaults are colors that Google uses for its Data Science libraries (e.g.
TensorFlow). They are considered to be colorblind-safe.
var color fastBullishColor = color.black
var color normalBullishColor = color.black
var color slowBullishColor = color.black
var color fastBearishColor = color.black
var color normalBearishColor = color.black
var color slowBearishColor =color.black
var color c_bullish = color.black
var color c_bearish = color.black
areaFastTrans =   areaBackgroundTrans
lineFastTrans =   lineBackgroundTrans
areaNormalTrans   = areaBackgroundTrans
lineNormalTrans   = lineBackgroundTrans
areaSlowTrans =   areaForegroundTrans
lineSlowTrans =   lineForegroundTrans
switch speedToEmphasize
    "Slow" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaForegroundTrans
        lineSlowTrans := lineForegroundTrans
    "Normal" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaForegroundTrans
        lineNormalTrans := lineForegroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "Fast" =>
        areaFastTrans := areaForegroundTrans
        lineFastTrans := lineForegroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "None" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
// =================================
// ==== Color Helper Functions =====
// =================================
// ================================
// ==== Main Helper Functions =====
// ================================
// =================================
// ==== Oscillator Calculations ====
// =================================
// =====================================
// ==== Color Gradient Calculations ====
// =====================================
// =========================================
// ==== Plot Parameters and Logic Gates ====
// =========================================
// Speed   Booleans
isSlow =   speedToEmphasize == "Slow"
isNormal   = speedToEmphasize == "Normal"
isFast =   speedToEmphasize == "Fast"
// Series Colors
seriesSlowColor = showOsc or isSlow ? color.new(slowLineGradientFromSource,
lineSlowTrans) : na
seriesNormalColor = showOsc or isNormal ? color.new(normalLineGradientFromSource,
lineNormalTrans) : na
seriesFastColor = showOsc or isFast ? color.new(fastLineGradientFromSource,
lineFastTrans) : na
seriesSlowMirrorColor = useMirror ? seriesSlowColor : na
seriesNormalMirrorColor = useMirror ? seriesNormalColor : na
seriesFastMirrorColor = useMirror ? seriesFastColor : na
colorAreaEmphasis = switch
    isFast => fastAreaGradientFromSource
    isNormal => normalAreaGradientFromSource
    isSlow => slowAreaGradientFromSource
    => na
// Crossover Signals
bearishCross = ta.crossunder(seriesFast, seriesNormal) and seriesNormal > 0
bullishCross = ta.crossover(seriesFast, seriesNormal) and seriesNormal < 0
slowBearishMedianCross = ta.crossunder(seriesSlow, 0)
slowBullishMedianCross = ta.crossover(seriesSlow, 0)
normalBearishMedianCross = ta.crossunder(seriesNormal, 0)
normalBullishMedianCross = ta.crossover(seriesNormal, 0)
fastBearishMedianCross = ta.crossunder(seriesFast, 0)
fastBullishMedianCross = ta.crossover(seriesFast, 0)
// ===========================
// ==== Kernel Estimators ====
// ===========================
// Gaussian Kernel with a lookback of 3 bars, starting on bar 2 of the chart (tight
fit)
yhat1 = kernels.gaussian(seriesEmphasis, 3, 2)
// Trend Assessment based on the relative position of the medium fit kernel to the
slow oscillator
isBearishKernelTrend = yhat0 < seriesSlow
isBullishKernelTrend = yhat0 > seriesSlow
// Divergence Signals
isBearishDivZone = ta.barssince(bearishCross[1]) < divThreshold
isBullishDivZone = ta.barssince(bullishCross[1]) < divThreshold
// Crossover Detection
isBearishTriggerWave = isSmallerBearishCross and isBearishDivZone and
isBearishKernelTrend
isBullishTriggerWave = isSmallerBullishCross and isBullishDivZone and
isBullishKernelTrend
// =======================
// ==== Plots & Fills ====
var position = 0
length := atrLength
minMult = math.max(sensitivity-4, 1)
maxMult = math.min(sensitivity, 26)
float step = .5
//Trigger error
if minMult > maxMult
    runtime.error('Minimum factor is greater than maximum factor in the range')
float perfAlpha = 10
fromCluster = 'Best'
//Optimization
maxIter = 250
maxData = 2500
//Style
bearCss = color.red
bullCss = color.teal
showGradient = true
//Dashboard
showDash = true
//dashboardLocation = input.string('Top Right', 'Location', options = ['Top
Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = 'Small'
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
    float upper = hl2
    float lower = hl2
    float output
    float perf = 0
    float factor
    int trend = 0
type vector
    array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
atr = ta.atr(length)
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
factor_array = array.new<float>(0)
data = array.new<float>(0)
//Intialize clusters
var array<vector> factors_clusters = na
var array<vector> perfclusters = na
              idx = dist.indexof(dist.min())
              perfclusters.get(idx).out.push(value)
              factors_clusters.get(idx).out.push(factor_array.get(i))
              i += 1
        //Update centroids
        new_centroids = array.new<float>(0)
        for cluster_ in perfclusters
            new_centroids.push(cluster_.out.avg())
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Signals and trailing stop
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float target_factor = na
var float perf_idx = na
var float perf_ama = na
if not na(perfclusters)
    //Get average factors within target cluster
    target_factor := nz(factors_clusters.get(from).out.avg(), target_factor)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------{
css = os ? bullCss : bearCss
//Candle coloring
//barcolor(showGradient ? color.from_gradient(perf_idx, 0, 1, color.new(css, 80),
css) : na)
//Signals
if showSignals
    if os > os[1] and (signalPresets != "Smart Trail [Filter]" or
smartTrailDirection == 'long') and (signalPresets != "Trend Tracer [Filter]" or
trendTracerDirection==#02ff65) and (signalPresets != "Trend Strength [Filter]" or
trendStrengthMetric >= 25) and (signalPresets != "Trend Catcher [Filter]" or
newTrendCatcherColor == #02ff65) and (signalPresets != "Neo Cloud [Filter]" or
int(lastNeo) >= last5Neo)
        int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :
int(perf_idx*10) < 5 ? 3 : 4
        label.new(n, low-ta.atr(30)/2, signalClassifier ?
str.tostring(signalStrength) : ema50 > ema200 ? "▲+" : "▲"
          , color = bullCss
          , style = label.style_label_up
          , textcolor = color.white
          , size = size.small)
        position := 1
// =======================
// Signal Plots
//plot(position == 1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_cross, linewidth=2, color=c_bearish, offset=-1)
//plot(position == -1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_circles, linewidth=2, color=c_bearish, offset=-1)
//plot(position == 1 and isBearishTriggerWave ? high+5 : na, title="Bearish Trigger
Cross", style=plot.style_cross, linewidth=3, color=c_bearish, offset=-1)
//plot(position == -1 and isBearishTriggerWave ? high+5 : na, title="Bearish
Trigger Cross", style=plot.style_circles, linewidth=3, color=c_bearish, offset=-1)
plotchar(bearishCross and position == 1, "Long", "✖", location.abovebar, color =
#4774f5, size = size.tiny, editable = false)
//plotchar(bearishCross and position == -1, "Long", "▼", location.abovebar, color =
c_bearish, size = size.tiny)
plotchar(isBearishTriggerWave and position == 1, "Long", "✖", location.abovebar,
color=#4774f5, size = size.tiny, editable = false)
//plotchar(isBearishTriggerWave and position == -1, "Long", "▼", location.abovebar,
color=c_bearish, size = size.small)
// Shit
atrMultiplier = input(2, title="ATR Multiplier")
boxHeightInAtr = atrMultiplier * ta.atr(10)
// Box TP 1
if (takeProfitBoxes == 'On')
    tp1box = box.new(left=bar_index + 1, top=close + midb, right=bar_index + 18,
bottom=close + lowb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 55), text="TP/SL 1 :   "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    bottom_tp1 = box.get_bottom(tp1box)
    box.delete(tp1box[1])
    // Box TP 2
    tp2box = box.new(left=bar_index + 1, top=close+highb, right=bar_index + 18,
bottom=close+midb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 65), text="TP/SL 2 :   "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    top_tp2 = box.get_top(tp2box)
    box.delete(tp2box[1])
    // Empty Box
    newBox = box.new(left=bar_index + 18, top=top_tp2, right=bar_index + 200,
bottom=bottom_tp1, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 50), text=" ",
text_size=size.normal, text_color=color.new(#3666f5, 0))
    box.delete(newBox[1])
    // SL Box
    slBox = box.new(left=bar_index + 3, top=close-lowb, right=bar_index + 18,
bottom=close-midb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 66), text="TP/SL 2 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl = box.get_top(slBox)
    box.delete(slBox[1])
    // SL2 Box
    sl2Box = box.new(left=bar_index + 3, top=close-midb, right=bar_index + 18,
bottom=close-highb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 65), text="TP/SL 1 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl2 = box.get_bottom(sl2Box)
    box.delete(sl2Box[1])
    // Empty Box SL
    Slboxem = box.new(left=bar_index + 18, top=bottom_sl, right=bar_index + 200,
bottom=bottom_sl2, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 50), text=" ",
text_size=size.normal, text_color=color.new(color.red, 0))
    box.delete(Slboxem[1])
//
    // Line tp Bottom
    var line tpb = na
    isLastBar = barstate.islast
    if (isLastBar)
        tpb := line.new(na, bottom_tp1, na, bottom_tp1, color=color.new(#3666f5,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        tp2Line := line.new(na, top_tp2, na, top_tp2, color=color.new(#3666f5, 0),
width=2, style=line.style_dashed)
    if (isLastBar)
        slLine := line.new(na, bottom_sl, na, bottom_sl, color=color.new(color.red,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        sl2Line := line.new(na, bottom_sl2, na, bottom_sl2,
color=color.new(color.red, 0), width=2, style=line.style_dashed)
###################################################################################
###################################################################################
##################################################
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
at https://mozilla.org/MPL/2.0/
// © Pieki
//@version=5
// # ========================================================================= #
// #                   |   Indicator |
// # ========================================================================= #
indicator(title = "[Pieki Algo] Signals And Overlays | [V.2.0]", shorttitle =
"Signals And Overlays", overlay = true, max_lines_count = 500, max_labels_count =
500, max_boxes_count = 500)
// # ==== [DASHBOARD]
gr_dashboard             = "DASHBOARD SETTINGS"
showDash                 = input(true, "Dashboard",group = gr_dashboard)
showDashtrend            = input(true, "Trend Dashboard",group = gr_dashboard)
dashLoc                  = input.string("Bottom Right", "Location", options = ["Top
Right", "Bottom Right", "Bottom Left"], group = gr_dashboard)
textSize                 = input.string("Normal", "Size", options = ["Tiny",
"Small", "Normal"], group = gr_dashboard)
// # ==== [RISK MANAGEMENT]
gr_risk                  = "RISK Management"
levels                   = input.bool(false, "Show TP/SL Levels" , group = gr_risk ,
inline = "1")
dynamic_tp               = input.bool(false, "Dynamic TP" , group = gr_risk , inline
= "1")
slrisk                   = input.int(1, "SL %", inline = "2", group = gr_risk)
tp1risk                  = input.int(1, "TP 1 %", inline = "3", group = gr_risk)
tp2risk                  = input.int(2, "TP 2 %", inline = "4", group = gr_risk)
tp3risk                  = input.int(3, "TP 3 %", inline = "5", group = gr_risk)
// # ==== [ALERTS]
gr_alert                 = "ALERT SETTINGS"
sigaler                  = input.bool(false, "Signals Alerts", inline = "1", group =
gr_alert, tooltip = "1")
trendtraceraalert        = input.bool(false, "Trend Tracer", inline = "2", group =
gr_alert, tooltip = "1")
revzonesalert            = input.bool(false, "Reversal Zones", inline = "3", group =
gr_alert, tooltip = "1")
cloudalert               = input.bool(false, "Cloud", inline = "4", group =
gr_alert, tooltip = "1")
// # ============================[FUNCTIONS]============================ #
// # ==== [Trend Tracer]
// ATR
get_atr(i_length) =>
    ta.atr(i_length)
    os = 0,max = 0.,min = 0.
    os := src > upper ? 1 : src < lower ? 0 : os[1]
    spt = os == 1 ? lower : upper
    max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ?
math.max(src,max[1]) : spt
    min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ?
math.min(src,min[1]) : spt
    math.avg(max,min)
// # ==== [SUPPORT RESISTANCE]
src_c = request.security(syminfo.tickerid,timef,close, gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off)
src_o = request.security(syminfo.tickerid,timef,open, gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off)
f_resInMinutes() =>
    _resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60.
* 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _resInMinutes
f_timefResInMinutes(_res) =>
    request.security(syminfo.tickerid, _res, f_resInMinutes())
f_timefIsIntraday(_res) =>
    [intraday, daily, weekly, monthly] = request.security(syminfo.tickerid, _res,
[timeframe.isintraday, timeframe.isdaily, timeframe.isweekly, timeframe.ismonthly])
    check = intraday ? "Intraday" : daily ? "Daily" : weekly ? "Weekly" : monthly ?
"Monthly" : "Error"
    check
mtimef_multiplier = int (f_timefResInMinutes(timef) / f_resInMinutes())
// # ============================[GET COMPONENTS]============================ #
src                     = close
rsi = 14
// # ==== [SIGNALS]
rsi_smooth              = 3 // RSI Smoothing for signals
wilders_Period          = rsi * 2 - 1
sig_rsi                 = ta.rsi(src, rsi)
sig_ma_rsi              = ta.ema(sig_rsi, rsi_smooth)
sig_atr_rsi             = math.abs(sig_ma_rsi[1] - sig_ma_rsi)
sig_ma_atr_rsi           = ta.ema(sig_atr_rsi, wilders_Period)
dar                      = ta.ema(sig_ma_atr_rsi, wilders_Period) * sigsensiviti
longband = 0.0
shortband = 0.0
trend1 = 0
DeltaFastAtrRsi          = dar
RSIndex                  = sig_ma_rsi
newshortband             = RSIndex + DeltaFastAtrRsi
newlongband              = RSIndex - DeltaFastAtrRsi
longband                := RSIndex[1] > longband[1] and RSIndex > longband[1] ?
math.max(longband[1], newlongband) : newlongband
shortband               := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ?
math.min(shortband[1], newshortband) : newshortband
cross_1                  = ta.cross(longband[1], RSIndex)
trend1                   := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 :
nz(trend1[1], 1)
FastAtrRsiTL             = trend1 == 1 ? longband : shortband
// Find all the QQE Crosses
QQExlong                 = 0
QQExlong                := nz(QQExlong[1])
QQExshort                = 0
QQExshort               := nz(QQExshort[1])
QQExlong                := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
QQExshort               := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0
//Conditions
qqeLong                  = QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na
qqeShort                 = QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na
// # ==== [TREND TRACER]
trend_length             = 10 // ATR Period
lr_length                = 20 // Linear Regression (LSMA)
lr_offset                = 0 // Linear Regression (LSMA)
// Highest/Lowest of source
lower = ta.lowest(src, trend_length)
upper = ta.highest(src, trend_length)
if trendtracer
    lower := ta.lowest(low, trend_length)
    upper := ta.highest(high, trend_length)
// Trend direction
string direction = upper > upper[1] ? "up" : lower < lower[1] ? "down" : "neutral"
// Trend and signal variables
float trend = 0.0
string up_down_trend = na
bool trendtracer_buy = false
bool trendtracer_sell = false
// ATR trend logic
if direction == "up"
    trend := low - atr
    if trend < trend[1]
         trend := trend[1]
if direction == "down"
    trend := high + atr
    if trend > trend[1]
         trend := trend[1]
if direction == "neutral"
    trend := trend[1]
// Buy/Sell signals
up_down_trend := up_down_trend[1]
if trend > trend[1]
    up_down_trend := "up"
if trend < trend[1]
    up_down_trend := "down"
// Buy/Sell Signals
trendtracer_buy := up_down_trend[1] == "down" and up_down_trend == "up" ? true :
false
trendtracer_sell := up_down_trend[1] == "up" and up_down_trend == "down" ? true :
false
// # ==== [REVERSAL ZONES]
rg = kama(ta.tr, revzonessens)
basis = kama(close, revzonessens)
upper1 = basis + rg * 9
upper2 = basis + rg * 11
upper3 = basis + rg * 14
lower1 = basis - rg * 9
lower2 = basis - rg * 11
lower3 = basis - rg * 14
smoothedSupert = ta.sma(supert, 2)
smoothedSupert2 = ta.sma(supert2,2)
tool = direction1 > 0 or direction1 < 0
// # ==== [RSI]
ma(x, len) => ta.rma(x, len)
upperr = ta.highest(src, rsi)
lowerr = ta.lowest(src, rsi)
r = upperr - lowerr
d = src - src[1]
dif = upperr > upperr[1] ? r
  : lowerr < lowerr[1] ? -r
  : d
num = ma(dif, rsi)
den = ma(math.abs(dif), rsi)
arsi = math.min(num / den * 50 + 50,100)
// # ==== [VOLUME]
volback = 13
up_bar = close > hl2
dn_bar = close < hl2
u_vol = up_bar ? volume : 0
d_vol = dn_bar ? volume : 0
up_vol = math.sum(u_vol, volback)
dn_vol = math.sum(d_vol, volback)
vol = math.min(100 * (up_vol - dn_vol) / (up_vol + dn_vol),100)
// # ==== [SQUEEZE]
var max = 0.0
var min = 0.0
max := nz(math.max(src, max - (max - src) / 50), src)
min := nz(math.min(src, min + (src - min) / 50), src)
diff = math.log(max - min)
// # ==== [MONEY FLOW]
mf = math.min(ta.mfi(src, 14),100)
// # ==== [ADX]
up = ta.change(high)
down = -ta.change(low)
trur = ta.rma(ta.tr, 14)
plus = fixnan(100 * ta.rma(up > down and up > 0 ? up : 0, 14) / trur)
minus = fixnan(100 * ta.rma(down > up and down > 0 ? down : 0, 14) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), 14)
// # ==== [TREND DETECTOR MTF]
ema = ta.ema(close, 144)
emaBull = close > ema
trend_5m   = request.security(syminfo.tickerid, "5"   , emaBull)
trend_15m = request.security(syminfo.tickerid, "15" , emaBull)
trend_30m = request.security(syminfo.tickerid, "30" , emaBull)
trend_1h = request.security(syminfo.tickerid, "60" , emaBull)
trend_4h = request.security(syminfo.tickerid, "240" , emaBull)
trend_1d   = request.security(syminfo.tickerid, "1440", emaBull)
// # ==== [RISK MANAGEMENT]
trigger2 = qqeLong ? 1 : 0
countBull = ta.barssince(qqeLong)
countBear = ta.barssince(qqeShort)
trigger   = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
// # ============================[PLOTTING]============================ #
// # ==== [SIGNALS]
// Normal
y1 = low - (ta.atr(30) * 2), y1B = low - ta.atr(30)
y2 = high + (ta.atr(30) * 2), y2B = high + ta.atr(30)
buy = qqeLong and showsignals and signfilter == "None" ? label.new(bar_index, y1,
"^", xloc.bar_index, yloc.price, bullish, label.style_label_up, color.white,
size.normal) : na
sell = qqeShort and showsignals and signfilter == "None"? label.new(bar_index, y2,
"¡", xloc.bar_index, yloc.price, bearish, label.style_label_down, color.white,
size.normal) : na
// Trend Tracer
trendtracer_b = trendtracer_buy and showsignals and signfilter == "Trend Tracer" ?
label.new(bar_index, y1, "^", xloc.bar_index, yloc.price, bullish,
label.style_label_up, color.white, size.normal) : na
trendtracer_s = trendtracer_sell and showsignals and signfilter == "Trend Tracer"?
label.new(bar_index, y2, "¡", xloc.bar_index, yloc.price, bearish,
label.style_label_down, color.white, size.normal) : na
// Reversal zones
revzones_s = revzonessell and showsignals and signfilter == "Reversal Zones" ?
label.new(bar_index, y2, "¡", xloc.bar_index, yloc.price, bearish,
label.style_label_down, color.white, size.normal) : na
revzones_b = revzonesbuy and showsignals and signfilter == "Reversal Zones" ?
label.new(bar_index, y1, "^", xloc.bar_index, yloc.price, bullish,
label.style_label_up, color.white, size.normal) : na
// Cloud
cloud_buy1 = cloud_buy and showsignals and signfilter == "Cloud" ?
label.new(bar_index, y1, "^", xloc.bar_index, yloc.price, bullish,
label.style_label_up, color.white, size.normal) : na
cloud_sell1 = cloud_sell and showsignals and signfilter == "Cloud" ?
label.new(bar_index, y2, "¡", xloc.bar_index, yloc.price, bearish,
label.style_label_down, color.white, size.normal) : na
// # ==== [TREND TRACER]
p1 = plot(trendtracer ? trend : na, "ATR Trend", color = up_down_trend == "up" ?
bullish : bearish, linewidth = 2, editable = false)
// # ==== [TREND TRACER]
pp1 = plot(revzones ? upper1 : na, transp=100, editable = false)
pp2 = plot(revzones ? upper2 : na, transp=100, editable = false)
pp3 = plot(revzones ? upper3 : na, transp=100, editable = false)
pp4 = plot(revzones ? lower1 : na, transp=100, editable = false)
pp5 = plot(revzones ? lower2 : na, transp=100, editable = false)
pp6 = plot(revzones ? lower3 : na, transp=100, editable = false)
fill(pp1, pp2, color=color.new(bearish, 70), editable = false)
fill(pp2, pp3, color=color.new(bearish, 50), editable = false)
fill(pp4, pp5, color=color.new(bullish, 70), editable = false)
fill(pp5, pp6, color=color.new(bullish, 50), editable = false)
// # ==== [CLOUD]
A = plot(cloudshow ? senkouA : na,'Senkou Span A',na,offset=offset-1, editable =
false)
B = plot(cloudshow ? senkouB : na,'Senkou Span B',na,offset=offset-1, editable =
false)
fill(A,B,senkouA > senkouB ? color.new(bullish, 80) : color.new(bearish,80))
// # ==== [TREND LINES]
var uptl = trendlineshow ? line.new(na,na,na,na, color = bullish, style =
line.style_dashed, extend = extend.right) : na
var dntl = trendlineshow ? line.new(na,na,na,na, color = bearish, style =
line.style_dashed, extend = extend.right) : na
if ph and trendlineshow
    uptl.set_xy1(n-offset_tl, trendlineshow ? ph : upper_tl - slope_ph *
trendlinesens)
    uptl.set_xy2(n-offset_tl+1, trendlineshow ? ph - slope : upper_tl - slope_ph *
(trendlinesens+1))
if pl and trendlineshow
    dntl.set_xy1(n-offset_tl, trendlineshow ? pl : lower_tl + slope_pl *
trendlinesens)
    dntl.set_xy2(n-offset_tl+1, trendlineshow ? pl + slope : lower_tl + slope_pl *
(trendlinesens+1))
// # ==== [SMART TRAIL]
tool12 = plot(smarttrailshow ? ((direction1 < 0 and direction1[1] < 0) or
(direction1 > 0 and direction1[1] > 0) ? smoothedSupert : na) : na, "Extreme line",
color=smarttrailshow ? (close > ((direction1 < 0 and direction1[1] < 0) or
(direction1 > 0 and direction1[1] > 0) ? smoothedSupert : na) ? bullish :
bearish) : na, style=plot.style_linebr, editable = false)
tool2 = plot(smarttrailshow ? (tool ? smoothedSupert2 : na) : na, "Zone line",
color=color.new(color.gray, 100), display=smarttrailshow ? display.none :
display.none, editable=false, style=plot.style_linebr, editable = false)
fill(tool12, tool2, color=close > supert ? color.new(bullish, 80) :
color.new(bearish, 80), fillgaps=false)
lineColor = close > supertrend ? bullish : close < supertrend ? bearish : na
plot(smarttrailshow ? ((direction1 < 0 and direction1[1] < 0) or (direction1 > 0
and direction1[1] > 0) ? smoothedSupert : na) : na, color=smarttrailshow ?
lineColor : na, linewidth=2, style=smarttrailshow ? plot.style_line :
plot.style_line, title="Trend Area Line", editable = false)
// # ==== [COLORING CANDLE]
barcolor(QQExlong ? bullish : bearish)
// # ==== [RISK MANAGEMENT]
entry = levels ? label.new(time, close, "ENTRY | " +
str.tostring(lastTrade(close), "#.####"), xloc.bar_time, yloc.price, #00e2ff,
label.style_none, color.white, size.normal) : na
label.set_x(entry, label.get_x(entry) + math.round(ta.change(time) * 10))
label.set_y(entry, lastTrade(close))
label.delete(entry[1])
stop_y = lastTrade(slris)
stop = levels ? label.new(time, close, "SL    | " + str.tostring(stop_y, "#.####"),
xloc.bar_time, yloc.price, bearish, label.style_none, color.white, size.normal) :
na
label.set_x(stop, label.get_x(stop) + math.round(ta.change(time) * 10))
label.set_y(stop, stop_y)
label.delete(stop[1])
// Dynamic TP
rsi_tp = ta.rsi(close ,14)
tpLabels(tp) =>
    tp1Bull = ta.crossover (rsi_tp, 70), tp2Bull = ta.crossover (rsi_tp, 75),
tp3Bull = ta.crossover (rsi_tp, 80)
    tp1Bear = ta.crossunder(rsi_tp, 30), tp2Bear = ta.crossunder(rsi_tp, 25),
tp3Bear = ta.crossunder(rsi_tp, 20)
    tp1Bull := tp1Bull and (nz(ta.barssince(tp1Bull)[1], 9999) > countBull),
tp2Bull := tp2Bull and (ta.barssince(tp1Bull)[1] <= countBull), tp2Bull := tp2Bull
and (nz(ta.barssince(tp2Bull)[1], 9999) > countBull), tp3Bull := tp3Bull and
(ta.barssince(tp2Bull)[1] <= countBull), tp3Bull := tp3Bull and
(nz(ta.barssince(tp3Bull)[1], 9999) > countBull)
    tp1Bear := tp1Bear and (nz(ta.barssince(tp1Bear)[1], 9999) > countBear),
tp2Bear := tp2Bear and (ta.barssince(tp1Bear)[1] <= countBear), tp2Bear := tp2Bear
and (nz(ta.barssince(tp2Bear)[1], 9999) > countBear), tp3Bear := tp3Bear and
(ta.barssince(tp2Bear)[1] <= countBear), tp3Bear := tp3Bear and
(nz(ta.barssince(tp3Bear)[1], 9999) > countBear)
    if dynamic_tp
        trigger ? (tp == 1 ? tp1Bull : tp == 2 ? tp2Bull : tp3Bull) : (tp == 1 ?
tp1Bear : tp == 2 ? tp2Bear : tp3Bear)
find_loc(strength) =>
    ret = array.size(sr_strength)
    for i = ret > 0 ? array.size(sr_strength) - 1 : na to 0 by 1
        if strength <= array.get(sr_strength, i)
            break
        ret := i
        ret
    ret
if ph6 or pl6
    //because of new calculation, remove old S/R levels
    array.clear(sr_up_level)
    array.clear(sr_dn_level)
    array.clear(sr_strength)
    //find S/R zones
    for x = 0 to array.size(pivotvals) - 1 by 1
        [hi, lo, strength] = get_sr_vals(x)
        if check_sr(hi, lo, strength)
            loc = find_loc(strength)
            // if strength is in first levels sr then insert it to the arrays
            if loc < levelssr and strength >= min_strength
                array.insert(sr_strength, loc, strength)
                array.insert(sr_up_level, loc, hi)
                array.insert(sr_dn_level, loc, lo)
                // keep size of the arrays = 5
                if array.size(sr_strength) > levelssr
                     array.pop(sr_strength)
                     array.pop(sr_up_level)
                    array.pop(sr_dn_level)
    for x = 1 to 10 by 1
        line.delete(array.get(sr_lines, x))
        label.delete(array.get(sr_labels, x))
        label.delete(array.get(timef_labels, x))
if showDash
    if barstate.islast
        tb.cell(1, 1, str.tostring(rsiemo) + " RSI",                  text_color
=color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(1, 2, str.tostring(volemo) + " Volume Sentiment" ,    text_color
=color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(1, 3,                         "?? Squeeze" ,          text_color
=color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(1, 4, str.tostring(mfemo) + " Money Flow" ,           text_color =
color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(1, 5, str.tostring(adxemo) + " ADX" ,                 text_color
=color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(2, 1, str.tostring(arsi, format.percent),            text_color =
txtrsi, text_size = table_size, bgcolor = bgrsi)
        tb.cell(2, 2, str.tostring(vol, format.percent),             text_color =
txtvol, text_size = table_size, bgcolor = bgvol)
        tb.cell(2, 3, str.tostring(squeeze, format.percent),         text_color =
txtsqueeze, text_size = table_size, bgcolor = bgsqueeze)
        tb.cell(2, 4, str.tostring(mf, format.percent) , text_color = txtmf,
text_size = table_size, bgcolor = bgmf)
        tb.cell(2, 5, str.tostring(adx, format.percent),             text_color =
txtadx, text_size = table_size, bgcolor = bgadx)
// # ============================[Alerts]============================ #
// Signals Normal
alertcondition(sigaler ? qqeLong : na, "New Signal", message = "New Buy Signal |
Normal")
alertcondition(sigaler ? qqeShort : na, "New Signal", message = "New Sell Signal |
Normal")
// Signals Trend Tracer
alertcondition(trendtraceraalert ? trendtracer_buy : na, title="New Signal",
message = "New Buy Signal | Trend Tracer")
alertcondition(trendtraceraalert ? trendtracer_sell : na, title="New Signal",
message = "New Sell Signal | Trend Tracer")
// Signals Reversal Zones
alertcondition(revzonesalert ? revzonesbuy : na, title="New Signal", message = "New
Buy Signal | Reversal Zones")
alertcondition(revzonesalert ? revzonessell : na, title="New Signal", message =
"New Sell Signal | Reversal Zones")
// Signals Cloud
alertcondition(cloudalert ? cloud_buy : na, title="New Signal", message = "New Buy
Signal | Cloud")
alertcondition(cloudalert ? cloud_sell : na, title="New Signal", message = "New
Sell Signal | Cloud")
###################################################################################
###################################################################################
##################################################
//@version=5
indicator("LuxAlgo Signals & Overlays", "LuxAlgo Signals & Overlays™", overlay =
true, max_labels_count = 500)
//Import libraries
//Import libraries
import ayvaliktrading/EyopsTelegram/1 as LAF
import ayvaliktrading/JoinUsEyopsTelegram/1 as kernels
// Advanced Settings
groupAdvanced = "ADVANCED SETTINGS"
takeProfitBoxes = input.string("Off", "TP/SL Points", options=["Off","On"], inline
= "2", tooltip = "Shows Take Profit and Stop Loss areas",group = groupAdvanced)
takeProfitStopLossDistance = input.int(5,"", minval = 1, maxval = 10, inline = "2",
group=groupAdvanced)
autopilotMode = input.string("Off", "Autopilot Sensivity",["Off","Short-Term",
"Mid-Term", "Long-Term"],tooltip = "Sets automatic settings for signals and
improves their quality" ,inline = "3", group = groupAdvanced)
dashboardLocation = input.string("Bottom Right","Dashboard Location", ["Top
Right","Bottom Right","Bottom Left"], inline = "4",tooltip = "Changes dashboard
positions" ,group = groupAdvanced)
dashboardSize = input.string("Normal","Dashboard Size",
["Tiny","Small","Normal","Large"], inline = "5",tooltip = "Changes the size of the
dashboard" ,group = groupAdvanced)
n = bar_index
// # ============================[BUY/SELL SIGNALS]============================ #
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------}
// # ============================[SESSIONS]============================ #
show_sesa = true
sesa_txt = 'New York'
sesa_ses = '1300-2200'
sesa_css = #ff5d00
sesa_range = true
sesa_tl = false
sesa_avg = false
sesa_vwap = false
sesa_maxmin = false
//Session B
show_sesb = true
sesb_txt = 'London'
sesb_ses = '0700-1600'
sesb_css = #2157f3
sesb_range = true
sesb_tl = false
sesb_avg = false
sesb_vwap = false
sesb_maxmin = false
//Timezones
tz_incr = 0
use_exchange = false
//Ranges Options
bg_transp = 90
show_outline = true
show_txt = true
//Dashboard
show_ses_div = false
show_day_div = false
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
sma
    var   float   y1 = na
    var   float   y2 = na
    var   float   stdev = na
    var   float   r2    = na
          y1 := 4 * sma - 3 * wma
          y2 := 3 * wma - 2 * sma
//Session Vwap
get_vwap(session) =>
    var float num = na
    var float den = na
//Set line
set_line(session, y1, y2, session_css)=>
    var line tl = na
        box.set_top(bx, max)
        box.set_rightbottom(bx, n, min)
        if show_txt
            label.set_xy(lbl, int(math.avg(t, time)), max)
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//Ranges
if show_sesa and sesa_range
    [max, min] = get_range(is_sesa, sesa_txt, sesa_css)
    max_sesa := max
    min_sesa := min
//Trendlines
//Mean
if show_sesa and sesa_avg
    avg = get_avg(is_sesa)
    set_line(is_sesa, avg, avg, sesa_css)
//VWAP
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot max/min
plot(showSessions and sesa_maxmin ? max_sesa : na, 'Session A Maximum', sesa_css,
1, plot.style_linebr, editable = false)
plot(showSessions and sesa_maxmin ? min_sesa : na, 'Session A Minimum', sesa_css,
1, plot.style_linebr, editable = false)
//Plot Divider A
plotshape(is_sesa and show_ses_div and show_sesa and showSessions, "·"
  , shape.square
  , location.bottom
  , na
  , text = "."
  ,   textcolor = sesa_css
  ,   size = size.tiny
  ,   display = display.all - display.status_line
  ,   editable = false)
//Plot Divider B
plotshape(is_sesb and show_ses_div and show_sesb and showSessions, "·"
  , shape.labelup
  , location.bottom
  , na
  , text = "."
  , textcolor = sesb_css
  , size = size.tiny
  , display = display.all - display.status_line
  , editable = false)
// # ============================[FUNCTIONS]============================ #
type bar
    float   o   =   open
    float   h   =   high
    float   l   =   low
    float   c   =   close
    float   v   =   volume
    int     i   =   bar_index
bar b = bar.new()
nzV = nz(b.v)
f_calcV() =>
    uV = 0.0
    dV = 0.0
      switch
          (b.c - b.l) > (b.h - b.c) => uV := nzV
        (b.c - b.l) < (b.h - b.c)   => dV := -nzV
        b.c > b.o => uV := nzV
        b.c < b.o => dV := -nzV
        b.c > nz(b.c[1]) => uV :=   nzV
        b.c < nz(b.c[1]) => dV :=   -nzV
        nz(uV[1]) > 0 => uV := uV   + nzV
        nz(dV[1]) < 0 => dV := dV   - nzV
[uV, dV]
// # ============================[CONSTANT VARIABLES]============================ #
sma4 = ta.sma(close, 4)
sma5 = ta.sma(close, 5)
sma9 = ta.sma(close, 9)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
bullishSignalColor = #59e08a
bearishSignalColor = #ff5959
dashboardRedText = #ee787d
dashboardGreenText = #42bda8
dashboardGreenBackground = #284444
dashboardRedBackground = #49343e
// # ============================[CANDLE COLORING]============================ #
macdFastLength = 12
macdSlowLength = 26
macdSignalLength = 9
// Yellow
yellowLow = #56328f
// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #56328f
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    redHigh := #ff0000
    redMidHigh := #c21637
    redMidLow := #c33252
    redLow := #8e215f
if (candleColorType == 'Contrarian Gradient')
    redHigh := #01d70c
    redMidHigh := #269444
    redMidLow :=#4f966c
    redLow := #425970
    // Yellow
    yellowLow := #513a88
    // 4 level of red
    greenHigh := #ff0000
    greenMidHigh := #c21637
    greenMidLow := #c33252
    greenLow := #8e215f
// Default color
candleBody = yellowLow
if histX > 0
    if histX > histX[1] and histX[1] > 0
        candleBody := greenLow
if histX < 0
    if histX < histX[1] and histX[1] < 0
        candleBody := redLow
// Bullish trend
if MacdX > 0 and histX > 0
    candleBody := greenMidLow
// Bearish trend
if MacdX < 0 and histX < 0
    candleBody := redMidLow
// # ============================[TREND CATCHER]============================ #
[trendCatcherLine, trendCatcherColor] = LAF.getTrendCatcher()
newTrendCatcherColor = trendCatcherColor == color.blue ? #02FF65 : #FF1100
plot(trendCatcher ? trendCatcherLine : na, title='Trend Catcher', linewidth=2,
color=newTrendCatcherColor, editable = false)
// # ============================[NEO CLOUD]============================ #
// # ============================[REVERSAL ZONES]============================ #
// # ============================[TREND TRACER]============================ #
[trendTracerLine, trendTracerDirection] = LAF.getTrendTracer()
trendTracerColor = trendTracerDirection == #02ff65 ? #F1FFE7 : #6C464E
plot(trendTracer ? trendTracerLine : na, title='Trend Tracer', linewidth=2,
style=plot.style_cross, color = trendTracerColor, editable = false)
// # ============================[DASHBOARD
COMPONENTS|]============================ #
volatilityMetric = LAF.getVolatilityMetric()
volatilityMetric2 = ta.sma(LAF.getVolatilityMetric(), 8)
volatilityText = volatilityMetric < 30 ? 'Stable' : volatilityMetric < 80 ?
'Moderate' : 'Volatile'
volatilityEmoji = volatilityMetric2 > volatilityMetric ? '📉' : '📈'
volatilityCellColor = newTrendCatcherColor == #02ff65 ? dashboardGreenBackground :
dashboardRedBackground
VolatilityTextColor = trendStrengthCellColor == dashboardGreenBackground ?
dashboardGreenText : dashboardRedText
totalVolume = uV + math.abs(dV)
//volumecolor = totalVolume >= 50 ? bullish : bearish
volumeCellColor = dashboardRedBackground
volumeTextColor = totalVolume >= 50 ? dashboardGreenText : dashboardRedText
if (totalVolume >= 50)
     totalVolume := totalVolume*2
     volumeCellColor := dashboardGreenBackground
else
     totalVolume := totalVolume*-2
volumeSentiment = totalVolume
tb = table.new(table_position, 7, 7
  , bgcolor = #1e222d
  , border_color = #373a46
  , border_width = 1
  , frame_color = #373a46
  , frame_width = 1)
if showDashboard
    if barstate.islast
        tb.cell(0, 2, autopilotMode == 'Off' ? "✈️
                                                 Optimal Sensivity" : " Autopilot
Enabled", text_color = color.white, text_size = table_size, text_halign =
text.align_left)
        tb.cell(0, 3, str.tostring(trendIndication) + "Trend Strength", text_color
= color.white, text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 4, volatilityEmoji+ " Lux Volatility", text_color = color.white,
text_size = table_size, text_halign = text.align_left)
        tb.cell(0, 5, "🔃 Squeeze", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
        tb.cell(0, 6, "💧 Volume Sentiment", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
//
***********************************************************************************
*************************
// REV ZONES
//
***********************************************************************************
*************************
indiSet = false
source = hlc3
type = 'SuperSmoother'
length = 100
innermult = 1.0
outermult = 2.415
ChartSet = false
drawchannel = true
displayzone = true
zonetransp = 60
displayline = true
MTFSet = false
enable_mtf = true
mtf_disp_typ = 'On Hover'
mtf_typ = 'Auto'
mtf_lvl1 = 'D'
mtf_lvl2 = 'W'
//
***********************************************************************************
*************************
// Functions Start {
//
***********************************************************************************
*************************
var pi = 2 * math.asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp
//-----------------------
// Ehler SwissArmyKnife Function
//-----------------------
SAK_smoothing(_type, _src, _length) =>
    c0 = 1.0
    c1 = 0.0
    b0 = 1.0
    b1 = 0.0
    b2 = 0.0
    a1 = 0.0
    a2 = 0.0
    alpha = 0.0
    beta = 0.0
    gamma = 0.0
    cycle = 2 * pi / _length
    _Input = _src
    _Output = 0.0
    _Output := c0 * (b0 * _Input + b1 * nz(_Input[1]) + b2 * nz(_Input[2])) + a1 *
nz(_Output[1]) + a2 * nz(_Output[2]) - c1 * nz(_Input[_length])
    _Output
//-----------------------
// SuperSmoother Function
//-----------------------
supersmoother(_src, _length) =>
    s_a1 = math.exp(-math.sqrt(2) * pi / _length)
    s_b1 = 2 * s_a1 * math.cos(math.sqrt(2) * pi / _length)
    s_c3 = -math.pow(s_a1, 2)
    s_c2 = s_b1
    s_c1 = 1 - s_c2 - s_c3
    ss = 0.0
    ss := s_c1 * _src + s_c2 * nz(ss[1], _src[1]) + s_c3 * nz(ss[2], _src[2])
    ss
//-----------------------
// Auto TimeFrame Function
//-----------------------
// ————— Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
    _resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60.
* 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _resInMinutes
get_tf(_lvl) =>
    y = f_resInMinutes()
    z = timeframe.period
    if mtf_typ == 'Auto'
         if y < 1
              z := _lvl == 1 ? '1' : _lvl == 2 ? '5' : z
              z
         else if y <= 3
              z := _lvl == 1 ? '5' : _lvl == 2 ? '15' : z
              z
         else if y <= 10
              z := _lvl == 1 ? '15' : _lvl == 2 ? '60' : z
              z
         else if y <= 30
              z := _lvl == 1 ? '60' : _lvl == 2 ? '240' : z
              z
         else if y <= 120
              z := _lvl == 1 ? '240' : _lvl == 2 ? 'D' : z
              z
         else if y <= 240
              z := _lvl == 1 ? 'D' : _lvl == 2 ? 'W' : z
              z
         else if y <= 1440
              z := _lvl == 1 ? 'W' : _lvl == 2 ? 'M' : z
              z
         else if y <= 10080
              z := _lvl == 1 ? 'M' : z
              z
         else
              z := z
              z
    else
         z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
         z
//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
    v_condition = 0
    v_meanline = source
    v_meanrange = supersmoother(ta.tr, length)
    if type != 'SuperSmoother'
        v_meanline := SAK_smoothing(type, source, length)
        v_meanline
//-----------------------
// MTF Analysis
//-----------------------
get_stat(_cond) =>
    ret = 'Price at Mean Line\n'
    if _cond == 1
        ret := 'Overbought (Weak)\n'
        ret
    else if _cond == 2
        ret := 'Overbought\n'
        ret
    else if _cond == 3
        ret := 'Overbought (Strong)\n'
        ret
    else if _cond == 4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == 5
        ret := 'Price Above Mean\n'
        ret
    else if _cond == -1
        ret := 'Oversold (Weak)\n'
        ret
    else if _cond == -2
        ret := 'Oversold\n'
        ret
    else if _cond == -3
        ret := 'Oversold (Strong)\n'
        ret
    else if _cond == -4
        ret := 'Price Near Mean\n'
        ret
    else if _cond == -5
        ret := 'Price Below Mean\n'
        ret
    ret
//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
    y = str.tostring(x, '0.00000')
    if x > 10
        y := str.tostring(x, '0.000')
        y
    if x > 1000
        y := str.tostring(x, '0.00')
        y
    y
//
***********************************************************************************
*************************
// Calculate Channel
//
***********************************************************************************
*************************
var tf_0 = timeframe.period
var tf_1 = get_tf(1)
var tf_2 = get_tf(2)
//
***********************************************************************************
*************************
// Drawing Start {
//
***********************************************************************************
*************************
float p_meanline = drawchannel ? meanline : na
float p_upband1 = drawchannel ? upband1 : na
float p_loband1 = drawchannel ? loband1 : na
float p_upband2 = drawchannel ? upband2 : na
float p_loband2 = drawchannel ? loband2 : na
//-----------------------
// Draw zone
//-----------------------
//---
var color1 = #FF0000
var color2 = #FF4200
var color3 = #FF5D00
var color4 = #FF7400
var color5 = #FF9700
var color6 = #FFAE00
var color7 = #FFC500
var color8 = #FFCD00
//---
float upband2_1 = drawchannel and displayzone ? upband2 + meanrange * gradsize *
4 : na
float loband2_1 = drawchannel and displayzone ? loband2 - meanrange * gradsize *
4 : na
float upband2_2     = drawchannel and displayzone ? upband2 + meanrange * gradsize *
3 : na
float loband2_2     = drawchannel and displayzone ? loband2 - meanrange * gradsize *
3 : na
float upband2_3     = drawchannel and displayzone ? upband2 + meanrange * gradsize *
2 : na
float loband2_3     = drawchannel and displayzone ? loband2 - meanrange * gradsize *
2 : na
float upband2_4     = drawchannel and displayzone ? upband2 + meanrange * gradsize *
1 : na
float loband2_4     = drawchannel and displayzone ? loband2 - meanrange * gradsize *
1 : na
float upband2_5     = drawchannel and displayzone ? upband2 + meanrange * gradsize *
0 : na
float loband2_5     = drawchannel and displayzone ? loband2 - meanrange * gradsize *
0 : na
float upband2_6     = drawchannel and displayzone ? upband2 + meanrange * gradsize * -1
: na
float loband2_6     = drawchannel and displayzone ? loband2 - meanrange * gradsize * -1
: na
float upband2_7     = drawchannel and displayzone ? upband2 + meanrange * gradsize * -2
: na
float loband2_7     = drawchannel and displayzone ? loband2 - meanrange * gradsize * -2
: na
float upband2_8     = drawchannel and displayzone ? upband2 + meanrange * gradsize * -3
: na
float loband2_8     = drawchannel and displayzone ? loband2 - meanrange * gradsize * -3
: na
float upband2_9     = drawchannel and displayzone ? upband2 + meanrange * gradsize * -4
: na
float loband2_9     = drawchannel and displayzone ? loband2 - meanrange * gradsize * -4
: na
kijun_len     = 365
kijun_mult    = 7
spanB_len    = 365
spanB_mult   = 15
offset      = 2
//------------------------------------------------------------------------------
avg(src,length,mult)=>
    atr = ta.atr(length)*mult
    up = hl2 + atr
    dn = hl2 - atr
    upper = 0.,lower = 0.
    upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
    lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
    os = 0,max = 0.,min = 0.
    os := src > upper ? 1 : src < lower ? 0 : os[1]
    spt = os == 1 ? lower : upper
    max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ?
math.max(src,max[1]) : spt
    min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ?
math.min(src,min[1]) : spt
    math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = #2156f300
kijun_css = #ff5e0000
chikou_css = #7b1fa2
plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none, editable =
false)
//box.delete(boxes.shift())
// Fundamental Assumptions:
// (1) There exists a probability density function that describes the relative
likelihood for a price to visit a given value.
// (2) The probability density function for price is a function of time.
// (3) The probability density function can approximate a Gaussian distribution
(shown below).
//                                                                              ___
//                                  .::~!:..                                     |
// :ΞΞΞΞ~!ΞΞΞ!. |
// .ΞJΞΞΞΞ~!ΞΞΞ?J^ |
// :J?ΞΞΞΞΞ~!ΞΞΞΞΞJ^ |
// :J?ΞΞΞΞΞΞ~!ΞΞΞΞΞΞ??. |
// :JΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞ?J^ |
//                          :JΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞ?J^
[ PRICE ]
//                        .:~ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!!~                            |
// :?~^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^Ξ! |
// ~:^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^!Ξ. |
// .Ξ!^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^~Ξ~ |
// .~Ξ~^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^!Ξ: |
// .~Ξ~^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^~!!^. |
// ....::^^!~~^^^^^^^^^ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!^^^^^^^^^~!^^::...... |
// ..:::^^^^^^^::::::::::::::ΞΞΞΞΞΞΞΞΞΞ~!ΞΞΞΞΞΞΞΞΞ!::::::::::::^^^^^^^^:::.. |
//
// -------------------------------- [ TIME ] -------------------------------|
// ================
// ==== Inputs ====
// ================
// Signal Settings
src = close
useMirror = false
useEma = false
emaLength = 3
useCog = false
cogLength = 6
oscillatorLookback =20
quadraticMeanLength = 50
src := useEma ? ta.ema(src, emaLength) : src
src := useCog ? ta.cog(src, cogLength) : src
speedToEmphasize = 'Normal'
emphasisWidth = 2
useKernelMA = false
useKernelEmphasis = false
// Oscillator Settings
offset := 0
showOsc = true
showOsc := showOsc
float f_length = 0.75
float f_smoothing = 0.45
float n_length = 1.0
float n_smoothing = 1.0
float s_length = 1.75
float s_smoothing = 2.5
// Divergence Detection
divThreshold = 30
sizePercent = 40
// The defaults are colors that Google uses for its Data Science libraries (e.g.
TensorFlow). They are considered to be colorblind-safe.
var color fastBullishColor = color.black
var color normalBullishColor = color.black
var color slowBullishColor = color.black
var color fastBearishColor = color.black
var color normalBearishColor = color.black
var color slowBearishColor =color.black
var color c_bullish = color.black
var color c_bearish = color.black
areaFastTrans =   areaBackgroundTrans
lineFastTrans =   lineBackgroundTrans
areaNormalTrans   = areaBackgroundTrans
lineNormalTrans   = lineBackgroundTrans
areaSlowTrans =   areaForegroundTrans
lineSlowTrans =   lineForegroundTrans
switch speedToEmphasize
    "Slow" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaForegroundTrans
        lineSlowTrans := lineForegroundTrans
    "Normal" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaForegroundTrans
        lineNormalTrans := lineForegroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "Fast" =>
        areaFastTrans := areaForegroundTrans
        lineFastTrans := lineForegroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
    "None" =>
        areaFastTrans := areaBackgroundTrans
        lineFastTrans := lineBackgroundTrans
        areaNormalTrans := areaBackgroundTrans
        lineNormalTrans := lineBackgroundTrans
        areaSlowTrans := areaBackgroundTrans
        lineSlowTrans := lineBackgroundTrans
// =================================
// ==== Color Helper Functions =====
// =================================
// ================================
// ==== Main Helper Functions =====
// ================================
// =================================
// ==== Oscillator Calculations ====
// =================================
// =====================================
// ==== Color Gradient Calculations ====
// =====================================
// =========================================
// ==== Plot Parameters and Logic Gates ====
// =========================================
// Speed   Booleans
isSlow =   speedToEmphasize == "Slow"
isNormal   = speedToEmphasize == "Normal"
isFast =   speedToEmphasize == "Fast"
// Series Colors
seriesSlowColor = showOsc or isSlow ? color.new(slowLineGradientFromSource,
lineSlowTrans) : na
seriesNormalColor = showOsc or isNormal ? color.new(normalLineGradientFromSource,
lineNormalTrans) : na
seriesFastColor = showOsc or isFast ? color.new(fastLineGradientFromSource,
lineFastTrans) : na
seriesSlowMirrorColor = useMirror ? seriesSlowColor : na
seriesNormalMirrorColor = useMirror ? seriesNormalColor : na
seriesFastMirrorColor = useMirror ? seriesFastColor : na
// Series Line Widths
seriesSlowWidth = isSlow ? emphasisWidth : 1
seriesNormalWidth = isNormal ? emphasisWidth : 1
seriesFastWidth = isFast ? emphasisWidth : 1
seriesSlowMirrorWidth = useMirror ? seriesSlowWidth : na
seriesNormalMirrorWidth = useMirror ? seriesNormalWidth : na
seriesFastMirrorWidth = useMirror ? seriesFastWidth : na
colorAreaEmphasis = switch
    isFast => fastAreaGradientFromSource
    isNormal => normalAreaGradientFromSource
    isSlow => slowAreaGradientFromSource
    => na
// Crossover Signals
bearishCross = ta.crossunder(seriesFast, seriesNormal) and seriesNormal > 0
bullishCross = ta.crossover(seriesFast, seriesNormal) and seriesNormal < 0
slowBearishMedianCross = ta.crossunder(seriesSlow, 0)
slowBullishMedianCross = ta.crossover(seriesSlow, 0)
normalBearishMedianCross = ta.crossunder(seriesNormal, 0)
normalBullishMedianCross = ta.crossover(seriesNormal, 0)
fastBearishMedianCross = ta.crossunder(seriesFast, 0)
fastBullishMedianCross = ta.crossover(seriesFast, 0)
// ===========================
// ==== Kernel Estimators ====
// ===========================
// Gaussian Kernel with a lookback of 3 bars, starting on bar 2 of the chart (tight
fit)
yhat1 = kernels.gaussian(seriesEmphasis, 3, 2)
// Trend Assessment based on the relative position of the medium fit kernel to the
slow oscillator
isBearishKernelTrend = yhat0 < seriesSlow
isBullishKernelTrend = yhat0 > seriesSlow
// Divergence Signals
isBearishDivZone = ta.barssince(bearishCross[1]) < divThreshold
isBullishDivZone = ta.barssince(bullishCross[1]) < divThreshold
// Crossover Detection
isBearishTriggerWave = isSmallerBearishCross and isBearishDivZone and
isBearishKernelTrend
isBullishTriggerWave = isSmallerBullishCross and isBullishDivZone and
isBullishKernelTrend
// =======================
// ==== Plots & Fills ====
var position = 0
length := atrLength
minMult = math.max(sensitivity-4, 1)
maxMult = math.min(sensitivity, 26)
float step = .5
//Trigger error
if minMult > maxMult
    runtime.error('Minimum factor is greater than maximum factor in the range')
float perfAlpha = 10
fromCluster = 'Best'
//Optimization
maxIter = 250
maxData = 2500
//Style
bearCss = color.red
bullCss = color.teal
showGradient = true
//Dashboard
showDash = true
//dashboardLocation = input.string('Top Right', 'Location', options = ['Top
Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = 'Small'
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
    float upper = hl2
    float lower = hl2
    float output
    float perf = 0
    float factor
    int trend = 0
type vector
    array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
atr = ta.atr(length)
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
factor_array = array.new<float>(0)
data = array.new<float>(0)
//Intialize clusters
var array<vector> factors_clusters = na
var array<vector> perfclusters = na
            idx = dist.indexof(dist.min())
            perfclusters.get(idx).out.push(value)
            factors_clusters.get(idx).out.push(factor_array.get(i))
            i += 1
        //Update centroids
        new_centroids = array.new<float>(0)
        for cluster_ in perfclusters
            new_centroids.push(cluster_.out.avg())
centroids := new_centroids
//-----------------------------------------------------------------------------}
//Signals and trailing stop
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float target_factor = na
var float perf_idx = na
var float perf_ama = na
if not na(perfclusters)
    //Get average factors within target cluster
    target_factor := nz(factors_clusters.get(from).out.avg(), target_factor)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
//-----------------------------------------------------------------------------{
css = os ? bullCss : bearCss
//Signals
if showSignals
    if os > os[1] and (signalPresets != "Smart Trail [Filter]" or
smartTrailDirection == 'long') and (signalPresets != "Trend Tracer [Filter]" or
trendTracerDirection==#02ff65) and (signalPresets != "Trend Strength [Filter]" or
trendStrengthMetric >= 25) and (signalPresets != "Trend Catcher [Filter]" or
newTrendCatcherColor == #02ff65) and (signalPresets != "Neo Cloud [Filter]" or
int(lastNeo) >= last5Neo)
        int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :
int(perf_idx*10) < 5 ? 3 : 4
        label.new(n, low-ta.atr(30)/2, signalClassifier ?
str.tostring(signalStrength) : ema50 > ema200 ? "▲+" : "▲"
          , color = bullCss
          , style = label.style_label_up
          , textcolor = color.white
          , size = size.small)
        position := 1
// =======================
// Signal Plots
//plot(position == 1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_cross, linewidth=2, color=c_bearish, offset=-1)
//plot(position == -1 and bearishCross ? high+5 : na, title="Bearish Cross",
style=plot.style_circles, linewidth=2, color=c_bearish, offset=-1)
//plot(position == 1 and isBearishTriggerWave ? high+5 : na, title="Bearish Trigger
Cross", style=plot.style_cross, linewidth=3, color=c_bearish, offset=-1)
//plot(position == -1 and isBearishTriggerWave ? high+5 : na, title="Bearish
Trigger Cross", style=plot.style_circles, linewidth=3, color=c_bearish, offset=-1)
plotchar(bearishCross and position == 1, "Long", "✖", location.abovebar, color =
#4774f5, size = size.tiny, editable = false)
//plotchar(bearishCross and position == -1, "Long", "▼", location.abovebar, color =
c_bearish, size = size.tiny)
plotchar(isBearishTriggerWave and position == 1, "Long", "✖", location.abovebar,
color=#4774f5, size = size.tiny, editable = false)
//plotchar(isBearishTriggerWave and position == -1, "Long", "▼", location.abovebar,
color=c_bearish, size = size.small)
//plot(position == 1 and bullishCross ? low -5: na, title="Bullish Cross", style=
plot.style_circles, linewidth=2, color=c_bullish, offset=-1)
//plot(position == -1 and bullishCross ? low -5: na, title="Bullish Cross", style=
plot.style_cross, linewidth=2, color=c_bullish, offset=-1)
//plot(position == 1 and isBullishTriggerWave ? low -5 : na, title="Bullish Trigger
Cross", style=plot.style_circles, linewidth=3, color=c_bullish, offset=-1)
//plot(position == -1 and isBullishTriggerWave ? low -5 : na, title="Bullish
Trigger Cross", style=plot.style_cross, linewidth=3, color=c_bullish, offset=-1)
// Shit
atrMultiplier = input(2, title="ATR Multiplier")
boxHeightInAtr = atrMultiplier * ta.atr(10)
// Box TP 1
if (takeProfitBoxes == 'On')
    tp1box = box.new(left=bar_index + 1, top=close + midb, right=bar_index + 18,
bottom=close + lowb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 55), text="TP/SL 1 :   "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    bottom_tp1 = box.get_bottom(tp1box)
    box.delete(tp1box[1])
    // Box TP 2
    tp2box = box.new(left=bar_index + 1, top=close+highb, right=bar_index + 18,
bottom=close+midb, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 65), text="TP/SL 2 :   "
+ str.tostring(close), text_size=size.normal, text_color=color.new(#3666f5, 0))
    top_tp2 = box.get_top(tp2box)
    box.delete(tp2box[1])
    // Empty Box
    newBox = box.new(left=bar_index + 18, top=top_tp2, right=bar_index + 200,
bottom=bottom_tp1, border_color=color.new(#3666f5, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 50), text=" ",
text_size=size.normal, text_color=color.new(#3666f5, 0))
    box.delete(newBox[1])
    // SL Box
    slBox = box.new(left=bar_index + 3, top=close-lowb, right=bar_index + 18,
bottom=close-midb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 66), text="TP/SL 2 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl = box.get_top(slBox)
    box.delete(slBox[1])
    // SL2 Box
    sl2Box = box.new(left=bar_index + 3, top=close-midb, right=bar_index + 18,
bottom=close-highb, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 65), text="TP/SL 1 :
" + str.tostring(close), text_size=size.normal, text_color=color.new(color.red, 0))
    bottom_sl2 = box.get_bottom(sl2Box)
    box.delete(sl2Box[1])
    // Empty Box SL
    Slboxem = box.new(left=bar_index + 18, top=bottom_sl, right=bar_index + 200,
bottom=bottom_sl2, border_color=color.new(color.red, 0), border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 50), text=" ",
text_size=size.normal, text_color=color.new(color.red, 0))
    box.delete(Slboxem[1])
//Telegram ==>> https://t.me/+UAk3hqvoD89jZTlk
    // Line tp Bottom
    var line tpb = na
    isLastBar = barstate.islast
    if (isLastBar)
        tpb := line.new(na, bottom_tp1, na, bottom_tp1, color=color.new(#3666f5,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        tp2Line := line.new(na, top_tp2, na, top_tp2, color=color.new(#3666f5, 0),
width=2, style=line.style_dashed)
    // Line SL
    var line slLine = na
    if (isLastBar)
        slLine := line.new(na, bottom_sl, na, bottom_sl, color=color.new(color.red,
0), width=2, style=line.style_dashed)
    if (isLastBar)
        sl2Line := line.new(na, bottom_sl2, na, bottom_sl2,
color=color.new(color.red, 0), width=2, style=line.style_dashed)
//@version=5
indicator("[X1]", overlay=true, max_lines_count=500, max_labels_count=500,
max_boxes_count=350)
// FUNCTIONS
// Parkinson Volatility
f_park(period, sqrtAnnual) =>
    var LOG2 = math.log(2)
    powLogHighLow = math.pow(math.log(high / low), 2)
    sqrtAnnual * math.sqrt(1.0 / period * math.sum(1.0 / (4.0 * LOG2) *
powLogHighLow, period))
//Rescale Function
f_rescale(_src, _size) =>
    math.max(0, math.min(_size, int(_src / 100 * _size)))
// Settings
H = EWMA
period = 10
Annual = 365
a = 1.34
Plen = 365
Pco = ON
sma = ON
malen = 55
bsg = OFF
stl = CL
lT = 3
i_invert = OFF
bg = OFF
sp = OFF
//Hv Stats
avgHV = ta.sma(Hv, malen)
HVP = ta.percentrank(Hv, Plen)
NearZero = HVP < 1.5 ? 1 : 0
HV50 = ta.percentile_nearest_rank(Hv, Plen, 50)
// // Text Functions
// texthv() =>
//     ' HV: ' + str.tostring(Round(Hv, 2))
// textphv() =>
//     'HV 50ᵗʰ Percentile: ' + str.tostring(Round(HV50, 2))
// texthvp() =>
//     'HV Percentile: ' + str.tostring(Round(HVP, 2)) + 'ᵗʰ'
// // Coloring
// var c_ = array.new_color(na)
// if barstate.isfirst
//     array.push(c_, #0effff)
//     array.push(c_, #00fdf6)
//     array.push(c_, #00fbee)
//     array.push(c_, #00f9e4)
//     array.push(c_, #00f6db)
//     array.push(c_, #00f4d1)
//     array.push(c_, #13f1c6)
//     array.push(c_, #24efbc)
//     array.push(c_, #31ecb1)
//     array.push(c_, #3ce9a6)
//     array.push(c_, #47e69b)
//     array.push(c_, #51e390)
//     array.push(c_, #5adf85)
//     array.push(c_, #62dc7a)
//     array.push(c_, #6ad96e)
//     array.push(c_, #72d563)
//     array.push(c_, #7ad157)
//     array.push(c_, #81cd4b)
//     array.push(c_, #88ca3f)
//     array.push(c_, #8fc532)
//     array.push(c_, #96c123)
//     array.push(c_, #9cbd0e)
//     array.push(c_, #a3b800)
//     array.push(c_, #a9b300)
//     array.push(c_, #b0ae00)
//     array.push(c_, #b6a900)
//     array.push(c_, #bca300)
//     array.push(c_, #c29e00)
//     array.push(c_, #c29e00)
//     array.push(c_, #c89800)
//     array.push(c_,       #ce9100)
//     array.push(c_,       #d48b00)
//     array.push(c_,       #da8400)
//     array.push(c_,       #df7c00)
//     array.push(c_,       #e57400)
//     array.push(c_,       #ea6c00)
//     array.push(c_,       #ef6200)
//     array.push(c_,       #f35800)
//     array.push(c_,       #f74c00)
//     array.push(c_,       #fb3e00)
//     array.push(c_,       #ff2d00)
//     if i_invert
//         array.reverse(c_)
// var sizeOf = array.size(c_) - 1
// colorHV = Pco ? array.get(c_, f_rescale(HVP, sizeOf)) : color.aqua
// Plots
// if sp
//     _label(H + texthv() + '\n' + textphv() + '\n' + texthvp() + '\n\n',
#000000c0)
// col2 = HVP >= 1 ? color.yellow : HVP <= 1 and HVP >= 0.5 ? color.orange : HVP <=
0.5 ?
//#8D0000 : color.silver
// // bgcolor(bsg and NearZero ? col2 : na, transp=50)
//Custrom MAS
maa = avgHV /   100   *   140
mab = avgHV /   100   *   180
mac = avgHV /   100   *   240
mad = avgHV /   100   *   60
mae = avgHV /   100   *   20
if auto_button == false
    sensitivity
else if auto_button == true
    sensitivity := volatility
// Functions
f_chartTfInMinutes() =>
     float _resInMinutes = timeframe.multiplier * (
       timeframe.isseconds ? 1. / 60             :
       timeframe.isminutes ? 1.                  :
       timeframe.isdaily   ? 60. * 24            :
       timeframe.isweekly ? 60. * 24 * 7         :
       timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
atr(len) =>
       tr = ta.tr
     atr = 0.0
     atr := nz(atr[1] + (tr - atr[1]) / len, tr)
supertrend(src, factor, len) =>
       atr = ta.atr(len)
       upperBand = src + factor * atr
       lowerBand = src - factor * atr
       prevLowerBand = nz(lowerBand[1])
       prevUpperBand = nz(upperBand[1])
       lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ?
lowerBand : prevLowerBand
       upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ?
upperBand : prevUpperBand
       int direction = na
       float superTrend = na
       prevSuperTrend = superTrend[1]
       if prevSuperTrend == prevUpperBand
             direction := close > upperBand ? 1 : -1
       else
             direction := close < lowerBand ? -1 : 1
       superTrend := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
dchannel(len)=>
     hh = ta.highest(len)
     ll = ta.lowest (len)
     trend = 0
     trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
trendScalper(show, len1, len2, len3, colorBull, colorBear, colorBarBull,
colorBarBear) =>
     avgOC = math.avg(open, close)
     ha_o = 0.0, ha_o := na(ha_o[1]) ? avgOC : (ha_o[1] + ohlc4[1]) / 2
     ema1 = ta.ema(ha_o, len1), ema2 = ta.ema(ha_o, len2), ema3 = ta.ema(ha_o, len3)
     ris1 = ema1 > ema1[1], ris2 = ema2 > ema2[1], ris3 = ema3 > ema3[1]
     fal1 = ema1 < ema1[1], fal2 = ema2 < ema2[1], fal3 = ema3 < ema3[1]
     colorEma1 = ris1 ? colorBull : fal1 ? colorBear : na, colorEma2 = ris2 ?
colorBull : fal2 ? colorBear : na, colorEma3 = ris3 ? colorBull : fal3 ? colorBear
: na
     fillEma1 = avgOC > ema1 ? colorBull : avgOC < ema1 ? colorBear : na, fillEma2 =
ema1 > ema2 ? colorBull : ema1 < ema2 ? colorBear : na, fillEma3 = ema2 > ema3 ?
colorBull : ema2 < ema3 ? colorBear : na
     colorBar = close < ema1 and close < ema2 ? colorBarBear : colorBarBull
     [avgOC, show ? ema1 : na, show ? ema2 : na, show ? ema3 : na,
color.new(colorEma1, 55), color.new(colorEma2, 45), color.new(colorEma3, 35),
color.new(fillEma1, 85), color.new (fillEma2, 80), color.new(fillEma3, 75),
colorBar]
candlesMom() =>
      [_, _, macd] = ta.macd(close, 12, 26, 9)
      (macd > 0 and macd > macd[1]) or (macd < 0 and macd < macd[1])
trailingSL(buy, sell, factor, len, usePerc, perc) =>
      atr = atr(len)
      upperBand = high + (usePerc ? high * (perc / 100) : factor * atr)
      lowerBand = low - (usePerc ? low * (perc / 100) : factor * atr)
      prevLowerBand = nz(lowerBand[1])
      prevUpperBand = nz(upperBand[1])
      lowerBand := lowerBand > prevLowerBand or buy ? lowerBand : prevLowerBand
      upperBand := upperBand < prevUpperBand or sell ? upperBand : prevUpperBand
      int direction = na
      float stop = na
      prevSuperTrend = stop[1]
      if prevSuperTrend == prevUpperBand
             direction := buy ? 1 : -1
      else
             direction := sell ? -1 : 1
      stop := direction == 1 ? lowerBand : direction == -1 ? upperBand : na
add_to_zz(zz, val, bi) =>
    array.unshift(zz, bi)
    array.unshift(zz, val)
    if array.size(zz) > 12
         array.pop(zz)
update_zz(zz, val, bi, dir) =>
    if array.size(zz) == 0
         add_to_zz(zz, val, bi)
    else
         if dir == 1 and val > array.get(zz, 0) or dir == -1 and val < array.get(zz,
0)
             array.set(zz, 0, val)
             array.set(zz, 1, bi)
         0
float ph = ta.pivothigh(high, 10, 10)
float pl = ta.pivotlow (low , 10, 10)
LSRstyle = lineSrStyle == "Dashed" ? line.style_dashed : lineSrStyle == "Solid" ?
line.style_solid : line.style_dotted
prdhighest = ta.highest(300)
prdlowest = ta.lowest (300)
cwidth = (prdhighest - prdlowest) * 10 / 100
var pivotvals = array.new_float(0)
if ph or pl
    array.unshift(pivotvals, ph ? ph : pl)
    if array.size(pivotvals) > 20
         array.pop(pivotvals)
get_sr_vals(ind) =>
    float lo = array.get(pivotvals, ind)
    float hi = lo
    int numpp = 0
    for y = 0 to array.size(pivotvals) - 1 by 1
         float cpp = array.get(pivotvals, y)
         float wdth = cpp <= lo ? hi - cpp : cpp - lo
         if wdth <= cwidth
             lo := cpp <= lo ? cpp : lo
             hi := cpp > lo ? cpp : hi
             numpp += 1
             numpp
    [hi, lo, numpp]
var sr_up_level = array.new_float(0)
var sr_dn_level = array.new_float(0)
sr_strength = array.new_float(0)
find_loc(strength) =>
    ret = array.size(sr_strength)
    for i = ret > 0 ? array.size(sr_strength) - 1 : na to 0 by 1
         if strength <= array.get(sr_strength, i)
             break
         ret := i
         ret
    ret
check_sr(hi, lo, strength) =>
    ret = true
    for i = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by
1
         if array.get(sr_up_level, i) >= lo and array.get(sr_up_level, i) <= hi or
array.get(sr_dn_level, i) >= lo and array.get(sr_dn_level, i) <= hi
             if strength >= array.get(sr_strength, i)
                  array.remove(sr_strength, i)
                  array.remove(sr_up_level, i)
                  array.remove(sr_dn_level, i)
                  ret
             else
                  ret := false
                  ret
             break
    ret
// Get components
rsi = ta.rsi(close, 14)
vosc = ta.obv - ta.ema(ta.obv, 20)
bs   = ta.ema(nz(math.abs((open - close) / (high - low) * 100)), 3)
ema = ta.ema(close, 200)
emaBull = close > ema
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and
str.tonumber(res) < 10)
securityNoRep(sym, res, src) =>
    bool bull = na
    bull := equal_tf(res) ? src : bull
    bull := higher_tf(res) ? request.security(sym, res, src, barmerge.gaps_off,
barmerge.lookahead_on) : bull
    bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ?
str.tostring (f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ? "3"
: "10") : res, src)
    if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
         bull := array.pop(bull_array)
    array.clear(bull_array)
    bull
TF1Bull    = securityNoRep(syminfo.tickerid, "1"   , emaBull)
TF3Bull    = securityNoRep(syminfo.tickerid, "3"   , emaBull)
TF5Bull    = securityNoRep(syminfo.tickerid, "5"   , emaBull)
TF10Bull = securityNoRep(syminfo.tickerid, "10" , emaBull)
TF15Bull = securityNoRep(syminfo.tickerid, "15" , emaBull)
TF30Bull = securityNoRep(syminfo.tickerid, "30" , emaBull)
TF60Bull = securityNoRep(syminfo.tickerid, "60" , emaBull)
TF120Bull = securityNoRep(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep(syminfo.tickerid, "240" , emaBull)
TF720Bull = securityNoRep(syminfo.tickerid, "720" , emaBull)
TFDBull   = securityNoRep(syminfo.tickerid, "1440", emaBull)
ema150 = ta.ema(close, 150)
ema250 = ta.ema(close, 250)
hma55 = ta.hma(close, 55 )
[_, _, macd] = ta.macd(close, 12, 26, 9)
supertrend = supertrend(ohlc4, sensitivity, 10)
maintrend = dchannel(30)
confBull   = (ta.crossover (close, supertrend) or (ta.crossover (close, supertrend)
[1] and maintrend[1] < 0)) and macd > 0 and macd > macd[1] and ema150 > ema250 and
hma55 > hma55[2] and maintrend > 0
confBear   = (ta.crossunder(close, supertrend) or (ta.crossunder(close, supertrend)
[1] and maintrend[1] > 0)) and macd < 0 and macd < macd[1] and ema150 < ema250 and
hma55 < hma55[2] and maintrend < 0
trendcloud = supertrend(ohlc4, periodTrendCloud == "Long term" ? 7 : 4, 10)
hma = fastTrendCloud ? ta.hma(close, fastTrendCloudLen) : na
none = close > 0
[_, _, adx] = ta.dmi(14, 14)
consFilter = adx > 20
smartFilter = ta.ema(close, 200)
volFilter = (ta.ema(volume, 25) - ta.ema(volume, 26)) / ta.ema(volume, 26) > 0
trendFilter = trendcloud
bull = (strategy == "Normal" ? ta.crossover (close, supertrend) : confBull and not
confBull[1]) and strategy != "Trend scalper" and (smartSignalsOnly ? close >
smartFilter : none) and (consSignalsFilter ? consFilter : none) and
(highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud ==
"New" ? ema150 > ema250 : close > trendFilter) : none)
bear = (strategy == "Normal" ? ta.crossunder(close, supertrend) : confBear and not
confBear[1]) and strategy != "Trend scalper" and (smartSignalsOnly ? close <
smartFilter : none) and (consSignalsFilter ? consFilter : none) and
(highVolSignals ? volFilter : none) and (signalsTrendCloud ? (periodTrendCloud ==
"New" ? ema150 < ema250 : close < trendFilter) : none)
countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
[avgOC, ema5, ema9, ema21, colorEma5, colorEma9, colorEma21, fillEma5, fillEma9,
fillEma21, colorBar] = trendScalper(strategy == "Trend scalper" ? true : false, 5,
9, 21, color.green,color.red, #00DD00, #DD0000)
l(css, k) =>
    line lr = enableAutoTrend ? line.new(bar_index - lenTrendChannel + 1, A + k,
bar_index, B + k, extend=extend.right, color=css) : na
    line.delete(lr[1])
l(color.blue, rmse), l(color.blue, 0), l(color.blue, -rmse)
//
//================================================================
//=============
// INDICATOR 11 - Trend Confidence
//================================================================
//============
// CCI
// ADX
lenadx = 21
lensig = 21
limadx = 34
ADX_up = ta.change(high)
ADX_down = -ta.change(low)
trur = ta.rma(ta.tr, lenadx)
plus = fixnan(100 * ta.rma(ADX_up > ADX_down and ADX_up > 0 ? ADX_up : 0, lenadx) /
trur)
minus = fixnan(100 * ta.rma(ADX_down > ADX_up and ADX_down > 0 ? ADX_down : 0,
lenadx) / trur)
sum = plus + minus
adxxs = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
macol = adxxs > limadx and plus > minus ? color.lime : adxxs > limadx and plus <
minus ? color.red : color.black
//Acumulation/Distribution
ACC_Dist = ta.sma(ta.accdist, 34)
// MFI
Long_Signal_Strength = 0
Short_Signal_Strength = 0
if entry_long
    if TM_Long
        Long_Signal_Strength   += 1
    if ADX_Long
        Long_Signal_Strength   += 1
    if ACC_Long
        Long_Signal_Strength   += 1
    if MFI_Long
        Long_Signal_Strength   += 1
    if MOML_Long
        Long_Signal_Strength   += 1
if entry_short
    if TM_Short
        Short_Signal_Strength +=   1
    if ADX_Short
        Short_Signal_Strength +=   1
    if ACC_Short
        Short_Signal_Strength +=   1
    if MFI_Short
        Short_Signal_Strength +=   1
    if MOML_Short
        Short_Signal_Strength +=   1
//Plot Buy/Sell Signals on chart
if ph or pl
    array.clear(sr_up_level)
    array.clear(sr_dn_level)
    array.clear(sr_strength)
    for x = 0 to array.size(pivotvals) - 1 by 1
        [hi, lo, strength] = get_sr_vals(x)
        if check_sr(hi, lo, strength)
            loc = find_loc(strength)
            if loc < 5 and strength >= 2
                array.insert(sr_strength, loc, strength)
                array.insert(sr_up_level, loc, hi)
                array.insert(sr_dn_level, loc, lo)
                if array.size(sr_strength) > (enableSR ? 5 : 0)
                    array.pop(sr_strength)
                    array.pop(sr_up_level)
                    array.pop(sr_dn_level)
    for x = 1 to 10 by 1
        line.delete(array.get(sr_lines, x))
    for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by
1
        float mid = math.round_to_mintick((array.get(sr_up_level, x) +
array.get(sr_dn_level, x)) / 2)
        rate = 100 * (mid - close) / close
         array.set(sr_lines, x + 1, line.new(x1=bar_index, y1=mid, x2=bar_index - 1,
y2=mid, extend=extend.both, color=mid >= close ? color.red : color.lime,
style=LSRstyle, width=lineSrWidth))
if showCons and barstate.isconfirmed
    dir := hb_ and na(lb_) ? 1 : lb_ and na(hb_) ? -1 : dir
    if hb_ and lb_
         if dir == 1
              zz_ := hb_
         else
              zz_ := lb_
    else
         zz_ := hb_ ? hb_ : lb_ ? lb_ : na
    for x = 0 to 1000
         if na(close) or dir != dir[x]
              break
         if zz_[x]
              if na(pp)
                   pp := zz_[x]
              else
                   if dir[x] == 1 and zz_[x] > pp
                       pp := zz_[x]
                   if dir[x] == -1 and zz_[x] < pp
                       pp := zz_[x]
    if pp != pp[1]
         if consCnt > lenCons
              if pp > condHi
                   breakUp := true
              if pp < condLo
                   breakDn := true
         if consCnt > 0 and pp <= condHi and pp >= condLo
              consCnt += 1
         else
              consCnt := 0
    else
         consCnt += 1
    if consCnt >= lenCons
         if consCnt == lenCons
              condHi := H_
              condLo := L_
         else
              line.delete(lineUp)
              line.delete(lineDn)
              condHi := math.max(condHi, high)
              condLo := math.min(condLo, low )
         lineUp := line.new(bar_index, condHi , bar_index - consCnt, condHi ,
color=color.red , style=line.style_dashed)
         lineDn := line.new(bar_index, condLo , bar_index - consCnt, condLo ,
color=color.lime, style=line.style_dashed)
fill(plot(condHi, "", na, 1, plot.style_stepline, editable=false), plot(condLo, "",
na, 1, plot.style_stepline, editable=false), paintCons and consCnt > lenCons ?
colorZone : na, "", false)
if box_ob and barstate.isconfirmed
    if pvh
         array.pop(pvh1_price)
         array.pop(pvh1_time)
         array.unshift(pvh1_price, pv1_high)
         array.unshift(pvh1_time, pv1_time)
         if array.size(pvh1_price) > 2
              temp_pv_0 := array.get(pvh1_price, 0)
            temp_pv_1 := array.get(pvh1_price, 1)
            temp_pv_2 := array.get(pvh1_price, 2)
            if temp_pv_0 > temp_pv_1
                for i = 0 to array.size(pvl1_time) - 1 by 1
                    temp_ltcmrhh_time = array.get(pvl1_time, i)
                    if temp_ltcmrhh_time < array.get(pvh1_time, 0)
                        ltcmrhh_price := array.get(pvl1_price, i)
                        ltcmrhh_time := temp_ltcmrhh_time
                        break
            if temp_pv_0 < temp_pv_1 and temp_pv_1 > temp_pv_2
                array.pop(pvh2_price)
                array.pop(pvh2_time)
                array.unshift(pvh2_price, temp_pv_1)
                array.unshift(pvh2_time, array.get(pvh1_time, 1))
    if pvl
        array.pop(pvl1_price)
        array.pop(pvl1_time)
        array.unshift(pvl1_price, pv1_low)
        array.unshift(pvl1_time, pv1_time)
        if array.size(pvl1_price) > 2
            temp_pv_0 := array.get(pvl1_price, 0)
            temp_pv_1 := array.get(pvl1_price, 1)
            temp_pv_2 := array.get(pvl1_price, 2)
            if temp_pv_0 < temp_pv_1
                for i = 0 to array.size(pvh1_time) - 1 by 1
                     temp_htcmrll_time = array.get(pvh1_time, i)
                     if temp_htcmrll_time < array.get(pvl1_time, 0)
                         htcmrll_price := array.get(pvh1_price, i)
                         htcmrll_time := temp_htcmrll_time
                         break
            if temp_pv_0 > temp_pv_1 and temp_pv_1 < temp_pv_2
                array.pop(pvl2_price)
                array.pop(pvl2_time)
                array.unshift(pvl2_price, temp_pv_1)
                array.unshift(pvl2_time, array.get(pvl1_time, 1))
    if trigger_high > htcmrll_price
        if box_sv
            loBox = box.new(left=array.get(pvl1_time, 0),
top=math.min(high[bar_index - array.get (pvl1_time, 0)], high[bar_index -
array.get(pvl1_time, 0) + 1]), right=bar_index, bottom=array.get(pvl1_price, 0),
bgcolor=color.rgb(0, 255, 0, 80), border_color=color.rgb(0, 255, 0, 80),
extend=extend.right)
            if array.size(long_boxes) >= 25
                box.delete(array.shift(long_boxes))
            array.push(long_boxes, loBox)
        htcmrll_price := na
        htcmrll_price
    if trigger_low < ltcmrhh_price
        if box_sv
            hiBox = box.new(left=array.get(pvh1_time, 0), top=array.get(pvh1_price,
0), right=bar_index, bottom=math.max(low[bar_index - array.get(pvh1_time, 0)],
low[bar_index - array.get(pvh1_time, 0) + 1]), bgcolor=color.rgb(255, 0, 0, 80),
border_color=color.rgb(255, 0, 0, 80), extend=extend.right)
            if array.size(short_boxes) >= 25
                box.delete(array.shift(short_boxes))
            array.push(short_boxes, hiBox)
        ltcmrhh_price := na
        ltcmrhh_price
    if array.size(short_boxes) > 0
        for i = array.size(short_boxes) - 1 to 0 by 1
            tbox = array.get(short_boxes, i)
            top = box.get_top(tbox)
            bottom = box.get_bottom(tbox)
            if trigger_high > bottom and box.get_left(tbox) + box_test_delay <
bar_index and box_test_sv
                if box_hide_gray
                     box.set_bgcolor(tbox, #00000000)
                     box.set_border_color(tbox, #00000000)
                else
                     box.set_bgcolor(tbox, color.rgb(192, 192, 192, 80))
                     box.set_border_color(tbox, color.rgb(192, 192, 192, 80))
            if trigger_high > top and box.get_left(tbox) + box_fill_delay <
bar_index
                if box_stop_sv
                     box.set_right(tbox, bar_index)
                     box.set_extend(tbox, extend.none)
                     array.remove(short_boxes, i)
    if array.size(long_boxes) > 0
        for i = array.size(long_boxes) - 1 to 0 by 1
            lbox = array.get(long_boxes, i)
            top = box.get_top(lbox)
            bottom = box.get_bottom(lbox)
            if trigger_low < top and box.get_left(lbox) + box_test_delay <
bar_index and box_test_sv
                if box_hide_gray
                     box.set_bgcolor(lbox, #00000000)
                     box.set_border_color(lbox, #00000000)
                else
                     box.set_bgcolor(lbox, color.rgb(192, 192, 192, 80))
                     box.set_border_color(lbox, color.rgb(192, 192, 192, 80))
            if trigger_low < bottom and box.get_left(lbox) + box_fill_delay <
bar_index
                if box_stop_sv
                     box.set_right(lbox, bar_index)
                     box.set_extend(lbox, extend.none)
                     array.remove(long_boxes, i)
if barstate.islast and eliteVP
    for i = 0 to levelNum - 1
        histogramLow = rangeLow + histogramHeight * i
        histogramHigh = rangeLow + histogramHeight * (i + 1)
        array.set(histogramLowList, i, histogramLow)
        array.set(histogramHighList, i, histogramHigh)
    for i = 0 to lookback - 1
        currentBarHeight = high[i] - low[i]
        currentBuyVolume = high[i] == low[i] ? 0 : volume[i] * (close[i] - low
[i]) / currentBarHeight
        currentSellVolume = high[i] == low[i] ? 0 : volume[i] * (high [i] -
close[i]) / currentBarHeight
        for j = 0 to levelNum - 1
            histogramLow = array.get(histogramLowList, j)
            histogramHigh = array.get(histogramHighList, j)
            target = math.max(histogramHigh, high[i]) - math.min(histogramLow,
low[i]) - (math.max (histogramHigh, high[i]) - math.min(histogramHigh, high[i])) -
(math.max(histogramLow, low[i]) - math.min(histogramLow, low[i]))
            histogramVolumePercentage = target / currentBarHeight
            histogramBuyVolume = array.get(histogramBuyVolumeList, j)
            histogramSellVolume = array.get(histogramSellVolumeList, j)
            if histogramVolumePercentage > 0
                 array.set(histogramBuyVolumeList, j, histogramBuyVolume +
currentBuyVolume * histogramVolumePercentage)
                 array.set(histogramSellVolumeList, j, histogramSellVolume +
currentSellVolume * histogramVolumePercentage)
    highestHistogramVolume = 0.0
    for i = 0 to levelNum - 1
        histogramBuyVolume = array.get(histogramBuyVolumeList, i)
        histogramSellVolume = array.get(histogramSellVolumeList, i)
        histogramVolume = histogramBuyVolume + histogramSellVolume
        highestHistogramVolume := math.max(highestHistogramVolume, histogramVolume)
        highestHistogramVolume
    for i = 0 to levelNum - 1
        histogramLow = array.get(histogramLowList, i)
        histogramHigh = array.get(histogramHighList, i)
        histogramBuyVolume = array.get(histogramBuyVolumeList, i)
        histogramSellVolume = array.get(histogramSellVolumeList, i)
        histogramVolume = histogramBuyVolume + histogramSellVolume
        histogramWidth = levelWidth * histogramVolume / highestHistogramVolume
        histogramBuyWidth = math.floor(histogramWidth * histogramBuyVolume /
histogramVolume)
        histogramSellWidth = math.floor(histogramWidth * histogramSellVolume /
histogramVolume)
        array.set(buyBars , i, box.new(bar_index + offset + levelWidth - 1 -
histogramBuyWidth, histogramHigh, bar_index + offset + levelWidth - 1 ,
histogramLow, colorBorderVP, bgcolor=colorBuyVP ))
        array.set(sellBars, i, box.new(bar_index + offset + levelWidth - 1 -
histogramBuyWidth, histogramHigh, bar_index + offset + levelWidth - 1 -
histogramBuyWidth - histogramSellWidth, histogramLow, colorBorderVP,
bgcolor=colorSellVP))
barcolor(momentumCandles and candlesMom() ? color.purple : candleColors ? (strategy
== "Trend scalper" ? colorBar : na(countBull) and na(countBear) ? color.gray :
trigger ? green : red) : na, editable=false)
fill(plot(showTrendCloud and periodTrendCloud == "New" ? ema150 : na, "", na,
editable=false), plot(showTrendCloud and periodTrendCloud == "New" ? ema250 : na,
"", na, editable=false), ema150 > ema250 ? color.new(color.green, 70) : ema150 <
ema250 ? color.new(color.red, 70) : na)
plot(enableTrailingSL and      trigger and nz(ta.barssince(low < trailingStop),
bar_index) > countBull ? trailingStop : na, "", green, 1, plot.style_linebr,
editable=false)
plot(enableTrailingSL and not trigger and nz(ta.barssince(high > trailingStop),
bar_index) > countBear ? trailingStop : na, "", red , 1, plot.style_linebr,
editable=false)
p0 = plot(avgOC, "", na         , editable=false)
p1 = plot(ema5 , "", colorEma5 , editable=false)
p2 = plot(ema9 , "", colorEma9 , editable=false)
p3 = plot(ema21, "", colorEma21, editable=false)
fill(p0, p1, fillEma5 )
fill(p1, p2, fillEma9 )
fill(p2, p3, fillEma21)
fill(plot(showTrendCloud and periodTrendCloud != "New" and trendcloud != 0 and
close > trendcloud ? trendcloud : na, "", color.green, 1, plot.style_linebr,
editable=false), p0, color.new (color.green, 90))
fill(plot(showTrendCloud and periodTrendCloud != "New" and trendcloud != 0 and
close < trendcloud ? trendcloud : na, "", color.red , 1, plot.style_linebr,
editable=false), p0, color.new (color.red , 90))
fill(plot(hma, "", hma > hma[2] ? green : hma < hma[2] ? red : na, editable=false),
plot(hma[2], "", hma > hma[2] ? green : hma < hma[2] ? red : na, editable=false),
hma > hma[2] ? green : hma < hma[2] ? red : na)
// Alerts
f_crossed_over() =>
    ret = false
    for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by
1
        float mid = math.round_to_mintick((array.get(sr_up_level, x) +
array.get(sr_dn_level, x)) / 2)
        if close[1] <= mid and close > mid
            ret := true
            ret
    ret
f_crossed_under() =>
    ret = false
    for x = 0 to array.size(sr_up_level) > 0 ? array.size(sr_up_level) - 1 : na by
1
        float mid = math.round_to_mintick((array.get(sr_up_level, x) +
array.get(sr_dn_level, x)) / 2)
        if close[1] >= mid and close < mid
            ret := true
            ret
    ret
f_sl_crossed() =>
    ret = false
    stop = enableTrailingSL ? trailingStop : stop_y
    crossBull = low [1] >= stop[1] and low < stop[1] and ta.barssince(low [1] >=
stop[1] and low < stop[1])[1] >= countBull - 1
    crossBear = high[1] <= stop[1] and high > stop[1] and ta.barssince(high[1] <=
stop[1] and high > stop[1])[1] >= countBear - 1
    ret := trigger[1] ? crossBull : crossBear
f_tp_crossed(tp) =>
    ret = false
    profit = tp
    crossBull = high[1] <= profit[1] and high > profit[1] and ta.barssince(high[1]
<= profit[1] and high > profit[1])[1] >= countBull - 1
    crossBear = low [1] >= profit[1] and low < profit[1] and ta.barssince(low [1]
>= profit[1] and low < profit[1])[1] >= countBear - 1
    ret := trigger[1] ? crossBull : crossBear
alert01 = (bull and close <= smartFilter) or (bear and close >= smartFilter)
alert02 = bull or bear
alert03 = (bull and close > smartFilter) or (bear and close < smartFilter)
alert04 = bull and close <= smartFilter
alert05 = f_crossed_over()
alert06 = bear and close >= smartFilter
alert07 = bull and close > smartFilter
alert08 = bear and close < smartFilter
alert09 = f_sl_crossed()
alert10 = f_crossed_under()
alert11 = f_tp_crossed(tp1_y)
alert12 = f_tp_crossed(tp2_y)
alert13 = f_tp_crossed(tp3_y)
alert14 = periodTrendCloud == "New" ? ta.crossunder(ema150, ema250) : (close <
trendcloud) and (close > trendcloud)[1]
alert15 = periodTrendCloud == "New" ? ta.crossover (ema150, ema250) : (close >
trendcloud) and (close < trendcloud)[1]
alerts(sym) =>
    if alert01 or alert02 or alert03 or alert04 or alert05 or alert06 or alert07 or
alert08 or alert09 or alert10 or alert11 or alert12 or alert13 or alert14 or
alert15
        alert("NEW ALERT", alert.freq_once_per_bar_close)
alerts(syminfo.tickerid)
alertcondition(alert01, "Any Signal Buy / sell", "Buy or Sell")
alertcondition(alert02, "Any signal Buy/Smart Buy or Sell/Smart Sell", "Buy/Smart
Buy or Sell/Smart Sell")
alertcondition(alert03, "Any signal Smart Buy / Smart Sell", "Smart Buy or Smart
Sell")
alertcondition(alert04, "Buy alert", "Buy")
alertcondition(alert05, "Resistance Broken", "Resistance Broken")
alertcondition(alert06, "Sell alert", "Sell")
alertcondition(alert07, "Smart Buy", "Smart Buy")
alertcondition(alert08, "Smart Sell", "Smart Sell")
alertcondition(alert09, "Stop loss", "Stop loss")
alertcondition(alert10, "Support Broken", "Support Broken")
alertcondition(alert11, "Target 1", "Target 1")
alertcondition(alert12, "Target 2", "Target 2")
alertcondition(alert13, "Target 3", "Target 3")
alertcondition(alert14, "Trend cloud Bearish Alert", "Trend cloud Bearish")
alertcondition(alert15, "Trend cloud Bullish Alert", "Trend cloud Bullish")
// Watermark
//text inputs
//symbol info
symInfoCheck = false
symInfo = syminfo.ticker + ' | ' + timeframe.period + (timeframe.isminutes ? 'M' :
na)
date = str.tostring(dayofmonth(time_close)) + '/' + str.tostring(month(time_close))
+ '/' + str.tostring(year(time_close))
//text positioning
textVPosition = 'middle'
textHPosition = 'center'
//symbol info positioning
symVPosition = 'top'
symHPosition = 'left'
//cell size
width = 0
height = 0
//title settings
c_title = color.new(color.orange, 0)
s_title = 'large'
a_title = 'center'
//subtitle settings
c_subtitle = color.new(color.orange, 50)
s_subtitle = 'normal'
a_subtitle = 'center'
//symbol settings
c_symInfo = color.new(color.orange, 50)
s_symInfo = 'normal'
a_symInfo = 'center'
c_bg = color.new(color.blue, 100)
###################################################################################
###################################################################################
##################################################
//@version=2
study("Breakout",overlay=true)
res1 = input(title="Close Time Frame", type=resolution, defval="D")
cld=security(tickerid, res1, close[1])
opd=security(tickerid,res1, open[1])
tu=(cld +opd)/2
plot( tu, "Breakout",color=black ,style=line,linewidth=2,transp=0)
###################################################################################
###################################################################################
##################################################
//@version=5
indicator(title='ATR Trailing Stops with Kernel Functions', shorttitle='ATR +
Kernels', overlay=true, linktoseries=true, timeframe='')
// ATR Inputs
atrLookback = input.int(defval=21, title='ATR Lookback Period')
atrMultiplier = input.float(defval=3, title='ATR Multiplier', step=0.1, minval=0.5,
maxval=4)
atrTrailMode = input.string(title='Trail Mode', defval='Trailing',
options=['Running', 'Trailing'])
atrFlipInput = input.string(title='Flip Trail on:', defval='Close',
options=['Close', 'Wick'])
atrBodyPercent = input.int(title='Percentage of Body to Include', defval=100,
minval=0, maxval=200, step=10, group="Advanced Settings")
atrWickPercent = input.int(title='Percentage of Wick to Include', defval=100,
minval=0, maxval=200, step=10)
atrSmoothingMode = input.string(title='ATR Smoothing Mode', defval='RMA',
options=['RMA', 'SMA', 'EMA', 'WMA'])
// ATR Calculations
f_ma(_source, _length, _atrSmoothingMode) =>
    if _atrSmoothingMode == 'RMA'
         ta.rma(_source, _length)
    else
         if _atrSmoothingMode == 'SMA'
              ta.sma(_source, _length)
         else
              if _atrSmoothingMode == 'EMA'
                   ta.ema(_source, _length)
              else
                   ta.wma(_source, _length)
// Flip function
f_flip(_flipInput, _longTrail, _shortTrail, _longReset, _shortReset) =>
    var bool _flipLongNow = false
    var bool _flipShortNow = false
    var bool _isLong = true
    var bool _isShort = true
    float _flipLongSource = _flipInput == 'Close' ? close : _flipInput == 'Wick' ?
high : na
    float _flipShortSource = _flipInput == 'Close' ? close : _flipInput == 'Wick' ?
low : na
    _flipLongNow := _isShort[1] and _flipLongSource > _shortTrail ? true : false
    _flipShortNow := _isLong[1] and _flipShortSource < _longTrail ? true : false
    _flipLongNow := _flipShortNow and _flipLongNow and close > _longTrail ? true :
_flipShortNow and _flipLongNow and close <= _longTrail ? false : _flipLongNow
    _flipShortNow := _flipLongNow and _flipShortNow and close < _shortTrail ?
true : _flipShortNow and _flipLongNow and close >= _shortTrail ? false :
_flipShortNow
    _isLong := _flipLongNow ? true : _flipShortNow ? false : na(_isLong[1]) ?
true : _isLong[1]
    _isShort := _flipShortNow ? true : _flipLongNow ? false : na(_isShort[1]) ?
true : _isShort[1]
    _longTrailOutput = _longTrail
    _shortTrailOutput = _shortTrail
    _longTrailOutput := _isLong and not _isLong[1] ? _longReset : _longTrailOutput
    _shortTrailOutput := _isShort and not _isShort[1] ? _shortReset :
_shortTrailOutput
    float _longTrailPlot = _isLong ? _longTrailOutput : _isLong and _isShort ?
_longTrailOutput : na
    float _shortTrailPlot = _isShort ? _shortTrailOutput : _isLong and _isShort ?
_shortTrailOutput : na
    [_longTrailOutput, _shortTrailOutput, _longTrailPlot, _shortTrailPlot]
trailAtrLong := trailAtrLongTemp
trailAtrShort := trailAtrShortTemp
// ATR Plots
plot(atrTrailMode == 'Running' ? atrLow : na, 'Running ATR Low',
color=color.new(color.white, 60), linewidth=1)
plot(atrTrailMode == 'Running' ? atrHigh : na, 'Running ATR High',
color=color.new(color.white, 60), linewidth=1)