Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
81 kB
6
Indexable
Never
//@version=5
// This code is created by algopoint. All other leaked algos is available at algopoint.mysellix.io
// AlgoPoint Official Contact Adrress
// Instagram:             algopoint
// Instagram:             algopoint01
// Website:               algopoint.mysellix.io
// Mail:                  algopointstore@gmail.com

//text inputs
var user_consensus = input.string(defval="", title="By going to algopoint.mysellix.io or by clicking on the link in the algopoint instagram bio you can get the leaked codes for all premium indicators like Elite Algo, EzAlgo and LuxAlgo. Free products are also available! algopoint.mysellix.io", confirm = true, group="AlgoPoint")
title = 'AlgoPoint'
subtitle = 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io'
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("AlgoPoint | Signals & Overlays", "[AlgoPoint] Signals & Overlays™ [2.2]", overlay = true, max_labels_count = 500)

//Import libraries
import achirameegasthanne/LuxFunctions/1 as LAF
import achirameegasthanne/KernelFunctions/1 as kernels

// # ============================[GET USERS INPUT]============================ #
groupBasic = "BASIC SETTINGS"
showSignals = input(true, "Show Signals", inline = "1", group = groupBasic, tooltip = "Enables or disables the signals")
signalPresets = input.string("None", "Presets / Filters", ["None", "Trend Trader [Preset]","Scalper [Preset]", "Swing Trader [Preset]", "Contrarian Trader [Preset]", "Smart Trail [Filter]", "Trend Tracer [Filter]", "Trend Strength [Filter]", "Trend Catcher [Filter]", "Neo Cloud [Filter]"],tooltip = "Automatically sets settings or filters for a given category", group= groupBasic)
signalMode = input.string("Confirmation + Exits", "Signal Mode", ["Confirmation + Exits", "Contrarian + Exits", "None"],tooltip = "Changes the Mode of the signals" ,group = groupBasic)
signalClassifier = input(true,"AI Signal Classifer",tooltip = "Shows signal quality from 1-4 on signals" ,group = groupBasic)
sensitivity  = input.float(5, "Signal Sensitivity ", minval = 1, maxval = 26,step=1, tooltip = "Changes the sensetivity of the signals, the lower this setting the more short term signals you will get, while a higher number will result in longer term signals.",group = groupBasic)
atrLength  = input.int(10, "Signal Tuner ", minval = 1, maxval = 25,step=1,tooltip = "Alows you to tune your signals, the higher the number the more refined but laggier the signal" ,group = groupBasic)
candleColorType = input.string("Confirmation Simple", "Candle Coloring", ["Confirmation Simple","Confirmation Gradient","Contrarian Gradient","None"],tooltip = "Changes the type of signal coloring", group = groupBasic) 

// Indicator Overlay Settings
groupOverlay = "INDICATOR OVERLAY"
smartTrail = input(true, "Smart Trail", inline = "1", group = groupOverlay)
trendCatcher = input(false, "Trend Catcher", inline = "2", group = groupOverlay)
neoCloud = input(false, "Neo Cloud", inline = "3", group = groupOverlay)
reversalZone = input(true, "Reversal Zones", inline = "1", group = groupOverlay)
trendTracer = input(false, "Trend Tracer", inline = "2", group = groupOverlay)
showDashboard = input(true, "Dashboard", inline = "3", group = groupOverlay)
showTrailingStoploss = input(false, "Trailing Stoploss", inline = "4", group = groupOverlay)
showMovingAverage = input(false, "AI Moving Average", inline = "4", group = groupOverlay)
showSessions = input(false, "Sessions", inline = "5", group = groupOverlay)

// 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)

if (signalPresets == "Trend Trader [Preset]")
    smartTrail := true
    trendCatcher := true
    neoCloud := true
    trendTracer := true
    smartTrail := true
if (signalPresets == "Scalper [Preset]")
    sensitivity := 4
    smartTrail := true
    trendTracer := true
    candleColorType := "Confirmation Gradient"
if (signalPresets == "Swing Trader [Preset]")
    sensitivity := 18
    neoCloud := true
    candleColorType := "Confirmation Simple"
if (signalPresets == "Contrarian Trader [Preset]")
    reversalZone := true
    smartTrail := true
    candleColorType := "Contrarian Gradient"

    
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
//-----------------------------------------------------------------------------{

//Get session average
get_avg(session)=>
    var len = 1
    var float csma = na
    var float sma = na

    if session > session[1]
        len := 1
        csma := close
    
    if session and session == session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
        len += 1    
        csma += close
        sma := csma / len
    
    sma

