0% found this document useful (0 votes)
759 views

Signals & Overlays

Algo

Uploaded by

pijolo4593
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
759 views

Signals & Overlays

Algo

Uploaded by

pijolo4593
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 30

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.

0
at https://mozilla.org/MPL/2.0/
// © deven0

//@version=5
indicator("Signals & Overlays™", overlay = true, max_labels_count = 500)

//Import libraries
import achirameegasthanne/LuxFunction/18 as LAF
import deven0/KernelFunction/1 as kernels

// # ============================[GET USERS INPUT]============================ #//


groupBasic = "BASIC SETTINGS"
showSignals = input(true, "Show Signals", inline = "1", group = groupBasic, tooltip
= "Enables or disables the signals",display = display.none)
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,display =
display.none)
signalMode = input.string("Confirmation + Exits", "Signal Mode", ["Confirmation +
Exits", "Contrarian + Exits", "None"],tooltip = "Changes the Mode of the
signals" ,group = groupBasic,display = display.none)
signalClassifier = input(false,"AI Signal Classifer",tooltip = "Shows signal
quality from 1-4 on signals" ,group = groupBasic,display = display.none)
sensitivity = input.float(12, "Signal Sensitivity ", minval = 1, maxval =
50,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,display = display.none)
atrLength = input.int(10, "Signal Tuner ", minval = 1, maxval = 50,step=1,tooltip
= "Alows you to tune your signals, the higher the number the more refined but
laggier the signal" ,group = groupBasic,display = display.none)
candleColorType = input.string("Confirmation Simple", "Candle Coloring",
["Confirmation Simple","Confirmation Gradient","Contrarian
Gradient","None"],tooltip = "Changes the type of signal coloring", group =
groupBasic,display = display.none)

// Indicator Overlay Settings


groupOverlay = "INDICATOR OVERLAY"
smartTrail = input(true, "Smart Trail ", inline = "1", group =
groupOverlay,display = display.none)
smartTrailValue = input.float(4, "", inline = "1", group = groupOverlay,display
= display.none)
reversalZone = input(false, "Reversal Zones", inline = "2", group =
groupOverlay,display = display.none)
reversalZoneValue = input.float(1, "", inline = "2", group = groupOverlay,display
= display.none)
trendCatcher = input(false, "Trend Catcher ", inline = "3", group =
groupOverlay,display = display.none)
trendCatcherValue = input.int(3, "", inline = "3", group = groupOverlay,display =
display.none)
trendTracer = input(false, "Trend Tracer ", inline = "4", group =
groupOverlay,display = display.none)
trendTracerValue = input.float(3, "", inline = "4", group = groupOverlay,display
= display.none)
neoCloud = input(false, "Neo Cloud ", inline = "5", group =
groupOverlay,display = display.none)
neoCloudValue = input.float(1, "", inline = "5", group = groupOverlay,display
= display.none)

showDashboard = true
showTrailingStoploss = false
showMovingAverage = false
showSessions = false

// Advanced Settings
groupAdvanced = "TAKE PROFITS/STOP LOSSES"
takeProfitBoxes = input.string("None", "TP/SL Points", options=["None","On"],
inline = "2", tooltip = "Shows Take Profit and Stop Loss areas",group =
groupAdvanced,display = display.none)
takeProfitStopLossDistance = input.int(5,"Distance", minval = 1, maxval = 10,
group=groupAdvanced,display = display.none)
TP1 = input.color(color.new(#3666f5, 0),"TP1",group=groupAdvanced,inline =
"3",display = display.none)
TP2 = input.color(color.new(#3666f5, 0),"TP2",group=groupAdvanced,inline =
"3",display = display.none)
SL1 = input.color(color.new(color.red, 0),"SL1",group=groupAdvanced,inline =
"3",display = display.none)
SL2 = input.color(color.new(color.red, 0),"SL2",group=groupAdvanced,inline =
"3",display = display.none)

groupAdvancedSettings = "ADVANCED SETTINGS"


aiclassifier = input.int(1234,"AI Classifier",tooltip = "Sets automatic settings
for signals and improves their quality" ,inline = "1", group =
groupAdvancedSettings,display = display.none)
bullclassifier = input.color(color.green,"",inline = "1", group =
groupAdvancedSettings,display = display.none)
bearclassifier = input.color(color.red,"",inline = "1", group =
groupAdvancedSettings,display = display.none)
autopilotMode = input.string("Off", "Autopilot Sensivity",["Off","Short-Term",
"Mid-Term", "Long-Term"],tooltip = "Sets automatic settings for signals and
improves their quality" ,inline = "2", group = groupAdvancedSettings,display =
display.none)

dashboard = "DASHBOARD"
dashboardLocation = input.string("Bottom Right","Dashboard Location", ["Top
Right","Bottom Right","Bottom Left"], inline = "3",tooltip = "Changes dashboard
positions" ,group = dashboard,display = display.none)
dashboardSize = input.string("Small","Dashboard Size",
["Tiny","Small","Normal","Large"], inline = "4",tooltip = "Changes the size of the
dashboard" ,group = dashboard,display = display.none)
dashboardbg = input.color(#1e222d,"Dashboard Color",tooltip = "Changes the size of
the dashboard" ,group = dashboard,display = display.none)
trendstrength = input.bool(true,"Trend Strength", inline = "5",tooltip = "Changes
the size of the dashboard" ,group = dashboard,display = display.none)
volatility = input.bool(false,"Volatility", inline = "5",tooltip = "Changes the
size of the dashboard" ,group = dashboard,display = display.none)
squeeze = input.bool(false,"Squeeze", inline = "6",tooltip = "Changes the size of
the dashboard" ,group = dashboard,display = display.none)
volumesentiment = input.bool(false,"Volume Sentiment", inline = "6",tooltip =
"Changes the size of the dashboard" ,group = dashboard,display = display.none)

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

// # ============================[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]


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]


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]


num := close * volume
den := volume

else if session and session == session[1]


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]


tl := line.new(n, close, n, close, color = session_css)

if session and session == session[1]


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


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


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


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
[max, min] = get_range(is_sesa, sesa_txt, sesa_css)
max_sesa := max
min_sesa := min

if show_sesb and sesb_range


[max, min] = get_range(is_sesb, sesb_txt, sesb_css)
max_sesb := max
min_sesb := min

//Trendlines
//Mean
if show_sesa and sesa_avg
avg = get_avg(is_sesa)
set_line(is_sesa, avg, avg, sesa_css)

if show_sesb and sesb_avg


avg = get_avg(is_sesb)
set_line(is_sesb, avg, avg, sesb_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(showSessions and sesb_maxmin ? max_sesb : na, 'Session B Maximum', sesb_css,


1, plot.style_linebr, editable = false)
plot(showSessions and sesb_maxmin ? 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 := #30a464
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 := #30a464
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

if histX > histX[1] and MacdX[1] > 0 and histX[1] > 0


candleBody := greenMidHigh

if histX > histX[2] and MacdX[2] > 0 and histX[2] > 0


candleBody := greenHigh

// Bearish trend
if MacdX < 0 and histX < 0
candleBody := redMidLow

if histX < histX[1] and MacdX[1] < 0 and histX[1] < 0


candleBody := redMidHigh

if histX < histX[2] and MacdX[2] < 0 and histX[2] < 0


candleBody := redHigh

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

// # ============================[SMART TRAIL]============================ #
[supert,supert2,smartTrailDirection] = LAF.getSmartTrail(smartTrailValue)
smb = #347cf8
smre = #f7525f
t = plot(smartTrail ?supert:na, color = close > supert ? smb:smre)
tt = plot(smartTrail ?supert2:na, color = color.new(color.black, 100))
fill(t, tt, close > supert?color.new(smb, 80) : color.new(smre, 80))

// # ============================[TREND CATCHER]============================ #
[trendCatcherLine, trendCatcherColor] = LAF.getTrendCatcher(trendCatcherValue)
newTrendCatcherColor = trendCatcherColor == color.blue ? #02ff65 : #ff1100
plot(trendCatcher ? trendCatcherLine : na, title='Trend Catcher', linewidth=2,
color=newTrendCatcherColor, editable = false)

// # ============================[TREND TRACER]============================ #
[trendTracerLine, trendTracerDirection] = LAF.getTrendTracer(trendTracerValue)
plot(trendTracer ? 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 ? ""❄️
: " "
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

[uV, dV] = f_calcV()

totalVolume = uV + math.abs(dV)
volumeCellColor = dashboardRedBackground
volumeTextColor = totalVolume >= 50 ? dashboardGreenText : dashboardRedText
if (totalVolume >= 50)
totalVolume := totalVolume*2
volumeCellColor := dashboardGreenBackground
else
totalVolume := totalVolume*-2

volumeSentiment = totalVolume

// Optimal Sensitivity
color blockColor = na
color textColor = na

knnSensitivity(close, sensitivity, k) =>


data = request.security(syminfo.tickerid, "D", close)
input_data = ta.sma(data, 20)
distance = math.abs(close - input_data)
array_size = 100
distance_array = array.new_float(size = array_size)
array.set(distance_array, 0, distance)
array.sort(distance_array)
lowest_distance = array.min(distance_array, k)
avg_distance = ta.sma(lowest_distance, k)
knn_sensitivity = avg_distance / ta.atr(14)
knn_sensitivity_bounded = knn_sensitivity > 26 ? 26 : (knn_sensitivity < 1 ?
1 : knn_sensitivity)
sensitivity_diff = knn_sensitivity_bounded - sensitivity
step_size = 0.1
knn_sensitivity_adjusted = math.abs(sensitivity_diff) > 4 ? (sensitivity +
step_size * sensitivity_diff) : knn_sensitivity_bounded
knn_sensitivity_adjusted

optimal_sensitivity = knnSensitivity(close, sensitivity, 5)


_sensitivity = ta.crossover(close, ta.sma(close, 13)) ? sensitivity :
optimal_sensitivity

final_sensitivity = autopilotMode == "Off" ? sensitivity : autopilotMode == "Short-


Term" ? sensitivity - 1 : autopilotMode == "Mid-Term" ? sensitivity : autopilotMode
== "Long-Term" ? sensitivity + 1 : sensitivity

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 = dashboardbg
, 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)
if(trendstrength)
tb.cell(0, 3, str.tostring(trendIndication) + "Trend Strength",
text_color = color.white, text_size = table_size, text_halign = text.align_left)
if(volatility)
tb.cell(0, 4, volatilityEmoji+ " Volatility", text_color = color.white,
text_size = table_size, text_halign = text.align_left)
if(squeeze)
tb.cell(0, 5, "🔃 Squeeze", text_color = color.white, text_size =
table_size, text_halign = text.align_left)
if(volumesentiment)
tb.cell(0, 6, "💧 Volume Sentiment", text_color = color.white, text_size
= table_size, text_halign = text.align_left)

tb.cell(1, 2, str.tostring(math.round(final_sensitivity,0)), text_color =


trendStrengthTextColor, text_size = table_size,bgcolor = trendStrengthCellColor)
if(trendstrength)
tb.cell(1, 3, str.tostring(trendStrengthMetric, format.percent),
text_color=trendStrengthTextColor, text_size=table_size, bgcolor =
trendStrengthCellColor)
if(volatility)
tb.cell(1, 4, volatilityText, text_color = VolatilityTextColor,
text_size = table_size, bgcolor = volatilityCellColor)
if(squeeze)
tb.cell(1, 5, str.tostring(squeezeMetric, format.percent), text_color=
squeezeTextColor, text_size=table_size, bgcolor = squeezeCellColor)
if(volumesentiment)
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 * reversalZoneValue
var mult2 = pi * outermult * reversalZoneValue
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)

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

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*neoCloudValue)
kijun = avg(close,kijun_len,kijun_mult*neoCloudValue)

senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult*neoCloudValue)
//------------------------------------------------------------------------------
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)

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

ExitSensitivity = 7

// Oscillator Settings
offset := 0
showOsc = true
showOsc := showOsc
float f_length = 0.75 * ExitSensitivity
float f_smoothing = 0.45 * ExitSensitivity
float n_length = 1.0 * ExitSensitivity
float n_smoothing = 1.0 * ExitSensitivity
float s_length = 1.75 * ExitSensitivity
float s_smoothing = 2.5 * ExitSensitivity

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

// 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
Sensitivity=sensitivity/4

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

float perfAlpha = 10
fromCluster = 'Best'

//Optimization
maxIter = 250
maxData = 2500

//Function
[os,perf_idx,lower,upper] = LAF.getSignalClassification(length, minMult, maxMult,
step, perfAlpha,maxIter,maxData,1)
//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
senkouA > senkouB )
int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :
int(perf_idx*10) < 5 ? 3 : 4
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
senkouA < senkouB )
int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :
int(perf_idx*10) < 5 ? 3 : 4
position := -1

int signalStrength = int(perf_idx*10) < 2 ? 1 : int(perf_idx*10) < 4 ? 2 :


int(perf_idx*10) < 5 ? 3 : 4
buy =showSignals and (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
senkouA > senkouB ))
sell =showSignals and (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 senkouA < senkouB ))

y1 = low - (ta.atr(30) * 2)
y2 = high + (ta.atr(30) * 2)
bull = buy ? label.new(bar_index, y1, signalClassifier ?
str.tostring(signalStrength) : ema50 < ema200 ? "▲+" : "▲", xloc.bar_index,
yloc.price,color.new(#30a464,10), label.style_label_up, color.white, size.normal) :
na
bear = sell ? label.new(bar_index, y2, signalClassifier ?
str.tostring(signalStrength) : ema50 > ema200 ? "▼+" : "▼", xloc.bar_index,
yloc.price, color.new(redHigh,30), label.style_label_down, color.white,
size.normal) : na
// =======================

if buy
blockColor := dashboardGreenBackground
textColor := dashboardGreenText
if sell
blockColor := dashboardRedBackground
textColor := dashboardRedText

plotshape(bearishCross and position == 1, "Long", shape.xcross, location.abovebar,


color = #4774f5, size = size.tiny, editable = false)
plotshape(bullishCross and position == -1, "Long", shape.xcross, location.belowbar,
color = #ff7322, size = size.tiny, editable = false)

// Shit
atrMultiplier = 2
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=TP1, border_width=2,
border_style=line.style_solid, bgcolor=color.new(#3666f5, 55), text="TP/SL 1 : "
+ str.tostring(close+ midb,format.mintick), 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=TP2, border_width=2, border_style=line.style_solid,
bgcolor=color.new(#3666f5, 65), text="TP/SL 2 : " +
str.tostring(close+highb,format.mintick), 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=SL1, border_width=2, border_style=line.style_solid,
bgcolor=color.new(color.red, 66), text="TP/SL 2 : " + str.tostring(close-
lowb,format.mintick), 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=SL2, border_width=2,
border_style=line.style_solid, bgcolor=color.new(color.red, 65), text="TP/SL 1 :
" + str.tostring(close-midb,format.mintick), 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])

//alerts-------
sellalert = 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)
buyalert = 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)
sellstop = bullishCross and position == -1
Strongsellstop = isBullishTriggerWave and position == -1
buystop = bearishCross and position == 1
Strongbuystop = isBearishTriggerWave and position == 1
trendchanged = sellalert or buyalert or sellstop or Strongsellstop or buystop or
Strongbuystop
alertcondition(showSignals and buyalert, "Long", "Long")
alertcondition(showSignals and sellalert, "Short", "Short")
alertcondition(showSignals and (sellalert or buyalert), "Short or Long ", "Short or
Long")
alertcondition(buystop and Strongbuystop, "LongStop", "LongStop")
alertcondition(sellstop and Strongsellstop, "ShortStop", "ShortStop")
alertcondition((buystop and Strongbuystop) or (sellstop and Strongsellstop) ,
"ShortStop or LongStop ", "ShortStop or LongStop")
alertcondition(trendchanged , "Trend Status", "Trend Is Changed")

You might also like