//Get trendline coordinates
get_linreg(session)=>
    var len = 1
    var float cwma  = na
    var float csma  = na
    var float csma2 = na

    var float y1 = na
    var float y2 = na
    var float stdev = na 
    var float r2    = na 

    if session > session[1]
        len   := 1
        cwma  := close
        csma  := close
        csma2 := close * close
    
    if session and session == session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
        len   += 1    
        csma  += close
        csma2 += close * close
        cwma  += close * len

        sma = csma / len
        wma = cwma / (len * (len + 1) / 2)

        cov   = (wma - sma) * (len+1)/2
        stdev := math.sqrt(csma2 / len - sma * sma)
        r2    := cov / (stdev * (math.sqrt(len*len - 1) / (2 * math.sqrt(3))))

        y1 := 4 * sma - 3 * wma
        y2 := 3 * wma - 2 * sma

    [y1 , y2, stdev, r2]

//Session Vwap
get_vwap(session) =>
    var float num = na
    var float den = na

    if session > session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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
    
    else if session and session == session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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
    else
        num := na

    [num, den]

//Set line
set_line(session, y1, y2, session_css)=>
    var line tl = na

    if session > session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
        tl := line.new(n, close, n, close, color = session_css)

    if session and session == session[1] and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
        line.set_y1(tl, y1)
        line.set_xy2(tl, n, y2)

//Set session range
get_range(session, session_name, session_css)=>
    var t = 0 
    var max = high
    var min = low
    var box bx = na
    var label lbl = na 
    
    if session > session[1] and showSessions and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
        t := time
        max := high
        min := low

        bx := box.new(n, max, n, min
          , bgcolor = color.new(session_css, bg_transp)
          , border_color = show_outline ? session_css : na
          , border_style = line.style_dotted)

        if show_txt and showSessions and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' 
            lbl := label.new(t, max, session_name
              , xloc = xloc.bar_time
              , textcolor = session_css
              , style = label.style_label_down
              , color = color.new(color.white, 100)
              , size = size.tiny)

    if session and session == session[1] and showSessions and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 := math.max(high, max)
        min := math.min(low, min)

        box.set_top(bx, max)
        box.set_rightbottom(bx, n, min)

        if show_txt
            label.set_xy(lbl, int(math.avg(t, time)), max)
    
    [session ? na : max, session ? na : min]

//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period

var tz = use_exchange ? syminfo.timezone :
  str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))

is_sesa = math.sign(nz(time(tf, sesa_ses, tz)))
is_sesb = math.sign(nz(time(tf, sesb_ses, tz)))

//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{

var float max_sesa = na
var float min_sesa = na
var float max_sesb = na
var float min_sesb = na
var float max_sesc = na
var float min_sesc = na
var float max_sesd = na
var float min_sesd = na

//Ranges
if show_sesa and sesa_range and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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

if show_sesb and sesb_range and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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_sesb, sesb_txt, sesb_css)
    max_sesb := max
    min_sesb := min

//Trendlines
//Mean
if show_sesa and sesa_avg and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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)

if show_sesb and sesb_avg and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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_sesb)
    set_line(is_sesb, avg, avg, sesb_css)

//VWAP
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot max/min
plot(showSessions and sesa_maxmin and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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(showSessions and sesb_maxmin and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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_sesb : na, 'Session B Maximum', sesb_css, 1, plot.style_linebr, editable = false)
plot(showSessions and sesb_maxmin and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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_sesb : na, 'Session B Minimum', sesb_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)

plotshape(is_sesa != is_sesa[1] and show_ses_div and show_sesa and showSessions, "NYE"
  , shape.labelup
  , 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

if (candleColorType != 'Confirmation Simple')
    macdFastLength := 10
    macdSlowLength := 25
    macdSignalLength:=8

[MacdX, signalX, histX] = ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)

//candle color scheme
greenHigh = #4ce653
greenMidHigh =#4ce653
greenMidLow =#4ce653
greenLow = #56328f

// Yellow
yellowLow = #56328f

// 4 level of red
redHigh = #ff0000
redMidHigh = #ff0000
redMidLow = #ff0000
redLow = #56328f

if (candleColorType == 'Confirmation Gradient')
    greenHigh := #01d70c
    greenMidHigh := #269444
    greenMidLow :=#4f966c
    greenLow := #425970

    // 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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

barcolor(candleColorType == 'None' ? na : candleBody, editable = false)

// # ============================[SMART TRAIL]============================ #
[smartTrailLine, fillerLine, smartTrailDirection] = LAF.getSmartTrail(10, 4, 8)
smartTrail1 = plot(smartTrail and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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 title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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|]============================ #

trendStrengthMetric = math.abs(LAF.getTrendStrengthMetric(14, 'RMA', 21, 'EMA'))
trendStrengthMetric := trendStrengthMetric*2.5
trendIndication = trendStrengthMetric > 30 and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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' ? "🔥" : "❄️"
trendStrengthCellColor = newTrendCatcherColor == #02ff65 ? dashboardGreenBackground : dashboardRedBackground
trendStrengthTextColor = trendStrengthCellColor == dashboardGreenBackground ? dashboardGreenText : dashboardRedText

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

squeezeMetric = LAF.getSqueezeMetric(45, 20)
squeezeIsHigh = squeezeMetric >= 80 ? true : false
squeezeCellColor = trendTracerDirection == #02ff65 ? #1a3a3e : #482632
squeezeTextColor = trendTracerDirection != #02ff65 ? #ed3544 : #0a907a
//  and title == 'AlgoPoint' and subtitle == 'All Leaked Algos \n Instagram: algopoint \n Website: algopoint.mysellix.io' 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'
//
[uV, dV] = f_calcV()

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


table_position = dashboardLocation == 'Bottom Left' ? position.bottom_left 
  : dashboardLocation == 'Top Right' ? position.top_right 
  : position.bottom_right

table_size = dashboardSize == 'Tiny' ? size.tiny 
  : dashboardSize == 'Small' ? size.small 
  : size.normal

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)

        tb.cell(1, 2, autopilotMode, text_color = color.white, text_size = table_size)
        tb.cell(1, 3, str.tostring(trendStrengthMetric, format.percent), text_color=trendStrengthTextColor, text_size=table_size, bgcolor = trendStrengthCellColor)
        tb.cell(1, 4, volatilityText, text_color = VolatilityTextColor, text_size = table_size, bgcolor = volatilityCellColor)
        tb.cell(1, 5, str.tostring(squeezeMetric, format.percent), text_color= squeezeTextColor, text_size=table_size, bgcolor = squeezeCellColor)
        tb.cell(1, 6, str.tostring(math.min(volumeSentiment, 100.), format.percent), text_color = volumeTextColor, text_size = table_size, bgcolor = volumeCellColor)





//************************************************************************************************************
// 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

    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

    z

//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
    v_condition = 0
    v_meanline = source
    v_meanrange = supersmoother(ta.tr, length)

    //-- Get Line value
    if type == 'SuperSmoother'
        v_meanline := supersmoother(source, length)
        v_meanline

    if type != 'SuperSmoother'
        v_meanline := SAK_smoothing(type, source, length)
        v_meanline

    v_upband1 = v_meanline + v_meanrange * mult
    v_loband1 = v_meanline - v_meanrange * mult
    v_upband2 = v_meanline + v_meanrange * mult2
    v_loband2 = v_meanline - v_meanrange * mult2

    //-- Check Condition
    if close > v_meanline
        v_upband2_1 = v_upband2 + v_meanrange * gradsize * 4
        v_upband2_9 = v_upband2 + v_meanrange * gradsize * -4
        if high >= v_upband2_9 and high < v_upband2
            v_condition := 1
            v_condition
        else if high >= v_upband2 and high < v_upband2_1
            v_condition := 2
            v_condition
        else if high >= v_upband2_1
            v_condition := 3
            v_condition
        else if close <= v_meanline + v_meanrange
            v_condition := 4
            v_condition
        else
            v_condition := 5
            v_condition

    if close < v_meanline
        v_loband2_1 = v_loband2 - v_meanrange * gradsize * 4
        v_loband2_9 = v_loband2 - v_meanrange * gradsize * -4
        if low <= v_loband2_9 and low > v_loband2
            v_condition := -1
            v_condition
        else if low <= v_loband2 and low > v_loband2_1
            v_condition := -2
            v_condition
        else if low <= v_loband2_1
            v_condition := -3
            v_condition
        else if close >= v_meanline + v_meanrange
            v_condition := -4
            v_condition
        else
            v_condition := -5
            v_condition

    [v_meanline, v_meanrange, v_upband1, v_loband1, v_upband2, v_loband2, v_condition]

//-----------------------
// 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

f_PriceLine(_ref, linecol) =>
    line.new(x1=bar_index, x2=bar_index - 1, y1=_ref, y2=_ref, extend=extend.left, color=linecol)

f_MTFLabel(_txt, _yloc) =>
    label.new(x=time + math.round(ta.change(time) * 20), y=_yloc, xloc=xloc.bar_time, text=mtf_disp_typ == 'Always Display' ? _txt : 'Check MTF', tooltip=mtf_disp_typ == 'Always Display' ? '' : _txt, color=color.black, textcolor=color.white, size=size.normal, style=mtf_disp_typ == 'On Hover' and displayline ? label.style_label_lower_left : label.style_label_left, textalign=text.align_left)

//} Function End

//************************************************************************************************************
// 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

//z = plot(p_meanline, color=color.new(#FFCD00, 0), style=plot.style_line, title=' Mean', linewidth=2)
//x1 = plot(p_upband1, color=color.new(color.green, 50), style=plot.style_circles, title=' R1', linewidth=1)
//x2 = plot(p_loband1, color=color.new(color.green, 50), style=plot.style_circles, title=' S1', linewidth=1)
//y1 = plot(p_upband2, color=color.new(color.red, 50), style=plot.style_line, title=' R2', linewidth=1)
//y2 = plot(p_loband2, color=color.new(color.red, 50), style=plot.style_line, title=' S2', linewidth=1)

//-----------------------
// 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
table.cell(textstylist, 0, 0, title, width, height, c_title, a_title, text_size=s_title, bgcolor=c_bg)
up1 = plot(reversalZone ? upband2_1 : na, color = color.black, transp = 100, editable = false)
up2 = plot(reversalZone ?upband2_5:na, color = color.black, transp = 100, editable = false)
up3 = plot(reversalZone ?upband2_9:na, color = color.black, transp = 100, editable = false)
dp1 = plot(reversalZone ?loband2_1:na, color = color.black, transp = 100, editable = false)
dp2 = plot(reversalZone ?loband2_5:na, color = color.black, transp = 100, editable = false)
dp3 = plot(reversalZone ?loband2_9:na, color = color.black, transp = 100, editable = false)

fill(up1, up2, color = #56202d, transp = 20, editable = false)
fill(up2, up3, color = #3f1d29, transp = 60, editable = false)
fill(dp1, dp2, color = #0f3e3f, transp = 20, editable = false)
fill(dp2, dp3, color = #113135, transp = 60, editable = false)

//[upband2_1, upband2_5, upband2_9, loband2_1, loband2_5, loband2_9]
tenkan_len  = 365
tenkan_mult = 3


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(neoCloud ? tenkan : na,'Tenkan-Sen',tenkan_css, editable = false)
plot(neoCloud ? kijun : na,'Kijun-Sen',kijun_css, editable = false)


plot(neoCloud and ta.crossover(tenkan,kijun) ? kijun : na,'Crossover',#2156f300,3,plot.style_circles, editable = false)
plot(neoCloud and ta.crossunder(tenkan,kijun) ? kijun : na,'Crossunder',#ff5e0000,3,plot.style_circles, editable = false)


A = plot(neoCloud ? senkouA: na,'Senkou Span A',na,offset=offset-1, editable = false)
B = plot(neoCloud ? senkouB : na,'Senkou Span B',na,offset=offset-1, editable = false)
fill(A,B,senkouA > senkouB ? cloud_a : cloud_b)

lastNeo = int(senkouA + senkouB)
last5Neo = ta.sma(lastNeo, 2)




plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none, editable = false)





// Wylicz pozycję kwadratu
ltp1 = bar_index 
rtp1 = bar_index + 40

[lowBound, midBound, highBound] = LAF.getTPSLBoxes(6.0)

// Stwórz rzeczywisty kwadrat
//tp1box = box.new(left=ltp1, top=ttp1, right=rtp1, bottom=btp1, border_color=#3666f5, border_width=2, border_style=line.style_solid, bgcolor=color.new(#3666f5, 53), text="TP1 :   " + str.tostring(close), text_size=size.large, text_color=color.new(#3666f5, 0), text_wrap=text.wrap_auto)
//var boxes = array.new<box>()
//boxes.push(box.new(left = ltp1, top = close+highBound, right = rtp1, bottom = close + midBound, border_color=#3666f5, border_width=2, border_style=line.style_solid, bgcolor=color.new(#3666f5, 70), text="TP/SL 2 :   " + str.tostring(close), text_size=size.large, text_color=color.new(#3666f5, 0), text_wrap=text.wrap_auto))
//boxes.push(box.new(left = ltp1, top = close+midBound, right = rtp1, bottom = close + lowBound, border_color=#3666f5, border_width=2, border_style=line.style_solid, bgcolor=color.new(#3666f5, 40), text="TP/SL 1 :   " + str.tostring(close), text_size=size.large, text_color=color.new(#3666f5, 0), text_wrap=text.wrap_auto))

//SL1 = box.new(left = ltp1, top = close-highBound, right = rtp1, bottom = close - midBound, border_color=#3666f5, border_width=2, border_style=line.style_solid, bgcolor=color.new(#3666f5, 70), text="TP/SL 2 :   " + str.tostring(close), text_size=size.large, text_color=color.new(#3666f5, 0), text_wrap=text.wrap_auto)
//SL2 = box.new(left = ltp1, top = close-midBound, right = rtp1, bottom = close - lowBound, border_color=#3666f5, border_width=2, border_style=line.style_solid, bgcolor=color.new(#3666f5, 40), text="TP/SL 1 :   " + str.tostring(close), text_size=size.large, text_color=color.new(#3666f5, 0), text_wrap=text.wrap_auto)


// Usuń poprzednie ramki
//box.delete(boxes.shift())
//box.delete(SL1[1])
//box.delete(SL2[1])

//box.delete(boxes.shift())


// ==== Overview ====
// ==================

// WaveTrend 3D (WT3D) is a novel implementation of the famous WaveTrend (WT) indicator and has been completely redesigned from the ground up to address some 
// of the inherent shortcomings associated with the traditional WT algorithm, including:
// (1) unbounded extremes
// (2) susceptibility to whipsaw
// (3) lack of insight into other timeframes

// Furthermore, WT3D expands upon the original functionality of WT by providing: 
// (1) first-class support for multi-timeframe (MTF) analysis
// (2) kernel-based regression for trend reversal confirmation
// (3) various options for signal smoothing and transformation
// (4) a unique mode for visualizing an input series as a symmetrical, three-dimensional waveform useful for pattern identification and cycle-related analysis

// 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

// Transparencies and Gradients
areaBackgroundTrans = 128.
areaForegroundTrans = 64.
lineBackgroundTrans = 2.6
lineForegroundTrans = 2.
customTransparency = 30
maxStepsForGradient = 8

// 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

lineBackgroundTrans := lineBackgroundTrans * customTransparency
areaBackgroundTrans := areaBackgroundTrans * customTransparency
lineForegroundTrans := lineForegroundTrans * customTransparency
areaForegroundTrans := areaForegroundTrans * customTransparency

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 =====
// =================================

getPlotColor(signal, bullColor, bearColor) =>
    signal >= 0.0 ? bullColor : bearColor

getAreaColor(signal, useMomentum, bullColor, bearColor) =>
    if useMomentum
        ta.rising(signal, 1) ? bullColor : bearColor
    else
        signal >= 0.0 ? bullColor : bearColor

getColorGradientFromSteps(_source, _center, _steps, weakColor, strongColor) =>
    var float _qtyAdvDec = 0.
    var float _maxSteps = math.max(1, _steps)
    bool _xUp = ta.crossover(_source, _center)
    bool _xDn = ta.crossunder(_source, _center)
    float _chg = ta.change(_source)
    bool _up = _chg > 0
    bool _dn = _chg < 0
    bool _srcBull = _source > _center
    bool _srcBear = _source < _center
    _qtyAdvDec := _srcBull ? _xUp ? 1 : _up ? math.min(_maxSteps, _qtyAdvDec + 1) : _dn ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _srcBear ? _xDn ? 1 : _dn ? math.min(_maxSteps, _qtyAdvDec + 1) : _up ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _qtyAdvDec      
    color colorGradient = color.from_gradient(_qtyAdvDec, 1, _maxSteps, weakColor, strongColor)
    colorGradient

getColorGradientFromSource(series, _min, _max, weakColor, strongColor) =>
    var float baseLineSeries = _min + (_max - _min) / 2
    color colorGradient = series >= baseLineSeries ? color.from_gradient(value=series, bottom_value=baseLineSeries, top_value=_max, bottom_color=weakColor, top_color=strongColor) : color.from_gradient(series, _min, baseLineSeries, strongColor, weakColor)
    colorGradient

// ================================
// ==== Main Helper Functions =====
// ================================

normalizeDeriv(_src, _quadraticMeanLength) =>
    float derivative = _src - _src[2]
    quadraticMean = math.sqrt(nz(math.sum(math.pow(derivative, 2), _quadraticMeanLength) / _quadraticMeanLength))
    derivative/quadraticMean

tanh(series float _src) =>
    -1 + 2/(1 + math.exp(-2*_src))

dualPoleFilter(float _src, float _lookback) =>
    float _omega = -99 * math.pi / (70 * _lookback)
    float _alpha = math.exp(_omega)
    float _beta = -math.pow(_alpha, 2)
    float _gamma = math.cos(_omega) * 2 * _alpha
    float _delta = 1 - _gamma - _beta
    float _slidingAvg = 0.5 * (_src + nz(_src[1], _src))
    float _filter = na
    _filter := (_delta*_slidingAvg) + _gamma*nz(_filter[1]) + _beta*nz(_filter[2])
    _filter

getOscillator(float src, float smoothingFrequency, int quadraticMeanLength) =>   
    nDeriv = normalizeDeriv(src, quadraticMeanLength)
    hyperbolicTangent = tanh(nDeriv)
    result = dualPoleFilter(hyperbolicTangent, smoothingFrequency)

// =================================
// ==== Oscillator Calculations ====
// =================================

// Fast Oscillator + Mirror
offsetFast = offset
f_lookback = f_smoothing * oscillatorLookback
signalFast = getOscillator(src, f_lookback, quadraticMeanLength)
seriesFast = f_length*signalFast+offsetFast
seriesFastMirror = useMirror ? -seriesFast + 2*offsetFast : na

// Normal Oscillator + Mirror
offsetNormal = 0
n_lookback = n_smoothing * oscillatorLookback
signalNormal = getOscillator(src, n_lookback, quadraticMeanLength)
seriesNormal = n_length*signalNormal+offsetNormal
seriesNormalMirror = useMirror ? -seriesNormal + 2*offsetNormal : na

// Slow Oscillator + Mirror
offsetSlow = -offset
s_lookback = s_smoothing * oscillatorLookback
signalSlow = getOscillator(src, s_lookback, quadraticMeanLength)
seriesSlow = s_length*signalSlow+offsetSlow
seriesSlowMirror = useMirror ? -seriesSlow + 2*offsetSlow : na

// =====================================
// ==== Color Gradient Calculations ====
// =====================================

// Fast Color Gradients (Areas and Lines)
fastBaseColor = getPlotColor(signalFast, fastBullishColor, fastBearishColor)
fastBaseColorInverse = getPlotColor(signalFast, fastBearishColor, fastBullishColor)
fastAreaGradientFromSource = getColorGradientFromSource(seriesFast, -1.+offsetFast, 1+offsetFast, color.new(fastBaseColor, areaFastTrans), fastBaseColor)
fastAreaGradientFromSteps = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColor, areaFastTrans), fastBaseColor)
fastLineGradientFromSource = getColorGradientFromSource(seriesFast, -1+offsetFast, 1+offsetFast, color.new(fastBaseColor, lineFastTrans), fastBaseColor)
fastLineGradientFromSteps = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColor, lineFastTrans), fastBaseColor)
fastAreaGradientFromSourceInverse = getColorGradientFromSource(seriesFast, -1.+offsetFast, 1+offsetFast, color.new(fastBaseColorInverse, areaFastTrans), fastBaseColorInverse)
fastAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesFast, offsetFast, maxStepsForGradient, color.new(fastBaseColorInverse, areaFastTrans), fastBaseColorInverse)

// Normal Color Gradients (Areas and Lines)
normalBaseColor = getPlotColor(signalNormal, normalBullishColor, normalBearishColor)
normalBaseColorInverse = getPlotColor(signalNormal, normalBearishColor, normalBullishColor)
normalAreaGradientFromSource = getColorGradientFromSource(seriesNormal, -1.+offsetNormal, 1.+offsetNormal, color.new(normalBaseColor, areaNormalTrans), normalBaseColor)
normalAreaGradientFromSteps = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColor, areaNormalTrans), normalBaseColor)
normalLineGradientFromSource = getColorGradientFromSource(seriesNormal, -1+offsetNormal, 1+offsetNormal, color.new(normalBaseColor, lineNormalTrans), normalBaseColor)
normalLineGradientFromSteps = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColor, lineNormalTrans), normalBaseColor)
normalAreaGradientFromSourceInverse = getColorGradientFromSource(seriesNormal, -1.+offsetNormal, 1.+offsetNormal, color.new(normalBaseColorInverse, areaNormalTrans), normalBaseColorInverse)
normalAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesNormal, offsetNormal, maxStepsForGradient, color.new(normalBaseColorInverse, areaNormalTrans), normalBaseColorInverse)

// Slow Color Gradients (Areas and Lines)
slowBaseColor = getPlotColor(signalSlow, slowBullishColor, slowBearishColor)
slowBaseColorInverse = getPlotColor(signalSlow, slowBearishColor, slowBullishColor)
slowAreaGradientFromSource = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColor, areaSlowTrans), slowBaseColor)
slowAreaGradientFromSteps = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColor, areaSlowTrans), slowBaseColor)
slowLineGradientFromSource = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColor, lineSlowTrans), slowBaseColor)
slowLineGradientFromSteps = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColor, lineSlowTrans), slowBaseColor)
slowAreaGradientFromSourceInverse = getColorGradientFromSource(seriesSlow, -1.75+offsetSlow, 1.75+offsetSlow, color.new(slowBaseColorInverse, areaSlowTrans), slowBaseColorInverse)
slowAreaGradientFromStepsInverse = getColorGradientFromSteps(seriesSlow, offsetSlow, maxStepsForGradient, color.new(slowBaseColorInverse, areaSlowTrans), slowBaseColorInverse)

// =========================================
// ==== 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

// Speed Related Switches
seriesEmphasis = switch
    isFast => seriesFast
    isNormal => seriesNormal
    isSlow => seriesSlow
    => na
//
colorLineEmphasis = switch
    isFast => fastLineGradientFromSource
    isNormal => normalLineGradientFromSource
    isSlow => slowLineGradientFromSource
    => 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)

// Last Crossover Values
lastBearishCrossValue = ta.valuewhen(condition=bearishCross, source=seriesNormal, occurrence=1)
lastBullishCrossValue = ta.valuewhen(condition=bullishCross , source=seriesNormal, occurrence=1)

// Trigger Wave Size Comparison
triggerWaveFactor = sizePercent/100
isSmallerBearishCross = bearishCross and seriesNormal < lastBearishCrossValue * triggerWaveFactor
isSmallerBullishCross = bullishCross and seriesNormal > lastBullishCrossValue * triggerWaveFactor

// ===========================
// ==== Kernel Estimators ====
// ===========================

// The following kernel estimators are based on the Gaussian Kernel.

// They are used for:
//     (1) Confirming directional changes in the slow oscillator (i.e. a type of trend filter)
//     (2) Visualizing directional changes as a dynamic ribbon (i.e. an additional oscillator that can crossover with the user specified oscillator of interest)
//     (3) Visualizing transient directional changes while in the midst of a larger uptrend or downtrend (i.e. via color changes on the ribbon)

// Gaussian Kernel with a lookback of 6 bars, starting on bar 6 of the chart (medium fit)
yhat0 = kernels.gaussian(seriesEmphasis, 6, 6) 

// 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)

if (autopilotMode == "Short Term")
    minMult:=1
    maxMult := 4
if (autopilotMode == 'Mid Term')
    minMult := 5
    maxMult := 10
if (autopilotMode == 'Long-Term')
    minMult :=8
    maxMult :=13


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

amaBearCss = color.new(color.red, 50)
amaBullCss = color.new(color.teal, 50)

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)

//Populate supertrend type array
if barstate.isfirst
    for i = 0 to int((maxMult - minMult) / step)
        factors.push(minMult + i * step)
        holder.push(supertrend.new())

atr = ta.atr(length)

//Compute Supertrend for multiple factors
k = 0
for factor in factors
    get_spt = holder.get(k)

    up = hl2 + atr * factor
    dn = hl2 - atr * factor
    
    get_spt.trend := close > get_spt.upper ? 1 : close < get_spt.lower ? 0 : get_spt.trend
    get_spt.upper := close[1] < get_spt.upper ? math.min(up, get_spt.upper) : up
    get_spt.lower := close[1] > get_spt.lower ? math.max(dn, get_spt.lower) : dn
    
    diff = nz(math.sign(close[1] - get_spt.output))
    get_spt.perf += 2/(perfAlpha+1) * (nz(close - close[1]) * diff - get_spt.perf)
    get_spt.output := get_spt.trend == 1 ? get_spt.lower : get_spt.upper
    get_spt.factor := factor
    k += 1

//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
factor_array = array.new<float>(0)
data = array.new<float>(0)
table.cell(textstylist, 0, 1, subtitle, width, height, c_subtitle, a_subtitle, text_size=s_subtitle, bgcolor=c_bg)
//Populate data arrays
if last_bar_index - bar_index <= maxData
    for element in holder
        data.push(element.perf)
        factor_array.push(element.factor)

//Intitalize centroids using quartiles
centroids = array.new<float>(0)
centroids.push(data.percentile_linear_interpolation(25))
centroids.push(data.percentile_linear_interpolation(50))
centroids.push(data.percentile_linear_interpolation(75))

//Intialize clusters
var array<vector> factors_clusters = na
var array<vector> perfclusters = na

if last_bar_index - bar_index <= maxData
    for _ = 0 to maxIter
        factors_clusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
        perfclusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
        
        //Assign value to cluster
        i = 0
        for value in data
            dist = array.new<float>(0)
            for centroid in centroids
                dist.push(math.abs(value - centroid))

            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())

        //Test if centroid changed
        if new_centroids.get(0) == centroids.get(0) and new_centroids.get(1) == centroids.get(1) and new_centroids.get(2) == centroids.get(2)
            break

        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

var from = switch fromCluster
    'Best' => 2
    'Average' => 1
    'Worst' => 0

//Performance index denominator
den = ta.ema(math.abs(close - close[1]), int(perfAlpha))

if not na(perfclusters)
    //Get average factors within target cluster 
    target_factor := nz(factors_clusters.get(from).out.avg(), target_factor)
    
    //Get performance index of target cluster 
    perf_idx := math.max(nz(perfclusters.get(from).out.avg()), 0) / den

//Get new supertrend
var upper = hl2
var lower = hl2
var os = 0

up = hl2 + atr * target_factor
dn = hl2 - atr * target_factor
upper := close[1] < upper ? math.min(up, upper) : up
lower := close[1] > lower ? math.max(dn, lower) : dn
os := close > upper ? 1 : close < lower ? 0 : os
ts = os ? lower : upper

//Get trailing stop adaptive MA
if na(ts[1]) and not na(ts)
    perf_ama := ts
else
    perf_ama += perf_idx * (ts - perf_ama)

//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{

//-----------------------------------------------------------------------------{
css = os ? bullCss : bearCss

plot(showTrailingStoploss ? ts : na, 'Trailing Stop', os != os[1] ? na : css, editable = false)

plot(showMovingAverage? perf_ama:na, 'Trailing Stop AMA',
  ta.cross(close, perf_ama) ? na
  : close > perf_ama ? amaBullCss : amaBearCss, editable = false)

//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

    if os < os[1] and (signalPresets != "Smart Trail [Filter]" or smartTrailDirection == 'short') 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, high+ta.atr(30)/2, signalClassifier ? str.tostring(signalStrength) : ema50 < ema200 ? "▼+" : "▼"
          , color = bearCss
          , style = label.style_label_down
          , 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) 

//plotchar(bullishCross and position == 1, "Long", "▲", location.belowbar, color = c_bullish, size = size.tiny)
plotchar(bullishCross and position == -1, "Long", "✖", location.belowbar, color = #ff7322, size = size.tiny, editable = false)
//plotchar(isBullishTriggerWave and position == 1, "Long", "▲", location.belowbar, color=c_bullish, size = size.small)
plotchar(isBullishTriggerWave and position == -1, "Long", "✖", location.belowbar, color=#ff7322, size = size.tiny, editable = false)


// Shit
atrMultiplier = input(2, title="ATR Multiplier")
boxHeightInAtr = atrMultiplier * ta.atr(10)

// Box TP 1

[lowb, midb, highb] = LAF.getTPSLBoxes(6.0)

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)

    line.set_xy1(tpb, bar_index[50], bottom_tp1)
    line.set_xy2(tpb, bar_index + 200, bottom_tp1)
    line.delete(tpb[1])
    // Line tp top
    var line tp2Line = na

    if (isLastBar)
        tp2Line := line.new(na, top_tp2, na, top_tp2, color=color.new(#3666f5, 0), width=2, style=line.style_dashed)

    line.set_xy1(tp2Line, bar_index[50], top_tp2)
    line.set_xy2(tp2Line, bar_index + 200, top_tp2)
    line.delete(tp2Line[1])

    // 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)

    line.set_xy1(slLine, bar_index[50], bottom_sl)
    line.set_xy2(slLine, bar_index + 400, bottom_sl)
    line.delete(slLine[1])
    // Line SL2
    var line sl2Line = na

    if (isLastBar)
        sl2Line := line.new(na, bottom_sl2, na, bottom_sl2, color=color.new(color.red, 0), width=2, style=line.style_dashed)

    line.set_xy1(sl2Line, bar_index[50], bottom_sl2)
    line.set_xy2(sl2Line, bar_index + 200, bottom_sl2)
    line.delete(sl2Line[1])
Leave a Comment