name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Educational: Fill | https://www.tradingview.com/script/6mhxHRNQ-Educational-Fill/ | fikira | https://www.tradingview.com/u/fikira/ | 124 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ fikira
//@version=5
indicator("Educational: Fill", overlay=true)
opt = input.string( '1', title= 'Type colour fill' , options=['1', '2', '1 & 2'] )
c_e = input.int ( 17, title= 'switch colors at ema x' , minval= 1 , maxval= 17 ,
tooltip= 'if close switches above/below the chosen ema \n-> this switches bullish/bearish colour')
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ input length's ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
len1 = input.int ( 5 , title= '', group= 'length ema\'s 1 -> 4' , inline= '1', minval= 1)
len2 = input.int ( 7 , title= '', group= 'length ema\'s 1 -> 4' , inline= '1', minval= 1)
len3 = input.int ( 10 , title= '', group= 'length ema\'s 1 -> 4' , inline= '1', minval= 1)
len4 = input.int ( 14 , title= '', group= 'length ema\'s 1 -> 4' , inline= '1', minval= 1)
len5 = input.int ( 20 , title= '', group= 'length ema\'s 5 -> 8' , inline= '2', minval= 1)
len6 = input.int ( 27 , title= '', group= 'length ema\'s 5 -> 8' , inline= '2', minval= 1)
len7 = input.int ( 35 , title= '', group= 'length ema\'s 5 -> 8' , inline= '2', minval= 1)
len8 = input.int ( 44 , title= '', group= 'length ema\'s 5 -> 8' , inline= '2', minval= 1)
len9 = input.int ( 50 , title= '', group= 'length ema\'s 9 -> 12' , inline= '3', minval= 1)
len10 = input.int ( 65 , title= '', group= 'length ema\'s 9 -> 12' , inline= '3', minval= 1)
len11 = input.int ( 75 , title= '', group= 'length ema\'s 9 -> 12' , inline= '3', minval= 1)
len12 = input.int ( 89 , title= '', group= 'length ema\'s 9 -> 12' , inline= '3', minval= 1)
len13 = input.int ( 100 , title= '', group= 'length ema\'s 13 -> 17', inline= '4', minval= 1)
len14 = input.int ( 111 , title= '', group= 'length ema\'s 13 -> 17', inline= '4', minval= 1)
len15 = input.int ( 131 , title= '', group= 'length ema\'s 13 -> 17', inline= '4', minval= 1)
len16 = input.int ( 150 , title= '', group= 'length ema\'s 13 -> 17', inline= '4', minval= 1)
len17 = input.int ( 200 , title= '', group= 'length ema\'s 13 -> 17', inline= '4', minval= 1)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ input colours ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
i_colUp1 = input.color (color.rgb( 0, 255, 38, 25), title= '', group='Fill 1 Up' , inline='1' )
i_colUp2 = input.color (color.rgb(255, 0, 0, 0), title= '', group='Fill 1 Up' , inline='1' )
i_colDn1 = input.color (color.rgb( 0, 47, 255, 25), title= '', group='Fill 1 Down' , inline='2' )
i_colDn2 = input.color (color.rgb(255, 0, 0, 1), title= '', group='Fill 1 Down' , inline='2' )
i_colUpa = input.color (color.rgb( 8, 0, 255, 25), title= '', group='Fill 2 Up' , inline='1' )
i_colUpb = input.color (color.rgb( 38, 255, 0, 25), title= '', group='Fill 2 Up' , inline='1' )
i_colDna = input.color (color.rgb(255, 0, 0, 25), title= '', group='Fill 2 Down' , inline='2' )
i_colDnb = input.color (color.rgb(255, 238, 88, 25), title= '', group='Fill 2 Down' , inline='2' )
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ ema's ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ema1 = ta.ema(close, len1 ), ema2 = ta.ema(close, len2 ), ema3 = ta.ema(close, len3 ), ema4 = ta.ema(close, len4 )
ema5 = ta.ema(close, len5 ), ema6 = ta.ema(close, len6 ), ema7 = ta.ema(close, len7 ), ema8 = ta.ema(close, len8 )
ema9 = ta.ema(close, len9 ), ema10 = ta.ema(close, len10), ema11 = ta.ema(close, len11), ema12 = ta.ema(close, len12)
ema13 = ta.ema(close, len13), ema14 = ta.ema(close, len14), ema15 = ta.ema(close, len15), ema16 = ta.ema(close, len16)
ema17 = ta.ema(close, len17)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ Put values in array's and sort ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
arr = array.from(close, ema1, ema2, ema3, ema4, ema5, ema6, ema7, ema8, ema9, ema10, ema11, ema12, ema13, ema14, ema15, ema16, ema17)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ Sort array ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
array.sort (arr, order.ascending)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ Plot ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// 'Type colour fill' -> '1' or '1 & 2'
p1 = plot(opt == '1' or opt == '1 & 2' ? array.get(arr, 0) : na, color= na, display= display.data_window)
p2 = plot(opt == '1' or opt == '1 & 2' ? array.get(arr, 17) : na, color= na, display= display.data_window)
// 'Type colour fill' -> '2' or '1 & 2'
pClose = plot(opt == '2' or opt == '1 & 2' ? close : na, color= na, display= display.data_window)
p_ema1 = plot(opt == '2' or opt == '1 & 2' ? ema1 : na, color= na, display= display.data_window)
p_ema2 = plot(opt == '2' or opt == '1 & 2' ? ema2 : na, color= na, display= display.data_window)
p_ema3 = plot(opt == '2' or opt == '1 & 2' ? ema3 : na, color= na, display= display.data_window)
p_ema4 = plot(opt == '2' or opt == '1 & 2' ? ema4 : na, color= na, display= display.data_window)
p_ema5 = plot(opt == '2' or opt == '1 & 2' ? ema5 : na, color= na, display= display.data_window)
p_ema6 = plot(opt == '2' or opt == '1 & 2' ? ema6 : na, color= na, display= display.data_window)
p_ema7 = plot(opt == '2' or opt == '1 & 2' ? ema7 : na, color= na, display= display.data_window)
p_ema8 = plot(opt == '2' or opt == '1 & 2' ? ema8 : na, color= na, display= display.data_window)
p_ema9 = plot(opt == '2' or opt == '1 & 2' ? ema9 : na, color= na, display= display.data_window)
p_ema10 = plot(opt == '2' or opt == '1 & 2' ? ema10 : na, color= na, display= display.data_window)
p_ema11 = plot(opt == '2' or opt == '1 & 2' ? ema11 : na, color= na, display= display.data_window)
p_ema12 = plot(opt == '2' or opt == '1 & 2' ? ema12 : na, color= na, display= display.data_window)
p_ema13 = plot(opt == '2' or opt == '1 & 2' ? ema13 : na, color= na, display= display.data_window)
p_ema14 = plot(opt == '2' or opt == '1 & 2' ? ema14 : na, color= na, display= display.data_window)
p_ema15 = plot(opt == '2' or opt == '1 & 2' ? ema15 : na, color= na, display= display.data_window)
p_ema16 = plot(opt == '2' or opt == '1 & 2' ? ema16 : na, color= na, display= display.data_window)
p_ema17 = plot(opt == '2' or opt == '1 & 2' ? ema17 : na, color= na, display= display.data_window)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ switch colors at ema x ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
a_ema = array.from(ema1, ema2, ema3, ema4, ema5, ema6, ema7, ema8, ema9, ema10, ema11, ema12, ema13, ema14, ema15, ema16, ema17)
pickEm = array.get(a_ema, c_e -1)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ Colour Fill ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// 'Type colour fill' -> '1' or '1 & 2'
colUp = color.from_gradient(array.get(arr, 2), array.get(arr, 0), array.get(arr, 17), i_colUp1, i_colUp2) // Position array.get(arr, 2) {= 3rd lowest ema} between lowest & highest values
colDn = color.from_gradient(array.get(arr, 15), array.get(arr, 0), array.get(arr, 17), i_colDn1, i_colDn2) // Position array.get(arr, 15) {= 3rd highest ema} between lowest & highest values
col = ema1 > pickEm ? colUp : colDn
// 'Type colour fill' -> '2' or '1 & 2'
pickColor(ema) => color.from_gradient(ema, array.get(arr, 0), array.get(arr, 17), close > pickEm ? i_colUpa : i_colDna, close > pickEm ? i_colUpb : i_colDnb)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[ Fill ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// 'Type colour fill' -> '1' or '1 & 2'
fill(p1, p2, color= col)
// 'Type colour fill' -> '2' or '1 & 2'
fill(pClose , p_ema1 , color= pickColor(close))
fill(p_ema1 , p_ema2 , color= pickColor(ema1 ))
fill(p_ema2 , p_ema3 , color= pickColor(ema2 ))
fill(p_ema3 , p_ema4 , color= pickColor(ema3 ))
fill(p_ema4 , p_ema5 , color= pickColor(ema4 ))
fill(p_ema5 , p_ema6 , color= pickColor(ema5 ))
fill(p_ema6 , p_ema7 , color= pickColor(ema6 ))
fill(p_ema7 , p_ema8 , color= pickColor(ema7 ))
fill(p_ema8 , p_ema9 , color= pickColor(ema8 ))
fill(p_ema9 , p_ema10, color= pickColor(ema9 ))
fill(p_ema10, p_ema11, color= pickColor(ema10))
fill(p_ema11, p_ema12, color= pickColor(ema11))
fill(p_ema12, p_ema13, color= pickColor(ema12))
fill(p_ema13, p_ema14, color= pickColor(ema13))
fill(p_ema14, p_ema15, color= pickColor(ema14))
fill(p_ema15, p_ema16, color= pickColor(ema15))
fill(p_ema16, p_ema17, color= pickColor(ema16))
|
Nearest Neighbor Extrapolation of Price [Loxx] | https://www.tradingview.com/script/PrvbOR2k-Nearest-Neighbor-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 274 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Nearest Neighbor Extrapolation of Price [Loxx]",
shorttitle = "NNEP [Loxx]",
overlay = true,
max_lines_count = 500)
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
_nn(Npast, Nfut, lastbar)=>
xnn = array.new<float>(Npast + Nfut, 0.)
ynn = array.new<float>(Npast + Nfut, 0.)
mx = array.new<float>(Npast - Nfut + 1, 0.)
sx = array.new<float>(Npast - Nfut + 1, 0.)
sxx = array.new<float>(Npast - Nfut + 1, 0.)
denx = array.new<float>(Npast - Nfut + 1, 0.)
sxy = array.new<float>(Npast - Nfut + 1, 0.)
my = 0.0
syy = 0.0
sumx =0.0
sumxx =0.0
sumxxx = 0.
si = Npast * (Npast + 1) / 2
for i = 0 to Npast - 1
y = nz(open[Npast + i + lastbar])
my += y * (i + 1)
syy += y * y * (i + 1)
deny = syy * si - my * my
deny := math.sqrt(deny)
for k = 0 to Npast - Nfut
if (k == 0)
array.set(mx, 0, 0)
array.set(sx, 0, 0)
sumx := 0.0
sumxxx := 0.0
for i = 0 to Npast - 1
x = nz(open[i + lastbar])
xx = x * x
array.set(mx, 0, array.get(mx, 0) + x * (i + 1))
array.set(sxx, 0, array.get(sxx, 0) + xx * (i + 1))
sumx += x
sumxx += xx
else
xnew = nz(open[k + Npast - 1 + lastbar])
xold = nz(open[k - 1 + lastbar])
array.set(mx, k, array.get(mx, k - 1) - sumx + xnew * Npast)
array.set(sxx, k, array.get(sxx, k - 1) - sumxx + xnew * xnew * Npast)
sumx += xnew - xold
sumxx += xnew * xnew - xold * xold
array.set(denx, k, array.get(sxx, k) * si - math.pow(array.get(mx, k), 2))
// Calculation of cross-correlation sums,
// correlation coefficients and finding nearest neighbors
error = "Passed"
stop = false
b = 0.
corrMax = 0.
int knn = 0
corr =0.
for k = 0 to Npast - Nfut
array.set(sxy, k, 0.)
for i = 0 to Npast - 1
array.set(sxy, k, array.get(sxy, k) + nz(open[k + i + lastbar]) * nz(open[Npast + i + lastbar]) * (i + 1))
// Calculate the correlation coefficient
if array.get(denx, k) <= 0
stop := true
error := "Null or negative value of the expression sxx[k]*Npast-mx[k]*mx[k]. Skip pattern # " + str.tostring(k)
continue
num = array.get(sxy, k) * si - array.get(mx, k) * my
corr := num / math.sqrt(array.get(denx, k)) / deny
if (corr > corrMax)
corrMax := corr
knn := k
b := num / array.get(denx, k)
delta = nz(open[1 + lastbar]) - b * nz(open[knn + Npast - 1 + lastbar])
// Calculate xm[] and ym[] by nearest neighbor scaling
for i = 0 to Npast + Nfut - 1
if (i <= Npast - 1)
array.set(xnn, Npast - 1 - i, b * nz(open[knn + i + lastbar]) + delta)
if (i >= Npast - 1)
array.set(ynn, i - Npast + 1, b * nz(open[knn + i + lastbar]) + delta)
[xnn, ynn, stop, error]
Npast = input.int(300, "Past Bars", group = "Basic Settings", tooltip = "How many bars for the calculation")
Nfut = input.int(50, "Future Bars", group = "Basic Settings")
lastbar = input.int(50, "Last Back", group = "Basic Settings", tooltip = "How many bars back to start forecast? Useful to show past prediction accuracy")
barsbark = input.int(200, "How many bars to calculate plots on?", group = "Calculation Time Settings", tooltip = "This prevents Pine from trying to calculate on all past bars")
mutebars = input.bool(true, "Bar color muting?", group = "UI Options")
var fvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to 500 - 1
array.push(fvlines, line.new(na, na, na, na))
out = 0.
if last_bar_index - bar_index < barsbark
[xnn, _, _, _] = _nn(Npast, Nfut, 0)
out := array.get(xnn, 0)
if barstate.islast
[xnn, ynn, stop, error] = _nn(Npast, Nfut, lastbar)
ym = array.copy(ynn)
int i = 0
int j = 0
skipperfv = array.size(ym) >= 2000 ? 8 : array.size(ym) >= 1000 ? 4 : array.size(ym) >= 500 ? 2 : 1
i := 0
j := 0
while i < Nfut - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - lastbar, array.get(ym, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - skipperfv - lastbar, array.get(ym, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 3)
i += skipperfv
j += 1
strout = stop ? "๐จ " + error : "โ
Passed"
colort = stop ? darkRedColor : darkGreenColor
var testTable = table.new(position = position.bottom_right, columns = 2, rows = 1, bgcolor = colort, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = strout, text_color = color.white, text_size = size.large)
colorout = greencolor
thisis = last_bar_index - bar_index < barsbark and bar_index <= last_bar_index - lastbar
plot(thisis? out : na, color = colorout, linewidth = 3)
barcolor(mutebars and last_bar_index - bar_index < barsbark ? color.gray : na)
|
Hodrick-Prescott Extrapolation of Price [Loxx] | https://www.tradingview.com/script/HCfWOt6F-Hodrick-Prescott-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 117 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Hodrick-Prescott Extrapolation of Price [Loxx]",
shorttitle = "HPEP [Loxx]",
max_lines_count = 500,
overlay = true)
greencolor = #2DD204
redcolor = #D2042D
_lambda(n)=>
lambda = 0.
w = 0.
if (n <= 37)
w := switch (n)
2 => math.pi / 3.0
3 => math.atan(math.sqrt(0.6))
4 => 2.153460564 / n
5 => 1.923796031 / n
6 => 1.915022415 / n
7 => 1.909786299 / n
8 => 1.906409362 / n
9 => 1.904103844 / n
10 => 1.902459533 / n
11 => 1.901245508 / n
12 => 1.900323600 / n
13 => 1.899607018 / n
14 => 1.899038987 / n
15 => 1.898581041 / n
16 => 1.898206498 / n
17 => 1.897896254 / n
18 => 1.897636390 / n
19 => 1.897416484 / n
20 => 1.897228842 / n
21 => 1.897067382 / n
22 => 1.896927473 / n
23 => 1.896805427 / n
24 => 1.896698359 / n
25 => 1.896603866 / n
26 => 1.896520032 / n
27 => 1.896445477 / n
28 => 1.896378692 / n
29 => 1.896318725 / n
30 => 1.896264646 / n
31 => 1.896215693 / n
32 => 1.896171301 / n
33 => 1.896130841 / n
34 => 1.896094060 / n
35 => 1.896060192 / n
36 => 1.896029169 / n
37 => 1.896000584 / n
else
w := math.pi / 2 / n
lambda := 0.0625 / math.pow(math.sin(w), 4)
lambda
_HPFilter(x, y, lamb, per)=>
H1 = 0., H2 = 0., H3 = 0., H4 = 0., H5 = 0.,
HH1 = 0., HH2 = 0., HH3 = 0., HH5 = 0.
HB= 0., HC= 0., Z= 0.
a = array.new<float>(per, 0.)
b = array.new<float>(per, 0.)
c = array.new<float>(per, 0.)
array.set(a, 0, 1.0 + lamb)
array.set(b, 0, -2.0 * lamb)
array.set(c, 0, lamb)
for i = 1 to per - 3
array.set(a, i, 6.0 * lamb + 1.0)
array.set(b, i, -4.0 * lamb)
array.set(c, i, lamb)
array.set(a, 1, 5.0 * lamb + 1)
array.set(a, per - 1, 1.0 + lamb)
array.set(a, per - 2, 5.0 * lamb + 1.0)
array.set(b, per - 2, -2.0 * lamb)
array.set(b, per - 1, 0.)
array.set(c, per - 2, 0.)
array.set(c, per - 1, 0.)
for i = 0 to per - 1
Z := array.get(a, i) - H4 * H1 - HH5 * HH2
if (Z == 0)
break
HB := array.get(b, i)
HH1 := H1
H1 := (HB - H4 * H2) / Z
array.set(b, i, H1)
HC := array.get(c, i)
HH2 := H2
H2 := HC / Z
array.set(c, i, H2)
array.set(a, i, (array.get(x, i) - HH3 * HH5 - H3 * H4) / Z)
HH3 := H3
H3 := array.get(a, i)
H4 := HB - H5 * HH1
HH5 := H5
H5 := HC
H2 := 0
H1 := array.get(a, per - 1)
array.set(y, per - 1, H1)
for i = per - 2 to 0
array.set(y, i, array.get(a, i) - array.get(b, i) * H1 - array.get(c, i) * H2)
H2 := H1
H1 := array.get(y, i)
src = input.source(close, "Source", group = "Basic Settings")
Method = input.int(2, "Method", maxval = 2, minval = 1, group = "Basic Settings")
LastBar = input.int(150, "Last Bar", group = "Basic Settings")
PastBars = input.int(2000, "Past Bars", group = "Basic Settings")
FutBars = input.int(100, "Future Bars", group = "Basic Settings")
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
if PastBars <= FutBars
runtime.error("Error: Past bars must be greater than future bars")
int n = 0
float[] x = array.new_float(PastBars, 0.)
float[] y = array.new_float(PastBars, 0.)
float[] fv = array.new_float(PastBars, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
for i = 0 to PastBars - 1
array.set(x, i, nz(src[i + LastBar]))
array.set(fv, FutBars, nz(src[LastBar]))
sum = nz(src[LastBar])
if Method == 2
n := 2 * FutBars + 1
_HPFilter(x, y, _lambda(n), PastBars)
for i = 1 to n - 2
sum += nz(src[i + LastBar])
for i = 1 to FutBars
if Method == 1
n := 2 * i + 1
_HPFilter(x, y, _lambda(n), PastBars)
sum += nz(src[i + LastBar])
array.set(fv, FutBars - i, n * array.get(y, 0) - sum)
sum := n * array.get(y, 0)
else
array.set(fv, FutBars - i, n * array.get(y, FutBars - i) - sum)
sum += array.get(fv, FutBars - i) - nz(src[n - 1 + LastBar - i])
xm = array.copy(y)
skipperpv = array.size(xm) >= 2000 ? 8 : array.size(xm) >= 1000 ? 4 : array.size(xm) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < array.size(xm) - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(xm, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(xm, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
i := 0
j := 0
if Method == 2
var ym = array.new_float(0)
for ix = 0 to FutBars - 2
array.push(ym, array.get(fv, ix))
array.reverse(ym)
array.insert(ym, 0, array.get(ym, 0))
array.insert(ym, 0, array.get(ym, 0))
skipperfv = array.size(ym) >= 2000 ? 8 : array.size(ym) >= 1000 ? 4 : array.size(ym) >= 500 ? 2 : 1
outer = math.min(250, array.size(ym))
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(ym, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(ym, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1
else
var ym = array.new_float(0)
for ix = 0 to FutBars
array.push(ym, array.get(fv, ix))
array.reverse(ym)
skipperfv = array.size(ym) >= 2000 ? 8 : array.size(ym) >= 1000 ? 4 : array.size(ym) >= 500 ? 2 : 1
outer = math.min(250, array.size(ym))
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(ym, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(ym, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1
barcolor(colorbars ? color.gray : na)
|
Defu_Divergence | https://www.tradingview.com/script/wZuc6eaG/ | Defuwa | https://www.tradingview.com/u/Defuwa/ | 26 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ defuwa
//@version=5
// CSML is price divergence. c=close,s=short,m=mid,l=long.
// ้่ฟๅฝๅไปทไธ็ญๅจใไธญๆใ้ฟๆEMAไน้ด็ๅ
ณ็ณป๏ผๅคๆญๅธๅบไน็ฆป็จๅบฆใ
indicator(title='Defu_Divergence')
//=============================ๅฎไน้ข่ฒ=========================================
yellow = color.yellow
red = color.red
black = color.black
hvi = #787b86
hei = #071513
hong0 = #e57373
hong1 = #ef5350
hong2 = #d32f2f
hong3 = #b71c1c
cheng1 = #ffa726
cheng2 = #f57c00
cheng3 = #e65100
lv0 = #a5d6a7
lv1 = #66bb6a
lv2 = #388e3c
lv3 = #00796b
lan0 = #52c3d0
lan1 = #90bff9
lan2 = #3179f5
lan3 = #0c3299
zi0 = #ce93d8
zi1 = #ba68c8
zi2 = #7b1fa2
zi3 = #4a148c
fen0 = #f48fb1
fen1 = #f06292
fen2 = #ec407a
fen3 = #c2185b
touming = color.new(color.blue, 100)
//================================่ช็ผๅ
ฌๅผ================================
wpr(len) => (ta.highest(high, len) - close) / (ta.highest(high, len) - ta.lowest(low, len)) * 100
rsif(scr, len) =>ta.sma(math.max(ta.change(scr), 0), len) / ta.sma(math.abs(ta.change(scr)), len) * 100
rmaf(src, n1, m1) => //m1/n1ๅ ๆ็งปๅจๅนณๅ็บฟ
alpha = m1 / n1
sum = 0.0
sman1 = ta.sma(src, n1)
sum := na(sum[1]) ? sman1 : alpha * src + (1 - alpha) * nz(sum[1])
sum
//================================่ฏดๆ=================
//var table logo = table.new(position.bottom_left, 1, 1)
//table.cell(logo, 0, 0," ่ๆฏ็บข็ปฟ่rsiOBV\n็ฐๅคง้่็บขๆฑMFI\n",text_size = size.auto, text_color = color.new(color.teal,70))
EMASwitch = input(defval=true, title='EMA123Switch')
s = input(defval=21, title='็ญๆ MA')
m = input(defval=55, title='ไธญๆ MA')
l = input(defval=120, title='้ฟๆ MA')
sr = input(defval=close, title='ๅฝๅไปท')
BBSwitch = input(defval=true, title='ๅธๆๅธฆSwitch')
volSwitch = input(defval=true, title='ๅทจๅคงๆไบค้Highlight large volume')
//================================ๆไบค้ๅคง้่ๆฏๆพ็คบ==============================
vema = input(defval=14, title='ๅคง้EMAๅจๆ')
vol = input.float(defval=2.25, title='ๅคง้ๅ ๆฐHighlight large volume', minval=1, step=0.01)
largevol = volume > vol * ta.ema(volume, vema)
bgcolor(volSwitch and largevol ? color.new(color.gray, 85) : na, title='ๅคง้large volume')
//================================ๅธๅบๆๆฌไน็ฆป็จๅบฆ price divergence ===============
//M1 = ta.ema(close, s)
//M2 = ta.ema(close, m)
//M3 = ta.ema(close, l)
EM1 = (sr / ta.ema(close, s) - 1) * 100
EM2 = (ta.ema(close, s) / ta.ema(close, m) - 1) * 100
EM3 = (ta.ema(close, m) / ta.ema(close, l) - 1) * 100
eEM1 = ta.ema(ta.sma(EM1, 3), 3)
//================================ๅธๆๅธฆ================================
[_, upperL, lowerL] = ta.bb(EM1, s, 1.5) // 1.5 = ไธ่ฝจLower Standard Deviation
[_, upperH, lowerH] = ta.bb(EM1, s, 2.25) // 2.25 = ไธ่ฝจHigher Standard Deviation
bu1 = plot(BBSwitch ? upperL : na, 'BB่ถ
ไนฐLower Line-Overbought', display=display.none)
bu2 = plot(BBSwitch ? upperH : na, 'BB่ถ
ไนฐUpper Line-Overbought', display=display.none)
fill(bu1, bu2, color=EM1 > upperL ? color.new(#e57373, 65) : color.new(#e57373, 85), title='่ถ
ไนฐOverbought Background')
bl1 = plot(BBSwitch ? lowerL : na, 'BB่ถ
ๅUpper Line-Oversold', display=display.none)
bl2 = plot(BBSwitch ? lowerH : na, 'BB่ถ
ๅLower Line-Oversold', display=display.none)
fill(bl1, bl2, color=EM1 < lowerL ? color.new(#66bb6a, 60) : color.new(#66bb6a, 85), title='่ถ
ๅOversold Background')
//่ฎพ็ฝฎ่ญฆๆฅ๏ผEM1> or <7.
alertcondition(ta.crossunder(EM1, upperL), title='ๅบ่ดงๆ้', message='ไน็ฆปๅพๅคง๏ผ่ฆๅบ่ดงๅ๏ผ')
alertcondition(ta.crossover(EM1, lowerH), title='ๆๅบๆ้', message='ไน็ฆปๅพๅคง๏ผ่ฆๅ
ฅๅบๅ๏ผ')
//================================่ต้ๆต้ๆๆ MFI================================
MFISwitch = input(true, title='MFI Switch')
length = input.int(defval=14, title='ๅจๆlength', minval=1)
mf = ta.mfi(hlc3, length)
mftclr = mf > 89 ? color.new(cheng2, 30) : mf > 85 ? color.new(cheng2, 45) : mf > 81 ? color.new(cheng2, 60) : touming
mflclr = mf < 13 ? color.new(lan1, 30) : mf < 16 ? color.new(lan1, 45) : mf < 19 ? color.new(lan1, 60) : touming
mfclr = mf > 81 ? mftclr : mflclr
mfil = plot(MFISwitch ? eEM1 : na, title='MFI', color=mfclr, style=plot.style_columns, linewidth=2, show_last=200)
//mfil = plot(MFISwitch ? mf : na, title='MFI', color=mfclr, style=plot.style_columns, linewidth=2, show_last=200)
//================================EM123ไบคๅ================================
crossed2 = ta.cross(EM2, EM3)
plot(crossed2 ? EM3 : na, title='55120ไบคๅ', style=plot.style_circles, linewidth=2, color=color.new(color.red, 0))
//================================ไน็ฆป็ๅถๅพ================================
B0 = plot(EMASwitch ? 0 : na, title='0่ฝด', color=color.new(#4db6ac,0), linewidth=1)
B3 = plot(EMASwitch ? EM3 : na, title='EM3', color=color.new(lan1, 0), linewidth=2)
B2 = plot(EMASwitch ? EM2 : na, title='EM2', color=color.new(fen2,0), linewidth=1)
B1 = plot(EMASwitch ? EM1 : na, title='EM1', color=color.new(#5d606b, 0), linewidth=1)
|
Fibonacci + Support/Resistant + Trendline (Price action) | https://www.tradingview.com/script/HJqjyjGi-Fibonacci-Support-Resistant-Trendline-Price-action/ | TrendCrypto2022 | https://www.tradingview.com/u/TrendCrypto2022/ | 1,047 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @TrendCrypto2022
//@version=5
indicator("Price action as in book: Fibonacci + Support/Resistant + Trendline", overlay=true, max_lines_count = 500)
//Input
buyonly = input.bool (title="Find entry Long", defval=true, group="Set up Find entry")
sellonly = input.bool (title="Find entry Short", defval=false, group="Set up Find entry")
leftbars = input.int(10, minval=1, title='Pivot Detection: Left Bars', group = "Set up Pivot High/Low")
rightbars = input.int(5, minval=1, title='Pivot Detection: Right Bars', group = "Set up Pivot High/Low")
width_fibo = input.int(2, minval=1, title='Width Fibonacci levels', group = "Custom Selection", inline = "1")
width_sup_res = input.int(2, minval=1, title='Width Sup/Res levels', group = "Custom Selection", inline = "2")
width_trendline = input.int(2, minval=1, title='Width Trendline', group = "Custom Selection")
extend_fibo = input.int(5, minval=1, title='Extention', group = "Custom Selection", inline = "1")
color_fibo_label = input.color(color.new(color.yellow, 0), title="Color Labels", group = "Custom Selection", inline = "1")
extend_sup_res = input.int(5, minval=1, title='Extention', group = "Custom Selection", inline = "2")
// Pivots
ph = ta.pivothigh(high, leftbars, rightbars)
pl = ta.pivotlow(low, leftbars, rightbars)
//Caculate Support/Resistant levels based on Pivots
phvalue1 = ta.valuewhen(ph, high[rightbars], 0)
phbar1 = ta.valuewhen(ph, bar_index[rightbars], 0), phv1low = ta.valuewhen(ph, close[rightbars]>open[rightbars] ? close[rightbars] : open[rightbars], 0)
phvalue2 = ta.valuewhen(ph, high[rightbars], 1)
phbar2 = ta.valuewhen(ph, bar_index[rightbars], 1), phv2low = ta.valuewhen(ph, close[rightbars]>open[rightbars] ? close[rightbars] : open[rightbars], 1)
phbar3 = ta.valuewhen(ph, bar_index[rightbars], 2),
phvalue3 = ta.valuewhen(ph, high[rightbars], 2)
plvalue1 = ta.valuewhen(pl, low[rightbars], 0)
plbar1 = ta.valuewhen(pl, bar_index[rightbars], 0), plv1low = ta.valuewhen(pl, close[rightbars]<open[rightbars] ? close[rightbars] : open[rightbars], 0)
plvalue2 = ta.valuewhen(pl, low[rightbars], 1)
plbar2 = ta.valuewhen(pl, bar_index[rightbars], 1)
plbar3 = ta.valuewhen(pl, bar_index[rightbars], 2), plv2low = ta.valuewhen(pl, close[rightbars]<open[rightbars] ? close[rightbars] : open[rightbars], 1)
plvalue3 = ta.valuewhen(pl, low[rightbars], 2)
plotshape(ph, style=shape.diamond, location=location.abovebar, color=color.new(color.red, 0), title='Pivot High', offset=-rightbars)
plotshape(pl, style=shape.diamond, location=location.belowbar, color=color.new(color.green, 0), title='Pivot Low', offset=-rightbars)
//Calculate trendlines
_slope(x1, x2, y1, y2) =>
m = (y2 - y1) / (x2 - x1)
m
get_y_oxy(m, x1, y1) =>
b = y1 - m * x1
b
get_y(m, b, ts) =>
Y = m * ts + b
Y
int res_x1 = na
float res_y1 = na
int res_x2 = na
float res_y2 = na
int sup_x1 = na
float sup_y1 = na
int sup_x2 = na
float sup_y2 = na
res_x1 := ph ? phbar2 : res_x1[1]
res_y1 := ph ? phvalue2 : res_y1[1]
res_x2 := ph ? phbar3 : res_x2[1]
res_y2 := ph ? phvalue3 : res_y2[1]
res_m = _slope(res_x1, res_x2, res_y1, res_y2)
res_b = get_y_oxy(res_m, res_x1, res_y1)
res_y = get_y(res_m, res_b, bar_index)
sup_x1 := pl ? plbar2 : sup_x1[1]
sup_y1 := pl ? plvalue2 : sup_y1[1]
sup_x2 := pl ? plbar3 : sup_x2[1]
sup_y2 := pl ? plvalue3 : sup_y2[1]
sup_m = _slope(sup_x1, sup_x2, sup_y1, sup_y2)
sup_b = get_y_oxy(sup_m, sup_x1, sup_y1)
sup_y = get_y(sup_m, sup_b, bar_index)
// Setup Alert
alert_input = input.string(title='Set alert Long Trade when price test', defval='Fibo 0.5', options=['Fibo 0.382', 'Fibo 0.5', 'Fibo 0.618', 'Fibo 0.786', 'Support Zone', 'Trendline'], group='Set up Alert')
alertshort_input = input.string(title='Set alert Short Trade when price test', defval='Fibo 0.5', options=['Fibo 0.382', 'Fibo 0.5', 'Fibo 0.618', 'Fibo 0.786', 'Resistant Zone', 'Trendline'], group='Set up Alert')
distance_x = timenow + math.round(ta.change(time) * 1)
//Draw Fibonacci levels, Support levels and labels
if ph and phvalue1 > phvalue2 and buyonly == true
line.new(plbar1, plvalue1, phbar1, phvalue1, style=line.style_arrow_right, color=color.lime, width = 2)
line.new(plbar1, phvalue1, phbar1+ rightbars+extend_fibo, phvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.236, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.236, style=line.style_solid, color=color.new(color.red, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.382, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.382, style=line.style_solid, color=color.new(#81c784, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.500, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.500, style=line.style_solid, color=color.new(color.green, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.618, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.618, style=line.style_solid, color=color.new(#089981, 60), width = width_fibo)
line.new(plbar1, phvalue1-(phvalue1-plvalue1)*0.786, phbar1+ rightbars+extend_fibo, phvalue1-(phvalue1-plvalue1)*0.786, style=line.style_solid, color=color.new(color.aqua, 60), width = width_fibo)
line.new(plbar1, plvalue1, phbar1+ rightbars+extend_fibo, plvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
p1=line.new(phbar2, phv2low, phbar1+ rightbars+extend_sup_res, phv2low, style=line.style_solid, color=color.new(color.lime, 20), width = width_sup_res)
p2=line.new(phbar2, phvalue2, phbar1+ rightbars+extend_sup_res, phvalue2, style=line.style_solid, color=color.new(color.lime, 20), width = width_sup_res)
linefill.new(p1, p2, color = color.new(color.lime, transp =85))
if phvalue2 < phvalue3
line.new(phbar3, phvalue3, phbar2, phvalue2, style=line.style_dotted, color=color.red, width = width_trendline)
line.new(phbar2, phvalue2, bar_index, res_y, style=line.style_dotted, color=color.red, width = width_trendline)
if close<phvalue1-(phvalue1-plvalue1)*0.382 and alert_input == 'Fibo 0.382'
alert(message = "Fibo 0.382", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.500 and alert_input == 'Fibo 0.5'
alert(message = "Fibo 0.5", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.618 and alert_input == 'Fibo 0.618'
alert(message = "Fibo 0.618", freq = alert.freq_once_per_bar)
if close<phvalue1-(phvalue1-plvalue1)*0.786 and alert_input == 'Fibo 0.786'
alert(message = "Fibo 0.786", freq = alert.freq_once_per_bar)
if close<phvalue2 and alert_input == 'Support Zone'
alert(message = "Support Zone", freq = alert.freq_once_per_bar)
if close<res_y + res_y*0.005 and alert_input == 'Trendline'
alert(message = "Trendline", freq = alert.freq_once_per_bar)
var label labelfibo0 = na
label.delete(labelfibo0)
labelfibo0 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0, text='0', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo236 = na
label.delete(labelfibo236)
labelfibo236 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.236, text='0.236', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo382 = na
label.delete(labelfibo382)
labelfibo382 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.382, text='0.382', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo5 = na
label.delete(labelfibo5)
labelfibo5 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.5, text='0.5', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo618 = na
label.delete(labelfibo618)
labelfibo618 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.618, text='0.618', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo786 = na
label.delete(labelfibo786)
labelfibo786 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*0.786, text='0.786', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo1 = na
label.delete(labelfibo1)
labelfibo1 := label.new(x=distance_x, y=phvalue1-(phvalue1-plvalue1)*1, text='1', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
//Draw Fibonacci levels, Resistant levels and labels
if pl and plvalue1 < plvalue2 and sellonly == true
line.new(phbar1, phvalue1, plbar1, plvalue1, style=line.style_arrow_right, color=color.red, width = 2)
line.new(phbar1, plvalue1, plbar1+ rightbars+extend_fibo, plvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.236, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.236, style=line.style_solid, color=color.new(color.red, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.382, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.382, style=line.style_solid, color=color.new(#81c784, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.500, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.500, style=line.style_solid, color=color.new(color.green, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.618, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.618, style=line.style_solid, color=color.new(#089981, 60), width = width_fibo)
line.new(plbar1, plvalue1-(plvalue1-phvalue1)*0.786, plbar1+ rightbars+extend_fibo, plvalue1-(plvalue1-phvalue1)*0.786, style=line.style_solid, color=color.new(color.aqua, 60), width = width_fibo)
line.new(phbar1, phvalue1, plbar1+ rightbars+extend_fibo, phvalue1, style=line.style_solid, color=color.new(color.silver, 60), width = width_fibo)
p1=line.new(plbar2, plv2low, plbar1+ rightbars+extend_sup_res, plv2low, style=line.style_solid, color=color.new(color.red, 20), width = width_sup_res)
p2=line.new(plbar2, plvalue2, plbar1+ rightbars+extend_sup_res, plvalue2, style=line.style_solid, color=color.new(color.red, 20), width = width_sup_res)
linefill.new(p1, p2, color = color.new(color.red, transp =85))
if plvalue2 > plvalue3
line.new(plbar3, plvalue3, plbar2, plvalue2, style=line.style_dotted, color=color.lime, width = width_trendline)
line.new(plbar2, plvalue2, bar_index, sup_y, style=line.style_dotted, color=color.lime, width = width_trendline)
if close>plvalue1-(plvalue1-phvalue1)*0.382 and alertshort_input == 'Fibo 0.382'
alert(message = "Fibo 0.382", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.500 and alertshort_input == 'Fibo 0.5'
alert(message = "Fibo 0.5", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.618 and alertshort_input == 'Fibo 0.618'
alert(message = "Fibo 0.618", freq = alert.freq_once_per_bar)
if close>plvalue1-(plvalue1-phvalue1)*0.786 and alertshort_input == 'Fibo 0.786'
alert(message = "Fibo 0.786", freq = alert.freq_once_per_bar)
if close>plvalue2 and alertshort_input == 'Resistant Zone'
alert(message = "Resistant Zone", freq = alert.freq_once_per_bar)
if close>sup_y - sup_y*0.005 and alertshort_input == 'Trendline'
alert(message = "Trendline", freq = alert.freq_once_per_bar)
var label labelfibo0 = na
label.delete(labelfibo0)
labelfibo0 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0, text='0', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo236 = na
label.delete(labelfibo236)
labelfibo236 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.236, text='0.236', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo382 = na
label.delete(labelfibo382)
labelfibo382 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.382, text='0.382', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo5 = na
label.delete(labelfibo5)
labelfibo5 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.5, text='0.5', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo618 = na
label.delete(labelfibo618)
labelfibo618 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.618, text='0.618', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo786 = na
label.delete(labelfibo786)
labelfibo786 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*0.786, text='0.786', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
var label labelfibo1 = na
label.delete(labelfibo1)
labelfibo1 := label.new(x=distance_x, y=plvalue1-(plvalue1-phvalue1)*1, text='1', color=color.new(#000000, 100), textcolor = color_fibo_label, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
|
Defu_RSI | https://www.tradingview.com/script/rZ44gCMC/ | Defuwa | https://www.tradingview.com/u/Defuwa/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Defuwa
//https://cn.tradingview.com/u/Defuwa/#published-scripts
//@version=5
indicator(title='Defu_RSI', overlay=false)
//var table logo = table.new(position.top_right, 1, 1)
//table.cell(logo, 0, 0,
// " ๅฎณๆ่ธ็ฉบๅชไผ่ฎฉไฝ ไธๆ ๆๆ\n
// ๅๅฒไผ้ๆผ๏ผ็ธไฟกไฝ ็็ผ็\n",
// text_size = size.auto,text_color = color.new(color.teal,60))
//==============================ๅฎไน้ข่ฒ==============================
yellow = color.yellow
red = color.red
black = color.black
hvi = #787b86
hei = #071513
hong0 = #e57373
hong1 = #ef5350
hong2 = #d32f2f
hong3 = #b71c1c
cheng1 = #ffa726
cheng2 = #f57c00
cheng3 = #e65100
lv0 = #a5d6a7
lv1 = #66bb6a
lv2 = #388e3c
lv3 = #00796b
lan0 = #52c3d0
lan1 = #90bff9
lan2 = #3179f5
lan3 = #0c3299
zi0 = #ce93d8
zi1 = #ba68c8
zi2 = #7b1fa2
zi3 = #4a148c
fen0 = #f48fb1
fen1 = #f06292
fen2 = #ec407a
fen3 = #c2185b
touming = color.new(color.blue, 100)
l = input(120, title='้ฟๅจๆ๏ผ') //0่ฝดไธๆน
//==============================่ช็ผๅ
ฌๅผ==============================
rsif(scr, len) => ta.sma(math.max(ta.change(scr), 0), len) / ta.sma(math.abs(ta.change(scr)), len) * 100 //rsi
wpr(len) => (ta.highest(high, len) - close) / (ta.highest(high, len) - ta.lowest(low, len)) * 100 //wprๅจๅปๆๆ
countf(sr, len) => //่ฎก็ฎlenๅจๆๅ
็ฌฆๅๆกไปถ็k็บฟๆฐ้
out = 0
src = sr
for i = 1 to len by 1
out := src[len - i] ? out + 1 : out
out
rmaf(src, n1, m1) => //m1/n1ๅ ๆ็งปๅจๅนณๅ็บฟ
alpha = m1 / n1
sum = 0.0
sum := na(sum[1]) ? ta.sma(src, n1) : alpha * src + (1 - alpha) * nz(sum[1])
sum
//==============================ๆฐดๅนณๅผบๅผฑๅ็็บฟ==============================
l00 = plot(0, title='hline0', color=color.new(#9598a1, 0), style=plot.style_stepline)
l20 = plot(20, title='hline20', color=lv0, style=plot.style_stepline)
l50 = plot(50, title='hline50', color=color.new(#787b86, 30), style=plot.style_stepline)
l80 = plot(80, title='hline80', color=fen0, style=plot.style_stepline)
l100 = plot(100, title='hline100', display=display.none)
//ld50 = plot(-50, title='hline-50', color=color.new(#787b86, 30), style=plot.style_stepline)
//==============================RSI่ถ
ไนฐ่ถ
ๅๅบ==============================
RSSwitch = input(defval=true, title='RSSwitch')
len1 = input.int(defval=8, title='RSๅจๆ', minval=1)
maim = rsif(close, len1)
//maid = plot(RSSwitch and ta.crossunder(rsif(close, 6), 81) ? 100 : na, title='่ถ
ๅ', style=plot.style_circles, color=fen0, linewidth=2, show_last=200)
fill(l00, l20, title='ไนฐๅ
ฅๅบ', color=maim < 19 ? color.new(lv1, 80) : touming)
fill(l80, l100, title='ๅๅบๅบ', color=maim > 81 ? color.new(fen0, 80) : touming)
//==============================ๅฐ้กถๆฑ็บฟ=============================
DDSwitch = input(true, title='ๅฐ้กถSwitch๏ผ')
//daod1 = wpr(9) - 70
daod2 = ta.sma(ta.sma(ta.stoch(close, high, low, 9), 3), 3) - (ta.sma(wpr(9) - 70, 9) + 100)
dding = daod2 > 40 ? daod2 - 40 : na
ddclr = ta.change(dding) > 0 ? color.new(hong2, 0) : color.new(hong1, 20)
plot(DDSwitch ? dding+50 : na, title='ๅฐ้กถๆฑ็บฟ', color=ddclr, style=plot.style_columns,histbase=50)
daodinal = dding > 0
//daodinal = (daodin[1] > 0 and daodin == 0 )or (daodin[2]>daodin[1] and daodin[1]>daodin)
bgcolor(DDSwitch and daodinal ? color.new(hong1, 93) : na, title='ๅฐ้กถ')
alertcondition(daodinal,title="้กถ้กถ้กถ๏ผ", message="ๅฐ้กถไบ๏ผ")
//==============================CCI ema็ปฟ็บฟ==============================
emCCwitch = input(defval=true, title='emCCwitch')
//cc1 = (hlc3 - ta.ema(hlc3, ltLB)) / (0.015 * ta.stdev(hlc3, ltLB))
ltLB = input.int(10, title='ltLB',minval=5, maxval = 21)
cci = (hlc3 - ta.ema(hlc3, ltLB)) / (0.015 * ta.ema(math.abs(hlc3 - ta.ema(hlc3, ltLB)), ltLB))
tci = ta.ema(cci, 21)
plot(emCCwitch ? tci+ 50 :na, title='emCC', color= tci > 55 ? color.new(hong1,0) : tci < -55 ? color.new(lv2,0): color.new(lan1,0), linewidth=1)
//==============================่ถๅฟXX==============================
TrendSwitch = input(true, title='trendSwitch๏ผ')
trenda = 5 * ta.sma(ta.stoch(close, high, low, 34), 5) - 3 * ta.sma(ta.sma(ta.stoch(close, high, low, 34), 5), 3) - ta.sma(ta.sma(ta.sma(ta.stoch(close, high, low, 34), 5), 3), 2)
zou = rmaf(rmaf(ta.stoch(close, high, low, 21), 13, 8), 13, 8) - rmaf(wpr(21) - 10, 21, 8)
plotshape(TrendSwitch and ta.crossover(trenda, 3) ? -15 : na, title='่ถๅฟๅบ',style= shape.triangleup, location=location.absolute, color=color.new(lv2, 0))
plotshape(TrendSwitch and ta.crossunder(trenda, 108) ? 100: na, title='่ถๅฟ้กถ',style= shape.triangledown, location=location.absolute, color=color.new(zi1, 0))
plot(TrendSwitch ? trenda : na, title='่ถๅฟ', color=color.new(cheng2, 30) ,linewidth=1)
putdll = plot(TrendSwitch ? trenda : na,title='ไธปๅ่ถ
่ฝฝ', color=zou > 85 ? color.new(fen2, 20) : touming, linewidth=2)
//=============================ๆฅๅ
ๆณขๅจ====================================
//=====================้ฟไธๅฝฑ็บฟ===================================
DaySwitch = input(true, title='ๆฅๅ
ๆณขๅจSwitch๏ผ')
hltrhigh = (high -math.max(open,close))/(math.min(open ,close) -low)
hltrhighl = hltrhigh >1.6 and hltrhigh < 30? -hltrhigh: hltrhigh >1.6 and hltrhigh > 30 ? -30 : na
hltrguolv = (high -math.max(open,close)) > math.abs(open - close)*0.5
plot(DaySwitch and hltrguolv and rsif(close,6) >60 ? hltrhighl: na, title='้ๆข', color=color.new(hong0,50),style=plot.style_columns)
alertcondition(hltrhigh>1.6,title="้คๅญ้๏ผ",message="ๅฐ้กถไบ๏ผ")
//=====================ไธญ่ฝฌ็น======================
hltrmid = (high - low)/math.abs(open - close)
hltrmidl = hltrmid >1.6 and hltrmid < 30? -hltrmid: hltrmid >1.6 and hltrmid > 30 ? -30 : na
plot(DaySwitch and rsif(close,6) >60 ? hltrmidl : na, title='ไธญ่ฝฌ็น', color=color.new(cheng1,65),linewidth=1,style=plot.style_columns)
alertcondition(hltrmid>1.6,title="้คๅญ้๏ผ",message="่ฝฌๆไบ๏ผ")
|
Polynomial Regression Bands w/ Extrapolation of Price [Loxx] | https://www.tradingview.com/script/Ub0Fq9AY-Polynomial-Regression-Bands-w-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 513 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Polynomial Regression Bands w/ Extrapolation of Price [Loxx]",
shorttitle ="PRBEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
polyfit(float[] src, int deg, int len, int bar)=>
sumout = 0.
AX = matrix.new<float>(12, 12, 0.)
BX = array.new<float>(12, 0.)
ZX = array.new<float>(12, 0.)
Pow = array.new<float>(12, 0.)
Row = array.new<int>(12, 0)
CX = array.new<float>(12, 0.)
// FILL MATRIX FIRST
if (len <= 1)
sumout := array.get(src, bar)
else
XK = 0.
Prod = 0.
for j = 1 to deg + 1
array.set(BX, j, 0)
for k = 1 to len
YK = array.get(src, len - k)
XK := k
Prod := 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
for j = 0 to 2 * deg
array.set(Pow, j, 0)
array.set(Pow, 0, len)
for k = 1 to len
XK := k
Prod := k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
//NOW SOLVE FOR COEFFICIENTS
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
//NOW COMPUTE NEXT POINT IN SERIES AND RETURN
sumout := array.get(CX, deg + 1)
for k = deg to 1
sumout := array.get(CX, k) + sumout * (len + bar)
sumout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
Length = input.int(30, "Period", group = "Basic Settings")
Degree = input.int(3, "Degree", group = "Basic Settings")
MA_Length = input.int(5, "Source Smoothing Period", group = "Basic Settings")
type = input.string("Exponential Moving Average - EMA", "Source Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
ProjLength = input.int(10, maxval = 99, minval = 5, group = "Basic Settings")
K_Sigma = input.float(3, "Inner Bands Multiplier", group = "Basic Settings")
K_Sigma2 = input.float(6, "Outer Bands Multiplier", group = "Basic Settings")
FitMode = input.string("Moving", "Fit Mode", options =["Moving", "Fitting"], group = "Basic Settings")
barsbark = input.int(600, "Bars back", group = "Basic Settings", tooltip = "Number of bars painted on screen. This controls the computation speed")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showbands = input.bool(true, "Show bands?", group = "UI Options")
showmid = input.bool(true, "Show center line?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
int len = 0
if FitMode == "Moving"
len := Length + MA_Length
else
len := Length + 1
Polynom = 0.
PolyFitMA = 0.
UpBand = 0.
DnBand = 0.
UpBand1 = 0.
DnBand1 = 0.
PriceArray = array.new<float>(Length, 0)
var Project = array.new_float(ProjLength + 1, 0)
var Projection = array.new_float(ProjLength + 1, 0)
var DnProject = array.new_float(ProjLength + 1, 0)
var UpProject = array.new_float(ProjLength + 1, 0)
var DnProject1 = array.new_float(ProjLength + 1, 0)
var UpProject1 = array.new_float(ProjLength + 1, 0)
poly = 0.
var uplines = array.new_line(0)
var uplines1 = array.new_line(0)
var fvlines = array.new_line(0)
var dnlines = array.new_line(0)
var dnlines1 = array.new_line(0)
if barstate.isfirst
for i = 0 to 100 - 1
array.push(uplines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
array.push(dnlines, line.new(na, na, na, na))
array.push(uplines1, line.new(na, na, na, na))
array.push(dnlines1, line.new(na, na, na, na))
if last_bar_index - bar_index < barsbark
for j = 0 to Length - 1
array.set(PriceArray, j, nz(variant(type, src, MA_Length)[j]))
Sum = 0.
for j = Length - 1 to 0
poly := polyfit(PriceArray, Degree, Length, -j)
del = array.get(PriceArray, j) - poly
Sum += del * del
if FitMode == "Fitting"
Polynom := poly
if FitMode == "Moving"
Polynom := poly
StdDev = 0.
if (Length - 1 > 0 and Sum > 0)
if Length < 32
StdDev := math.sqrt(Sum / (Length - 1))
else
StdDev := math.sqrt(Sum / Length)
UpBand := Polynom + K_Sigma * StdDev
DnBand := Polynom - K_Sigma * StdDev
UpBand1 := Polynom + K_Sigma2 * StdDev
DnBand1 := Polynom - K_Sigma2 * StdDev
if barstate.islast
for j = 0 to ProjLength
array.set(Project, j, polyfit(PriceArray, Degree, Length, ProjLength - j))
for j = 0 to ProjLength
array.set(Projection, j, array.get(Project, j))
array.set(UpProject, j, array.get(Project, j) + K_Sigma * StdDev)
array.set(DnProject, j, array.get(Project, j) - K_Sigma * StdDev)
array.set(UpProject1, j, array.get(Project, j) + K_Sigma2 * StdDev)
array.set(DnProject1, j, array.get(Project, j) - K_Sigma2 * StdDev)
psize = array.size(Projection)
skipperfv = psize >= 165 * 3 ? 8 : psize >= 165 * 2 ? 4 : psize >= 165 ? 2 : 1
i = 0
j = 0
array.reverse(Projection)
array.reverse(UpProject)
array.reverse(DnProject)
array.reverse(UpProject1)
array.reverse(DnProject1)
outer = math.min(psize, ProjLength)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
if showmid
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1, array.get(Projection, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - skipperfv, array.get(Projection, i))
line.set_color(fvline, color.white)
line.set_style(fvline, line.style_dotted)
line.set_width(fvline, 3)
if showbands
upline = array.get(uplines, j)
line.set_xy1(upline, bar_index + i + 1, array.get(UpProject, i + skipperfv))
line.set_xy2(upline, bar_index + i + 1 - skipperfv, array.get(UpProject, i))
line.set_color(upline, lightgreencolor)
line.set_style(upline, line.style_dotted)
line.set_width(upline, 2)
upline1 = array.get(uplines1, j)
line.set_xy1(upline1, bar_index + i + 1, array.get(UpProject1, i + skipperfv))
line.set_xy2(upline1, bar_index + i + 1 - skipperfv, array.get(UpProject1, i))
line.set_color(upline1, greencolor)
line.set_style(upline1, line.style_dotted)
line.set_width(upline1, 2)
dnline = array.get(dnlines, j)
line.set_xy1(dnline, bar_index + i + 1, array.get(DnProject, i + skipperfv))
line.set_xy2(dnline, bar_index + i + 1 - skipperfv, array.get(DnProject, i))
line.set_color(dnline, lightredcolor)
line.set_style(dnline, line.style_dotted)
line.set_width(dnline, 2)
dnline1 = array.get(dnlines1, j)
line.set_xy1(dnline1, bar_index + i + 1, array.get(DnProject1, i + skipperfv))
line.set_xy2(dnline1, bar_index + i + 1 - skipperfv, array.get(DnProject1, i))
line.set_color(dnline1, redcolor)
line.set_style(dnline1, line.style_dotted)
line.set_width(dnline1, 2)
i += skipperfv
j += 1
colorout = Polynom > Polynom[1] ? greencolor : redcolor
plot(last_bar_index - bar_index < barsbark and showmid ? Polynom : na, "Poly MA", color = colorout, linewidth = 4)
plot(last_bar_index - bar_index < barsbark and showbands ? UpBand : na, "Upper inner band", color = lightgreencolor)
plot(last_bar_index - bar_index < barsbark and showbands ? UpBand1 : na, "Upper outer band", color = greencolor)
plot(last_bar_index - bar_index < barsbark and showbands ? DnBand : na, "Lower inner band", color = lightredcolor)
plot(last_bar_index - bar_index < barsbark and showbands ? DnBand1 : na, "Lower outer band", color = redcolor)
barcolor(last_bar_index - bar_index < barsbark and colorbars ? colorout : na)
|
AlphaTrend Option Trade | https://www.tradingview.com/script/l4zWb0QT-AlphaTrend-Option-Trade/ | DeuceDavis | https://www.tradingview.com/u/DeuceDavis/ | 308 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// author ยฉ KivancOzbilgic
// developer ยฉ KivancOzbilgic
// Modded by DeuceDavis
//@version=5
indicator('AlphaTrend Option Trade', shorttitle='AlphaTrend Option Trade', overlay=true, format=format.price, precision=2)
coeff = input.float(1, 'Multiplier', step=0.1)
AP = input(14, 'Common Period')
ATR = ta.sma(ta.tr, AP)
src = input(close)
showsignalsk = input(title='Show Signals?', defval=true)
novolumedata = input(title='Change calculation (no volume data)?', defval=false)
upT = low - ATR * coeff
downT = high + ATR * coeff
AlphaTrend = 0.0
AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT
color1 = AlphaTrend > AlphaTrend[2] ? #00E60F : AlphaTrend < AlphaTrend[2] ? #80000B : AlphaTrend[1] > AlphaTrend[3] ? #00E60F : #80000B
k1 = plot(AlphaTrend, title="AlphaTrend", color=color.new(#0022FC, 0), linewidth=3)
k2 = plot(AlphaTrend[2], title="AlphaTrend Offset", color=color.new(#FC0400, 0), linewidth=3)
fill(k1, k2, color=color1)
buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2])
sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2])
K1 = ta.barssince(buySignalk)
K2 = ta.barssince(sellSignalk)
O1 = ta.barssince(buySignalk[1])
O2 = ta.barssince(sellSignalk[1])
plotshape(buySignalk and showsignalsk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na,
title='Call', text='Call', location=location.absolute, style=shape.labelup, size=size.tiny,
color=color.new(#0022FC, 0), textcolor=color.new(color.white, 0))
plotshape(sellSignalk and showsignalsk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na,
title='Put', text='Put', location=location.absolute, style=shape.labeldown, size=size.tiny,
color=color.new(color.maroon, 0), textcolor=color.new(color.white, 0))
//TRADING SYSTEM
//Initialize
backTestStartDate = input.time(title='Back Test From', defval=timestamp("1 Jan 2022"))
capitalValue = input.float(defval = 100000.0, title="Amount of Capital to Risk on Trade")
tpMoveRatio = input.float(defval = 0.50, title="Movement Ratio", step=.01)
showBackTestResults = input.bool(defval = true, title="Show Backtest Results")
var longTrades = 0
var longWins = 0
var longBars = 0
var maxLongBars = 0
var shortTrades = 0
var shortWins = 0
var shortBars = 0
var maxShortBars = 0
var stopValue = 0.0
var tpValue = 0.0
var sharesInTrade = 0
var plFromTrades = 0.0
var entryPrice = 0.0
calcShares = math.floor(capitalValue/open)
goLong = buySignalk and O1 > K2 and time >= backTestStartDate
goShort = sellSignalk and O2 > K1 and time >= backTestStartDate
barsLong = ta.barssince(goLong != goLong[1])
barsShort = ta.barssince(goShort != goShort[1])
valueMove = math.abs(AlphaTrend - close[1])
if sharesInTrade > 0
if low <= stopValue
plFromTrades := plFromTrades + (stopValue - entryPrice) * sharesInTrade
longBars := longBars + barsLong
maxLongBars := math.max(barsLong, maxLongBars)
sharesInTrade := 0
if high >= tpValue
plFromTrades := plFromTrades + (tpValue - entryPrice) * sharesInTrade
sharesInTrade := 0
longBars := longBars + barsLong
maxLongBars := math.max(barsLong, maxLongBars)
longWins := longWins + 1
if goShort[1]
plFromTrades := plFromTrades + (open - entryPrice) * sharesInTrade
sharesInTrade := 0
longBars := longBars + barsLong
maxLongBars := math.max(barsLong, maxLongBars)
longWins := open > entryPrice ? longWins + 1 : longWins
if sharesInTrade < 0
if low <= tpValue
plFromTrades := plFromTrades + (tpValue - entryPrice) * sharesInTrade
sharesInTrade := 0
shortWins := shortWins + 1
shortBars := shortBars + barsShort
maxShortBars := math.max(barsShort, maxShortBars)
if high >= stopValue
plFromTrades := plFromTrades + (stopValue - entryPrice) * sharesInTrade
sharesInTrade := 0
shortBars := shortBars + barsShort
maxShortBars := math.max(barsShort, maxShortBars)
if goLong[1]
plFromTrades := plFromTrades + (open - entryPrice) * sharesInTrade
sharesInTrade := 0
shortWins := open < entryPrice ? shortWins + 1 : shortWins
shortBars := shortBars + barsShort
maxShortBars := math.max(barsShort, maxShortBars)
if goLong[1]
longTrades := longTrades + 1
sharesInTrade := calcShares
tpValue := math.ceil(open + valueMove * tpMoveRatio)
stopValue := AlphaTrend - valueMove
entryPrice := open
label.new(bar_index, tpValue + 1, style=label.style_label_down, textcolor=color.white,
text="Buy Call\nStrike Near: " +
str.tostring(tpValue,"#") + "\nOpen: " + str.tostring(entryPrice))
if goShort[1]
shortTrades := shortTrades + 1
sharesInTrade := -calcShares
tpValue := math.floor(open - valueMove * tpMoveRatio)
stopValue := AlphaTrend + valueMove
entryPrice := open
label.new(bar_index, tpValue - 1, style=label.style_label_up, textcolor=color.white,
text="Buy Put\nStrike Near: " +
str.tostring(tpValue,"#") + "\nOpen: " + str.tostring(entryPrice))
inTrade = sharesInTrade != 0
plot(not inTrade ? na : tpValue, color=color.purple, style=plot.style_linebr)
plot(not inTrade ? na : stopValue, color=color.red, style=plot.style_linebr)
var table resultsDisplay = table.new(position.bottom_right, 6, 4)
if barstate.islast and showBackTestResults
table.cell(resultsDisplay, 1, 0, 'Trades', text_color=color.white)
table.cell(resultsDisplay, 2, 0, 'Wins', text_color=color.white)
table.cell(resultsDisplay, 3, 0, 'Win %', text_color=color.white)
table.cell(resultsDisplay, 4, 0, 'Avg Bars', text_color=color.white)
table.cell(resultsDisplay, 5, 0, 'Max Bars', text_color=color.white)
table.cell(resultsDisplay, 0, 1, 'All', text_color=color.white)
table.cell(resultsDisplay, 1, 1, str.tostring(longTrades + shortTrades, '#'), text_color=color.white)
table.cell(resultsDisplay, 2, 1, str.tostring(longWins + shortWins, '#'), text_color=color.white)
table.cell(resultsDisplay, 3, 1, str.tostring((longWins + shortWins)/(longTrades + shortTrades)*100, '#.#') , text_color=color.white)
table.cell(resultsDisplay, 4, 1, str.tostring((shortBars + longBars)/(longTrades + shortTrades), '#.#') , text_color=color.white)
table.cell(resultsDisplay, 5, 1, str.tostring(math.max(maxShortBars, maxLongBars), '#.#') , text_color=color.white)
table.cell(resultsDisplay, 0, 2, 'Longs', text_color=color.white)
table.cell(resultsDisplay, 1, 2, str.tostring(longTrades, '#'), text_color=color.white)
table.cell(resultsDisplay, 2, 2, str.tostring(longWins, '#') , text_color=color.white)
table.cell(resultsDisplay, 3, 2, str.tostring(longWins/(longTrades)*100, '#.#') , text_color=color.white)
table.cell(resultsDisplay, 4, 2, str.tostring((longBars)/(longTrades ), '#.#') , text_color=color.white)
table.cell(resultsDisplay, 5, 2, str.tostring(maxLongBars, '#.#') , text_color=color.white)
table.cell(resultsDisplay, 0, 3, 'Shorts', text_color=color.white)
table.cell(resultsDisplay, 1, 3, str.tostring(shortTrades, '#'), text_color=color.white)
table.cell(resultsDisplay, 2, 3, str.tostring(shortWins, '#') , text_color=color.white)
table.cell(resultsDisplay, 3, 3, str.tostring(shortWins/(shortTrades)*100, '#.#') , text_color=color.white)
table.cell(resultsDisplay, 4, 3, str.tostring((shortBars)/(shortTrades ), '#.#') , text_color=color.white)
table.cell(resultsDisplay, 5, 3, str.tostring(maxShortBars, '#.#') , text_color=color.white)
// table.cell(resultsDisplay, 0, 4, 'P&L', text_color=color.white)
// table.cell(resultsDisplay, 1, 4, str.tostring(plFromTrades, '#.##'), text_color=color.white)
// table.cell(resultsDisplay, 2, 4, str.tostring("") , text_color=color.white)
// table.cell(resultsDisplay, 3, 4, str.tostring("") , text_color=color.white)
|
Polynomial Regression Derivatives [Loxx] | https://www.tradingview.com/script/Z4QpxkWD-Polynomial-Regression-Derivatives-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 107 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Polynomial Regression Derivatives [Loxx]",
shorttitle = "PRD [Loxx]",
overlay = false)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
_specpolyfitMA(mode, ord, float[] src, deg, len, bar)=>
sumout = 0.
AX = matrix.new<float>(14, 14, 0.)
BX = array.new<float>(14, 0.)
ZX = array.new<float>(14, 0.)
Pow = array.new<float>(26, 0.)
Row = array.new<int>(14, 0)
CX = array.new<float>(14, 0.)
if (len <= 1)
sumout := array.get(src, bar)
else
if mode == 1 or (mode == 0 and bar == -len + 1)
XK = 0.
Prod = 0.
for j = 1 to deg + 1
array.set(BX, j, 0)
for k = 1 to len
YK = array.get(src, len - k)
XK := k
Prod := 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
for j = 0 to 2 * deg
array.set(Pow, j, 0)
array.set(Pow, 0, len)
for k = 1 to len
XK := k
Prod := k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
if matrix.get(AX, array.get(Row, deg + 1), deg + 1) != 0.
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
int mult = 1
if (ord >= 1)
for k = 1 to ord
mult *= (deg - k + 1)
sumout := mult * array.get(CX, deg + 1)
if (deg > ord)
for k = deg to ord + 1
int mult1 = 1
if (ord > 0)
for i = 1 to ord
mult1 *= (k - i)
sumout := mult1 * array.get(CX, k) + sumout * (len + bar)
sumout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
MA_Length = input.int(5, "Source Smoothing Period", group = "Source Settings", minval = 1)
type = input.string("Simple Moving Average - SMA", "Source Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Source Settings")
per = input.int(14, "Period", group = "Basic Settings", minval = 2)
deg = input.int(2, "Degree", group = "Basic Settings", minval = 1, maxval = 12)
order = input.string("1rst Velocity", "Order", options = ["Polynomial Line", "1rst Velocity" ,"2nd Acceleration", "3rd Jerk", "4th Snap", "5th Crackle", "6th Pop"], group = "Basic Settings")
barsbark = input.int(600, "Bars back", group = "Basic Settings", tooltip = "Number of bars painted on screen. This controls the computation speed")
sigper = input.int(5, "Signal Period", group = "Signal Settings")
sigtype = input.string("Simple Moving Average - SMA", "Signal Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
Polynom = src
sig = src
orderout = switch order
"Polynomial Line" => 0
"1rst Velocity" => 1
"2nd Acceleration" => 2
"3rd Jerk" => 3
"4th Snap" => 4
"5th Crackle" => 4
"6th Pop" => 4
=> 0
if deg < orderout
runtime.error("Error: Degree must be greater than or equal to order.")
srcarray = array.new<float>(per, 0)
for j = 0 to per - 1
array.set(srcarray, j, nz(variant(type, src, MA_Length)[j]))
if last_bar_index - bar_index < barsbark
Polynom := _specpolyfitMA(1, orderout, srcarray, deg, per, 0)
sig := variant(sigtype, Polynom, sigper)
colorout = Polynom > sig ? greencolor : redcolor
plot(last_bar_index - bar_index < barsbark ? Polynom : na, "Poly Derivative", color = colorout, linewidth = 3)
plot(last_bar_index - bar_index < barsbark ? sig : na, "Signal", color = color.white, linewidth = 1)
barcolor(last_bar_index - bar_index < barsbark and colorbars ? colorout : na)
plot(last_bar_index - bar_index < barsbark ? 0 : na, "Middle", color = bar_index % 2 ? color.gray : na)
|
Rolling Quartiles | https://www.tradingview.com/script/0VZeLDp7-Rolling-Quartiles/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 182 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ DojiEmoji
//@version=5
indicator("Quartiles with Box Plot [KL]", overlay=true)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Settings
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
float src = input.source(close, title="Source data")
var int n = input.int(20, title="Lookback", minval=1)
var int offset = input.int(5, minval=5, maxval=150, title="Offset: Box Plot", step=5, tooltip="Relative to recenrt bar (right hand side)")
var string GROUP_1 = "Box plot"
var color color1 = input.color(color.blue, title="Box plot", group=GROUP_1)
var int ln_width = input.int(2, title="Width", minval=1, maxval=4, group=GROUP_1)
var bool mod_boxplot = input.bool(false, title="Use modified boxplot (Whiskers = 1.5x IQR)")
var bool show_hline_iqr = input.bool(true, title="Show lines for rolling IQR", group=GROUP_1)
var bool show_hline_maxmin = input.bool(false, title="Show lines for rolling Min & Max", group=GROUP_1)
var string GROUP_2 = "Historical IQR - Moving lines"
var string _tt = "Go to 'Style' tab to modify color/width"
var bool show_bands_iqr = input.bool(false, title="Show moving IQR", group=GROUP_2, tooltip=_tt)
var bool show_bands_mm = input.bool(false, title="Show moving Min & Max", group=GROUP_2, tooltip=_tt)
var string GROUP_3 = "Trend Indicator"
var bool use_barcol = input.bool(false, title="Modify bar colors according to trend:", tooltip="Based on whether price is above/within/below IQR.", group=GROUP_3)
var color color2_up = input.color(color.blue, title="Uptrend", group=GROUP_3)
var color color3_neutral = input.color(color.gray, title="Neutral", group=GROUP_3)
var color color4_dn = input.color(color.red, title="Downtrend", group=GROUP_3)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Quartiles
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
float Q1 = ta.percentile_linear_interpolation(src, n, 25)
float Q2 = ta.percentile_linear_interpolation(src, n, 50)
float Q3 = ta.percentile_linear_interpolation(src, n, 75)
float iqr_mod = (Q3 - Q1) * 1.5
float Q0 = mod_boxplot ? Q1 - iqr_mod : ta.percentile_linear_interpolation(src, n, 0)
float Q4 = mod_boxplot ? Q3 + iqr_mod : ta.percentile_linear_interpolation(src, n, 100)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Drawing Box Plot - to represent the quartiles
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Horizontal lines:
var line hline_q0 = na // --- <- hline_q0
var line hline_q1 = na // |
var line hline_q2 = na // |
var line hline_q3 = na // ------- <- hline_q1
var line hline_q4 = na // | |
// | |
// Box plot: // |-------| <- hline_q2
var box box_iqr = na // | |
var line ln_q0 = na // ------- <- hline_q3
var line ln_q0q1 = na // |
var line ln_q2 = na // |
var line ln_q4 = na // --- <- hline_q4
var line ln_q3q4 = na
// Helper functions:
// {
var line[] dump_lns = array.new_line()
// Lines drawn with draw_line() will be temporaily stored in an array of line ("AOL")
draw_line(offset_x1, y1, offset_x2, y2, ln_color, ln_width, ln_style=line.style_solid) =>
ln = line.new(bar_index+offset_x1, y1, bar_index+offset_x2, y2, xloc.bar_index, color=ln_color, width=ln_width, style=ln_style)
array.push(dump_lns, ln)
ln
// All lines in AOL will get deleted in the next bar-iteration through del_lines()
del_lines() =>
while array.size(dump_lns) > 0
line.delete(array.pop(dump_lns))
// }
// Box and whisker
del_lines()
ln_q0 := draw_line(offset-1, Q0, offset+1, Q0, color1, ln_width)
ln_q0q1 := draw_line(offset+0, Q1, offset+0, Q0, color1, ln_width)
ln_q2 := draw_line(offset-2, Q2, offset+2, Q2, color1, ln_width)
ln_q3q4 := draw_line(offset+0, Q3, offset+0, Q4, color1, ln_width)
ln_q4 := draw_line(offset-1, Q4, offset+1, Q4, color1, ln_width)
box.delete(box_iqr[1])
box_iqr := box.new(bar_index+offset-2, Q3, bar_index+offset+2, Q1,
border_color=color1, bgcolor=na, border_width=ln_width)
// Rolling quartiles
if show_hline_iqr
hline_q1 := draw_line(-n, Q1, offset-4, Q1, color1, 1, line.style_dotted)
hline_q2 := draw_line(-n, Q2, offset-4, Q2, color1, 1, line.style_dotted)
hline_q3 := draw_line(-n, Q3, offset-4, Q3, color1, 1, line.style_dotted)
if show_hline_maxmin
hline_q0 := draw_line(-n, Q0, offset-4, Q0, color1, 1, line.style_dotted)
hline_q4 := draw_line(-n, Q4, offset-4, Q4, color1, 1, line.style_dotted)
// Moving quartiles
p1 = plot(Q1, color=show_bands_iqr ? color1 : na, title="Q1 Lower band")
plot(Q2, color=show_bands_iqr ? color1 : na, title="Q2 Center line")
p2 = plot(Q3, color=show_bands_iqr ? color1 : na, title="Q3 Upper band")
fill(p1, p2, color=color.new(color.gray,100), title="Moving IQR")
plot(Q0, color=show_bands_mm ? color1 : na, title="Q0 Min band")
plot(Q4, color=show_bands_mm ? color1 : na, title="Q4 Max band")
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Bar Color (Trend Indicator)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barcolor(use_barcol and close > Q3 ? color2_up : na, editable=false)
barcolor(use_barcol and close < Q3 and close > Q1 ? color3_neutral : na, editable=false)
barcolor(use_barcol and close < Q1 ? color4_dn : na, editable=false)
|
PrevHighLow Trend Indicator | https://www.tradingview.com/script/CXjVYCkG-prevhighlow-trend-indicator/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 208 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ tarasenko_
//@version=5
indicator("PrevHighLow Trend Indicator", shorttitle = "PHLTI", overlay=true, timeframe="")
// Inputs
SmMA(source, length, type) =>
var m = matrix.new<float>(1, length, 0)
for i = 0 to length-1
matrix.set(m, 0, i, source)
type == "SMA" ? ta.sma(source, length) :
type == "EMA" ? ta.ema(source, length) :
type == "SMMA (RMA)" ? ta.rma(source, length) :
type == "WMA" ? ta.wma(source, length) :
type == "VWMA" ? ta.vwma(source, length) :
type == "HMA" ? ta.hma(source, length) :
type == "ALMA" ? ta.alma(source, length, 0.85, 6) :
type == "SWMA" ? ta.swma(source) :
type == "RMA" ? ta.rma(source, length) :
type == "VWAP" ? ta.vwap(source) :
type == "LSMA" ? ta.linreg(source, length, 0) :
na
useSourceSmoothing = input(false, "Use source smoothing?", group="Source smoothing", tooltip="Source smoothing eliminates noise in price source data and thus helps you get much \"cleaner\" price data.\n\nNote: it only affects signals!\n\nDisabled by default. Default source - open.")
ma_type = input.string("SMA", title="MA type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA", "ALMA", "SWMA", "RMA", "VWAP", "LSMA"], group="Source smoothing")
ma_source = input(open, title="MA source", group="Source smoothing")
ma_period = input.int(20, title="MA period", minval=1, group="Source smoothing")
src = useSourceSmoothing ? SmMA(ma_source, ma_period, ma_type) : open
p1 = input.int(50, "Slow period", minval=1, group = "Main settings", tooltip="This MA's purpose is to show main trend.\n\nAlso may work as support/resistance.")
p2 = input.int(10, "Fast period", minval=1, group = "Main settings", tooltip="This MA shows faster trend AND controls filters.\n\nMay work as support/resistance as well as slow MA, but as it is fast, it is kinda risky to use it in this way.")
useF = input(true, "Use filters at all?", group="Filter switch", tooltip="Filter is connected to the Fast MA, so whenever you change it, filter will be also changed.")
useRSI = input(false, "Use RSI filter?", group="Filter switch", tooltip="RSI usually shows good reversals, if customised well.")
rsi_p = input.int(14, "RSI period", group="RSI Filter Settings")
rsi_src = input(open, "RSI source", group="RSI Filter Settings")
rsi_hhl = input.int(60, "RSI higher band", group = "RSI Filter Settings", minval=0)
rsi_lhl = input.int(40, "RSI lower band", group="RSI Filter Settings", minval=0)
useMACD = input(false, "Use MACD filter?", group="Filter switch", tooltip="MACD usually shows nice trend, if customised well.")
macd_src = input(open, "MACD source", group="MACD Filter Settings")
macd_fastlen = input.int(10, "MACD fast length", minval = 1, group="MACD Filter Settings")
macd_slowlen = input.int(6, "MACD low length", minval = 1, group="MACD Filter Settings")
macd_siglen = input.int(2, "MACD signal length", minval = 1, group="MACD Filter Settings")
useMACDRSI = input(false, "Use MACD+RSI filter?", group="Filter switch", tooltip="Basically summarises advantages of MACD and RSI.")
useCOG = input(false, 'Use COG filter?', group="Filter switch", tooltip="COG uses advanced statistic and Fibonacci ratio.\n\nGood for identifying trend, like MACD, but better time to time.")
cog_period = input.int(5, "COG period", group="COG Filter Settings")
cog_src = input(open, "COG source", group="COG Filter Settings")
useMACDCOG = input(false, "Use MACD+COG filter?", group="Filter switch", tooltip="Helps you find more accurate trends, if customised well.")
useMACDCOGRSI = input(false, "Use MCR filter?", group="Filter switch", tooltip="Helps you find more accurate trends, if customised well.")
useOffset = input(true, "Use offest?", group = "Offset", tooltip="Offset helps time signals better.")
useClassicOffset = input(true, "Use classic offest?", group="Classic offset", tooltip="Classic offset is 1.")
classicOffsetPeriod = input.int(1, "Classic offset period", minval=1, group="Classic offset")
useATROffset = input(false, "Use ATR offest?", group="ATR Offset")
ATROffsetPeriod = input.int(3, "ATR offset period", group="ATR Offset", minval=1)
// Declarations and calculations
classicOffset=useOffset and useClassicOffset? classicOffsetPeriod : 0
ATROffset = useOffset and useATROffset ? int(ta.atr(ATROffsetPeriod)) : 0
h1 = ta.highest(p1)
l1 = ta.lowest(p1)
h2 = ta.highest(p2)
l2 = ta.lowest(p2)
lh12 = (l1[1]+h1[1])/2
lh22 = (l2[1]+h2[1])/2
rsi = ta.rsi(rsi_src, rsi_p)
[macd_line, signal_line, hist_line] = ta.macd(macd_src, macd_fastlen, macd_slowlen, macd_siglen)
cog = ta.cog(src, cog_period)
// Signals
cog_sell = cog < cog[1]
cog_buy = cog > cog[1]
macd_sell = signal_line > macd_line and ((lh22 > src and lh12 > src) or (lh22 < src and lh12 < src))
macd_buy = signal_line < macd_line and ((src > lh22 and lh12 < src) or (src < lh22 and lh12 > src))
rsi_sell = math.max(rsi, rsi[1]) >= rsi_hhl //and ((lh22 > src and lh12 > src) or (lh22 < src and lh12 < src))
rsi_buy = math.min(rsi, rsi[1]) <= rsi_lhl //and ((src > lh22 and src > lh12) or (src < lh22 and src < lh12))
strong_sell = rsi_sell and macd_sell and cog_sell and ((lh12 > src and lh22 > src) or (lh12 < src and lh22 < src))
strong_buy = rsi_buy and macd_buy and cog_buy and ((src > lh22 and src > lh12) or (src < lh22 and src < lh12))
macdrsi_sell = rsi_sell and macd_sell
macdrsi_buy = rsi_sell and macd_buy
macdcog_sell = macd_sell and cog_sell
macdcog_buy = macd_buy and cog_buy
mcr_sell = macd_sell and cog_sell and rsi_sell
mcr_buy = macd_buy and cog_buy and rsi_buy
// Coloring
colour1 = open > lh12 ? #00cc00 : open < lh12 ? #ff0000 : #ffad00
colour2 = open > lh22 ? #00cc00 : open < lh22 ? #ff0000 : #ffad00
colour_fill = open > lh12 ? #00cc0020 : open < lh12 ? #ff000020 : #ffad0020
// Plotting
ma1 = plot(lh12, color = colour1, linewidth = 2, style=plot.style_stepline, title="Slow MA")
ma2 = plot(src > lh22 ? low : src < lh22 ? high : lh22, color = #00000000)
color_line = plot(lh22, color = colour2, linewidth = 2, style=plot.style_circles, title="Fast MA")
fill(ma1, ma2, color = colour_fill, title="Cloud")
// Labeling signals
// Strong signals' labeling
plotshape(useF and strong_sell and strong_sell[1]!=true, title="Strong sell", style=shape.labeldown, color=#ff0000, text = "SS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and strong_buy and strong_buy[1]!=true, title="Strong buy", style=shape.labelup, color=#00cc00, text = "SB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// RSI signals' labeling
plotshape(useF and useRSI and rsi_sell and rsi_sell[1]!=true, title="RSI sell", style=shape.labeldown, color=#6200ca, text = "RS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useRSI and rsi_buy and rsi_buy[1]!=true, title="RSI buy", style=shape.labelup, color=#ed00a0, text = "RB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// MACD signals' labeling
plotshape(useF and useMACD and macd_sell and macd_sell[1]!=true, title="MACD sell", style=shape.labeldown, color=#ff7000, text = "MS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useMACD and macd_buy and macd_buy[1]!=true, title="MACD buy", style=shape.labelup, color=#0057cc, text = "MB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// MACD+RSI signals' labeling
plotshape(useF and useMACDRSI and macdrsi_sell and macdrsi_sell[1]!=true, title="MACD+RSI sell", style=shape.labeldown, color=#000000, text = "MRS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useMACDRSI and macdrsi_buy and macdrsi_buy[1]!=true, title="MACD+RSI buy", style=shape.labelup, color=#3c3c3c, text = "MRB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// COG signals' labeling
plotshape(useF and useCOG and cog_sell and cog_sell[1]!=true, title="COG sell", style=shape.labeldown, color=#ff1a00, text = "CS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useCOG and cog_buy and cog_buy[1]!=true, title="COG buy", style=shape.labelup, color=#77bc15, text = "CB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// MACD+COG signals' labeling
plotshape(useF and useMACDCOG and macdcog_sell and macdcog_sell[1]!=true, title="MACD+COG sell", style=shape.labeldown, color=#9f3737, text = "MCS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useMACDCOG and macdcog_buy and macdcog_buy[1]!=true, title="MACD+COG buy", style=shape.labelup, color=#086d0b, text = "MCB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// MCR signals' labeling
plotshape(useF and useMACDCOGRSI and mcr_sell and mcr_sell[1]!=true, title="MCR sell", style=shape.labeldown, color=#9f3737, text = "MCRS", textcolor=color.white, offset=classicOffset+ATROffset)
plotshape(useF and useMACDCOGRSI and mcr_buy and mcr_buy[1]!=true, title="MCR buy", style=shape.labelup, color=#086d0b, text = "MCRB", textcolor=color.white, location=location.belowbar, offset=classicOffset+ATROffset)
// Alerts for RSI signals
alertcondition(useF and useRSI and rsi_sell and rsi_sell[1]!=true, message="RSI Sell", title="SHORT")
alertcondition(useF and useRSI and rsi_buy and rsi_buy[1]!=true, message="RSI Buy", title="LONG")
alertcondition(useF and useRSI and ((rsi_buy and rsi_buy[1]!=true) or (rsi_sell and rsi_sell[1]!=true)), message="RSI Signal", title="SIGNAL") |
2nd 3rd 4th Order Pivots | https://www.tradingview.com/script/RoHoAyuy-2nd-3rd-4th-Order-Pivots/ | schroederjoa | https://www.tradingview.com/u/schroederjoa/ | 147 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ schroederjoa
// This indicator calculates pivots of 2nd, 3rd and 4th order in the current timeframe.
// The idea is borrowed from the book "The Art and Science of Technical Trading" by Adam Grimes:
// "A pivot high is a bar that has a higher high than the bar that came before it and the bar that comes after it"
// "Second-order pivot highs are first-order pivot highs that are preceded and followed by lower first-order pivot highs.
// The type of picot calculation can be found as well in script "Higher Order Pivots" by rumpypumpydumpy.
// However, this script is different in the following ways:
// 1. Shows pivots of order 2, 3 and 4
// 2. The chart timeframe can be different than the pivot timeframe, allowing e.g. to map daily pivots to intraday charts via lines
// 2. Labels and/or Lines can be used to show pivot points
// 3. Use of extended session data be be enabled/disabled, independently from the current chart settings
// 4. To disable older pivots, a starting time for the pivot calculation can be set
// Please consider following limitations:
// 1. Maximum of 500 drawing objects per chart: Use Notification option to keep track of when running out of chart objects.
// 2. Lookback history: The max lookback history is limited by the currently selected timeframe. E.g. on a 5min timeframe,
// 20000 bars (Premium Plan) result in approx. 5 months of lookback period, meaning you may want to have a 30 min or higher
// chart open to get a complete picture of pivots, while trading on a lower timeframe.
//@version=5
indicator("2nd 3rd 4th Order Pivots", shorttitle="234 Piv", overlay=true, max_lines_count=500, max_labels_count=500)
f_print(_text) => var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_none, color.orange, size.large, text.align_right), label.set_xy(_label, bar_index, ta.highest(10)[1]), label.set_text(_label, _text)
tfInput = input.string("D", "Timeframe", options = ["Current","1","3","5","10","15","30","60","120","180","240","D","W","M"])
var bool time_skip = input.bool(false, title="",inline = "21")
var time_start = input.time(timestamp("01 Jan 2022 09:30:00 UTC-5"), "Only consider data after",inline = "21")
bool max_objects_notify = input.bool(true, title="Enable Notification for > 480 drawing Objects")
var g01 = "Pivots 2nd Order"
show_order_2_labels = input.bool(false, title="Show Labels", group=g01)
show_order_2_lines = input.bool(false, title="Show Lines", group=g01)
width_order_2 = input.int(1, title="Line Width", group=g01)
col_order_2_h = input(color.new(color.teal, 40), title = "Pivot High Color", group=g01)
col_order_2_l = input(color.new(color.maroon, 40), title = "Pivot Low Color", group=g01)
var g02 = "Pivots 3rd Order"
show_order_3_labels = input.bool(true, title="Show Labels", group=g02)
show_order_3_lines = input.bool(true, title="Show Lines", group=g02)
width_order_3 = input.int(2, title="Line Width", group=g02)
col_order_3_h = input(color.new(color.teal, 20), title = "Pivot High Color", group=g02)
col_order_3_l = input(color.new(color.maroon, 20), title = "Pivot Low Color", group=g02)
var g03 = "Pivots 4th Order"
show_order_4_labels = input.bool(true, title="Show Labels", group=g03)
show_order_4_lines = input.bool(true, title="Show Lines", group=g03)
width_order_4 = input.int(3, title="Line Width", group=g03)
col_order_4_h = input(color.new(color.teal, 0), title = "Pivot High Color", group=g03)
col_order_4_l = input(color.new(color.maroon, 0), title = "Pivot Low Color", group=g03)
f_is_order_1_pivot() =>
[high[1] > high and high[1] > high[2],high[1], low[1] < low and low[1] < low[2], low[1], time[1]]
ticker = ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session)
[is_1st_pivot_high, hval, is_1st_pivot_low, lval, ti] = request.security(ticker, tfInput == "Current" ? timeframe.period : tfInput, f_is_order_1_pivot())
// array definitions for pivot low and highs, each with its value and time
var arr_order_1_vh = array.new_float(0)
var arr_order_1_th = array.new_int(0)
var arr_order_2_vh = array.new_float(0)
var arr_order_2_th = array.new_int(0)
var arr_order_3_vh = array.new_float(0)
var arr_order_3_th = array.new_int(0)
var arr_order_4_vh = array.new_float(0)
var arr_order_4_th = array.new_int(0)
var arr_order_1_vl = array.new_float(0)
var arr_order_1_tl = array.new_int(0)
var arr_order_2_vl = array.new_float(0)
var arr_order_2_tl = array.new_int(0)
var arr_order_3_vl = array.new_float(0)
var arr_order_3_tl = array.new_int(0)
var arr_order_4_vl = array.new_float(0)
var arr_order_4_tl = array.new_int(0)
// create 1st order pivots as starting point
if is_1st_pivot_high and not (time_skip and ti < time_start) and ti != ti[1]
array.push(arr_order_1_vh, hval)
array.push(arr_order_1_th, ti)
if is_1st_pivot_low and not (time_skip and ti < time_start) and ti != ti[1]
array.push(arr_order_1_vl, lval)
array.push(arr_order_1_tl, ti)
num_objects = 0
if barstate.islast
array.clear(arr_order_2_th)
array.clear(arr_order_2_vh)
// calculate 2nd, 3rd and 4th order arrays, always based on the lower order arrays
// if it has minimum 3 entries, a possible higher order pivot can be determined
if array.size(arr_order_1_vh) > 3
for i = 1 to array.size(arr_order_1_vh) - 2
if array.get(arr_order_1_vh,i) > array.get(arr_order_1_vh,i-1) and array.get(arr_order_1_vh,i) > array.get(arr_order_1_vh,i+1)
array.push(arr_order_2_th,array.get(arr_order_1_th,i))
array.push(arr_order_2_vh,array.get(arr_order_1_vh,i))
array.clear(arr_order_2_tl)
array.clear(arr_order_2_vl)
if array.size(arr_order_1_vl) > 3
for i = 1 to array.size(arr_order_1_vl) - 2
if array.get(arr_order_1_vl,i) < array.get(arr_order_1_vl,i-1) and array.get(arr_order_1_vl,i) < array.get(arr_order_1_vl,i+1)
array.push(arr_order_2_tl,array.get(arr_order_1_tl,i))
array.push(arr_order_2_vl,array.get(arr_order_1_vl,i))
array.clear(arr_order_3_th)
array.clear(arr_order_3_vh)
if array.size(arr_order_2_vh) > 3
for i = 1 to array.size(arr_order_2_vh) - 2
if array.get(arr_order_2_vh,i) > array.get(arr_order_2_vh,i-1) and array.get(arr_order_2_vh,i) > array.get(arr_order_2_vh,i+1)
array.push(arr_order_3_th,array.get(arr_order_2_th,i))
array.push(arr_order_3_vh,array.get(arr_order_2_vh,i))
array.clear(arr_order_3_tl)
array.clear(arr_order_3_vl)
if array.size(arr_order_2_vl) > 3
for i = 1 to array.size(arr_order_2_vl) - 2
if array.get(arr_order_2_vl,i) < array.get(arr_order_2_vl,i-1) and array.get(arr_order_2_vl,i) < array.get(arr_order_2_vl,i+1)
array.push(arr_order_3_tl,array.get(arr_order_2_tl,i))
array.push(arr_order_3_vl,array.get(arr_order_2_vl,i))
array.clear(arr_order_4_th)
array.clear(arr_order_4_vh)
if array.size(arr_order_3_vh) > 3
for i = 1 to array.size(arr_order_3_vh) - 2
if array.get(arr_order_3_vh,i) > array.get(arr_order_3_vh,i-1) and array.get(arr_order_3_vh,i) > array.get(arr_order_3_vh,i+1)
array.push(arr_order_4_th,array.get(arr_order_3_th,i))
array.push(arr_order_4_vh,array.get(arr_order_3_vh,i))
array.clear(arr_order_4_tl)
array.clear(arr_order_4_vl)
if array.size(arr_order_3_vl) > 3
for i = 1 to array.size(arr_order_3_vl) - 2
if array.get(arr_order_3_vl,i) < array.get(arr_order_3_vl,i-1) and array.get(arr_order_3_vl,i) < array.get(arr_order_3_vl,i+1)
array.push(arr_order_4_tl,array.get(arr_order_3_tl,i))
array.push(arr_order_4_vl,array.get(arr_order_3_vl,i))
if show_order_2_labels or show_order_2_lines
for i = 0 to (array.size(arr_order_2_th) == 0 ? na : array.size(arr_order_2_th) - 1)
t = array.get(arr_order_2_th,i)
v = array.get(arr_order_2_vh,i)
if show_order_2_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_2_h, style=line.style_solid, width=width_order_2, extend=extend.right)
num_objects := num_objects + 1
if show_order_2_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_2_h, style=label.style_label_down, size = size.tiny)
num_objects := num_objects + 1
for i = 0 to (array.size(arr_order_2_tl) == 0 ? na : array.size(arr_order_2_tl) - 1)
t = array.get(arr_order_2_tl,i)
v = array.get(arr_order_2_vl,i)
if show_order_2_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_2_l, style=line.style_solid, width=width_order_2, extend=extend.right)
num_objects := num_objects + 1
if show_order_2_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_2_l, style=label.style_label_up, size = size.tiny)
num_objects := num_objects + 1
if show_order_3_labels or show_order_3_lines
for i = 0 to (array.size(arr_order_3_th) == 0 ? na : array.size(arr_order_3_th) - 1)
t = array.get(arr_order_3_th,i)
v = array.get(arr_order_3_vh,i)
if show_order_3_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_3_h, style=line.style_solid, width=width_order_3, extend=extend.right)
num_objects := num_objects + 1
if show_order_3_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_3_h, style=label.style_label_down, size = size.small)
num_objects := num_objects + 1
for i = 0 to (array.size(arr_order_3_tl) == 0 ? na : array.size(arr_order_3_tl) - 1)
t = array.get(arr_order_3_tl,i)
v = array.get(arr_order_3_vl,i)
if show_order_3_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_3_l, style=line.style_solid, width=width_order_3, extend=extend.right)
num_objects := num_objects + 1
if show_order_3_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_3_l, style=label.style_label_up, size = size.small)
num_objects := num_objects + 1
if show_order_4_labels or show_order_4_lines
for i = 0 to (array.size(arr_order_4_th) == 0 ? na : array.size(arr_order_4_th) - 1)
t = array.get(arr_order_4_th,i)
v = array.get(arr_order_4_vh,i)
if show_order_4_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_4_h, style=line.style_solid, width=width_order_4, extend=extend.right)
num_objects := num_objects + 1
if show_order_4_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_4_h, style=label.style_label_down, size = size.normal)
num_objects := num_objects + 1
for i = 0 to (array.size(arr_order_4_tl) == 0 ? na : array.size(arr_order_4_tl) - 1)
t = array.get(arr_order_4_tl,i)
v = array.get(arr_order_4_vl,i)
if show_order_4_lines
line.new(t, v, t+1, v, xloc=xloc.bar_time, color=col_order_4_l, style=line.style_solid, width=width_order_4, extend=extend.right)
num_objects := num_objects + 1
if show_order_4_labels
label.new(x=t, y=v, xloc=xloc.bar_time, color=col_order_4_l, style=label.style_label_up, size = size.normal)
num_objects := num_objects + 1
info_str = ""
if num_objects > 480 and max_objects_notify
info_str := info_str + str.tostring(num_objects) + " Drawing Objects (max 500 per chart!)"
f_print(info_str)
|
the Flasher | https://www.tradingview.com/script/ToCOzXOT-the-Flasher/ | allanster | https://www.tradingview.com/u/allanster/ | 526 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ allanster
//@version=5
indicator("the Flasher", overlay = true)
// โ ๏ธ Seizure warning.
// WARNING: This indicator may potentially trigger seizures for people with photosensitive epilepsy. User discretion is advised.
warns = input.text_area('โ ๏ธ Seizure warning.\n\nWARNING: This indicator may potentially trigger seizures for people with photosensitive epilepsy. User discretion is advised.')
agree = input.bool(false, 'Enable the Flasher')
// Briefly flashes chart background colors as a visual alert whenever a condition occurs, from the insatiable mind of @scarf.
// Special thanks to @LucF for his advice on improving efficiency of dynamic tables.
blipt = 'Persistent conditions that remain true will cycle only once. Transient conditions will cycle on each intrabar ' +
'occurrence. Flashes for some transient conditions may be skipped if the color cycle for the previous condition has not ' +
'concluded when the new condition occurs. If this is of concern then reducing the Cycles value lower will reduce the ' +
'chance of overlapping cycles being skipped.\n\nCandles and other indicators may be obscured when colors are flashing if ' +
'the mouse cursor is anywhere on the chart. Color cycling is dependent upon and only occurs upon feed updates.'
mssgt = 'Option to include flashed messages. Leave the Option field blank if no message is desired. Message colors are ' +
'syncronized to occur with the corresponding color cycles that are set in the Cycles color settings.'
cntFt = 'Uncheck this box to disable the displaying of the current cycle number that is being flashed.'
blipU = input.int (3, 'Cycles', minval = 0, inline = '1')
colU1 = input.color (color.new(#00ff00, 0), '', inline = '1')
colU2 = input.color (color.new(#673ab7, 0), '', inline = '1', tooltip = blipt)
mssgU = input.string('MA CROSSED UP!', 'Option', inline = '2')
colu1 = input.color (color.new(#000000, 0), '', inline = '2')
colu2 = input.color (color.new(#ffffff, 0), '', inline = '2', tooltip = mssgt)
blipD = input.int (3, 'Cycles', minval = 0, inline = '3')
colD1 = input.color (color.new(#ff0000, 0), '', inline = '3')
colD2 = input.color (color.new(#ffff00, 0), '', inline = '3', tooltip = blipt)
mssgD = input.string('MA CROSSED DN!', 'Option', inline = '4')
cold1 = input.color (color.new(#ffffff, 0), '', inline = '4')
cold2 = input.color (color.new(#000000, 0), '', inline = '4', tooltip = mssgt)
cntFl = input (true, 'Show Cycles Counter', tooltip = cntFt)
// This is "the Flasher" function.
flash(_agree, _tblNo, _condition, _blips, _colb1, _colb2, _string, _count, _cols1, _cols2) => //{
tblNo = switch _tblNo
1 => position.top_center
=> position.bottom_center // declare position of tabLe instances
var tabLe = table.new(tblNo, 1, 1, color(na)) // create tabLe instance
table.cell(tabLe, 0, 0, "", 100, 100, #000000,
text.align_center, text.align_top, size.huge) // define and set attributes for tabLe cell
varip ticks = 0 // declare intrabar count of price/volume updates
varip state = _condition // declare intrabar value of _condition
varip blink = false // declare intrabar monitor of change in _condition
varip store = _condition // declare intrabar store of value of first _condition
varip cycle = 0 // declare intrabar cycle toggle for colors 1 & 2
if _agree and barstate.isrealtime and _blips > 0 // true for duration of realtime bars, _blips is the total allowed number of color flashes
blink := _condition != state ? true : blink // once a change of _condition is true blink remains true, a persistent _condition is never true
renew = _condition and _condition != state // a new transient condition has occurred
state := _condition // update intrabar value of _condition
store := _condition ? true : store // once first occurrence of _condition is true store remains true
reset = blink ? renew and ticks > _blips : false // reset flag if transient condition refires and number of _blips is met for previous transient _condition
ticks := reset ? 1 : ticks + 1 // tick counter resets after _blips is met for transient _condition, else increments on price update
cycle := reset ? 0 : cycle // cycle resets to first color after flashes is met for intrabar _condition, else continues current cycle
nFlsh = _count ? '\nFlashes: ' + str.tostring(ticks) : '' // display number of flashes
if store and ticks <= _blips // flash up to blips of color
cycle := 1 - (cycle % 2) // cycles repeating values of 1 and 0
table.set_bgcolor(tabLe, cycle ? _colb1 : _colb2) // cycles tabLe's background color attribute
table.cell_set_text_color(tabLe, 0, 0, cycle ? _cols1 : _cols2) // cycles tabLe cell's string color attribute
table.cell_set_text(tabLe, 0, 0, '\n' + _string + nFlsh) // cycles tabLe cell's string attribute
else // clear tabLe and cell attributes
table.set_bgcolor(tabLe, color(na)) // remove tabLe color
table.cell_set_text(tabLe, 0, 0, '') // remove tabLe cell text }
// Replace This Code Block With The Conditions Needing To Be Flashed On Chart. {
fastr = ta.ema(hlc3, 1), plot(fastr, '', #ff9800, 2)
slowr = ta.ema(hlc3, 2), plot(slowr, '', #00bcd4, 2)
condU = ta.crossover (fastr, slowr)
condD = ta.crossunder(fastr, slowr)
//}
// Call "the Flasher" function with assigned parameters. Bottom line's call statement supercedes top line's call statement.
flash(agree, 0, condU, blipU, colU1, colU2, mssgU, cntFl, colu1, colu2)
flash(agree, 1, condD, blipD, colD1, colD2, mssgD, cntFl, cold1, cold2) |
Aroon Oscillator [bkeevil] | https://www.tradingview.com/script/rGhM7LNu-Aroon-Oscillator-bkeevil/ | bkeevil | https://www.tradingview.com/u/bkeevil/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ bkeevil
// Purpose: to highlight short term trend changes.
// Reference: https://www.investopedia.com/terms/a/aroon.asp
// https://www.investopedia.com/terms/a/aroonoscillator.asp
// @version=5
indicator(title="Aroon Oscillator [bkeevil]", shorttitle="Aroon Osc", overlay=false, precision=0, timeframe="", timeframe_gaps=true)
DEFAULT_LENGTH = 25 // Number of periods to consider
UPPER_LIMIT = 50 // Upper range limit
LOWER_LIMIT = -50 // Lower range limit
COLOR_BACKGROUND = color.new(color.teal,95)
COLOR_LIMIT = color.new(color.teal,25)
COLOR_ZERO = color.new(color.gray,33)
COLOR_OSCILLATOR = color.new(color.blue,50)
COLOR_DOWNTREND = color.new(color.green,90)
COLOR_UPTREND = color.new(color.red,90)
lengthInput = input.int(DEFAULT_LENGTH, title="Length", minval=1, tooltip="Number of periods to consider when searching for the last high/low. Default is 25")
// The number of periods since the last lengthInput period high
highest = 100 * (ta.highestbars(high, lengthInput) + lengthInput) / lengthInput
// The number of periods since the last lengthInput period low
lowest = 100 * (ta.lowestbars(low, lengthInput) + lengthInput) / lengthInput
// Oscillator is the difference between upper & lower
oscillator = highest - lowest
// fillColor indicates buy/sell conditions. Use background color if neither condition is present
fillColor = oscillator > UPPER_LIMIT ? COLOR_UPTREND : oscillator < LOWER_LIMIT ? COLOR_DOWNTREND : COLOR_BACKGROUND
// Paint the visuals
midlinePlot = hline(0,"Zero Line",COLOR_ZERO,hline.style_solid)
upperPlot = hline(UPPER_LIMIT,"Upper Limit",COLOR_LIMIT,hline.style_dotted)
lowerPlot = hline(LOWER_LIMIT,"Lower Limit",COLOR_LIMIT,hline.style_dotted)
fill(upperPlot,lowerPlot,fillColor,title="Background")
oscillatorPlot = plot(oscillator, "Value", color=COLOR_OSCILLATOR) |
[SS]Multicolor BB with Squeez Moving Average & Colored Bars | https://www.tradingview.com/script/qm8gIcMP-SS-Multicolor-BB-with-Squeez-Moving-Average-Colored-Bars/ | World_of_Indicators | https://www.tradingview.com/u/World_of_Indicators/ | 329 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ World_of_Indicators
//@version=5
indicator("[SS]Multicolor BB with Squeez Moving Average & Colored Bars",
shorttitle='[SS]Multicolor BB & SQZ MA with Color Bars',
overlay = true, precision=8,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
_calcBaseUnit() =>
bool isForexSymbol = syminfo.type == "forex"
bool isYenPair = syminfo.currency == "JPY"
float result = isForexSymbol ? isYenPair ? 0.01 : 0.0001 : syminfo.mintick
result
greencolor = #2DD204
redcolor = #D2042D
fsmthtype = input.string("Kaufman", "Fast Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Fast MA Settings")
fastsrc = input.string("Close", "Fast Source", group= "Fast MA Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
ftype = input.string("Exponential Moving Average - EMA", "Fast MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Fast MA Settings")
fastper = input.int(5, "Fast Period", group= "Fast MA Settings")
ssmthtype = input.string("Kaufman", "Slow Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Slow MA Settings")
slowsrc = input.string("Close", "Slow Source", group= "Slow MA Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
stype = input.string("Exponential Moving Average - EMA", "Slow MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
slowper = input.int(23, "Slow Period", group= "Slow MA Settings")
atrper = input.int(50, "ATR Period", group= "Filter Settings")
atrmult = input.float(.4, "ATR Multiplier", group= "Filter Settings")
pipsfiltin = input.int(36, "MA Threshhold Ticks", group= "Filter Settings")
filttype = input.string("ATR", "Filter type", options = ["ATR", "Pips"], group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showfillbands = input.bool(true, "Show fill bands?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
outsrc(srcin, smthtype)=>
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
src
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
ma1 = variant(ftype, outsrc(fastsrc, fsmthtype), fastper)
ma2 = variant(stype, outsrc(slowsrc, ssmthtype), slowper)
madif = math.abs(ma1-ma2)
pipsout = _calcBaseUnit()
delta = filttype == "ATR" ? ta.atr(atrper) * atrmult / pipsout : pipsfiltin
out1 = 0., out2 = 0.
swithit = false
if (madif / pipsout < delta)
dPoint = delta * pipsout
out1 := ma2 + dPoint
out2 := ma2 - dPoint
swithit := true
else
swithit := false
e1 = plot(out1 ? out1 : na, "Upper band", color = out1 ? color.gray : na, style = plot.style_linebr)
e2 = plot(out1 ? out2 : na, "Lower band", color = out1 ? color.gray : na, style = plot.style_linebr)
fill(e1, e2, color = showfillbands ? (out1 ? color.new(color.gray, 20) : na) : na)
sqstrart = swithit and not nz(swithit[1])
sqzend = not swithit and nz(swithit[1])
goLong = sqzend and ma1 > ma2
goShort = sqzend and ma1 < ma2
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong ? 1 : goShort ? -1 : contSwitch
candleout = out1 ? color.white : contSwitch == 1 ? greencolor : redcolor
colorout = out1 ? color.gray : contSwitch == 1 ? greencolor : redcolor
barcolor(colorbars ? candleout : na)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.small)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.small)
length = input.int(50, minval=1)
src = close
price=open
mult = input.float(2.4, minval=0.1, maxval=50)
show_sma = input(false, title='Show SMAs?')
// Bollinger
basis = ta.sma(price, length)
dev = mult * ta.stdev(price, length)
upper = basis + dev
lower = basis - dev
up = basis > basis[1]
down = basis < basis[1]
// SMA
sma20 = ta.sma(src, 20)
sma50 = ta.sma(src, 50)
sma100 = ta.sma(src, 100)
sma200 = ta.sma(src, 200)
// color management
var color_bb = color.green
// red color zone: trend is bearish, price is below the 200 periods moving average
if close < sma200
color_bb := color.new(color.red, 20)
color_bb
// orange color zone: price operate a technical rebound below the 200 periods moving average
if close < sma200 and close > sma20
color_bb := color.new(color.orange, 20)
color_bb
// yellow color zone: (phase 1 which indicate a new bearish cycle)
if close < sma200 and close > sma50 and sma50 < sma200
color_bb := color.new(color.yellow, 20)
color_bb
// light green zone: (phase 2 which indicate a new bullish cycle)
if close > sma200 and close > sma50 and sma50 > sma200
color_bb := color.new(color.lime, 20)
color_bb
// dark green zone: trend is bullish, price is above the 200 periods moving average
if sma200 < sma50 and sma50 < close and close > sma20
color_bb := color.new(color.green, 20)
color_bb
// light blue zones: price will revert to a new opposite trend (either long or short new trend)
if sma100 < sma200 and sma50 < sma200 and sma200 > close and sma100 < close and sma50 < sma100
color_bb := color.new(color.aqua, 20)
color_bb
// light blue zones: price will revert to a new opposite trend (either long or short new trend)
// same as above but using a slight different condition
if sma100 < sma200 and sma50 < sma200 and sma200 > close and sma50 < close and sma100 < sma50
color_bb := color.new(color.aqua, 20)
color_bb
// grey color zone: calm phase of price
if sma200 < close and close < sma100 and sma200 < sma100 and sma200 < sma50
color_bb := color.new(color.gray, 20)
color_bb
// dark blue color zone: price is consolidating in either bullish or bearish trend
if sma200 < sma50 and sma200 < close and sma100 < close and (close < sma50 or close < sma20)
color_bb := color.new(color.blue, 20)
color_bb
mycolor = up ? #2DD204 : down ? #D2042D : color.black
plot(basis, color=mycolor, title='Basis', linewidth=3)
p1 = plot(upper, color=color.new(color_bb, 0), title='Upper Bound')
p2 = plot(lower, color=color.new(color_bb, 0), title='Lower Bound')
fill(p1, p2, color=color.new(color_bb, 90))
// plot the SMAs
plot(show_sma ? sma20 : na, color=color.new(color.aqua, 20), linewidth=2, title='SMA 20')
plot(show_sma ? sma50 : na, color=color.new(color.purple, 20), linewidth=2, title='SMA 50')
plot(show_sma ? sma100 : na, color=color.new(color.orange, 20), linewidth=2, title='SMA 100')
plot(show_sma ? sma200 : na, color=color.new(color.red, 20), linewidth=2, title='SMA 200')
//============================================================================//
|
Reverse Ehler Instantaneous Trendline - TraderHalai | https://www.tradingview.com/script/0kuFBrLa-Reverse-Ehler-Instantaneous-Trendline-TraderHalai/ | TraderHalai | https://www.tradingview.com/u/TraderHalai/ | 70 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// This script uses a reverse function of the famous Ehler Instantaneous Trendline to calculate the source price required in order
// to change from Bullish to bearish
//
// From my analysis, the reverse price does appear to be rather choppy, though it is accurate. This is because Ehler's Instantaneous
// Trendline tends to remain trending for longer periods of time with above average hold periods.
//
// The main suitability for this would be higher level functions. However, I have found that SHA Trend is more accurate and provides better
// Risk adjusted return than using this function
//
// As I had spent a bit of time getting the reverse function mathematics to work, I decided to publish this as open source for the benefit, scrutiny and for further development by the TradingView community anyways.
//
// Enjoy!
// ยฉ TraderHalai
// @version=5
indicator(title = "Reverse Ehler Instantaneous Trendline - TraderHalai", shorttitle="Reverse Ehler Instant Trend - TraderHalai" , overlay = true)
//Inputs
src = input.source(close, "Source", group = "Calculation Parameters")
alpha = input.float(0.07, "Alpha", group = "Calculation Parameters")
i_showIT = input.bool(true, "Show Ehler Instantaneous Trendline", group = "Display Options")
i_infoBox = input.bool(true, "Show info box", group = "Display Options")
i_showTriggerLine = input.bool(false, "Show trigger line", group = "Display Options")
i_colorBars = input.bool(false, "Color bars", group = "Display Options")
i_showReverseCloseLine = input.bool(false, "Show Reverse Function Calculation", group = "Display Options")
i_decimalP = input.int(2, "Number of decimal places", group = "Infobox Options")
i_boxOffSet = input.int(0, "Info box offset", group = "Infobox Options")
//Reverse Instantaneous Trendline Function
//
//Calculated using the following formula (sourced from Wolfram alpha)
//Reverse Src = (-4 (a^2 - 2 a + 2) k - 8 (a - 1) j + a (2 a t + 3 a u - 4 u))/((a - 4) a) and a^2 !=4 a
instant(float src, float alpha) =>
itrend = 0.0
itrend := bar_index < 7 ? (src + 2 * nz(src[1]) + nz(src[2])) / 4 :
(alpha - math.pow(alpha, 2) / 4) * src + 0.5 * math.pow(alpha, 2) * nz(src[1]) - (alpha - 0.75 * math.pow(alpha, 2)) * nz(src[2]) + 2 * (1 - alpha) * nz(itrend[1]) - math.pow(1 - alpha, 2) * nz(itrend[2])
trigger = 2 * itrend - nz(itrend[2])
reverseSrc = bar_index < 7 ? -4 * itrend[2] -(2 * src[1]) - src[2] + 8 * itrend :
(-4 * (math.pow(alpha, 2) - 2 * alpha + 2) * itrend[2] - 8 * (alpha - 1) * itrend[1] + alpha * (2 * alpha * src[1] + 3 * alpha * src[2] -4 * src[2])) / ((alpha - 4) * alpha)
[trigger, itrend, reverseSrc]
//Calculations
[trig, sig, reverseSrc] = instant(src, alpha)
bull = trig > sig
col = bull ? color.green : color.red
//Info box
haDirectionText = bull ? 'BULLISH Above: ' : 'BEARISH Below: '
f_truncdNum ( Val, DecPl ) =>
Fact = math.pow (10, DecPl)
int( Val * Fact) / Fact
var label Infobox = na
labelXLoc = time_close + ( i_boxOffSet * ( time_close - time_close[1] ) )
infoBoxText = haDirectionText + str.tostring(f_truncdNum(reverseSrc, i_decimalP))
if i_infoBox
Infobox := label.new ( labelXLoc, close, infoBoxText, xloc.bar_time, yloc.price, color.new(#00000f, 50), label.style_label_left, color.white )
label.delete ( Infobox[1] )
//Plots
plot(i_showIT ? trig : na, title="Instantaneous TrendLine", color=col, linewidth=2)
plot(i_showTriggerLine ? sig : na, color=color.gray, title= "Trigger Line")
barcolor(i_colorBars ? col : na)
plot(i_showReverseCloseLine ? reverseSrc : na, color=color.aqua) |
Candle Strength | https://www.tradingview.com/script/ecnJXleY-Candle-Strength/ | Trade_by_DB | https://www.tradingview.com/u/Trade_by_DB/ | 227 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Trade_by_DB
//@version=5
indicator("Candle Strength",overlay = true )
//round function for rounding up to n decimal places
//Thanks to Proper Round Function - QuantNomad
roundn(x, n) =>
mult = 1
if n != 0
for i = 1 to math.abs(n) by 1
mult *= 10
mult
n >= 0 ? math.round(x * mult) / mult : math.round(x / mult) * mult
//calculating strength
green = roundn(((close-low)/(high-low) *100), 2)
red = roundn(((high-close)/(high-low)*100), 2)
if (close>open)
l = label.new(x = bar_index,y = close,text=str.tostring(green) + " %",color=color.green,textcolor = color.white,style=label.style_label_up)
label.set_yloc(l,yloc.belowbar)
if (open > close)
l2 = label.new(x = bar_index,y = close,text=str.tostring(red)+ " %",color=color.red,textcolor=color.white,style=label.style_label_down)
label.set_yloc(l2,yloc = yloc.abovebar)
|
Ultimate Oscillator + Divergences | https://www.tradingview.com/script/6NDDewpI-Ultimate-Oscillator-Divergences/ | tvenn | https://www.tradingview.com/u/tvenn/ | 181 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ tvenn
//@version=4
study(title="Ultimate Oscillator + Divergences", shorttitle="UO + Divs")
//=======================================
//=UO core code
//=======================================
length7 = input(7, title="UO fast length", minval=1, tooltip="Standard UO fast length is 7"), length14 = input(14, title="UO middle length", minval=1, tooltip="Standard UO middle length is 14"), length28 = input(28, title="UO slow length", minval=1, tooltip="Standard UO slow length is 28")
average(bp, tr_, length) => sum(bp, length) / sum(tr_, length)
high_ = max(high, close[0])
low_ = min(low, close[0])
bp = close - low_
tr_ = high_ - low_
avg7 = average(bp, tr_, length7)
avg14 = average(bp, tr_, length14)
avg28 = average(bp, tr_, length28)
out = 100 * (4*avg7 + 2*avg14 + avg28)/7
// //=======================================
lbR = input(title="Pivot Lookback Right", defval=5)
lbL = input(title="Pivot Lookback Left", defval=5)
rangeUpper = input(title="Max of Lookback Range", defval=30)
rangeLower = input(title="Min of Lookback Range", defval=2)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=true)
bearColor = color.new(#EA1889, 0)
bullColor = color.new(#95BD5F, 0)
hiddenBullColor = color.new(#95BD5F, 0)
hiddenBearColor = color.new(#EA1889, 0)
textColor = color.new(#FFFFFF, 0)
noneColor = color.new(#FFFFFF, 100)
uo = out
osc = uo
plot(out, linewidth=1, color=#2962FF, title="UO")
band1 = hline(70,color=#CCCCCC,linewidth=1)
band2 = hline(50,color=#444444,linewidth=1)
band0 = hline(30,color=#CCCCCC,linewidth=1)
fill(band1, band0, color.new(#AAAAAA, 100), editable=1)
plFound = na(pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
)
plotshape(
bullCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
display=0
)
alertcondition(bullCond, title="Regular bullish divergence in UO found", message="Check charts for a regular bullish divergence found with UO")
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
display=0
)
alertcondition(hiddenBullCond, title="Hidden bullish divergence in UO found", message="Check charts for a hidden bullish divergence found with UO")
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
display=0
)
alertcondition(bearCond, title="Regular bearish divergence in UO found", message="Check charts for a regular bearish divergence found with UO")
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
display=0
)
alertcondition(hiddenBearCond, title="Hidden bearish divergence in UO found", message="Check charts for a hidden bearish divergence found with UO")
|
Modified Covariance Autoregressive Estimator of Price [Loxx] | https://www.tradingview.com/script/sgN2j9bH-Modified-Covariance-Autoregressive-Estimator-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 111 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Modified Covariance Autoregressive Estimator of Price [Loxx]",
shorttitle = "MCAEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
darkGreenColor = #1B7E02
darkRedColor = #93021F
//+-------------------------------------------------------------------------+
// Fast algorithm for the solution of the modified covariance least squares normal equations.
//
// This implementation is based on Modified Covariance method from Marple's book
//
// x : - Array of complex data samples X(1) through X(N)
// ip: - Order of linear prediction model (integer)
//
// variables
// v - Real linear prediction variance at order IP
// a - Array of complex linear prediction coefficients
//
// Bool stop value at time of exit
// false - for normal exit (no numerical ill-conditioning)
// true - if v is not a positive value
// true - if delta and gamma do not lie in the range 0 to 1
// true - if v is not a positive value
// true - if delta and gamma do not lie in the range 0 to 1
// Error message
// see above for bool stop
//+-------------------------------------------------------------------------+
_MCov(float[] x, int ip)=>
string errormessage = ""
bool stop = false
int n = array.size(x)
float[] c = array.new_float(ip + 1, 0.)
float[] d = array.new_float(ip + 1, 0.)
float[] r = array.new_float(ip, 0.)
float[] a = array.new<float>(n, 0.)
float v = 0.
int mk = 0
float r1 = 0.
float r2 = 0.
float r3 = 0.
float r4 = 0.
float r5 = 0.
float delta = 0.
float gamma = 0.
float lambda = 0.
float theta = 0.
float psi = 0.
float xi = 0.
float save1 = 0.
float save2 = 0.
float save3 = 0.
float save4 = 0.
float c1 = 0.
float c2 = 0.
float c3 = 0.
float c4 = 0.
float ef = 0.
float eb = 0.
r1 := 0.0
for k = 1 to n - 2
r1 += 2.0 * math.pow(array.get(x, k), 2)
r2 := math.pow(array.get(x, n - 1), 2)
r3 := math.pow(array.get(x, 0), 2)
r4 := 1.0 / (r1 + 2.0 * (r2 + r3))
v := r1 + r2 + r3
delta := 1.0 - r2 * r4
gamma := 1.0 - r3 * r4
lambda := array.get(x, 0) * array.get(x, n - 1) * r4
array.set(c, 0, array.get(x, 0) * r4)
array.set(c, 0, array.get(x, n - 1) * r4)
int m = 0
while true
save1 := 0.0
for k = m + 1 to n - 1
save1 += array.get(x, n - 1 - k) * array.get(x, n - k + m)
save1 *= 2.0
array.set(r, m, save1)
theta := array.get(x, 0) * array.get(d, 0)
psi := array.get(x, 0) * array.get(c, 0)
xi := array.get(x, n - 1) * array.get(d, 0)
if m > 0
for k = 1 to m
theta += array.get(x, k) * array.get(d, k)
psi += array.get(x, k) * array.get(c, k)
xi += array.get(x, n - 1 - k) * array.get(d, k)
array.set(r, k - 1, array.get(r, k - 1) - array.get(x, m) * array.get(x, m - k) + array.get(x, n - 1 - m) * array.get(x, n - 1 - m + k))
save1 += array.get(r, k - 1) * array.get(a, m - k)
//Order update of a vector
c1 := -save1 / v
array.set(a, m, c1)
v *= (1.0 - c1 * c1)
if m > 0
for k = 0 to (m + 1) / 2 - 1
mk := m - k - 1
save1 := array.get(a, k)
array.set(a, k, save1 + c1 * array.get(a, mk))
if k != mk
array.set(a, mk, array.get(a, mk) + c1 * save1)
if m == ip - 1
v *= (0.5 / (n - 1 - m))
break
//Time update of c,d vectors and gamma, delta, lambda scalars
r1 := 1.0 / (delta * gamma - lambda * lambda)
c1 := (theta * lambda + psi * delta) * r1
c2 := (psi * lambda + theta * gamma) * r1
c3 := (xi * lambda + theta * delta) * r1
c4 := (theta * lambda + xi * gamma) * r1
for k = 0 to m / 2
mk := m - k
save1 := array.get(c, k)
save2 := array.get(d, k)
save3 := array.get(c, mk)
save4 := array.get(d, mk)
array.set(c, k, array.get(c, k) + (c1 * save3 + c2 * save4))
array.set(d, k, array.get(d, k) + (c3 * save3 + c4 * save4))
if (k != mk)
array.set(c, k, array.get(c, k) + (c1 * save1 + c2 * save2))
array.set(d, k, array.get(d, k) + (c3 * save1 + c4 * save2))
r2 := psi * psi
r3 := theta * theta
r4 := xi * xi
r5 := gamma - (r2 * delta + r3 * gamma + 2.0 * psi * lambda * theta) * r1
r2 := delta - (r3 * delta + r4 * gamma + 2. * theta * lambda * xi) * r1
gamma := r5
delta := r2
lambda += (c3 * psi + c4 * theta)
if (v <= 0.0)
errormessage := "Error: Negative or zero value of the v variable"
stop := true
break
if (delta <= 0.0 or delta > 1.0 or gamma <= 0.0 or gamma > 1.0)
errormessage := "Error: delta and gamma variables values out of the range (0,1)"
stop := true
break
r1 := 1.0 / v
r2 := 1.0 / (delta * gamma - lambda * lambda)
ef := array.get(x, n - m - 2)
eb := array.get(x, m + 1)
for k = 0 to m
ef += array.get(a, k) * array.get(x, n - 1 - m + k)
eb += array.get(a, k) * array.get(x, m - k)
c1 := eb * r1
c2 := ef * r1
c3 := (eb * delta + ef * lambda) * r2
c4 := (ef * gamma + eb * lambda) * r2
for k = m to 0
save1 := array.get(a, k)
array.set(a, k, save1 + c3 * array.get(c, k) + c4 * array.get(d, k))
array.set(c, k + 1, array.get(c, k) + c1 * save1)
array.set(d, k + 1, array.get(d, k) + c2 * save1)
array.set(c, 0, c1)
array.set(d, 0, c2)
r3 := eb * eb
r4 := ef * ef
v -= (r3 * delta + r4 * gamma + 2.0 * ef * eb * lambda) * r2
delta -= r4 * r1
gamma -= r3 * r1
lambda += ef * eb * r1
if (v <= 0.0)
errormessage := "Error: Negative or zero value of the v variable"
stop := true
break
if (delta <= 0.0 or delta > 1.0 or gamma <= 0.0 or gamma > 1.0)
errormessage := "Error: delta and gamma variables values out of the range (0,1)"
stop := true
break
m += 1
[a, stop, errormessage]
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(500, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.1, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 0.67, step = 0.01,
tooltip = "Order must be less than or equal to 2/3 the input frame size")
FutBars = input.int(20, "Future Bars", group = "Basic Settings", maxval = 500)
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
//Find average of past values
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
cnp = np >= 250 ? 250 : np
cnf = nf >= 250 ? 250 : nf
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction _Geom
[result, stop, errormessage] = _MCov(x, no)
//grab test results
strout = stop ? "๐จ " + errormessage : "โ
Passed"
colort = stop ? darkRedColor : darkGreenColor
var testTable = table.new(position = position.bottom_right, columns = 2, rows = 1, bgcolor = colort, border_width = 1)
table.cell(table_id = testTable, column = 0, row = 0, text = strout, text_color = color.white, text_size = size.large)
//correct data
for i = no to 1
array.set(result, i, array.get(result, i - 1))
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1
|
EMA 21 + MacD + RSI + Alma | https://www.tradingview.com/script/Ss7WsRBl-EMA-21-MacD-RSI-Alma/ | markaguirre26 | https://www.tradingview.com/u/markaguirre26/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ markaguirre26
//@version=5
indicator(title="Moving Average Exponential", shorttitle="EMA", overlay=true, timeframe="", timeframe_gaps=true)
len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.ema(src, len)
plot(out, title="EMA", color=color.yellow, offset=offset)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
len2 = input.int(21, minval=1, title="length")
src2 = input(close, title="Source")
offset2 = input.int(title="offset2", defval=0, minval=-500, maxval=500)
out2 = ta.ema(src2, len2)
plot(out2, title="EMA", color=color.green, offset=offset2)
typeMA2 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothinglength2 = input.int(title = "length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
smoothingLine2 = ma(out2, smoothinglength2, typeMA2)
plot(smoothingLine2, title="Smoothing Line", color=#f37f20, offset=offset2, display=display.none)
source = close
windowsize = input(title="Window Size", defval=20)
offset3 = input.float(title="Offset", defval=0.8)
sigma = input.float(title="Sigma", defval=8)
plot(ta.alma(source, windowsize, offset3, sigma),color=color.white)
|
Volume Histogram [SpiritualHealer117] | https://www.tradingview.com/script/gQxULEX3-Volume-Histogram-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 155 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ spiritualhealer117
//@version=5
indicator("Volume Histogram", overlay=true)
src = input(hl2, "Source")
src2 = volume
bins = input(20, "Number of bins")
len = input(50, "Length")
offset = input(5, "Histogram Offset")
direction = input(false,"Plot Histogram Left")
sml = input(false,"Draw major levels")
sensitivity = input(80, "Major Sensitivity")
show_gap = input(true,"Show Gaps Between Bins")
adj_daily = input(true,"Adjust volume for length?")
shw_label = input(true,"Show Label")
kl_color = input.color(color.rgb(255, 20, 147, 0), "Key Level Line Color")
ml_color = input.color(color.rgb(255, 20, 147, 75), "Major Level Line Color")
fill_clr_1 = input.color(color.rgb(255,182,193, 80), "Histogram Fill Color")
outline_clr = input.color(color.rgb(255,182,193, 0), "Bar Outline Color")
fill_clr_2 = input.color(color.rgb(255,182,255, 60), "Major Histogram Bar Fill Color")
outline_clr_2 = input.color(color.rgb(255,182,255, 0), "Major Histogram Bar Outline Color")
// Calculate Range of Source Data {
max = ta.highest(src,len)
min = ta.lowest(src,len)
range_ = max - min
ma = ta.sma(src2,len)
//}
// Find Volume in each bin and store to array
volumes = array.new<float>(bins,0)
bin_tops = array.new<float>(bins,0)
bin_bots = array.new<float>(bins,0)
if barstate.islast
for i=0 to bins-1
bin_bottom = min + ((range_/bins) * i)
bin_top = bin_bottom + ((range_/bins) * 1)
array.set(bin_bots, i, bin_bottom)
array.set(bin_tops, i, bin_top)
for z=0 to len
if src[z] >= bin_bottom and src[z] < bin_top
old_arr_val = array.get(volumes, i)
new_arr_val = old_arr_val + src2[z]
array.set(volumes, i, new_arr_val)
// Draw Histogram {
if barstate.islast
for i=0 to bins-1
v_at_i = array.get(volumes,i)
bt_at_i = array.get(bin_tops,i)
bb_at_i = array.get(bin_bots,i)
v_max = array.max(volumes)
v_major = array.percentrank(volumes,i) > sensitivity
if v_max == v_at_i
line.new(bar_index, ((bt_at_i+bb_at_i)/2), bar_index+offset, ((bt_at_i+bb_at_i)/2), extend=extend.left, color=kl_color)
if v_major and sml
line.new(bar_index, ((bt_at_i+bb_at_i)/2), bar_index+offset, ((bt_at_i+bb_at_i)/2), extend=extend.left, color=ml_color)
adjusted_volume = math.round(v_at_i/ma)
v_ati_corrected = adj_daily?v_at_i/len:v_at_i
v_at_i_label = (v_ati_corrected > 1000? (v_ati_corrected>1000000?v_ati_corrected>1000000000?str.tostring(math.round(v_ati_corrected/1000000000))+"B":str.tostring(math.round(v_ati_corrected/1000000))+"M":str.tostring(math.round(v_ati_corrected/1000))+"K"):str.tostring(math.round(v_ati_corrected)))
box.new(bar_index-(direction?adjusted_volume:-adjusted_volume)+offset,bt_at_i, bar_index+offset, bb_at_i+(show_gap?(range_/bins)*0.1:0), border_color=v_major?outline_clr_2:outline_clr, bgcolor=v_major?fill_clr_2:fill_clr_1,xloc=xloc.bar_index)
if shw_label
label.new(bar_index+math.round(1.5*offset),bb_at_i+(range_/bins)*0.1,text=v_at_i_label,xloc=xloc.bar_index, style=label.style_none, size=size.small)
//}
|
Aggregated Delta (Buy/Sell) Volume - InFinito | https://www.tradingview.com/script/lfovzRfC-Aggregated-Delta-Buy-Sell-Volume-InFinito/ | In_Finito_ | https://www.tradingview.com/u/In_Finito_/ | 230 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ In_Finito_
// Based of
// Aggregation by Crypt0rus - https://www.tradingview.com/script/V3q0WkG6-Aggregated-Volume-Colored-Bitcoin-ETH-Altcoins-everything/
// Buy Sell Volume by Ricardo M Arjona @XeL_Arjona - https://www.tradingview.com/script/NHcilGl8-MARKET-VOLUME-by-BeloTrade-XeL-Arjona/
// Delta Calculations & Exchange Sorting & Exchange Data Normalization by InFinito
//@version=5
indicator("Aggregated Delta (Buy/Sell) Volume", shorttitle=" Aggregated Delta Volume", format=format.volume)
////////////////////GENERAL INPUTS/////////////////////////////////////////
////////////////////MARKET TYPE INPUT/////////////////////////////////////
aggr = input.bool(defval=true, title='Use Aggregated Data', inline='1', group='Aggregation')
markettype = input.string(defval='Spot', title='Market Type Aggregation', options=['Spot', 'Futures' , 'Perp', 'Derivatives F+P', 'Spot+Derivs'], inline='2', group='Aggregation', tooltip='Disable to check by symbol OR if you want to use this indicator with any other pair than BTC')
//////////////////////////Display INPUTS//////////////////////////////////
showd = input.bool(defval=false, title='Show All Volume by Side', inline='2', group='Display Options')
//////////////////// Inputs FOR SPOT AGGREGATION///////////////////////////
i_sym1 = input.bool(true, '', inline='1', group='Spot Symbols')
i_sym2 = input.bool(true, '', inline='2', group='Spot Symbols')
i_sym3 = input.bool(true, '', inline='3', group='Spot Symbols')
i_sym4 = input.bool(true, '', inline='4', group='Spot Symbols')
i_sym5 = input.bool(true, '', inline='5', group='Spot Symbols')
i_sym6 = input.bool(true, '', inline='6', group='Spot Symbols')
i_sym7 = input.bool(true, '', inline='7', group='Spot Symbols')
i_sym8 = input.bool(true, '', inline='8', group='Spot Symbols')
i_sym9 = input.bool(true, '', inline='9', group='Spot Symbols')
i_sym10 = input.bool(false, '', inline='10', group='Spot Symbols')
i_sym11 = input.bool(false, '', inline='11', group='Spot Symbols')
i_sym12 = input.bool(true, '', inline='12', group='Spot Symbols')
i_sym13 = input.bool(true, '', inline='13', group='Spot Symbols')
i_sym14 = input.bool(false, '', inline='14', group='Spot Symbols')
i_sym15 = input.bool(false, '', inline='15', group='Spot Symbols')
i_sym16 = input.bool(false, '', inline='16', group='Spot Symbols')
i_sym1_ticker = input.symbol('BINANCE:BTCUSDT', '', inline='1', group='Spot Symbols')
i_sym2_ticker = input.symbol('BINANCE:BTCBUSD', '', inline='2', group='Spot Symbols')
i_sym3_ticker = input.symbol('BITSTAMP:BTCUSD', '', inline='3', group='Spot Symbols')
i_sym4_ticker = input.symbol('HUOBI:BTCUSDT', '', inline='4', group='Spot Symbols')
i_sym5_ticker = input.symbol('OKEX:BTCUSDT', '', inline='5', group='Spot Symbols')
i_sym6_ticker = input.symbol('COINBASE:BTCUSD', '', inline='6', group='Spot Symbols')
i_sym7_ticker = input.symbol('COINBASE:BTCUSDT', '', inline='7', group='Spot Symbols')
i_sym8_ticker = input.symbol('GEMINI:BTCUSD', '', inline='8', group='Spot Symbols')
i_sym9_ticker = input.symbol('KRAKEN:XBTUSD', '', inline='9', group='Spot Symbols')
i_sym10_ticker = input.symbol('FTX:BTCUSD', '', inline='10', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym11_ticker = input.symbol('FTX:BTCUSDT', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Spot Symbols')
i_sym12_ticker = input.symbol('BITFINEX:BTCUSD', '', inline='12', group='Spot Symbols')
i_sym13_ticker = input.symbol('BINGX:BTCUSDT', '', inline='13', group='Spot Symbols')
i_sym14_ticker = input.symbol('GATEIO:BTCUSDT', '', inline='14', group='Spot Symbols')
i_sym15_ticker = input.symbol('PHEMEX:BTCUSDT', '', inline='15', group='Spot Symbols')
i_sym16_ticker = input.symbol('BITGET:BTCUSDT', '', inline='16', group='Spot Symbols')
sbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Spot Symbols')
sbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Spot Symbols')
sbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Spot Symbols')
sbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Spot Symbols')
sbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Spot Symbols')
sbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Spot Symbols')
sbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Spot Symbols')
sbase8 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Spot Symbols')
sbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Spot Symbols')
sbase10 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Spot Symbols')
sbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Spot Symbols')
sbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Spot Symbols')
sbase13 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='13', group='Spot Symbols')
sbase14 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='14', group='Spot Symbols')
sbase15 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='15', group='Spot Symbols')
sbase16 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='16', group='Spot Symbols')
samount1 = input.float(defval=1, title='#', inline='1', group='Spot Symbols')
samount2 = input.float(defval=1, title='#', inline='2', group='Spot Symbols')
samount3 = input.float(defval=1, title='#', inline='3', group='Spot Symbols')
samount4 = input.float(defval=1, title='#', inline='4', group='Spot Symbols')
samount5 = input.float(defval=1, title='#', inline='5', group='Spot Symbols')
samount6 = input.float(defval=1, title='#', inline='6', group='Spot Symbols')
samount7 = input.float(defval=1, title='#', inline='7', group='Spot Symbols')
samount8 = input.float(defval=1, title='#', inline='8', group='Spot Symbols')
samount9 = input.float(defval=1, title='#', inline='9', group='Spot Symbols')
samount10 = input.float(defval=1, title='#', inline='10', group='Spot Symbols')
samount11 = input.float(defval=1, title='#', inline='11', group='Spot Symbols')
samount12 = input.float(defval=1, title='#', inline='12', group='Spot Symbols')
samount13 = input.float(defval=1, title='#', inline='13', group='Spot Symbols')
samount14 = input.float(defval=1, title='#', inline='14', group='Spot Symbols')
samount15 = input.float(defval=1, title='#', inline='15', group='Spot Symbols')
samount16 = input.float(defval=1, title='#', inline='16', group='Spot Symbols')
//////INPUTS FOR FUTURES AGGREGATION///////////////////
i_sym1b = input.bool(true, '', inline='1', group='Futures Symbols')
i_sym2b = input.bool(true, '', inline='2', group='Futures Symbols')
i_sym3b = input.bool(true, '', inline='3', group='Futures Symbols')
i_sym4b = input.bool(false, '', inline='4', group='Futures Symbols')
i_sym5b = input.bool(false, '', inline='5', group='Futures Symbols')
i_sym6b = input.bool(false, '', inline='6', group='Futures Symbols')
i_sym7b = input.bool(false, '', inline='7', group='Futures Symbols')
i_sym8b = input.bool(true, '', inline='8', group='Futures Symbols')
i_sym9b = input.bool(true, '', inline='9', group='Futures Symbols')
i_sym10b = input.bool(true, '', inline='10', group='Futures Symbols')
i_sym11b = input.bool(false, '', inline='11', group='Futures Symbols')
i_sym12b = input.bool(false, '', inline='12', group='Futures Symbols')
i_sym1b_ticker = input.symbol('BINANCE:BTCUSDTPERP', '', inline='1', group='Futures Symbols')
i_sym2b_ticker = input.symbol('BINANCE:BTCBUSDPERP', '', inline='2', group='Futures Symbols')
i_sym3b_ticker = input.symbol('BYBIT:BTCUSDT.P', '', inline='3', group='Futures Symbols')
i_sym4b_ticker = input.symbol('CME:BTC1!', '', inline='4', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol',group='Futures Symbols')
i_sym5b_ticker = input.symbol('CME:BTC2!', '', inline='5', tooltip='This volume is reported in 5 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym6b_ticker = input.symbol('CME:MBT1!', '', inline='6', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym7b_ticker = input.symbol('CME:MBT2!', '', inline='7', tooltip='This volume is reported in 0.10 BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym8b_ticker = input.symbol('PHEMEX:BTCUSDPERP', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym9b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='9', tooltip='This volume is reported in 100x BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym10b_ticker = input.symbol('BITMEX:XBTUSDT', '', inline='10', tooltip='This volume is reported as 1 million per BTC and it is recalculated to work properly, beware when changing this symbol', group='Futures Symbols')
i_sym11b_ticker = input.symbol('BITGET:BTCUSDT.P', '', inline='11', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol - THIS IS NOT REPORTED IN REAL TIME', group='Futures Symbols')
i_sym12b_ticker = input.symbol('OKEX:BTCUSDT.P', '', inline='12', group='Futures Symbols')
fbase1 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Futures Symbols')
fbase2 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Futures Symbols')
fbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Futures Symbols')
fbase4 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Futures Symbols')
fbase5 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Futures Symbols')
fbase6 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Futures Symbols')
fbase7 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Futures Symbols')
fbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Futures Symbols')
fbase9 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='9', group='Futures Symbols')
fbase10 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='10', group='Futures Symbols')
fbase11 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='11', group='Futures Symbols')
fbase12 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='12', group='Futures Symbols')
famount1 = input.float(defval=1, title='#', inline='1', group='Futures Symbols')
famount2 = input.float(defval=1, title='#', inline='2', group='Futures Symbols')
famount3 = input.float(defval=1, title='#', inline='3', group='Futures Symbols')
famount4 = input.float(defval=5, title='#', inline='4', group='Futures Symbols')
famount5 = input.float(defval=5, title='#', inline='5', group='Futures Symbols')
famount6 = input.float(defval=0.1, title='#', inline='6', group='Futures Symbols')
famount7 = input.float(defval=0.1, title='#', inline='7', group='Futures Symbols')
famount8 = input.float(defval=1, title='#', inline='8', group='Futures Symbols')
famount9 = input.float(defval=0.01, title='#', inline='9', group='Futures Symbols')
famount10 = input.float(defval=0.000001, title='#', inline='10', group='Futures Symbols')
famount11 = input.float(defval=1, title='#', inline='11', group='Futures Symbols')
famount12 = input.float(defval=1, title='#', inline='12', group='Futures Symbols')
//, tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol'
////////////////////////////////////////////////////////////////////
//////INPUTS FOR PERP AGGREGATION///////////////////
i_sym1c = input.bool(true, '', inline='1', group='Perpetuals Symbols')
i_sym2c = input.bool(true, '', inline='2', group='Perpetuals Symbols')
i_sym3c = input.bool(true, '', inline='3', group='Perpetuals Symbols')
i_sym4c = input.bool(true, '', inline='4', group='Perpetuals Symbols')
i_sym5c = input.bool(false, '', inline='5', group='Perpetuals Symbols')
i_sym6c = input.bool(true, '', inline='6', group='Perpetuals Symbols')
i_sym7c = input.bool(true, '', inline='7', group='Perpetuals Symbols')
i_sym8c = input.bool(true, '', inline='8', group='Perpetuals Symbols')
i_sym1c_ticker = input.symbol('BINANCE:BTCPERP', '', inline='1', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym2c_ticker = input.symbol('OKEX:BTCUSD.P', '', inline='2', tooltip='This volume is reported in blocks of 100 USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym3c_ticker = input.symbol('HUOBI:BTCUSD.P', '', inline='3', group='Perpetuals Symbols')
i_sym4c_ticker = input.symbol('PHEMEX:BTCPERP', '', inline='4', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym5c_ticker = input.symbol('FTX:BTCPERP', '', inline='5', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol' ,group='Perpetuals Symbols')
i_sym6c_ticker = input.symbol('BYBIT:BTCUSD.P', '', inline='6', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym7c_ticker = input.symbol('DERIBIT:BTCUSD.P', '', inline='7', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
i_sym8c_ticker = input.symbol('BITMEX:XBTUSD.P', '', inline='8', tooltip='This volume is reported in USD instead of BTC and it is recalculated to work properly, beware when changing this symbol', group='Perpetuals Symbols')
pbase1 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='1', group='Perpetuals Symbols')
pbase2 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='2', group='Perpetuals Symbols')
pbase3 = input.string(defval='Coin', title='', options=['Coin', 'USD', 'Other'], inline='3', group='Perpetuals Symbols')
pbase4 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='4', group='Perpetuals Symbols')
pbase5 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='5', group='Perpetuals Symbols')
pbase6 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='6', group='Perpetuals Symbols')
pbase7 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='7', group='Perpetuals Symbols')
pbase8 = input.string(defval='USD', title='', options=['Coin', 'USD', 'Other'], inline='8', group='Perpetuals Symbols')
pamount1 = input.float(defval=100, title='#', inline='1', group='Perpetuals Symbols')
pamount2 = input.float(defval=100, title='#', inline='2', group='Perpetuals Symbols')
pamount3 = input.float(defval=1, title='#', inline='3', group='Perpetuals Symbols')
pamount4 = input.float(defval=1, title='#', inline='4', group='Perpetuals Symbols')
pamount5 = input.float(defval=1, title='#', inline='5', group='Perpetuals Symbols')
pamount6 = input.float(defval=1, title='#', inline='6', group='Perpetuals Symbols')
pamount7 = input.float(defval=1, title='#', inline='7', group='Perpetuals Symbols')
pamount8 = input.float(defval=1, title='#', inline='8', group='Perpetuals Symbols')
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////AGGREGATED VOLUME CALCULATION///////////////////////
//// VOLUME REQUEST FUNCTION//////////////////////////
f_volume(_ticker) =>
request.security(_ticker, timeframe.period, volume)
//////////////////////////////////////////////////////////
var float finvol = 0
if aggr==true///////////SPOT////////////////////////////////////////////////////////////////////
v1x = (i_sym1 ? f_volume(i_sym1_ticker) : 0)
v1 = sbase1=='Coin' ? v1x*samount1 : sbase1=='USD' or sbase1=='Other' ? (v1x*samount1)/ohlc4 : v1x
v2x = (i_sym2 ? f_volume(i_sym2_ticker) : 0)
v2 = sbase2=='Coin' ? v2x*samount2 : sbase2=='USD' or sbase2=='Other' ? (v2x*samount2)/ohlc4 : v2x
v3x = (i_sym3 ? f_volume(i_sym3_ticker) : 0)
v3 = sbase2=='Coin' ? v3x*samount3 : sbase3=='USD' or sbase3=='Other' ? (v3x*samount4)/ohlc4 : v3x
v4x = (i_sym4 ? f_volume(i_sym4_ticker) : 0)
v4 = sbase4=='Coin' ? v4x*samount4 : sbase4=='USD' or sbase4=='Other' ? (v4x*samount4)/ohlc4 : v4x
v5x = (i_sym5 ? f_volume(i_sym5_ticker) : 0)
v5 = sbase5=='Coin' ? v5x*samount5 : sbase5=='USD' or sbase5=='Other' ? (v5x*samount5)/ohlc4 : v5x
v6x = (i_sym6 ? f_volume(i_sym6_ticker) : 0)
v6 = sbase6=='Coin' ? v6x*samount6 : sbase6=='USD' or sbase6=='Other' ? (v6x*samount6)/ohlc4 : v6x
v7x = (i_sym7 ? f_volume(i_sym7_ticker) : 0)
v7 = sbase7=='Coin' ? v7x*samount7 : sbase7=='USD' or sbase7=='Other' ? (v7x*samount7)/ohlc4 : v7x
v8x = (i_sym8 ? f_volume(i_sym8_ticker) : 0)
v8 = sbase8=='Coin' ? v8x*samount8 : sbase8=='USD' or sbase8=='Other' ? (v8x*samount8)/ohlc4 : v8x
v9x = (i_sym9 ? f_volume(i_sym9_ticker) : 0)
v9 = sbase9=='Coin' ? v9x*samount9 : sbase9=='USD' or sbase9=='Other' ? (v9x*samount9)/ohlc4 : v9x
v10x = (i_sym10 ? f_volume(i_sym10_ticker) : 0) //FTX reported in usd
v10 = sbase10=='Coin' ? v10x*samount10 : sbase10=='USD' or sbase10=='Other' ? (v10x*samount10)/ohlc4 : v10x
v11x = (i_sym11 ? f_volume(i_sym11_ticker) : 0) //FTX reported in usd
v11 = sbase11=='Coin' ? v11x*samount11 : sbase11=='USD' or sbase11=='Other' ? (v11x*samount11)/ohlc4 : v11x
v12x = (i_sym12 ? f_volume(i_sym12_ticker) : 0)
v12 = sbase12=='Coin' ? v12x*samount12 : sbase12=='USD' or sbase12=='Other' ? (v12x*samount10)/ohlc4 : v12x
v13x = (i_sym13 ? f_volume(i_sym13_ticker) : 0)
v13 = sbase13=='Coin' ? v13x*samount13 : sbase13=='USD' or sbase13=='Other' ? (v13x*samount13)/ohlc4 : v13x
v14x = (i_sym14 ? f_volume(i_sym14_ticker) : 0)
v14 = sbase14=='Coin' ? v14x*samount14 : sbase14=='USD' or sbase14=='Other' ? (v14x*samount14)/ohlc4 : v14x
v15x = (i_sym15 ? f_volume(i_sym15_ticker) : 0)
v15 = sbase15=='Coin' ? v15x*samount15 : sbase15=='USD' or sbase15=='Other' ? (v15x*samount15)/ohlc4 : v15x
v16x = (i_sym16 ? f_volume(i_sym16_ticker) : 0)
v16 = sbase16=='Coin' ? v16x*samount16 : sbase16=='USD' or sbase16=='Other' ? (v16x*samount16)/ohlc4 : v16x
vsf=v1+v2+v3+v4+v5+v6+v7+v8+v9+v10+v11+v12+v13+v14+v15+v16
///////////////////////////////////////////////////////////////////////////////////
///////////////////////FUTURES////////////////////////////////////////////////////
v1bx = (i_sym1b ? f_volume(i_sym1b_ticker) : 0)
v1b = fbase1=='Coin' ? v1bx*famount1 : fbase1=='USD' or fbase1=='Other' ? (v1bx*famount1)/ohlc4 : v1bx
v2bx = (i_sym2b ? f_volume(i_sym2b_ticker) : 0)
v2b = fbase2=='Coin' ? v2bx*famount2 : fbase2=='USD' or fbase2=='Other' ? (v2bx*famount2)/ohlc4 : v2bx
v3bx = (i_sym3b ? f_volume(i_sym3b_ticker) : 0)
v3b = fbase3=='Coin' ? v3bx*famount3 : fbase3=='USD' or fbase3=='Other' ? (v3bx*famount3)/ohlc4 : v3bx
v4bx =(i_sym4b ? f_volume(i_sym4b_ticker) : 0) //CME NORMAL (each contract reported equals 5btc)
v4b = fbase4=='Coin' ? v4bx*famount4 : fbase4=='USD' or fbase4=='Other' ? (v4bx*famount4)/ohlc4 : v4bx
v5bx = (i_sym5b ? f_volume(i_sym5b_ticker) : 0)//CME NORMAL (each contract reported equals 5btc)
v5b = fbase5=='Coin' ? v5bx*famount5 : fbase5=='USD' or fbase5=='Other' ? (v5bx*famount5)/ohlc4 : v5bx
v6bx = (i_sym6b ? f_volume(i_sym6b_ticker) : 0)//CME mini (each contract reported equals 0.60btc)
v6b = fbase6=='Coin' ? v6bx*famount6 : fbase6=='USD' or fbase6=='Other' ? (v6bx*famount6)/ohlc4 : v6bx
v7bx = (i_sym7b ? f_volume(i_sym7b_ticker) : 0)//CME mini (each contract reported equals 0.7btc)
v7b = fbase7=='Coin' ? v7bx*famount7 : fbase7=='USD' or fbase7=='Other' ? (v7bx*famount7)/ohlc4 : v7bx
v8bx = (i_sym8b ? f_volume(i_sym8b_ticker) : 0)// PHEMEX reported in usd
v8b = fbase8=='Coin' ? v8bx*famount8 : fbase8=='USD' or fbase8=='Other' ? (v8bx*famount8)/ohlc4 : v8bx
v9bx = (i_sym9b ? f_volume(i_sym9b_ticker) : 0)// OKEX reported in 900xBTC, meaning every 900 contracts is only one
v9b = fbase9=='Coin' ? v9bx*famount9 : fbase9=='USD' or fbase9=='Other' ? (v9bx*famount9)/ohlc4 : v9bx
v10bx = (i_sym10b ? f_volume(i_sym10b_ticker) : 0)// BITMEX REPORTED IN 1 MILLION BTC, MEANING EACH MILLION CONTRACTS ON TV REPRESENT 1 BTC
v10b = fbase10=='Coin' ? v1bx*famount10 : fbase10=='USD' or fbase10=='Other' ? (v10bx*famount10)/ohlc4 : v10bx
v11bx = (i_sym11b ? f_volume(i_sym11b_ticker) : 0)// BITGET REPORTED IN USD - TURNED OFF BECAUSE DOESNT PROVIDE REAL TIME DATA
v11b = fbase11=='Coin' ? v11bx*famount11 : fbase11=='USD' or fbase11=='Other' ? (v11bx*famount11)/ohlc4 : v11bx
v12bx = (i_sym12b ? f_volume(i_sym12b_ticker) : 0)
v12b = fbase12=='Coin' ? v12bx*famount12 : fbase12=='USD' or fbase12=='Other' ? (v12bx*famount12)/ohlc4 : v12bx
vff=v1b+v2b+v3b+v4b+v5b+v6b+v7b+v8b+v9b+v10b+v11b+v12b
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////PERPS///////////////////////////////////////////////////////////
v1cx = (i_sym1c ? f_volume(i_sym1c_ticker) : 0)//BINANCE REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v1c = pbase1=='Coin' ? v1cx*pamount1 : pbase1=='USD' or pbase1=='Other' ? (v1cx*pamount1)/ohlc4 : v1cx
v2cx = (i_sym2c ? f_volume(i_sym2c_ticker) : 0)//OKEX REPORTED IN BLOCKS OF 100 USD, MEANING EACH CONTRACT REPORTED IS EQUAL TO 100 USD
v2c = pbase2=='Coin' ? v2cx*pamount2 : pbase2=='USD' or pbase2=='Other' ? (v2cx*pamount2)/ohlc4 : v2cx
v3cx = (i_sym3c ? f_volume(i_sym3c_ticker) : 0)// HUOBI REPORTED IN BTC
v3c = pbase3=='Coin' ? v3cx*pamount3 : pbase3=='USD' or pbase3=='Other' ? (v3cx*pamount3)/ohlc4 : v3cx
v4cx =(i_sym4c ? f_volume(i_sym4c_ticker) : 0)// PHEMEX REPORTED IN USD
v4c = pbase4=='Coin' ? v4cx*pamount4 : pbase4=='USD' or pbase4=='Other' ? (v4cx*pamount4)/ohlc4 : v4cx
v5cx = (i_sym5c ? f_volume(i_sym5c_ticker) : 0)// FTX REPORTED IN USD
v5c = pbase5=='Coin' ? v5cx*pamount5 : pbase5=='USD' or pbase5=='Other' ? (v5cx*pamount5)/ohlc4 : v5cx
v6cx = (i_sym6c ? f_volume(i_sym6c_ticker) : 0)//BYBIT REPORTED IN USD
v6c = pbase6=='Coin' ? v6cx*pamount6 : pbase6=='USD' or pbase6=='Other' ? (v6cx*pamount6)/ohlc4 : v6cx
v7cx = (i_sym7c ? f_volume(i_sym7c_ticker) : 0)//DERIBIT REPORTED IN USD
v7c = pbase7=='Coin' ? v7cx*pamount7 : pbase7=='USD' or pbase7=='Other' ? (v7cx*pamount7)/ohlc4 : v7cx
v8cx = (i_sym8c ? f_volume(i_sym8c_ticker) : 0)//BITMEX REPORTED IN USD
v8c = pbase8=='Coin' ? v8cx*pamount8 : pbase8=='USD' or pbase8=='Other' ? (v8cx*pamount8)/ohlc4 : v8cx
vpf=v1c+v2c+v3c+v4c+v5c+v6c+v7c+v8c
///////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL DERIV VOLUME//////////////////////////////////////////////////////////////////
alldvol = vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////ALL VOLUME//////////////////////////////////////////////////////////////////
allvol = vsf + vff + vpf
/////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////FINAL AGGREGATION SELECTION/////////////////////////////////////////
if markettype == 'Spot'
finvol := vsf
finvol
else if markettype == 'Futures'
finvol := vff
finvol
else if markettype == 'Perp'
finvol := vpf
finvol
else if markettype == 'Derivatives F+P'
finvol := alldvol
finvol
else if markettype == 'Spot+Derivs'
finvol := allvol
finvol
else if aggr==false
finvol := volume
///////////////////////////////////AGGREGATED OR BY CHART////////////////////////////////////////////////
vol = finvol
//////////// RESET BASIS ///////////////////////////////////////////////////////
var float minus = 0
var bool sw = false
//////////////////////////////////BUY SELL VOLUME CALCS///////////////////////////////////////////////////////
// PRESSURE ALGORITHMS AND VARIABLES
TR = ta.atr(1)
// Bull And Bear "Power-Balance" by Vadim Gimelfarb Algorithm's
BP = close<open ? (close[1]<open ? math.max(high-close[1], close-low) : math.max(high-open, close-low)) : (close>open ? (close[1]>open ? high-low : math.max(open-close[1], high-low)) : (high-close>close-low ? (close[1]<open ? math.max(high-close[1],close-low) : high-open) : (high-close<close-low ? (close[1]>open ? high-low : math.max(open-close[1], high-low)) : (close[1]>open ? math.max(high-open, close-low) : (close[1]<open ? math.max(open-close[1], high-low) : high-low)))))
SP = close<open ? (close[1]>open ? math.max(close[1]-open, high-low): high-low) : (close>open ? (close[1]>open ? math.max(close[1]-low, high-close) : math.max(open-low, high-close)) : (high-close>close-low ? (close[1]>open ? math.max(close[1]-open, high-low) : high-low) : (high-close<close-low ? (close[1]>open ? math.max(close[1]-low, high-close) : open-low) : (close[1]>open ? math.max(close[1]-open, high-low) : (close[1]<open ? math.max(open-low, high-close) : high-low)))))
TP = BP+SP
// RAW Pressure Volume Calculations
BPV = (BP/TP)*vol
SPV = (SP/TP)*vol
TPV = BPV+SPV
/////////////BUY ALWAYS UO SELL ALWAYS DOWN//////////////////////
bpp = math.abs(BPV)
spp = -math.abs(SPV)
///////////////////////BUY SELL BARS//////////////////////////////
plot(showd ? spp : na , color=color.red, title="Selling", style=plot.style_columns, linewidth=3)
plot(showd ? bpp : na , color=color.green, title="Buying", style=plot.style_columns, linewidth=3)
///////////////////DELTA///////////////////////////////////////////////////////
var float cvd = na
var float cvd1 = na
var float cvd2 = na
delt = bpp+spp
plot((not showd) ? delt : na, title='Delta Volume', color=(delt>0 ? color.green : color.red), style=plot.style_columns)
////////////////////////CVD BASIS RESET////////////////////////////////////////
|
Daily Levels Suite + Market Breadth | https://www.tradingview.com/script/eIS3JPxY-Daily-Levels-Suite-Market-Breadth/ | mcthatsme | https://www.tradingview.com/u/mcthatsme/ | 336 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ mcthatsme
//@version=5
indicator("Daily Levels Suite + Premarket High/Low", shorttitle="Daily Levels",overlay=true, max_lines_count=500, max_labels_count=500)
//////////////////////////////////////////////////
///////// Inputs ///////////
//////////////////////////////////////////////////
//Groups
var dailyGroup = "Daily Levels"
var weeklyGroup = "Weekly Levels"
var monthlyGroup = "Monthly Levels"
//Input for level colors
showDailyLevels = input.bool (defval=true, title="Show Daily Levels" , group=dailyGroup)
//Previous Day High/Low
currHighName = input.string(defval="Current Day High" , title="", group=dailyGroup, inline="1")
currHighColor = input.color (defval=color.gray , title="", group=dailyGroup, inline="1")
showCurrHigh = input.bool (defval=false , title="", group=dailyGroup, inline="1")
currLowName = input.string(defval="Current Day Low" , title="", group=dailyGroup, inline="1")
currLowColor = input.color (defval=color.gray , title="", group=dailyGroup, inline="1")
showCurrLow = input.bool (defval=false , title="", group=dailyGroup, inline="1")
//Globex Open (9:30 AM open on stocks, globex on futures), RTH Open (when using futures)
globexOpenName = input.string(defval="Globex Open" , title="", group=dailyGroup, inline="2")
globexOpenColor = input.color (defval=color.white , title="", group=dailyGroup, inline="2")
showGlobexOpen = input.bool (defval=false , title="", group=dailyGroup, inline="2")
rthOpenName = input.string(defval="RTH Open" , title="", group=dailyGroup, inline="2")
rthOpenColor = input.color (defval=color.orange , title="", group=dailyGroup, inline="2")
showRthOpen = input.bool (defval=true , title="", group=dailyGroup, inline="2")
//London Open (3:00 AM EST) and Midnight Open (12:00 AM EST)
londonOpenName = input.string(defval="London Open" , title="", group=dailyGroup, inline="3")
londonOpenColor = input.color (defval=color.blue , title="", group=dailyGroup, inline="3")
showLondonOpen = input.bool (defval=false , title="", group=dailyGroup, inline="3")
midNOpenName = input.string(defval="Midnight Open" , title="", group=dailyGroup, inline="3")
midNOpenColor = input.color (defval=color.rgb(200, 0, 255) , title="", group=dailyGroup, inline="3")
showMidNOpen = input.bool (defval=false , title="", group=dailyGroup, inline="3")
//Previous Day High/Low
prevHighName = input.string(defval="Previous Day High" , title="", group=dailyGroup, inline="4")
prevHighColor = input.color (defval=color.green , title="", group=dailyGroup, inline="4")
showPrevHigh = input.bool (defval=true , title="", group=dailyGroup, inline="4")
prevLowName = input.string(defval="Previous Day Low" , title="", group=dailyGroup, inline="4")
prevLowColor = input.color (defval=color.green , title="", group=dailyGroup, inline="4")
showPrevLow = input.bool (defval=true , title="", group=dailyGroup, inline="4")
//Previous Day H/L 50% and Previous Day O/C 50% Close
midHLName = input.string(defval="Prev Day 50% (HL2)" , title="", group=dailyGroup, inline="5")
midHLColor = input.color (defval=color.yellow , title="", group=dailyGroup, inline="5")
showPrevMidHL = input.bool (defval=true , title="", group=dailyGroup, inline="5")
midOCName = input.string(defval="Prev Day 50% (OC2)" , title="", group=dailyGroup, inline="5")
midOCColor = input.color (defval=color.fuchsia , title="", group=dailyGroup, inline="5")
showPrevMidOC = input.bool (defval=false , title="", group=dailyGroup, inline="5")
//T2 Open/Close
t2OpenName = input.string(defval="T+2 Open" , title="", group=dailyGroup, inline="6")
t2OpenColor = input.color (defval=color.rgb(248, 217, 44), title="", group=dailyGroup, inline="6")
showT2Open = input.bool (defval=false , title="", group=dailyGroup, inline="6")
t2CloseName = input.string(defval="T+2 Close" , title="", group=dailyGroup, inline="6")
t2CloseColor = input.color (defval=color.rgb(55, 248, 248), title="", group=dailyGroup, inline="6")
showT2Close = input.bool (defval=false , title="", group=dailyGroup, inline="6")
//T2 High/Low
t2HighName = input.string(defval="T+2 High" , title="", group=dailyGroup, inline="7")
t2HighColor = input.color (defval=color.red , title="", group=dailyGroup, inline="7")
showT2High = input.bool (defval=true , title="", group=dailyGroup, inline="7")
t2LowName = input.string(defval="T+2 Low" , title="", group=dailyGroup, inline="7")
t2LowColor = input.color (defval=color.red , title="", group=dailyGroup, inline="7")
showT2Low = input.bool (defval=true , title="", group=dailyGroup, inline="7")
//Overnight High/Low
onHighName = input.string(defval="Overnight High" , title="", group=dailyGroup, inline="8")
onHighColor = input.color (defval=color.purple , title="", group=dailyGroup, inline="8")
showOnHigh = input.bool (defval=true , title="", group=dailyGroup, inline="8")
onLowName = input.string(defval="Overnight Low" , title="", group=dailyGroup, inline="8")
onLowColor = input.color (defval=color.purple , title="", group=dailyGroup, inline="8")
showOnLow = input.bool (defval=true , title="", group=dailyGroup, inline="8")
//Previous Close
prevCloseName = input.string(defval="Previous Close" , title="", group=dailyGroup, inline="9")
prevCloseColor = input.color (defval=color.aqua , title="", group=dailyGroup, inline="9")
showPrevClose = input.bool (defval=true , title="", group=dailyGroup, inline="9")
//Daily Settings
numDailyPeriods = input.int(title="Number of Previous Days", defval=1, group = dailyGroup, minval = 1, maxval = 40)
showUntestedHLCLevels = input.bool(title="Keep Untested High/Low/Close Levels", defval=false, group = dailyGroup)
showInactiveHLCLevels = input.bool(title="Show Already Tested High/Low/Close Levels", defval=false, group = dailyGroup)
extendOptionDaily = input.string(title="Extend Daily Lines", options=["Right","Both", "None"], defval="Right", group = dailyGroup)
extendLineDaily = (extendOptionDaily == "Right") ? extend.right :
(extendOptionDaily == "Both") ? extend.both :
extend.none
linewidthDaily = input.int(1, "Daily Line Thickness", group = dailyGroup)
styleOptionDaily = input.string(title="Daily Line Style", options=["solid (โ)", "dashed (โ)", "dotted (โ)"],
defval="solid (โ)", group = dailyGroup)
lineStyleDaily = (styleOptionDaily == "dotted (โ)") ? line.style_dotted :
(styleOptionDaily == "dashed (โ)") ? line.style_dashed :
line.style_solid
labelColorDaily = input.color(title="", defval=color.white, group = dailyGroup, inline="labelDaily")
showDailyLabels = input.bool(title="Show Daily Level Labels", defval=true, group = dailyGroup, inline="labelDaily")
labelColorMatchLineD = input.bool(title="Match Label Color With Line Color", defval=false, group=dailyGroup)
labelDailyTextOption = input.string(title="Daily Label Text Size", options=[ "Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group=dailyGroup)
labelDailyTextSize = switch labelDailyTextOption
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
labeloffsetDaily = input.int(title="Daily Label Offset", defval=20, group = dailyGroup)
///////////////////////////
// Weekly Levels Inputs //
///////////////////////////
showWeeklyLevels = input.bool(defval=true, title="Show Weekly Levels", group=weeklyGroup)
prevWeekHighName = input.string(defval="Prev Week High" , title="", group=weeklyGroup, inline="6")
wkHighColor = input.color (defval=color.lime , title="", group=weeklyGroup, inline="6")
showPrevWeekHigh = input.bool (defval=true , title="", group=weeklyGroup, inline="6")
prevWeekLowName = input.string(defval="Prev Week Low" , title="", group=weeklyGroup, inline="6")
wkLowColor = input.color (defval=color.lime , title="", group=weeklyGroup, inline="6")
showPrevWeekLow = input.bool (defval=true , title="", group=weeklyGroup, inline="6")
prevWeekHalfHLName = input.string(defval="Prev Week Half (HL2)", title="", group=weeklyGroup, inline="7")
wkHalfHLColor = input.color (defval=color.yellow , title="", group=weeklyGroup, inline="7")
showPrevWeekHalfHL = input.bool (defval=true , title="", group=weeklyGroup, inline="7")
prevWeekHalfOCName = input.string(defval="Prev Week Half (OC2)", title="", group=weeklyGroup, inline="7")
wkHalfOCColor = input.color (defval=color.fuchsia , title="", group=weeklyGroup, inline="7")
showPrevWeekHalfOC = input.bool (defval=false , title="", group=weeklyGroup, inline="7")
wkOpenName = input.string(defval="Current Week Open" , title="", group=weeklyGroup, inline="8")
wkOpenColor = input.color (defval=color.orange , title="", group=weeklyGroup, inline="8")
showRthWeekOpen = input.bool (defval=true , title="", group=weeklyGroup, inline="8")
wkCloseName = input.string(defval="Prev Week Close" , title="", group=weeklyGroup, inline="8")
wkCloseColor = input.color (defval=color.aqua , title="", group=weeklyGroup, inline="8")
showPrevWeekClose = input.bool (defval=true , title="", group=weeklyGroup, inline="8")
wkVWAPName = input.string(defval="Prev Week VWAP" , title="", group=weeklyGroup, inline="9")
wkVWAPColor = input.color (defval=color.white , title="", group=weeklyGroup, inline="9")
showPrevWeekVWAP = input.bool (defval=false , title="", group=weeklyGroup, inline="9")
wkVSD1Name = input.string(defval="Prev Week VWAP SD1" , title="", group=weeklyGroup, inline="9")
wkVSD1Color = input.color (defval=color.green , title="", group=weeklyGroup, inline="9")
showPrevWeekSD1 = input.bool (defval=false , title="", group=weeklyGroup, inline="9")
wkVSD2Name = input.string(defval="Prev Week VWAP SD2" , title="", group=weeklyGroup, inline="10")
wkVSD2Color = input.color(defval=color.olive , title="", group=weeklyGroup, inline="10")
showPrevWeekSD2 = input.bool (defval=false , title="", group=weeklyGroup, inline="10")
wkVSD3Name = input.string(defval="Prev Week VWAP SD3" , title="", group=weeklyGroup, inline="10")
wkVSD3Color = input.color(defval=color.teal , title="", group=weeklyGroup, inline="10")
showPrevWeekSD3 = input.bool (defval=false , title="", group=weeklyGroup, inline="10")
//Weekly Settings
numWklyPeriods = input.int(title="Number of Previous Weeks", defval=1, group = weeklyGroup, minval = 1, maxval = 20)
extendOptionWeekly = input.string(title="Extend Weekly Lines", options=["Right","Both", "None"], defval="Right", group = weeklyGroup)
extendLineWeekly = (extendOptionWeekly == "Right") ? extend.right :
(extendOptionWeekly == "Both") ? extend.both :
extend.none
linewidthWeekly = input.int(1, "Weekly Line Thickness", group = weeklyGroup)
styleOptionWeekly = input.string(title="Weekly Line Style", options=["solid (โ)", "dashed (โ)", "dotted (โ)"], defval="dotted (โ)", group = weeklyGroup)
lineStyleWeekly = (styleOptionWeekly == "dotted (โ)") ? line.style_dotted :
(styleOptionWeekly == "dashed (โ)") ? line.style_dashed :
line.style_solid
labelColorWeekly = input.color(title="", defval=color.white, group = weeklyGroup, inline="labelWeekly")
showWeeklyLabels = input.bool(title="Show Weekly Level Labels", defval=true, group = weeklyGroup, inline="labelWeekly")
labelColorMatchLineW = input.bool(title="Match Label Color With Line Color", defval=false, group=weeklyGroup)
labelWklyTextOption = input.string(title="Weekly Label Text Size", options=[ "Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group=weeklyGroup)
labelWklyTextSize = switch labelWklyTextOption
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
labeloffsetWeekly = input.int(title="Weekly Label Offset", defval=10, group = weeklyGroup)
////////////////////////////
// Monthly Levels Inputs //
////////////////////////////
showMonthlyLevels = input.bool(title="Show Monthly Levels", defval=true, group = monthlyGroup)
monHighName = input.string(defval="Prev Month High" , title="", group=monthlyGroup, inline="9")
monHighColor = input.color (defval=color.rgb(1, 219, 147), title="", group=monthlyGroup, inline="9")
showPrevMonthHigh = input.bool (defval=true , title="", group=monthlyGroup, inline="9")
monLowName = input.string(defval="Prev Month Low" , title="", group=monthlyGroup, inline="9")
monLowColor = input.color (defval=color.rgb(1, 219, 147), title="", group=monthlyGroup, inline="9")
showPrevMonthLow = input.bool (defval=true , title="", group=monthlyGroup, inline="9")
monHalfHLName = input.string(defval="Prev Month 50% (HL2)" , title="", group=monthlyGroup, inline="10")
monHalfColorHL = input.color (defval=color.rgb(255, 230, 1), title="", group=monthlyGroup, inline="10")
showPrevMonthHalfHL = input.bool (defval=true , title="", group=monthlyGroup, inline="10")
monHalfOCName = input.string(defval="Prev Month 50% (OC2)" , title="", group=monthlyGroup, inline="10")
monHalfOCColor = input.color (defval=color.fuchsia , title="", group=monthlyGroup, inline="10")
showPrevMonthHalfOC = input.bool (defval=false , title="", group=monthlyGroup, inline="10")
monOpenName = input.string(defval="Month Open" , title="", group=monthlyGroup, inline="11")
monOpenColor = input.color(defval=color.orange , title="", group=monthlyGroup, inline="11")
showRthMonthOpen = input.bool (defval=true , title="", group=monthlyGroup, inline="11")
monCloseName = input.string(defval="Prev Month Close" , title="", group=monthlyGroup, inline="11")
monCloseColor = input.color(defval=color.aqua , title="", group=monthlyGroup, inline="11")
showPrevMonthClose = input.bool (defval=true , title="", group=monthlyGroup, inline="11")
//Monthly Settings
numMonPeriods = input.int(title="Number of Previous Months", defval=1, group = monthlyGroup, minval = 1, maxval = 12)
extendOptionMonthly = input.string(title="Extend Monthly Lines", options=["Right","Both", "None"], defval="Right", group = monthlyGroup)
extendLineMonthly = (extendOptionMonthly == "Right") ? extend.right :
(extendOptionMonthly == "Both") ? extend.both :
extend.none
linewidthMonthly = input.int(1, "Line Thickness", group = monthlyGroup)
styleOptionMonthly = input.string(title="Line Style", options=["solid (โ)", "dashed (โ)", "dotted (โ)"], defval="dashed (โ)", group = monthlyGroup)
lineStyleMonthly = (styleOptionMonthly == "dotted (โ)") ? line.style_dotted :
(styleOptionMonthly == "dashed (โ)") ? line.style_dashed :
line.style_solid
labelColorMonthly = input.color(title="", defval=color.white, group = monthlyGroup, inline="labelMonthly")
labelColorMatchLineM = input.bool(title="Match Label Color With Line Color", defval=false, group=monthlyGroup)
showMonthlyLabels = input.bool(title="Show Monthly Level Labels", defval=true, group = monthlyGroup, inline="labelMonthly")
labelMonTextOption = input.string(title="Monthly Label Text Size", options=[ "Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group=monthlyGroup)
labelMonTextSize = switch labelMonTextOption
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
labeloffsetMonthly = input.int(title="Monthly Label Offset", defval=10, group = monthlyGroup)
//When lines are first created, the below values are used for the offset
initialLabelOffset = bar_index + labeloffsetDaily
initialLineOffset = time + timeframe.multiplier * (timeframe.in_seconds()*1000)
//Creating a UDT to capture all relevant information for a given level
type ValueLine
float price = 0
int barIndex = bar_index
int barTime = time
label llabel = na
line level = na
bool testedInFuture = false
//Type for Weekly VWAP Calc
type VWAP
float sum
float volume
float value
//method to copy values from other valueLine except for label and line objects
method copyValueLine(ValueLine this) =>
ValueLine.new(this.price, this.barIndex, this.barTime)
// SessionHigh() returns the highest price during the specified
// session, optionally corrected for the given time zone.
// Returns "na" when the session hasn"t started or isn"t on the chart.
SessionHigh(sessionTime, sessionTimeZone=syminfo.timezone) =>
insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone))
newDayofWeek = (syminfo.session == session.regular and
(syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr")) and
dayofweek(time, sessionTimeZone) != dayofweek(time, sessionTimeZone)[1]
var float sessionHighPrice = na
var int sessionHighBarIndex = na
var int sessionHighTime = na
if insideSession and (not insideSession[1] or newDayofWeek)
sessionHighPrice := high
sessionHighBarIndex := bar_index
sessionHighTime := time
else if insideSession
sessionHighPrice := math.max(sessionHighPrice, high)
if sessionHighPrice != sessionHighPrice[1]
sessionHighBarIndex := bar_index
sessionHighTime := time
[sessionHighPrice, sessionHighBarIndex, sessionHighTime]
// SessionLow() returns the lowest price during the given session,
// optionally corrected for the specified time zone.
// Returns "na" when the session hasn"t started or isn"t on the chart.
SessionLow(sessionTime, sessionTimeZone=syminfo.timezone) =>
insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone))
newDayofWeek =(syminfo.session == session.regular and
(syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr")) and
dayofweek(time, sessionTimeZone) != dayofweek(time, sessionTimeZone)[1]
var float sessionLowPrice = na
var int sessionLowBarIndex = na
var int sessionLowTime = na
if insideSession and (not insideSession[1] or newDayofWeek)
sessionLowPrice := low
sessionLowBarIndex := bar_index
sessionLowTime := time
else if insideSession
sessionLowPrice := math.min(sessionLowPrice, low)
if sessionLowPrice != sessionLowPrice[1]
sessionLowBarIndex := bar_index
sessionLowTime := time
[sessionLowPrice, sessionLowBarIndex, sessionLowTime]
// SessionOpen() returns the lowest price during the given session,
// optionally corrected for the specified time zone.
// Returns "na" when the session hasn"t started or isn"t on the chart.
SessionOpen(sessionTime, sessionTimeZone=syminfo.timezone) =>
insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone))
newDayofWeek =(syminfo.session == session.regular and
(syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr")) and
dayofweek(time, sessionTimeZone) != dayofweek(time, sessionTimeZone)[1]
var float sessionOpenPrice = na
if insideSession and (not insideSession[1] or newDayofWeek)
sessionOpenPrice := open
sessionOpenPrice
// MonthName() returns the lowest price during the given session,
// optionally corrected for the specified time zone.
MonthName(monthInput, sessionTimeZone=syminfo.timezone) =>
string monthName = switch monthInput
1 => "Jan"
2 => "Feb"
3 => "Mar"
4 => "Apr"
5 => "May"
6 => "Jun"
7 => "Jul"
8 => "Aug"
9 => "Sep"
10 => "Oct"
11 => "Nov"
12 => "Dec"
monthName
// NewMonth() returns a boolean if the next trading session is the start of a new month when using extended hours charts
// optionally corrected for the specified time zone.
NewMonth(int timeInput, sessionTimeZone=syminfo.timezone) =>
bool newMonth = na
dayOfWeek = dayofweek(timeInput, sessionTimeZone)
dayOfMonth = dayofmonth(timeInput, sessionTimeZone)
monthNum = month(timeInput, sessionTimeZone)
numDaysInMonth = switch monthNum
1 => 31
2 => year(timeInput, sessionTimeZone) % 4 == 0 ? 29 : 28
3 => 31
4 => 30
5 => 31
6 => 30
7 => 31
8 => 31
9 => 30
10 => 31
11 => 30
12 => 31
//Condiitonal statment to deal with friday session being the end of the month
if dayOfWeek == dayofweek.friday
//if day of week is friday and days in month is 31 and current day of month is 29
//then a new month at the start of next week"s session
if numDaysInMonth == 31 and (dayOfMonth >= 29 or (monthNum == 5 and dayOfMonth == 28))
newMonth := true
else if numDaysInMonth == 30 and dayOfMonth >= 28
newMonth := true
else if numDaysInMonth == 29 and dayOfMonth >= 27
newMonth := true
else if numDaysInMonth == 28 and dayOfMonth >= 26
newMonth := true
//On any other day (i.e. Monday - Thursday) and the days of the month is equal to the number of days in the month
//then the next session will be a new month
else if dayOfMonth == numDaysInMonth
newMonth := true
else
newMonth := false
newMonth
updateIntraDayLines(ValueLine ValueLine, string name, int labelOffset, color lineColor) =>
if na(ValueLine.llabel)
ValueLine.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = ValueLine.price,
text = name + ": " + str.tostring(ValueLine.price),
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? lineColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
ValueLine.llabel.set_x(bar_index + labeloffsetDaily)
ValueLine.llabel.set_y(ValueLine.price)
ValueLine.llabel.set_text(name + ": " + str.tostring(ValueLine.price))
if na(ValueLine.level)
ValueLine.level := line.new(
x1 = ValueLine.barTime,
y1 = ValueLine.price,
x2 = initialLineOffset,
y2 = ValueLine.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = lineColor,
style = lineStyleDaily,
width = linewidthDaily)
ValueLine.level.set_x1(ValueLine.barTime)
ValueLine.level.set_x2(ValueLine.barTime == time ? initialLineOffset : time)
ValueLine.level.set_y1(ValueLine.price)
ValueLine.level.set_y2(ValueLine.price)
updateLines(array<ValueLine> ValueLines, int numLines, bool showOlderLabels, int labelOffset, bool saveUntestedLines = false, bool showInactivePositions = false) =>
lineAdd = 0
sizeArr = ValueLines.size()
if sizeArr > 0
//Updates the number of lines allowed to be plotted for instances where a Value Line object has a value
//but no line created yet. This keeps the prior line plotted. Mostly necessary for futures due to new values
// added to a new ValueLinew object at 4PM EST but new lines using that new value not created until 6PM EST.
if na(ValueLines.last().level)
lineAdd := 1
//Remove any line that is still stored beyond the numLines value
//also update label locations and lines locations of all but current line
for i = sizeArr - 1 to 0
valueLine = ValueLines.get(i)
if saveUntestedLines == true
if valueLine.testedInFuture == true
if showInactivePositions
valueLine.level.set_extend(extend.none)
valueLine.llabel.delete()
else
valueLine.level.delete()
valueLine.llabel.delete()
else if valueLine.testedInFuture == false
if i < sizeArr - (1 + lineAdd)
valueLine.level.set_x2(time)
valueLine.llabel.set_x(bar_index + labelOffset)
if not showOlderLabels
label.delete(valueLine.llabel)
else if i == sizeArr - (1 + lineAdd)
valueLine.level.set_x2(time)
valueLine.llabel.set_x(bar_index + labelOffset)
else if saveUntestedLines == false
//if lines in array go above what user wants on screen, delete lines and labels for that valueline
if i < sizeArr - (numLines + lineAdd)
label.delete(valueLine.llabel)
line.delete(valueLine.level)
//Update prior line to stop at the previous bar
else if i < sizeArr - (1 + lineAdd)
valueLine.llabel.set_x(bar_index + labelOffset)
if not showOlderLabels
valueLine.level.set_extend(extend.none)
label.delete(valueLine.llabel)
else if i == sizeArr - (1 + lineAdd)
valueLine.level.set_x2(valueLine.barTime == time ? initialLineOffset : time)
valueLine.llabel.set_x(bar_index + labelOffset)
deleteLines(array<ValueLine> ValueLines, int maxValueLines) =>
sizeArr = ValueLines.size()
if sizeArr > 0
//Check if number of values in ValueLine array is greater than the max allowed
if sizeArr > maxValueLines
//If level is not na, shift out value and then delete line
firstEntry = ValueLines.shift()
if not na(firstEntry.level)
line.delete(firstEntry.level)
if not na(firstEntry.llabel)
label.delete(firstEntry.llabel)
///////////////////////////////////////////////////////
////////// End Functions Section /////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////
//// Variable Declaration ///////////
///////////////////////////////////////////////////
//Timeframe variables
newDay = dayofweek(time, "America/New_York") != dayofweek(time, "America/New_York")[1]
ONSessionRange = syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr"
? "1600-0930"
: "1800-0930"
insideONSession = not na(time(timeframe.period, ONSessionRange, "America/New_York"))
insideUSSession = not na(time(timeframe.period, "0930-1600", "America/New_York"))
lonOpenSession = not na(time(timeframe.period, "0300-0301", "America/New_York"))
midnightOpenSess = not na(time(timeframe.period, "0000-0001", "America/New_York"))
newUSSession = insideUSSession and not insideUSSession[1]
endOfUSSession = insideUSSession[1] and not insideUSSession
newLonSession = lonOpenSession and not lonOpenSession[1]
newMidnightSession = midnightOpenSess and not midnightOpenSess[1]
newONsession = insideONSession and not insideONSession[1]
rthOnlyChart = syminfo.session == session.regular and (syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr")
or (syminfo.type == "futures" and syminfo.session == "us_regular")
rthOpenSess = rthOnlyChart ? newDay : newUSSession
//Weekly Time Variables
newWeekRTH = dayofweek(time, "America/New_York")[1] > dayofweek(time, "America/New_York")
newWeekETH = dayofweek(time, "America/New_York") == dayofweek.friday and endOfUSSession
newWeek = rthOnlyChart ? newWeekRTH : newWeekETH
//Monthly Time Variables
newMonthRTH = dayofmonth(time, "America/New_York")[1] > dayofmonth(time, "America/New_York")
newMonthETH = NewMonth(time) and endOfUSSession
newMonth = rthOnlyChart ? newMonthRTH : newMonthETH
//Determines RTH vs. ETH for futures charts since pinscript shows session.regular
//regardless of having RTH or ETH selected
var bool futuresRTH = syminfo.type == "futures" and syminfo.session == "us_regular"
futuresNewSession = futuresRTH == true ? rthOpenSess : newONsession
var ValueLine currDayHigh = ValueLine.new()
var ValueLine currDayLow = ValueLine.new()
var ValueLine prevDayHigh = ValueLine.new()
var ValueLine prevDayLow = ValueLine.new()
var ValueLine prevDayClose = ValueLine.new()
var ValueLine prevDayMid = ValueLine.new()
var ValueLine prevDayOCMid = ValueLine.new()
var ValueLine rthOpen = ValueLine.new()
var ValueLine globexOpen = ValueLine.new()
var ValueLine londonOpen = ValueLine.new()
var ValueLine midnightOpen = ValueLine.new()
var ValueLine t2Open = ValueLine.new()
var ValueLine t2Close = ValueLine.new()
var ValueLine t2High = ValueLine.new()
var ValueLine t2Low = ValueLine.new()
var ValueLine onHigh = ValueLine.new()
var ValueLine onLow = ValueLine.new()
var ValueLine prevWeekHigh = ValueLine.new()
var ValueLine prevWeekLow = ValueLine.new()
var ValueLine prevWeek50HL = ValueLine.new()
var ValueLine prevWeek50OC = ValueLine.new()
var ValueLine rthWeekOpen = ValueLine.new()
var ValueLine prevWeekClose = ValueLine.new()
var ValueLine prevMonthHigh = ValueLine.new()
var ValueLine prevMonthLow = ValueLine.new()
var ValueLine prevMonth50HL = ValueLine.new()
var ValueLine prevMonth50OC = ValueLine.new()
var ValueLine rthMonthOpen = ValueLine.new()
var ValueLine prevMonthClose = ValueLine.new()
//Array Initialization
var prevHigh_Arr = array.new<ValueLine>(0)
var prevLow_Arr = array.new<ValueLine>(0)
var prev50HL_Arr = array.new<ValueLine>(0)
var prev50OC_Arr = array.new<ValueLine>(0)
var t2Open_Arr = array.new<ValueLine>(0)
var t2Close_Arr = array.new<ValueLine>(0)
var t2High_Arr = array.new<ValueLine>(0)
var t2Low_Arr = array.new<ValueLine>(0)
var prevClose_Arr = array.new<ValueLine>(0)
var rthOpen_Arr = array.new<ValueLine>(0)
var globexOpen_Arr = array.new<ValueLine>(0)
var londonOpen_Arr = array.new<ValueLine>(0)
var midnightOpen_Arr = array.new<ValueLine>(0)
var onHigh_Arr = array.new<ValueLine>(0)
var onLow_Arr = array.new<ValueLine>(0)
var newWeekVar = false
var prevWeekHigh_Arr = array.new<ValueLine>(0)
var prevWeekLow_Arr = array.new<ValueLine>(0)
var prevWeek50HL_Arr = array.new<ValueLine>(0)
var prevWeek50OC_Arr = array.new<ValueLine>(0)
var rthWeekOpen_Arr = array.new<ValueLine>(0)
var prevWeekClose_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_LBand1_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_UBand1_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_LBand2_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_UBand2_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_LBand3_Arr = array.new<ValueLine>(0)
var prevWeekVWAP_UBand3_Arr = array.new<ValueLine>(0)
var prevMonthHigh_Arr = array.new<ValueLine>(0)
var prevMonthLow_Arr = array.new<ValueLine>(0)
var prevMonth50HL_Arr = array.new<ValueLine>(0)
var prevMonth50OC_Arr = array.new<ValueLine>(0)
var rthMonthOpen_Arr = array.new<ValueLine>(0)
var prevMonthClose_Arr = array.new<ValueLine>(0)
[sessionHighPrice, sessionHighBarIndex, sessionHighTime] = SessionHigh("0930-1600", "America/New_York")
[sessionLowPrice , sessionLowBarIndex, sessionLowTime] = SessionLow("0930-1600", "America/New_York")
//Overnight Calculations
[ONsessionHighPrice, ONsessionHighBarIndex, ONsessionHighTime] = SessionHigh(ONSessionRange, "America/New_York")
[ONsessionLowPrice, ONsessionLowBarIndex , ONsessionLowTime] = SessionLow(ONSessionRange, "America/New_York")
//Overnight Levels when an RTH Chart is being shown need to be gathered via request secutiry function with extended hours checked
[ONsessionHighPrice_RS, ONsessionHighBarIndex_RS, ONsessionHighTime_RS] = request.security(ticker.modify(syminfo.tickerid, session.extended), "30", SessionHigh(ONSessionRange, "America/New_York"), lookahead=barmerge.lookahead_on)
[ONsessionLowPrice_RS, ONsessionLowBarIndex_RS, ONsessionLowTime_RS] = request.security(ticker.modify(syminfo.tickerid, session.extended), "30", SessionLow(ONSessionRange, "America/New_York"), lookahead=barmerge.lookahead_on)
globexOpenPrice_RS = request.security(syminfo.tickerid, "D", open, lookahead=barmerge.lookahead_on)
londonOpenPrice_RS = request.security(ticker.modify(syminfo.tickerid, session.extended), "30", SessionOpen("0300-0301", "America/New_York"), lookahead=barmerge.lookahead_on)
midnightOpenPrice_RS = request.security(ticker.modify(syminfo.tickerid, session.extended), "30", SessionOpen("0000-0001", "America/New_York"), lookahead=barmerge.lookahead_on)
if newONsession and syminfo.type == "futures"
globexOpen.price := open
globexOpen.barIndex := bar_index
globexOpen.barTime := time
globexOpen_Arr.push(globexOpen.copy())
if newLonSession
londonOpen.price := open
londonOpen.barIndex := bar_index
londonOpen.barTime := time
londonOpen_Arr.push(londonOpen.copy())
if newMidnightSession
midnightOpen.price := open
midnightOpen.barIndex := bar_index
midnightOpen.barTime := time
midnightOpen_Arr.push(midnightOpen.copy())
if rthOpenSess
//Reset Current Day High/Low Value Lines
currDayHigh.price := high
currDayHigh.barIndex := bar_index
currDayHigh.barTime := time
currDayHigh.llabel.delete()
currDayHigh.level.delete()
currDayLow.price := low
currDayLow.barIndex := bar_index
currDayLow.barTime := time
currDayLow.llabel.delete()
currDayLow.level.delete()
//for RTH stock charts use newday to filter when to save prev day prices
if rthOnlyChart
if prevClose_Arr.size() > 0 and prevHigh_Arr.size() > 0 and prevLow_Arr.size() > 0
for i = 0 to prevClose_Arr.size() - 1
closeLine = prevClose_Arr.get(i)
highLine = prevHigh_Arr.get(i)
lowLine = prevLow_Arr.get(i)
prevSessionLow = sessionLowPrice[1]
prevSessionHigh = sessionHighPrice[1]
//Check if previous close lines have been traded through
if prevSessionLow < closeLine.price and prevSessionHigh > closeLine.price
closeLine.testedInFuture := true
//Check for if previous high lines have been tested by the last session"s highs
if prevSessionHigh > highLine.price
highLine.testedInFuture := true
//Check for if previous low lines have been tested by the last session"s lows
if prevSessionLow < lowLine.price
lowLine.testedInFuture := true
//Daily Level Calculations for RTH Charts (i.e. strictly 9:30AM - 4PM)
if rthOpen_Arr.size() > 2
t2Open_Arr.push(rthOpen_Arr.get(rthOpen_Arr.size() - 2).copy())
t2Close_Arr.push(prevDayClose.copy())
t2High_Arr.push(prevDayHigh.copy())
t2Low_Arr.push(prevDayLow.copy())
//Logic needed to distinguish RTH close on futures since it closes at 4:15 PM EST
prevDayClose.price := close[syminfo.type == "futures" ? 4 : 1]
prevDayClose.barIndex := bar_index[syminfo.type == "futures" ? 4 : 1]
prevDayClose.barTime := time[syminfo.type == "futures" ? 4 : 1]
prevClose_Arr.push(prevDayClose.copy())
prevDayHigh.price := sessionHighPrice[1]
prevDayHigh.barIndex := sessionHighBarIndex[1]
prevDayHigh.barTime := sessionHighTime[1]
prevHigh_Arr.push(prevDayHigh.copy())
prevDayLow.price := sessionLowPrice[1]
prevDayLow.barIndex := sessionLowBarIndex[1]
prevDayLow.barTime := sessionLowTime[1]
prevLow_Arr.push(prevDayLow.copy())
prevDayMid.price := math.round_to_mintick((prevDayHigh.price + prevDayLow.price) / 2)
prevDayMid.barIndex := rthOpen.barIndex
prevDayMid.barTime := rthOpen.barTime
prev50HL_Arr.push(prevDayMid.copy())
prevDayOCMid.price := math.round_to_mintick((prevDayClose.price + rthOpen.price) / 2)
prevDayOCMid.barIndex := rthOpen.barIndex
prevDayOCMid.barTime := rthOpen.barTime
prev50OC_Arr.push(prevDayOCMid.copy())
if prevWeekHigh.price < prevDayHigh.price
prevWeekHigh := prevDayHigh.copy()
if prevWeekLow.price > prevDayLow.price
prevWeekLow := prevDayLow.copy()
prevWeek50HL.price := (prevWeekHigh.price + prevWeekLow.price) / 2
if prevMonthHigh.price < prevDayHigh.price
prevMonthHigh := prevDayHigh.copy()
if prevMonthLow.price > prevDayLow.price
prevMonthLow := prevDayLow.copy()
prevMonth50HL.price := (prevMonthHigh.price + prevMonthLow.price) / 2
//Filter to determine if we are in RTH for either futures or stocks/funds, if we are, use the request security data from line 430, otherwise use the sessionHigh/Low function
onHigh.price := ONsessionHighPrice_RS
onLow.price := ONsessionLowPrice_RS
onHigh.barIndex := bar_index
onLow.barIndex := bar_index
onHigh.barTime := time
onLow.barTime := time
onHigh_Arr.push(onHigh.copy())
onLow_Arr.push(onLow.copy())
londonOpen.price := londonOpenPrice_RS
londonOpen.barIndex := bar_index
londonOpen.barTime := time
londonOpen_Arr.push(londonOpen.copy())
midnightOpen.price := midnightOpenPrice_RS
midnightOpen.barIndex := bar_index
midnightOpen.barTime := time
midnightOpen_Arr.push(midnightOpen.copy())
if syminfo.type == "futures"
globexOpen.price := globexOpenPrice_RS
globexOpen.barIndex := bar_index
globexOpen.barTime := time
globexOpen_Arr.push(globexOpen.copy())
else
onHigh.level.delete()
onHigh.llabel.delete()
onLow.level.delete()
onLow.llabel.delete()
onHigh_Arr.push(onHigh.copy())
onLow_Arr.push(onLow.copy())
rthOpen.barIndex := bar_index
rthOpen.barTime := time
rthOpen.price := open
rthOpen_Arr.push(rthOpen.copy())
//Check for new week
if dayofweek(time, "America/New_York") == dayofweek.monday or
(dayofweek(prevDayMid.barTime, "America/New_York") == dayofweek.friday and
dayofweek(time, "America/New_York") == dayofweek.tuesday)
rthWeekOpen_Arr.push(rthOpen.copy())
//Check for new month
if dayofmonth(prevDayMid.barTime, "America/New_York") >= 28 and
dayofmonth(time, "America/New_York") < dayofmonth(prevDayMid.barTime, "America/New_York")
rthMonthOpen_Arr.push(rthOpen.copy())
//Logic for Plotting Current Daily High/Low on each new bar
if insideUSSession and barstate.isconfirmed
if currDayHigh.price < sessionHighPrice
currDayHigh.barIndex := sessionHighBarIndex
currDayHigh.barTime := sessionHighTime
currDayHigh.price := sessionHighPrice
if currDayLow.price > sessionLowPrice
currDayLow.barIndex := sessionLowBarIndex
currDayLow.barTime := sessionLowTime
currDayLow.price := sessionLowPrice
if showCurrHigh
updateIntraDayLines(currDayHigh, currHighName, labeloffsetDaily, currHighColor)
if showCurrLow
updateIntraDayLines(currDayLow, currLowName, labeloffsetDaily, currLowColor)
//Reset ON High/Low when new ON session starts
if newONsession
onHigh.barIndex := bar_index
onHigh.barTime := time
onHigh.price := high
updateLines(onHigh_Arr, numDailyPeriods - 1, false, labeloffsetDaily)
onLow.barIndex := bar_index
onLow.barTime := time
onLow.price := low
updateLines(onLow_Arr, numDailyPeriods - 1, false, labeloffsetDaily)
//Monitor ON Session High/Low
if insideONSession and barstate.isconfirmed
if onHigh.price < ONsessionHighPrice
onHigh.barIndex := ONsessionHighBarIndex
onHigh.barTime := ONsessionHighTime
onHigh.price := ONsessionHighPrice
if onLow.price > ONsessionLowPrice
onLow.barIndex := ONsessionLowBarIndex
onLow.barTime := ONsessionLowTime
onLow.price := ONsessionLowPrice
if showOnHigh
updateIntraDayLines(onHigh, onHighName, labeloffsetDaily, onHighColor)
if showOnLow
updateIntraDayLines(onLow, onLowName, labeloffsetDaily, onLowColor)
//for ETH charts and capturing RTH close information at 4:00PM close
if endOfUSSession and not rthOnlyChart
//Delete Current Day High/Low Lines
currDayHigh.llabel.delete()
currDayHigh.level.delete()
currDayLow.llabel.delete()
currDayLow.level.delete()
if prevClose_Arr.size() > 0 and prevHigh_Arr.size() > 0 and prevLow_Arr.size() > 0
for i = 0 to prevClose_Arr.size() - 1
closeLine = prevClose_Arr.get(i)
highLine = prevHigh_Arr.get(i)
lowLine = prevLow_Arr.get(i)
prevSessionLow = sessionLowPrice[1]
prevSessionHigh = sessionHighPrice[1]
//Check if previous close lines have been traded through
if prevSessionLow < closeLine.price and prevSessionHigh > closeLine.price
closeLine.testedInFuture := true
//Check for if previous high lines have been tested by the last session"s highs
if prevSessionHigh > highLine.price
highLine.testedInFuture := true
//Check for if previous low lines have been tested by the last session"s lows
if prevSessionLow < lowLine.price
lowLine.testedInFuture := true
if rthOpen_Arr.size() > 2
t2Open_Arr.push(rthOpen_Arr.get(rthOpen_Arr.size() - 2).copy())
t2Close_Arr.push(prevDayClose.copy())
t2High_Arr.push(prevDayHigh.copy())
t2Low_Arr.push(prevDayLow.copy())
prevDayClose.price := close[1]
prevDayClose.barIndex := bar_index[1]
prevDayClose.barTime := time[1]
prevClose_Arr.push(prevDayClose.copy())
prevDayHigh.price := sessionHighPrice[1]
prevDayHigh.barIndex := sessionHighBarIndex[1]
prevDayHigh.barTime := sessionHighTime[1]
prevHigh_Arr.push(prevDayHigh.copy())
prevDayLow.price := sessionLowPrice[1]
prevDayLow.barIndex := sessionLowBarIndex[1]
prevDayLow.barTime := sessionLowTime[1]
prevLow_Arr.push(prevDayLow.copy())
prevDayMid.price := math.round_to_mintick((prevDayHigh.price + prevDayLow.price) / 2)
prevDayMid.barIndex := rthOpen.barIndex
prevDayMid.barTime := rthOpen.barTime
prev50HL_Arr.push(prevDayMid.copy())
prevDayOCMid.price := math.round_to_mintick((prevDayClose.price + rthOpen.price) / 2)
prevDayOCMid.barIndex := rthOpen.barIndex
prevDayOCMid.barTime := rthOpen.barTime
prev50OC_Arr.push(prevDayOCMid.copy())
if prevWeekHigh.price < prevDayHigh.price
prevWeekHigh := prevDayHigh.copy()
if prevWeekLow.price > prevDayLow.price
prevWeekLow := prevDayLow.copy()
prevWeek50HL.price := (prevWeekHigh.price + prevWeekLow.price) / 2
if prevMonthHigh.price < prevDayHigh.price
prevMonthHigh := prevDayHigh.copy()
if prevMonthLow.price > prevDayLow.price
prevMonthLow := prevDayLow.copy()
prevMonth50HL.price := (prevMonthHigh.price + prevMonthLow.price) / 2
//Weekly level Calculations
//Weekly VWAP Calculations
var string anchorWeekly = "1W"
var int index = 1
var float psum = hlc3
var float v1 = 0
var float mean = psum / index
//vwapWeekly = ta.vwap(hlc3, timeframe.change(anchorWeekly))
var vwapWeekly = VWAP.new(0,0,0)
if rthOpenSess and dayofweek(time) == dayofweek.monday
vwapWeekly := VWAP.new(hlc3 * volume, volume, (hlc3 * volume) / volume)
index := 1
psum := hlc3
mean := psum / index
v1 := math.pow(hlc3 - mean,2)
else if insideUSSession
vwapWeekly.sum := vwapWeekly.sum + (hlc3 * volume)
vwapWeekly.volume := vwapWeekly.volume + volume
vwapWeekly.value := vwapWeekly.sum/vwapWeekly.volume
index := index + 1
psum := psum + hlc3
mean := psum / index
v1 := v1 + math.pow(hlc3 - mean,2)
vwapVariance = nz(v1 / (index - 1))
vwapStdDev = math.sqrt(vwapVariance)
weeklyUpperBandValue1 = vwapWeekly.value + vwapStdDev
weeklyLowerBandValue1 = vwapWeekly.value - vwapStdDev
weeklyUpperBandValue2 = vwapWeekly.value + vwapStdDev * 2
weeklyLowerBandValue2 = vwapWeekly.value - vwapStdDev * 2
weeklyUpperBandValue3 = vwapWeekly.value + vwapStdDev * 3
weeklyLowerBandValue3 = vwapWeekly.value - vwapStdDev * 3
if newWeek
prevWeekClose := prevDayClose.copy()
//Get last weeks RTH value to update HL2 and OC2 barIndex/barTime
if rthWeekOpen_Arr.size() > 1
lastWeekRTH = rthOnlyChart ? rthWeekOpen_Arr.get(rthWeekOpen_Arr.size() - 2) : rthWeekOpen_Arr.get(rthWeekOpen_Arr.size() - 1)
prevWeek50OC.price := (prevWeekClose.price + lastWeekRTH.price) / 2
prevWeek50HL.barIndex := lastWeekRTH.barIndex
prevWeek50OC.barIndex := lastWeekRTH.barIndex
prevWeek50HL.barTime := lastWeekRTH.barTime
prevWeek50OC.barTime := lastWeekRTH.barTime
//push values to their respective arrays
prevWeekHigh_Arr.push(prevWeekHigh.copy())
prevWeekLow_Arr.push(prevWeekLow.copy())
prevWeekClose_Arr.push(prevWeekClose.copy())
prevWeek50HL_Arr.push(prevWeek50HL.copy())
prevWeek50OC_Arr.push(prevWeek50OC.copy())
//Push VWAP values to respective arrays
prevWeekVWAP_Arr.push(ValueLine.new(vwapWeekly.value[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_UBand1_Arr.push(ValueLine.new(weeklyUpperBandValue1[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_LBand1_Arr.push(ValueLine.new(weeklyLowerBandValue1[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_UBand2_Arr.push(ValueLine.new(weeklyUpperBandValue2[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_LBand2_Arr.push(ValueLine.new(weeklyLowerBandValue2[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_UBand3_Arr.push(ValueLine.new(weeklyUpperBandValue3[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
prevWeekVWAP_LBand3_Arr.push(ValueLine.new(weeklyLowerBandValue3[1], prevWeek50HL.barIndex, prevWeek50HL.barTime))
//Monthly Level Calculations
if newMonth
prevMonthClose := prevDayClose.copy()
//get last months RTH value to update HL2 and OC2 barIndex/barTime
if rthMonthOpen_Arr.size() > 1
lastMonthRTH = rthOnlyChart ? rthMonthOpen_Arr.get(rthMonthOpen_Arr.size() - 2) : rthMonthOpen_Arr.get(rthMonthOpen_Arr.size() - 1)
prevMonth50OC.price := (prevMonthClose.price + lastMonthRTH.price) / 2
prevMonth50HL.barIndex := lastMonthRTH.barIndex
prevMonth50OC.barIndex := lastMonthRTH.barIndex
prevMonth50HL.barTime := lastMonthRTH.barTime
prevMonth50OC.barTime := lastMonthRTH.barTime
//push values to their respective arrays
prevMonthHigh_Arr.push(prevMonthHigh.copy())
prevMonthLow_Arr.push(prevMonthLow.copy())
prevMonthClose_Arr.push(prevMonthClose.copy())
prevMonth50HL_Arr.push(prevMonth50HL.copy())
prevMonth50OC_Arr.push(prevMonth50OC.copy())
//New Session Filters for all types of tickers
//Globex Open Filter (Futures)
//End of US Session (Forex and Crypto)
//New Day filter (Securities and Indexes) when showing only RTH
//End of RTH filter (Securities and Indexes) when showing ETH
resetLineFilter = (syminfo.type == "futures" and futuresNewSession) or
((syminfo.type =="crypto" or syminfo.type == "forex" or syminfo.type == "index") and endOfUSSession) or
(((syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr") and syminfo.session == session.regular) and newDay) or
(((syminfo.type == "stock" or syminfo.type == "index" or syminfo.type == "fund" or syminfo.type == "dr") and syminfo.session == session.extended) and endOfUSSession)
//Updating Value Lines collected above into a label description and new line
//Only show on 30m chart or below
if showDailyLevels == true and timeframe.in_seconds() <= timeframe.in_seconds("30")
//Globex Open
if showGlobexOpen == true and globexOpen_Arr.size() > 0
if futuresNewSession and syminfo.type == "futures"
newGlobexOpen = globexOpen_Arr.last()
globexOpen_Name = globexOpenName + ": " + str.tostring(newGlobexOpen.price, format.mintick)
newGlobexOpen.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newGlobexOpen.price,
text = globexOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? globexOpenColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newGlobexOpen.level := line.new(
x1 = newGlobexOpen.barTime,
y1 = newGlobexOpen.price,
x2 = initialLineOffset,
y2 = newGlobexOpen.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = globexOpenColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(globexOpen_Arr, numDailyPeriods, false, labeloffsetDaily)
//RTH Open
if showRthOpen == true and rthOpen_Arr.size() > 0
if rthOpenSess
newRthOpen = rthOpen_Arr.last()
rthOpen_Name = rthOpenName + ": " + str.tostring(newRthOpen.price, format.mintick)
newRthOpen.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newRthOpen.price,
text = rthOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? rthOpenColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newRthOpen.level := line.new(
x1 = newRthOpen.barTime,
y1 = newRthOpen.price,
x2 = initialLineOffset,
y2 = newRthOpen.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = rthOpenColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(rthOpen_Arr, numDailyPeriods, false, labeloffsetDaily)
//London Open
if showLondonOpen == true and londonOpen_Arr.size() > 0
if rthOnlyChart ? rthOpenSess : newLonSession
newLondonOpen = londonOpen_Arr.last()
londonOpen_Name = londonOpenName + ": " + str.tostring(newLondonOpen.price, format.mintick)
newLondonOpen.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newLondonOpen.price,
text = londonOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? londonOpenColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newLondonOpen.level := line.new(
x1 = newLondonOpen.barTime,
y1 = newLondonOpen.price,
x2 = initialLineOffset,
y2 = newLondonOpen.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = londonOpenColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(londonOpen_Arr, numDailyPeriods, false, labeloffsetDaily)
//Midnight Open
if showMidNOpen == true and midnightOpen_Arr.size() > 0
if rthOnlyChart ? rthOpenSess : midnightOpenSess
newMidnightOpen = midnightOpen_Arr.last()
midnightOpen_Name = midNOpenName + ": " + str.tostring(newMidnightOpen.price, format.mintick)
newMidnightOpen.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newMidnightOpen.price,
text = midnightOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? midNOpenColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newMidnightOpen.level := line.new(
x1 = newMidnightOpen.barTime,
y1 = newMidnightOpen.price,
x2 = initialLineOffset,
y2 = newMidnightOpen.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = midNOpenColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(midnightOpen_Arr, numDailyPeriods, false, labeloffsetDaily)
//Overnight High
if showOnHigh == true and onHigh_Arr.size() > 0
if rthOpenSess
newONHigh = onHigh_Arr.last()
onHigh_Name = onHighName + ": " + str.tostring(newONHigh.price, format.mintick)
newONHigh.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newONHigh.price,
text = onHigh_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? onHighColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newONHigh.level := line.new(
x1 = newONHigh.barTime,
y1 = newONHigh.price,
x2 = initialLineOffset,
y2 = newONHigh.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = onHighColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(onHigh_Arr, numDailyPeriods, false, labeloffsetDaily)
//Overnight Low
if showOnLow == true and onLow_Arr.size() > 0
if rthOpenSess
newONLow = onLow_Arr.last()
onLow_Name = onLowName + ": " + str.tostring(newONLow.price, format.mintick)
newONLow.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newONLow.price,
text = onLow_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? onLowColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newONLow.level := line.new(
x1 = newONLow.barTime,
y1 = newONLow.price,
x2 = initialLineOffset,
y2 = newONLow.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = onLowColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(onLow_Arr, numDailyPeriods, false, labeloffsetDaily)
if showPrevHigh == true and prevHigh_Arr.size() > 0
if resetLineFilter
newPrevHigh = prevHigh_Arr.last()
prevHigh_Name = prevHighName + ": " + str.tostring(newPrevHigh.price, format.mintick)
newPrevHigh.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newPrevHigh.price,
text = prevHigh_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? prevHighColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newPrevHigh.level := line.new(
x1 = newPrevHigh.barTime,
y1 = newPrevHigh.price,
x2 = initialLineOffset,
y2 = newPrevHigh.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = prevHighColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(prevHigh_Arr, numDailyPeriods, false, labeloffsetDaily, showUntestedHLCLevels, showInactiveHLCLevels)
if showPrevLow == true and prevLow_Arr.size() > 0
if resetLineFilter
newPrevLow = prevLow_Arr.last()
prevLow_Name = prevLowName + ": " + str.tostring(newPrevLow.price, format.mintick)
newPrevLow.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newPrevLow.price,
text = prevLow_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? prevLowColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newPrevLow.level := line.new(
x1 = newPrevLow.barTime,
y1 = newPrevLow.price,
x2 = initialLineOffset,
y2 = newPrevLow.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = prevLowColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(prevLow_Arr, numDailyPeriods, false, labeloffsetDaily, showUntestedHLCLevels, showInactiveHLCLevels)
if showPrevMidHL == true and prev50HL_Arr.size() > 0
if resetLineFilter
newPrevMidHL = prev50HL_Arr.last()
prevMidHL_Name = midHLName + ": " + str.tostring(newPrevMidHL.price, format.mintick)
newPrevMidHL.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMidHL.price,
text = prevMidHL_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? midHLColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newPrevMidHL.level := line.new(
x1 = newPrevMidHL.barTime,
y1 = newPrevMidHL.price,
x2 = initialLineOffset,
y2 = newPrevMidHL.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = midHLColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(prev50HL_Arr, numDailyPeriods, false, labeloffsetDaily)
if showPrevMidOC == true and prev50OC_Arr.size() > 0
if resetLineFilter
newPrevMidOC = prev50OC_Arr.last()
prevMidOC_Name = midOCName + ": " + str.tostring(newPrevMidOC.price, format.mintick)
newPrevMidOC.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMidOC.price,
text = prevMidOC_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? midOCColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newPrevMidOC.level := line.new(
x1 = newPrevMidOC.barTime,
y1 = newPrevMidOC.price,
x2 = initialLineOffset,
y2 = newPrevMidOC.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = midOCColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(prev50OC_Arr, numDailyPeriods, false, labeloffsetDaily)
if showPrevClose == true and prevClose_Arr.size() > 0
if resetLineFilter
newPrevClose = prevClose_Arr.last()
prevDayClose_Name = prevCloseName + ": " + str.tostring(newPrevClose.price, format.mintick)
newPrevClose.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newPrevClose.price,
text = prevDayClose_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? prevCloseColor : labelColorDaily,
textalign = text.align_left,
style = label.style_none,
size = labelDailyTextSize) : na
newPrevClose.level := line.new(
x1 = newPrevClose.barTime,
y1 = newPrevClose.price,
x2 = initialLineOffset,
y2 = newPrevClose.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = prevCloseColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(prevClose_Arr, numDailyPeriods, false, labeloffsetDaily, showUntestedHLCLevels, showInactiveHLCLevels)
// //T+2 Settlement Open/Close(settlement levels)
if showT2Open == true and t2Open_Arr.size() > 0
if resetLineFilter
newt2Open = t2Open_Arr.last()
t2Open_Name = t2OpenName + ": " + str.tostring(newt2Open.price, format.mintick)
newt2Open.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newt2Open.price,
text = t2Open_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? t2OpenColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newt2Open.level := line.new(
x1 = newt2Open.barTime,
y1 = newt2Open.price,
x2 = initialLineOffset,
y2 = newt2Open.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = t2OpenColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(t2Open_Arr, numDailyPeriods, false, labeloffsetDaily)
if showT2Close == true and t2Close_Arr.size() > 0
if resetLineFilter
newt2Close = t2Close_Arr.last()
t2Close_Name = t2CloseName + ": " + str.tostring(newt2Close.price, format.mintick)
newt2Close.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newt2Close.price,
text = t2Close_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? t2CloseColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newt2Close.level := line.new(
x1 = newt2Close.barTime,
y1 = newt2Close.price,
x2 = initialLineOffset,
y2 = newt2Close.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = t2CloseColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(t2Close_Arr, numDailyPeriods, false, labeloffsetDaily)
// //T+2 Settlement High/Low (settlement levels)
if showT2High == true and t2High_Arr.size() > 0
if resetLineFilter
newt2High = t2High_Arr.last()
t2High_Name = t2HighName + ": " + str.tostring(newt2High.price, format.mintick)
newt2High.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newt2High.price,
text = t2High_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? t2HighColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newt2High.level := line.new(
x1 = newt2High.barTime,
y1 = newt2High.price,
x2 = initialLineOffset,
y2 = newt2High.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = t2HighColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(t2High_Arr, numDailyPeriods, false, labeloffsetDaily)
if showT2Low == true and t2Low_Arr.size() > 0
if resetLineFilter
newt2Low = t2Low_Arr.last()
t2Low_Name = t2LowName + ": " + str.tostring(newt2Low.price, format.mintick)
newt2Low.llabel := showDailyLabels ? label.new(
x = initialLabelOffset,
y = newt2Low.price,
text = t2Low_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineD ? t2LowColor : labelColorDaily,
textalign = text.align_right,
style = label.style_none,
size = labelDailyTextSize) : na
newt2Low.level := line.new(
x1 = newt2Low.barTime,
y1 = newt2Low.price,
x2 = initialLineOffset,
y2 = newt2Low.price,
xloc = xloc.bar_time,
extend = extendLineDaily,
color = t2LowColor,
style = lineStyleDaily,
width = linewidthDaily)
updateLines(t2Low_Arr, numDailyPeriods, false, labeloffsetDaily)
if showWeeklyLevels
initialLabelOffset := bar_index + labeloffsetWeekly
if rthOpenSess and (dayofweek(time, "America/New_York") == dayofweek.monday or
(dayofweek(prevDayMid.barTime, "America/New_York") == dayofweek.friday and
dayofweek(time, "America/New_York") == dayofweek.tuesday))
if showRthWeekOpen and rthWeekOpen_Arr.size() > 0
newrthWeekOpen = rthWeekOpen_Arr.last()
rthWeekOpen_Name = wkOpenName + ": " + str.tostring(newrthWeekOpen.price, format.mintick)
newrthWeekOpen.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newrthWeekOpen.price,
text = rthWeekOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkOpenColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newrthWeekOpen.level := line.new(
x1 = newrthWeekOpen.barTime,
y1 = newrthWeekOpen.price,
x2 = initialLineOffset,
y2 = newrthWeekOpen.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkOpenColor,
style = lineStyleWeekly,
width = linewidthWeekly)
if newWeek
if showPrevWeekHigh and prevWeekHigh_Arr.size() > 0
newPrevWeekHigh = prevWeekHigh_Arr.last()
prevWeekHigh_Name = prevWeekHighName + ": " + str.tostring(newPrevWeekHigh.price, format.mintick)
newPrevWeekHigh.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekHigh.price,
text = prevWeekHigh_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkHighColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekHigh.level := line.new(
x1 = newPrevWeekHigh.barTime,
y1 = newPrevWeekHigh.price,
x2 = initialLineOffset,
y2 = newPrevWeekHigh.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkHighColor,
style = lineStyleWeekly,
width = linewidthWeekly)
prevWeekHigh.price := 0
if showPrevWeekLow and prevWeekLow_Arr.size() > 0
newPrevWeekLow = prevWeekLow_Arr.last()
prevWeekLow_Name = prevWeekLowName + ": " + str.tostring(newPrevWeekLow.price, format.mintick)
newPrevWeekLow.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekLow.price,
text = prevWeekLow_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkLowColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekLow.level := line.new(
x1 = newPrevWeekLow.barTime,
y1 = newPrevWeekLow.price,
x2 = initialLineOffset,
y2 = newPrevWeekLow.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkLowColor,
style = lineStyleWeekly,
width = linewidthWeekly)
prevWeekLow.price := 100000000
if showPrevWeekHalfHL and prevWeek50HL_Arr.size() > 0
newPrevWeek50HL = prevWeek50HL_Arr.last()
prevWeek50HL_Name =prevWeekHalfHLName + ": " + str.tostring(prevWeek50HL.price, format.mintick)
newPrevWeek50HL.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeek50HL.price,
text = prevWeek50HL_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkHalfHLColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeek50HL.level := line.new(
x1 = newPrevWeek50HL.barTime,
y1 = newPrevWeek50HL.price,
x2 = initialLineOffset,
y2 = newPrevWeek50HL.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkHalfHLColor,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekHalfOC and prevWeek50OC_Arr.size() > 0
newPrevWeek50OC = prevWeek50OC_Arr.last()
prevWeek50OC_Name = prevWeekHalfOCName + ": " + str.tostring(prevWeek50OC.price, format.mintick)
newPrevWeek50OC.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeek50OC.price,
text = prevWeek50OC_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkHalfOCColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeek50OC.level := line.new(
x1 = newPrevWeek50OC.barTime,
y1 = newPrevWeek50OC.price,
x2 = initialLineOffset,
y2 = newPrevWeek50OC.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkHalfOCColor,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekClose and prevWeekClose_Arr.size() > 0
newPrevWeekClose = prevWeekClose_Arr.last()
prevWeekClose_Name = wkCloseName + ": " + str.tostring(prevWeekClose.price, format.mintick)
newPrevWeekClose.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekClose.price,
text = prevWeekClose_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkCloseColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekClose.level := line.new(
x1 = newPrevWeekClose.barTime,
y1 = newPrevWeekClose.price,
x2 = initialLineOffset,
y2 = newPrevWeekClose.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkCloseColor,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekVWAP and prevWeekVWAP_Arr.size() > 0
newPrevWeekVWAP = prevWeekVWAP_Arr.last()
prevWeekVWAP_Name = wkVWAPName + ": " + str.tostring(newPrevWeekVWAP.price, format.mintick)
newPrevWeekVWAP.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekVWAP.price,
text = prevWeekVWAP_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVWAPColor : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekVWAP.level := line.new(
x1 = newPrevWeekVWAP.barTime,
y1 = newPrevWeekVWAP.price,
x2 = initialLineOffset,
y2 = newPrevWeekVWAP.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVWAPColor,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD1 and prevWeekVWAP_UBand1_Arr.size() > 0
newPrevWeekSD1 = prevWeekVWAP_UBand1_Arr.last()
prevWeekSD1_Name = wkVSD1Name + ": " + str.tostring(newPrevWeekSD1.price, format.mintick)
newPrevWeekSD1.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD1.price,
text = prevWeekSD1_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD1Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD1.level := line.new(
x1 = newPrevWeekSD1.barTime,
y1 = newPrevWeekSD1.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD1.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD1Color,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD1 and prevWeekVWAP_LBand1_Arr.size() > 0
newPrevWeekSD1 = prevWeekVWAP_LBand1_Arr.last()
prevWeekSD1_Name = wkVSD1Name + ": " + str.tostring(newPrevWeekSD1.price, format.mintick)
newPrevWeekSD1.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD1.price,
text = prevWeekSD1_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD1Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD1.level := line.new(
x1 = newPrevWeekSD1.barTime,
y1 = newPrevWeekSD1.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD1.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD1Color,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD2 and prevWeekVWAP_UBand2_Arr.size() > 0
newPrevWeekSD2 = prevWeekVWAP_UBand2_Arr.last()
prevWeekSD2_Name = wkVSD2Name + ": " + str.tostring(newPrevWeekSD2.price, format.mintick)
newPrevWeekSD2.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD2.price,
text = prevWeekSD2_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD2Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD2.level := line.new(
x1 = newPrevWeekSD2.barTime,
y1 = newPrevWeekSD2.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD2.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD2Color,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD2 and prevWeekVWAP_LBand2_Arr.size() > 0
newPrevWeekSD2 = prevWeekVWAP_LBand2_Arr.last()
prevWeekSD2_Name = wkVSD2Name + ": " + str.tostring(newPrevWeekSD2.price, format.mintick)
newPrevWeekSD2.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD2.price,
text = prevWeekSD2_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD2Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD2.level := line.new(
x1 = newPrevWeekSD2.barTime,
y1 = newPrevWeekSD2.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD2.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD2Color,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD3 and prevWeekVWAP_UBand3_Arr.size() > 0
newPrevWeekSD3 = prevWeekVWAP_UBand3_Arr.last()
prevWeekSD3_Name = wkVSD3Name + ": " + str.tostring(newPrevWeekSD3.price, format.mintick)
newPrevWeekSD3.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD3.price,
text = prevWeekSD3_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD3Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD3.level := line.new(
x1 = newPrevWeekSD3.barTime,
y1 = newPrevWeekSD3.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD3.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD3Color,
style = lineStyleWeekly,
width = linewidthWeekly)
if showPrevWeekSD3 and prevWeekVWAP_LBand3_Arr.size() > 0
newPrevWeekSD3 = prevWeekVWAP_LBand3_Arr.last()
prevWeekSD3_Name = wkVSD3Name + ": " + str.tostring(newPrevWeekSD3.price, format.mintick)
newPrevWeekSD3.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevWeekSD3.price,
text = prevWeekSD3_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineW ? wkVSD3Color : labelColorWeekly,
textalign = text.align_right,
style = label.style_none,
size = labelWklyTextSize) : na
newPrevWeekSD3.level := line.new(
x1 = newPrevWeekSD3.barTime,
y1 = newPrevWeekSD3.price,
x2 = initialLineOffset,
y2 = newPrevWeekSD3.price,
xloc = xloc.bar_time,
extend = extendLineWeekly,
color = wkVSD3Color,
style = lineStyleWeekly,
width = linewidthWeekly)
updateLines(prevWeekHigh_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekLow_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeek50HL_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeek50OC_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(rthWeekOpen_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekClose_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_Arr , numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_UBand1_Arr, numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_LBand1_Arr, numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_UBand2_Arr, numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_LBand2_Arr, numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_UBand3_Arr, numWklyPeriods, false, labeloffsetWeekly)
updateLines(prevWeekVWAP_LBand3_Arr, numWklyPeriods, false, labeloffsetWeekly)
if showMonthlyLevels
initialLabelOffset := bar_index + labeloffsetMonthly
if rthOpenSess and (dayofmonth(prevDayMid.barTime, "America/New_York") >= 28 and
dayofmonth(time, "America/New_York") < dayofmonth(prevDayMid.barTime, "America/New_York"))
if showRthMonthOpen and rthMonthOpen_Arr.size() > 0
newrthMonthOpen = rthMonthOpen_Arr.last()
rthMonthOpen_Name = monOpenName + ": " + str.tostring(newrthMonthOpen.price, format.mintick)
newrthMonthOpen.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newrthMonthOpen.price,
text = rthMonthOpen_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monOpenColor : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newrthMonthOpen.level := line.new(
x1 = newrthMonthOpen.barTime,
y1 = newrthMonthOpen.price,
x2 = initialLineOffset,
y2 = newrthMonthOpen.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monOpenColor,
style = lineStyleMonthly,
width = linewidthMonthly)
if newMonth
if showPrevMonthHigh and prevMonthHigh_Arr.size() > 0
newPrevMonthHigh = prevMonthHigh_Arr.last()
prevMonthHigh_Name = monHighName + ":" + str.tostring(prevMonthHigh.price, format.mintick)
newPrevMonthHigh.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = prevMonthHigh.price,
text = prevMonthHigh_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monHighColor : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newPrevMonthHigh.level := line.new(
x1 = newPrevMonthHigh.barTime,
y1 = newPrevMonthHigh.price,
x2 = initialLineOffset,
y2 = newPrevMonthHigh.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monHighColor,
style = lineStyleMonthly,
width = linewidthMonthly)
prevMonthHigh.price := 0
if showPrevMonthLow and prevMonthLow_Arr.size() > 0
newPrevMonthLow = prevMonthLow_Arr.last()
prevMonthLow_Name = monLowName + ":" + str.tostring(newPrevMonthLow.price, format.mintick)
newPrevMonthLow.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMonthLow.price,
text = prevMonthLow_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monLowColor : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newPrevMonthLow.level := line.new(
x1 = newPrevMonthLow.barTime,
y1 = newPrevMonthLow.price,
x2 = initialLineOffset,
y2 = newPrevMonthLow.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monLowColor,
style = lineStyleMonthly,
width = linewidthMonthly)
prevMonthLow.price := 100000000
if showPrevMonthHalfHL and prevMonth50HL_Arr.size() > 0
newPrevMonth50HL = prevMonth50HL_Arr.last()
prevMonth50HL_Name = monHalfHLName + ":" + str.tostring(newPrevMonth50HL.price, format.mintick)
newPrevMonth50HL.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMonth50HL.price,
text = prevMonth50HL_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monHalfColorHL : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newPrevMonth50HL.level := line.new(
x1 = newPrevMonth50HL.barTime,
y1 = newPrevMonth50HL.price,
x2 = initialLineOffset,
y2 = newPrevMonth50HL.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monHalfColorHL,
style = lineStyleMonthly,
width = linewidthMonthly)
if showPrevMonthHalfOC and prevMonth50OC_Arr.size() > 0
newPrevMonth50OC = prevMonth50OC_Arr.last()
prevMonth50OC_Name = monHalfOCName + ":" + str.tostring(newPrevMonth50OC.price, format.mintick)
newPrevMonth50OC.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMonth50OC.price,
text = prevMonth50OC_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monHalfOCColor : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newPrevMonth50OC.level := line.new(
x1 = newPrevMonth50OC.barTime,
y1 = newPrevMonth50OC.price,
x2 = initialLineOffset,
y2 = newPrevMonth50OC.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monHalfOCColor,
style = lineStyleMonthly,
width = linewidthMonthly)
if showPrevMonthClose and prevMonthClose_Arr.size() > 0
newPrevMonthClose = prevMonthClose_Arr.last()
prevMonthClose_Name = monCloseName + ":" + str.tostring(newPrevMonthClose.price, format.mintick)
newPrevMonthClose.llabel := showWeeklyLabels ? label.new(
x = initialLabelOffset,
y = newPrevMonthClose.price,
text = prevMonthClose_Name,
xloc = xloc.bar_index,
textcolor = labelColorMatchLineM ? monCloseColor : labelColorMonthly,
textalign = text.align_right,
style = label.style_none,
size = labelMonTextSize) : na
newPrevMonthClose.level := line.new(
x1 = newPrevMonthClose.barTime,
y1 = newPrevMonthClose.price,
x2 = initialLineOffset,
y2 = newPrevMonthClose.price,
xloc = xloc.bar_time,
extend = extendLineMonthly,
color = monCloseColor,
style = lineStyleMonthly,
width = linewidthMonthly)
updateLines(prevMonthHigh_Arr , numMonPeriods, false, labeloffsetMonthly)
updateLines(prevMonthLow_Arr , numMonPeriods, false, labeloffsetMonthly)
updateLines(prevMonth50HL_Arr , numMonPeriods, false, labeloffsetMonthly)
updateLines(prevMonth50OC_Arr , numMonPeriods, false, labeloffsetMonthly)
updateLines(rthMonthOpen_Arr , numMonPeriods, false, labeloffsetMonthly)
updateLines(prevMonthClose_Arr, numMonPeriods, false, labeloffsetMonthly)
//Delete Lines over the max limit
deleteLines(prevHigh_Arr , showUntestedHLCLevels and showDailyLevels ? 1000 : numDailyPeriods + 2)
deleteLines(prevLow_Arr , showUntestedHLCLevels and showDailyLevels ? 1000 : numDailyPeriods + 2)
deleteLines(prev50HL_Arr , numDailyPeriods)
deleteLines(prev50OC_Arr , numDailyPeriods)
deleteLines(t2Open_Arr , numDailyPeriods)
deleteLines(t2Close_Arr , numDailyPeriods)
deleteLines(t2High_Arr , numDailyPeriods)
deleteLines(t2Low_Arr , numDailyPeriods)
deleteLines(prevClose_Arr , showUntestedHLCLevels and showDailyLevels ? 1000 : numDailyPeriods + 2)
deleteLines(rthOpen_Arr , numDailyPeriods + 2)
deleteLines(globexOpen_Arr , numDailyPeriods)
deleteLines(londonOpen_Arr , numDailyPeriods)
deleteLines(midnightOpen_Arr, numDailyPeriods)
deleteLines(onHigh_Arr , numDailyPeriods)
deleteLines(onLow_Arr , numDailyPeriods)
deleteLines(prevWeekHigh_Arr , numWklyPeriods)
deleteLines(prevWeekLow_Arr , numWklyPeriods)
deleteLines(prevWeek50HL_Arr , numWklyPeriods)
deleteLines(prevWeek50OC_Arr , numWklyPeriods)
deleteLines(rthWeekOpen_Arr , numWklyPeriods + 1)
deleteLines(prevWeekClose_Arr , numWklyPeriods)
deleteLines(prevWeekVWAP_Arr , numWklyPeriods)
deleteLines(prevWeekVWAP_LBand1_Arr, numWklyPeriods)
deleteLines(prevWeekVWAP_UBand1_Arr, numWklyPeriods)
deleteLines(prevWeekVWAP_LBand2_Arr, numWklyPeriods)
deleteLines(prevWeekVWAP_UBand2_Arr, numWklyPeriods)
deleteLines(prevWeekVWAP_LBand3_Arr, numWklyPeriods)
deleteLines(prevWeekVWAP_UBand3_Arr, numWklyPeriods)
deleteLines(prevMonthHigh_Arr , numMonPeriods)
deleteLines(prevMonthLow_Arr , numMonPeriods)
deleteLines(prevMonth50HL_Arr , numMonPeriods)
deleteLines(prevMonth50OC_Arr , numMonPeriods)
deleteLines(rthMonthOpen_Arr , numMonPeriods + 1)
deleteLines(prevMonthClose_Arr, numMonPeriods)
//////////////////////////////
// Intraday Market Breatdth //
//////////////////////////////
//variable declaration
showMarketBreadth = input.bool (title="Show Market Breadth Table" , defval=true , group="Market Breadth")
showUpDownVol = input.bool (title="Show NYSE/NASDAQ Breadth" , defval=true , group="Market Breadth")
showADD = input.bool (title="Show Advance/Decline Value", defval=true , group="Market Breadth")
showTRIN = input.bool (title="Show TRIN.US" , defval=false , group="Market Breadth")
showTICK = input.bool (title="Show TICK" , defval=false , group="Market Breadth")
showVIX = input.bool (title="Show VIX" , defval=false , group="Market Breadth")
showVXN = input.bool (title="Show VXN" , defval=false , group="Market Breadth")
showIorODay = input.bool (title="Show Inside/Outside Day" , defval=false , group="Market Breadth", tooltip="Inside Day = Current Day Range has not broken Prev Day High/Low\nOutside Day = Current Day Range broke Prev Day High/Low")
showSecurity1 = input.bool (title="" , defval=false , group="Market Breadth", inline="sym1")
security1 = input.symbol(title="" , defval = "ES1!" , group="Market Breadth", inline="sym1")
showSecurity2 = input.bool (title="" , defval=false , group="Market Breadth", inline="sym2")
security2 = input.symbol(title="" , defval = "NQ1!" , group="Market Breadth", inline="sym2")
showSecurity3 = input.bool (title="" , defval=false , group="Market Breadth", inline="sym3")
security3 = input.symbol(title="" , defval = "TVC:DXY", group="Market Breadth", inline="sym3")
showSecurity4 = input.bool (title="" , defval=false , group="Market Breadth", inline="sym4")
security4 = input.symbol(title="" , defval = "YM1!" , group="Market Breadth", inline="sym4")
showSecurity5 = input.bool (title="" , defval=false , group="Market Breadth", inline="sym5")
security5 = input.symbol(title="" , defval = "CL1!" , group="Market Breadth", inline="sym5")
showTPOInfo = input.bool (title="Show Market Profile TPO Period", defval=false, group="Market Breadth")
sizeOption = input.string(title="Text Size", options=["Small", "Normal", "Large"], defval="Normal", group="Market Breadth", inline="mb")
textSize = (sizeOption == "Small") ? size.small :
(sizeOption == "Normal") ? size.normal :
size.large
//option for where you want to table to be
positionOption = input.string(title="Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], defval="Top Right", group="Market Breadth", inline="mb")
position = (positionOption == "Top Right") ? position.top_right :
(positionOption == "Top Left") ? position.top_left :
(positionOption == "Bottom Right") ? position.bottom_right :
position.bottom_left
//Up and down VOL for NYSE and NASDAQ
UVOL = request.security("USI:UVOL","",close)
DVOL = request.security("USI:DVOL","",close)
UVOLQ = request.security("USI:UVOLQ","",close)
DVOLQ = request.security("USI:DVOLQ","",close)
//ADD data
ADVDCL = request.security("ADD","",close)
//TRIN data
TRIN = request.security("USI:TRIN.NY","",close)
//TICK
TICK = request.security("USI:TICK", "",close)
//VIX
VIX = request.security("TVC:VIX","",close)
//VXN NASDAQ Volatility Index
VXN = request.security("CBOE:VXN","",close)
//SECURITES
SEC1 = request.security(security1, "", close)
SEC2 = request.security(security2, "", close)
SEC3 = request.security(security3, "", close)
SEC4 = request.security(security4, "", close)
SEC5 = request.security(security5, "", close)
//NYSE Breadth
NYSEratio = UVOL >= DVOL ? UVOL/DVOL : -(DVOL/UVOL)
//NASDAQ Breadth
NASDAQratio = UVOLQ >= DVOLQ ? UVOLQ/DVOLQ : -(DVOLQ/UVOLQ)
//Inside or Outside Day Calc
IorODay = currDayHigh.price < prevDayHigh.price and currDayLow.price > prevDayLow.price ? "Inside Day" : "Outside Day"
//Table Creation
var table breadthTable = table.new(position, 3, 8, border_color = color.black, border_width = 1)
string breadthformat = "##.##"
string addformat = ""
//Plot Table
if barstate.islast and showMarketBreadth == true
if showUpDownVol == true
table.cell(breadthTable, 2, 0, str.tostring(NYSEratio, breadthformat) + " NYSE", text_size = textSize, text_color = #000000, bgcolor = NYSEratio > 0 ? color.green : color.red)
table.cell(breadthTable, 2, 1, str.tostring(NASDAQratio, breadthformat) + " NASD", text_size = textSize, text_color = #000000, bgcolor = NASDAQratio > 0 ? color.green : color.red)
if showADD == true
table.cell(breadthTable, 2, 2, str.tostring(ADVDCL, addformat) + " ADD", text_size = textSize, text_color = #000000, bgcolor = ADVDCL > 0 ? color.green : color.red)
if showVIX == true
table.cell(breadthTable, 2, 3, str.tostring(VIX, format.mintick) + " VIX", text_size = textSize, text_color = #000000, bgcolor = VIX > VIX[1] ? color.green : color.red)
if showVXN == true
table.cell(breadthTable, 2, 4, str.tostring(VXN, format.mintick) + " VXN", text_size = textSize, text_color = #000000, bgcolor = VXN > VXN[1] ? color.green : color.red)
if showTRIN == true
table.cell(breadthTable, 2, 5, str.tostring(TRIN, format.mintick) + " TRIN", text_size = textSize, text_color = #000000, bgcolor = TRIN < 0.5 ? color.green : TRIN > 1.6 ? color.red : color.white)
if showTICK == true
table.cell(breadthTable, 2, 6, str.tostring(TICK, format.mintick) +" TICK", text_size = textSize, text_color = #000000, bgcolor = TICK > 0 ? color.green : color.red)
if showIorODay
table.cell(breadthTable, 2, 7, IorODay, text_size= textSize, text_color = #000000, bgcolor= IorODay == "Inside Day" ? color.red : color.green )
if showSecurity1 == true
table.cell(breadthTable, 1, 0, str.tostring(syminfo.ticker(security1)) + " " + str.tostring(SEC1, format.mintick), text_size= textSize, text_color = #000000, bgcolor = SEC1 > SEC1[1] ? color.green : color.red)
if showSecurity2 == true
table.cell(breadthTable, 1, 1, str.tostring(syminfo.ticker(security2)) + " " + str.tostring(SEC2, format.mintick), text_size= textSize, text_color = #000000, bgcolor = SEC2 > SEC2[1] ? color.green : color.red)
if showSecurity3 == true
table.cell(breadthTable, 1, 2, str.tostring(syminfo.ticker(security3)) + " " + str.tostring(SEC3, format.mintick), text_size= textSize, text_color = #000000, bgcolor = SEC3 > SEC3[1] ? color.green : color.red)
if showSecurity4 == true
table.cell(breadthTable, 1, 3, str.tostring(syminfo.ticker(security4)) + " " + str.tostring(SEC4, format.mintick), text_size= textSize, text_color = #000000, bgcolor = SEC4 > SEC4[1] ? color.green : color.red)
if showSecurity5 == true
table.cell(breadthTable, 1, 4, str.tostring(syminfo.ticker(security5)) + " " + str.tostring(SEC5, format.mintick), text_size= textSize, text_color = #000000, bgcolor = SEC5 > SEC5[1] ? color.green : color.red)
/////////////////////////////////////
//// Market Profile Period /////////
////////////////////////////////////
// Get seconds till 30m bar closes
timeLeft = barstate.isrealtime ?
(time_close("30") - timenow) / 1000 :
na
// Translate seconds left into minutes and seconds
minsLeft = math.floor(timeLeft / 60)
secsLeft = timeLeft % 60
string secsFormat = "##"
//timeframe.change(30) provides boolean when 30 min timeframe changes
TPO_DESC = array.new<string>(0)
var int count = 0
//TPO periods RTH A-O
//TPO periods globex P-x
array.push(TPO_DESC, "A") //RTH open
array.push(TPO_DESC, "B")
array.push(TPO_DESC, "C")
array.push(TPO_DESC, "D")
array.push(TPO_DESC, "E")
array.push(TPO_DESC, "F")
array.push(TPO_DESC, "G")
array.push(TPO_DESC, "H")
array.push(TPO_DESC, "I")
array.push(TPO_DESC, "J")
array.push(TPO_DESC, "K")
array.push(TPO_DESC, "L")
array.push(TPO_DESC, "M")
array.push(TPO_DESC, "N")
array.push(TPO_DESC, "O")
array.push(TPO_DESC, "R") //globex open period
array.push(TPO_DESC, "S")
array.push(TPO_DESC, "T")
array.push(TPO_DESC, "U")
array.push(TPO_DESC, "V")
array.push(TPO_DESC, "W")
array.push(TPO_DESC, "X")
array.push(TPO_DESC, "a")
array.push(TPO_DESC, "b")
array.push(TPO_DESC, "c")
array.push(TPO_DESC, "d")
array.push(TPO_DESC, "e")
array.push(TPO_DESC, "f")
array.push(TPO_DESC, "g")
array.push(TPO_DESC, "h")
array.push(TPO_DESC, "i")
array.push(TPO_DESC, "j")
array.push(TPO_DESC, "k")
array.push(TPO_DESC, "l")
array.push(TPO_DESC, "m")
array.push(TPO_DESC, "n")
array.push(TPO_DESC, "o")
array.push(TPO_DESC, "p")
array.push(TPO_DESC, "q")
array.push(TPO_DESC, "r")
array.push(TPO_DESC, "s")
array.push(TPO_DESC, "t")
array.push(TPO_DESC, "u")
array.push(TPO_DESC, "v")
array.push(TPO_DESC, "w")
array.push(TPO_DESC, "x")
if showTPOInfo == true and timeframe.isminutes and timeframe.multiplier < 31 and showMarketBreadth == true
if rthOpenSess
//reset counter back to 0
count := 0
table.cell(breadthTable, 0, 0, "TPO Period: " + array.get(TPO_DESC, count), text_size = textSize, text_color = #000000, bgcolor = color.white)
//create a new line when a new 30 min time period starts
if not rthOpenSess and (minute == 00 or minute == 30) and count < 45
//increment count
count := count + 1
table.cell(breadthTable, 0, 0, "TPO Period: " + array.get(TPO_DESC, count), text_size = textSize, text_color = #000000, bgcolor = color.white)
table.cell(breadthTable, 0, 1, "Time Left: " + str.tostring(minsLeft) + ":" + str.tostring(secsLeft, secsFormat), text_size = textSize, text_color = #000000, bgcolor = color.white)
|
Synthetic EMA Momentum w/ DSL [Loxx] | https://www.tradingview.com/script/CcEMGDoW-Synthetic-EMA-Momentum-w-DSL-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 141 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Synthetic EMA Momentum w/ DSL [Loxx]",
shorttitle='SEMAMDSL [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
SM02 = 'Levels Crosses'
SM03 = 'Middle Crosses'
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
inpPeriod1 = input.int(5, "Period 1", group = "Basic Settings")
inpPeriod2 = input.int(20, "Period 2", group = "Basic Settings")
inpPeriod3 = input.int(50, "Period 3", group = "Basic Settings")
inpPeriod4 = input.int(100, "Period 4", group = "Basic Settings")
inpPeriod5 = input.int(200, "Period 5", group = "Basic Settings")
inpSignal = input.int(20, "Signal Period", group = "Signal/DSL Settings")
sigtype = input.string(SM02, "Signal type", options = [SM02, SM03], group = "Signal/DSL Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
coeff1 = float(inpPeriod5 / inpPeriod4)
coeff2 = float(inpPeriod5 / inpPeriod3)
coeff3 = float(inpPeriod5 / inpPeriod2)
avg = ta.ema(src, inpPeriod1)
avg1 = ta.ema(src, inpPeriod2)
mom1 = 100. * (avg - avg1) / avg1
avg2 = ta.ema(src, inpPeriod3)
mom2 = 100. * (avg - avg2) / avg2
avg3 = ta.ema(src, inpPeriod4)
mom3 = 100. * (avg - avg3) / avg3
avg4 = ta.ema(src, inpPeriod5)
mom4 = 100. * (avg - avg4) / avg4
val = (mom4 + mom3 * coeff1 + mom2 * coeff2 + mom1 * coeff3) / 4.0
sig = val[1]
mid = 0
dslupl = 0., dsldnl = 0.
tempu = ta.ema(val, inpSignal)
dslupl := val > 0 ? tempu : nz(dslupl[1])
dsldnl := val < 0 ? tempu : nz(dsldnl[1])
state = 0.
if sigtype == SM02
if (val < dsldnl)
state :=-1
if (val > dslupl)
state := 1
else if sigtype == SM03
if (val < mid)
state :=-1
if (val > mid)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(val, "Synthetic Super Smoother Momentum", color = colorout, linewidth = 3)
plot(dslupl, "DSL Level Up", color = lightgreencolor)
plot(dsldnl, "DSL Level Down", color = lightredcolor)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
goLong_pre = sigtype == SM02 ? ta.crossover(val, dslupl) : ta.crossover(val, mid)
goShort_pre = sigtype == SM02 ? ta.crossunder(val, dsldnl) : ta.crossunder(val, mid)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = contSwitch == 1 and ta.change(contSwitch)
goShort = contSwitch == -1 and ta.change(contSwitch)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Synthetic EMA Momentum w/ DSL [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Synthetic EMA Momentum w/ DSL [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Copy/Paste Levels | https://www.tradingview.com/script/UuTsVm9e-Copy-Paste-Levels/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 223 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ SamRecio
//@version=5
indicator("Copy/Paste Levels", overlay = true, max_lines_count = 500, max_labels_count = 500)
//Format = Ticker,Color,Style,Width(Negative Numbers),Text*,lvl1,lvl2,lvl3;
//*No Commas(,) or semi-colons(;)...for obvious reasons...
//Sample//
//qqq, , , , ,325;Qqq,red, , , ,325.5;QqQ, ,dotted, , ,326.0;QQQ,blue,dashed,-2,Hello World!,326.50;qqQ,green,solid,-10,text here,327,327.5,328;
//Inputs/////////////////////////////////////////////////////////////////
paste = str.upper(input.text_area("", title = "Input Levels:", confirm = true, tooltip = "Format:\nTicker,Color,Style,-Width,Text*,lvl1,lvl2,lvl3;\n*No Commas(,) or semi-colons(;)"))
lab_size = input.string("small", title = "Label Size", options = ["tiny","small","normal","large","huge"], inline = "2")
lab_offset = input.int(10, title = "Label Offset", inline = "2")
z_op = input.int(90, title = "Zone Opacity", minval = 0, maxval = 100, inline = "3")
tog_lvl = input.bool(true, title = "Toggle Price Labels", inline = "3")
//No Level Message//////////////////////////////////////////////////////////////
if str.contains(paste,syminfo.ticker) == false
runtime.error("No levels for this ticker. Please input levels or change ticker. Current Ticker: " + syminfo.ticker)
//Variable initialization///////////////////////////////////////////////////////
var line lvl_line = na
var label lvl_lab = na
var line z1 = na
var line z2 = na
//Color & Style Functions///////////////////////////////////////////////////////
colorpicker(_input) =>
_input == "RED"?color.red:
_input == "ORANGE"?color.orange:
_input == "YELLOW"?color.yellow:
_input == "GREEN"?color.green:
_input == "BLUE"?color.blue:
_input == "PURPLE"?color.fuchsia:
_input == "WHITE"?color.white:
_input == "BLACK"?color.rgb(0,0,0):
_input == "GRAY"?color.gray:
chart.fg_color
stylepicker(_input) =>
_input == "SOLID"?line.style_solid:
_input == "DASHED"?line.style_dashed:
_input == "DOTTED"?line.style_dotted:
str.contains(_input,"SOLID")?line.style_solid:
str.contains(_input,"DASHED")?line.style_dashed:
str.contains(_input,"DOTTED")?line.style_dotted:
line.style_solid
////////////////////////////////////////////////////////////////////////////////
//Delete all lines & Labels
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
a_allLabels = label.all
if array.size(a_allLabels) > 0
for i = 0 to array.size(a_allLabels) - 1
label.delete(array.get(a_allLabels, i))
////////////////////////////////////////////////////////////////////////////////
//Line and label drawing
split = str.split(paste,";")
for i = 0 to array.size(split) - 1
split_get = array.get(split,i)
small_split = str.split(split_get,",")
if array.size(small_split) > 5
ssf = str.replace_all(array.get(small_split,0)," ","")
if (ssf == syminfo.ticker) or (ssf == syminfo.tickerid) or (ssf == "\n" + syminfo.ticker) or (ssf == "\n" + syminfo.tickerid)
for e = 5 to array.size(small_split) - 1
lvl = str.replace_all(array.get(small_split,e)," ","")
co = colorpicker(str.replace_all(array.get(small_split,1)," ",""))
sty = stylepicker(str.replace_all(array.get(small_split,2)," ",""))
z = str.contains(str.replace_all(array.get(small_split,2)," ",""),"ZONE")
thick = str.tonumber(str.replace_all(array.get(small_split,3)," ","")) < 0? str.tonumber(str.replace_all(array.get(small_split,3)," ","")) * -1:1
txt = tog_lvl?array.get(small_split,4) +" "+ str.format("{0,number,currency}",str.tonumber(lvl)):array.get(small_split,4)
if str.tonumber(lvl) > 0 and (z == false)
lvl_line := line.new(bar_index,str.tonumber(lvl),bar_index+1,str.tonumber(lvl), extend = extend.right, color = co, style = sty, width = int(thick))
lvl_lab := label.new(bar_index + lab_offset, str.tonumber(lvl), text = txt , color = color.new(color.black,100), size = lab_size, textcolor = co, style = label.style_label_lower_left)
if z and (array.size(small_split) == 7) and (e == 6)
z_lvl1 = math.max(str.tonumber(str.replace_all(array.get(small_split,5)," ","")),str.tonumber(str.replace_all(array.get(small_split,6)," ","")))
z_lvl2 = math.min(str.tonumber(str.replace_all(array.get(small_split,5)," ","")),str.tonumber(str.replace_all(array.get(small_split,6)," ","")))
z_txt = tog_lvl?array.get(small_split,4) +" "+ str.format("{0,number,currency}",z_lvl2) + " - " + str.format("{0,number,currency}",z_lvl1):array.get(small_split,4)
lvl_lab := label.new(bar_index + lab_offset, z_lvl1, text = z_txt , color = color.new(color.black,100), size = lab_size, textcolor = co, style = label.style_label_lower_left)
z1 := line.new(bar_index,z_lvl1,bar_index+1,z_lvl1, extend = extend.right, color = co, style = sty, width = int(thick))
z2 := line.new(bar_index,z_lvl2,bar_index+1,z_lvl2, extend = extend.right, color = co, style = sty, width = int(thick))
linefill.new(z1,z2, color = color.new(co,z_op))
|
Normalized, Variety, Fast Fourier Transform Explorer [Loxx] | https://www.tradingview.com/script/gRjglovZ-Normalized-Variety-Fast-Fourier-Transform-Explorer-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 140 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Normalized, Variety, Fast Fourier Transform Explorer [Loxx]",
shorttitle = "NVFFTE [Loxx]",
overlay = false,
max_lines_count = 500,
precision = 8)
greencolor = #2DD204
redcolor = #D2042D
_fastsinetransform(float[] a, int tnn, bool inversefst)=>
int j = 0
int tm = 0
int n2 = 0
float sum = 0.
float y1 = 0.
float y2 = 0.
float theta = 0.
float wi = 0.
float wr = 0.
float wpi = 0.
float wpr = 0.
float wtemp = 0.
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int istep = 0
int isign = 0
float tempr = 0.
float tempi = 0.
theta := math.pi/tnn
wr := 1.0
wi := 0.0
wpr := - 2.0 * math.pow(math.sin(0.5 * theta),2)
wpi := math.sin(theta)
array.set(a, 0, 0.)
tm := tnn / 2
n2 := tnn + 2
for jx = 2 to tm + 1
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
y1 := wi * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1))
y2 := 0.5 * (array.get(a, jx - 1) - array.get(a, n2 - jx - 1))
array.set(a, jx - 1, y1 + y2)
array.set(a, n2 - jx - 1, y1 - y2)
ttheta := 2.0 * math.pi/tnn
c1 := 0.5
c2 := - 0.5
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if j > i
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n/2
while(m >= 2 and j > m)
j := j - m
m := m/2
j := j + m
mmax := 2
while(n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := - 2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax/2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
twpr := - 2.0 * math.pow(math.sin(0.5 * ttheta),2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn/4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := - c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, - h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
sum := 0.0
array.set(a, 0, 0.5 * array.get(a, 0))
array.set(a, 1, 0.)
for jj = 0 to tm - 1
j := 2 * jj + 1
sum := sum + array.get(a, j - 1)
array.set(a, j - 1, array.get(a, j))
array.set(a, j, sum)
if inversefst
for jx = 1 to tnn
array.set(a, jx - 1, array.get(a, jx - 1) * 2 / tnn)
a
_fastcosinetransform(float[] a, int tnn, bool inversefct)=>
int j = 0
int n2 = 0
float sum = 0.
float y1 = 0.
float y2 = 0.
float theta = 0.
float wi = 0.
float wpi = 0.
float wr = 0.
float wpr = 0.
float wtemp = 0.
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int istep = 0
int isign = 0
float tempr = 0.
float tempi = 0.
while true
if (tnn == 1)
y1 := array.get(a, 0)
y2 := array.get(a, 1)
array.set(a, 0, 0.5 * (y1 + y2))
array.set(a, 1, 0.5 * (y1 - y2))
if inversefct
array.set(a, 0, array.get(a, 0) * 2)
array.set(a, 1, array.get(a, 1) * 2)
break
wi := 0
wr := 1
theta := math.pi / tnn
wtemp := math.sin(theta * 0.5)
wpr := -2.0 * wtemp * wtemp
wpi := math.sin(theta)
sum := 0.5 * (array.get(a, 0) - array.get(a, tnn))
array.set(a, 0, 0.5 * (array.get(a, 0) + array.get(a, tnn)))
n2 := tnn + 2
for jx = 2 to tnn / 2
wtemp := wr
wr := wtemp * wpr - wi * wpi + wtemp
wi := wi * wpr + wtemp * wpi + wi
y1 := 0.5 * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1))
y2 := array.get(a, jx - 1) - array.get(a, n2 - jx - 1)
array.set(a, jx - 1, y1 - wi * y2)
array.set(a, n2 - jx - 1, y1 + wi * y2)
sum := sum + wr * y2
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
array.set(a, tnn, array.get(a, 1))
array.set(a, 1, sum)
j := 4
while (j <= tnn)
sum := sum + array.get(a, j - 1)
array.set(a, j - 1, sum)
j := j + 2
if (inversefct)
for jx = 0 to tnn
array.set(a, jx, array.get(a, jx) * 2 / tnn)
break
a
_realFastFourierTransform(float[] a, int tnn, bool inversefft)=>
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int j = 0
int istep = 0
int isign = 0
float wtemp = 0.
float wr = 0.
float wpr = 0.
float wpi = 0.
float wi = 0.
float theta = 0.
float tempr = 0.
float tempi = 0.
if (tnn != 1)
if (not inversefft)
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
else
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := 0.5
ttheta := -ttheta
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, c1 * (h1r + array.get(a, 1)))
array.set(a, 1, c1 * (h1r - array.get(a, 1)))
if (inversefft)
isign := -1
else
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
if (inversefft)
for ix = 1 to 2 * nn
array.set(a, ix - 1, array.get(a, ix - 1) / nn)
if (not inversefft)
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
a
//Normalize data
_InSigNormalize(float[] aa)=>
float sum_sqrt = 0.
int element_count = array.size(aa)
for i = 0 to element_count - 1
sum_sqrt += math.pow(array.get(aa, i), 2)
sum_sqrt := math.sqrt(sum_sqrt)
if (sum_sqrt != 0)
for i = 0 to element_count - 1
array.set(aa, i, array.get(aa, i) / sum_sqrt)
aa
src = input.source(open, "Source")
windowper = input.string("1024", "Window Period", options = ["16", "32", "64", "128", "256", "512", "1024", "2048"])
SS = input.int(20, "Smoothing Period")
type = input.string("Fast Sine", "Fast Fourier Transform Type", options =["Fast Cosine", "Fast Sine", "Real Fast"])
Fmin1 = input.int(3, "Minimum Frequency Filter")
Fmax1 = input.int(21, "Maximum Frequency Filter")
barsback = input.int(0, "Last Bar", minval = 0)
Inverse = input.bool(true, "Add inverse step?")
Window = str.tonumber(windowper)
n = int(math.log(Window) / math.log(2))
N = int(math.max(math.pow(2, n), 16))
var aa = array.new<float>(N + (type == "Fast Cosine" ? 1 : 0), 0.)
var pvlines = array.new_line(0)
countout = N >= 256 ? 250 : N
if barstate.isfirst
for i = 0 to countout - 1
array.push(pvlines, line.new(na, na, na, na))
if barstate.islast
for i = 0 to N - 1
array.set(aa, i, nz(src[i + barsback]))
M = array.size(aa)
end = M - 1
ss = int(math.min(SS, M))
_InSigNormalize(aa)
if type == "Fast Cosine"
_fastcosinetransform(aa, N, false)
else if type == "Fast Sine"
_fastsinetransform(aa, N, false)
else
_realFastFourierTransform(aa, N, false)
for k = 0 to end
if k >= ss
array.set(aa, k, 0.)
Fmax1 := math.min(Fmax1, array.size(aa) - 1)
for i = 0 to array.size(aa) - 1
if i < Fmin1 or i > Fmax1
array.set(aa, i, 0.)
if (Inverse)
if type == "Fast Cosine"
_fastcosinetransform(aa, N, true)
else if type == "Fast Sine"
_fastsinetransform(aa, N, true)
else
_realFastFourierTransform(aa, N, true)
xm = array.copy(aa)
skipper = N >= 2048 ? 8 : N >= 1024 ? 4 : N == 512 ? 2 : 1
int i = 0
int j = 0
while i < N and i < array.size(xm) - 2
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
colorout = i < array.size(xm) - 2 ? array.get(xm, i) > array.get(xm, i + skipper) ? greencolor : redcolor : na
line.set_xy1(pvline, bar_index - i - skipper - barsback, array.get(xm, i + skipper))
line.set_xy2(pvline, bar_index - i - barsback, array.get(xm, i))
line.set_color(pvline, colorout)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 2)
i += skipper
j += 1
plot(0, color = bar_index % 2 ? color.gray : na) |
STD-Stepped Fast Cosine Transform Moving Average [Loxx] | https://www.tradingview.com/script/0VkUjdBV-STD-Stepped-Fast-Cosine-Transform-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 228 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("STD-Stepped Fast Cosine Transform Moving Average [Loxx]",
shorttitle = "STDSFCTMA [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
//==========================================================================================
//Fast Discrete Cosine Transform
//The algorithm performs a fast cosine transform of the real
//function defined by nn samples on the real axis.
//Depending on the passed parameters, it can be executed
//both direct and inverse conversion.
//Input parameters:
// tnn - Number of function values minus one. Should be 1024
// degree of two. The algorithm does not check
// correct value passed.
// a - array [0 .. nn] of Real 1025
// Function values.
// InverseFCT
// - the direction of the transformation.
// True if reverse, False if direct.
//
//Output parameters:
// a - the result of the transformation. For more details, see
// description on the site. https://www.alglib.net/fasttransforms/fft.php
//==========================================================================================
_fastcosinetransform(float[] a, int tnn, bool inversefct)=>
int j = 0
int n2 = 0
float sum = 0.
float y1 = 0.
float y2 = 0.
float theta = 0.
float wi = 0.
float wpi = 0.
float wr = 0.
float wpr = 0.
float wtemp = 0.
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int istep = 0
int isign = 0
float tempr = 0.
float tempi = 0.
while true
if (tnn == 1)
y1 := array.get(a, 0)
y2 := array.get(a, 1)
array.set(a, 0, 0.5 * (y1 + y2))
array.set(a, 1, 0.5 * (y1 - y2))
if inversefct
array.set(a, 0, array.get(a, 0) * 2)
array.set(a, 1, array.get(a, 1) * 2)
break
wi := 0
wr := 1
theta := math.pi / tnn
wtemp := math.sin(theta * 0.5)
wpr := -2.0 * wtemp * wtemp
wpi := math.sin(theta)
sum := 0.5 * (array.get(a, 0) - array.get(a, tnn))
array.set(a, 0, 0.5 * (array.get(a, 0) + array.get(a, tnn)))
n2 := tnn + 2
for jx = 2 to tnn / 2
wtemp := wr
wr := wtemp * wpr - wi * wpi + wtemp
wi := wi * wpr + wtemp * wpi + wi
y1 := 0.5 * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1))
y2 := array.get(a, jx - 1) - array.get(a, n2 - jx - 1)
array.set(a, jx - 1, y1 - wi * y2)
array.set(a, n2 - jx - 1, y1 + wi * y2)
sum := sum + wr * y2
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
array.set(a, tnn, array.get(a, 1))
array.set(a, 1, sum)
j := 4
while (j <= tnn)
sum := sum + array.get(a, j - 1)
array.set(a, j - 1, sum)
j := j + 2
if (inversefct)
for jx = 0 to tnn
array.set(a, jx, array.get(a, jx) * 2 / tnn)
break
a
_filt(src, len, filter)=>
price = src
filtdev = filter * ta.stdev(src, len)
price := math.abs(price - price[1]) < filtdev ? price[1] : price
price
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("HAB Trend Biased (Extreme)", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
windowper = input.string("256", "Window", options = ["16", "32", "64", "128", "256", "512", "1024", "2048"], group = "Basic Settings")
smthcutoff = input.int(12, "Smoothing Period", group = "Basic Settings")
filterop = input.string("FCT MA", "Filter Options", options = ["Price", "FCT MA", "Both"], group= "Filter Settings")
filter = input.float(1, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
//source filtering
src := filterop == "Both" or filterop == "Price" and filter > 0 ? _filt(src, filterperiod, filter) : src
Window = str.tonumber(windowper)
//check that indow is power of 2
n = int(math.log(Window) / math.log(2))
N = int(math.max(math.pow(2, n), 16))
var aa = array.new<float>(N + 1, 0.)
//fill caculation array with source values
for i = 0 to N - 1
array.set(aa, i, nz(src[i]))
M = array.size(aa)
end = M - 1
smthcutoff := int(math.min(smthcutoff, M))
//regular pass of FCT
_fastcosinetransform(aa, N, false)
//filter of FCT, values above smthcutoff are zeroed out
for k = 0 to end
if k >= smthcutoff
array.set(aa, k, 0.)
//inverse pass of FCT
_fastcosinetransform(aa, N, true)
//we are only interested in the first value; although accessing additional values can create ribbons and boundaries
out = array.get(aa, 0)
//output filtering
out := filterop == "Both" or filterop == "FCT MA" and filter > 0 ? _filt(out, filterperiod, filter) : out
sig = out[1]
//draw plots, create signals, configure alerts
goLong_pre = ta.crossover(out, sig)
goShort_pre = ta.crossunder(out, sig)
contSwitch = 0
contSwitch := nz(contSwitch[1])
contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitch
goLong = goLong_pre and ta.change(contSwitch)
goShort = goShort_pre and ta.change(contSwitch)
plot(out,"FCT MA", color = contSwitch == 1 ? greencolor : redcolor, linewidth = 3)
barcolor(colorbars ? contSwitch == 1 ? greencolor : redcolor : na)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="STD-Stepped Fast Cosine Transform Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="STD-Stepped Fast Cosine Transform Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Trade Pro - Rejection Zone Indicator | https://www.tradingview.com/script/f7uPGgC0-Trade-Pro-Rejection-Zone-Indicator/ | Stratfather | https://www.tradingview.com/u/Stratfather/ | 294 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// ยฉ Stratfather
//
// @version=5
var string VERSION = "2022.07.31-r1"
indicator(title = "Trade Pro - Rejection Zone Indicator", overlay = true)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Constants โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var string MA_TYPE_EMA = "EMA (Exponential Moving Average)"
var string MA_TYPE_SMA = "SMA (Simple Moving Average)"
var string MA_TYPE_WMA = "WMA (Weighted Moving Average)"
var string MA_TYPE_HMA = "HMA (Hull Moving Average)"
var string MA_TYPE_RMA = "RMA (Relative Moving Average)"
var string MA_TYPE_SWMA = "SWMA (Symmetrically-Weighted Moving Average)"
var string MA_TYPE_ALMA = "ALMA (Arnaud Legoux Moving Average)"
var string MA_TYPE_VWMA = "VWMA (Volume-Weighted Moving Average)"
var string MA_TYPE_VWAP = "VWAP (Volume-Weighted Average Price)"
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Inputs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// About โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var string aboutGroup = "About"
string i_version = input.string(title = "Version", defval = VERSION, options = [VERSION], group = aboutGroup, tooltip = "Current version of the indicator.")
// Fast MA โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var string maFastGroup = "Fast MA Settings"
string i_maFastType = input.string(title = "Type", defval = MA_TYPE_EMA, options = [MA_TYPE_EMA, MA_TYPE_SMA, MA_TYPE_WMA, MA_TYPE_HMA, MA_TYPE_RMA, MA_TYPE_SWMA, MA_TYPE_ALMA, MA_TYPE_VWMA, MA_TYPE_VWAP], group = maFastGroup)
int i_maFastLength = input.int(20, minval = 1, title = "Length", group = maFastGroup)
float i_maFastSource = input.source(close, title = "Source", group = maFastGroup)
float i_maFastAlmaOffset = input.float(0.85, title = "ALMA Offset", step = 0.01, group = maFastGroup, tooltip = "Only used when ALMA is selected.")
int i_maFastAlmaSigma = input.int(6, title = "ALMA Sigma", group = maFastGroup, tooltip = "Only used when ALMA is selected.")
// Slow MA โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
var string maSlowGroup = "Slow MA Settings"
string i_maSlowType = input.string(title = "Type", defval = MA_TYPE_EMA, options = [MA_TYPE_EMA, MA_TYPE_SMA, MA_TYPE_WMA, MA_TYPE_HMA, MA_TYPE_RMA, MA_TYPE_SWMA, MA_TYPE_ALMA, MA_TYPE_VWMA, MA_TYPE_VWAP], group = maSlowGroup)
int i_maSlowLength = input.int(50, minval = 1, title = "Length", group = maSlowGroup)
float i_maSlowSource = input.source(close, title = "Source", group = maSlowGroup)
float i_maSlowAlmaOffset = input.float(0.85, title = "ALMA Offset", step = 0.01, group = maSlowGroup, tooltip = "Only used when ALMA is selected.")
int i_maSlowAlmaSigma = input.int(6, title = "ALMA Sigma", group = maSlowGroup, tooltip = "Only used when ALMA is selected.")
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
calculateMA(_type, _length, _src, _almaOffset, _almaSigma) =>
switch _type
MA_TYPE_EMA => ta.ema(_src, _length)
MA_TYPE_SMA => ta.sma(_src, _length)
MA_TYPE_WMA => ta.wma(_src, _length)
MA_TYPE_HMA => ta.hma(_src, _length)
MA_TYPE_RMA => ta.rma(_src, _length)
MA_TYPE_SWMA => ta.swma(_src)
MA_TYPE_ALMA => ta.alma(_src, _length, _almaOffset, _almaSigma)
MA_TYPE_VWMA => ta.vwma(_src, _length)
MA_TYPE_VWAP => ta.vwap(_src)
=> na
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Calculations โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
float maFast = calculateMA(i_maFastType, i_maFastLength, i_maFastSource, i_maFastAlmaOffset, i_maFastAlmaSigma)
float maSlow = calculateMA(i_maSlowType, i_maSlowLength, i_maSlowSource, i_maSlowAlmaOffset, i_maSlowAlmaSigma)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Plots โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
plotMaFast = plot(maFast, color = #2962FF, title = "Fast MA", linewidth = 2)
plotMaSlow = plot(maSlow, color = #FF6D00, title = "Slow MA", linewidth = 2)
fill(plotMaFast, plotMaSlow, color = maFast > maSlow ? color.new(color.green, 70) : color.new(color.red, 70), title = "Rejection Zone")
|
Commodity Channel Relative Strength | https://www.tradingview.com/script/QuyE0iF1-Commodity-Channel-Relative-Strength/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 64 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ EsIstTurnt
//@version=5
indicator("Commodity Channel Relative Strength",shorttitle='CCRSI+FIB')
tf = input.timeframe('' ,'TimeFrame ',group='Resolution')
Fib = input.bool (false ,'Plot Fib Levels ',group='Fibonacci ')
SmoothFib = input.bool (true ,'Smooth Fib Levels ',group='Fibonacci ')
Bound = input.bool (true ,'Plot Boundarys ',group='Fibonacci ')
AltLength = input.bool (true ,'Use Alternate Length Calc? ',group='Calc ')
Background = input.bool (false ,'Plot Background ',group='Plot ')
FibOffset = input.int (0 ,'Fib Offset ',group='Fibonacci ')
SmoothLen = input.int (16 ,'Fib Smoothing Length ',group='Fibonacci ')
momLen = input.int (16 ,'Loppock Length ',group='Length ')
A1Length = input.int (16 ,'Length 1 ',group='Length ')
A2Length = AltLength ? input.int (32 ,'Length 2 ',group='Length ') : A1Length*2
A3Length = AltLength ? input.int (64 ,'Length 3 ',group='Length ') : A1Length*3
A4Length = AltLength ? input.int (80 ,'Length 4 ',group='Length ') : A1Length*4
A5Length = AltLength ? input.int (128 ,'Length 5 ',group='Length ') : A1Length*5
A6Length = AltLength ? input.int (160 ,'Length 6 ',group='Length ') : A1Length*6
A7Length = AltLength ? input.int (200 ,'Length 7 ',group='Length ') : A1Length*7
A8Length = AltLength ? input.int (256 ,'Length 8 ',group='Length ') : A1Length*8
A9Length = AltLength ? input.int (300 ,'Length 9 ',group='Length ') : A1Length*9
A10Length = AltLength ? input.int (360 ,'Length 10 ',group='Length ') : A1Length*10
A11Length = AltLength ? input.int (420 ,'Length 11 ',group='Length ') : A1Length*10
lookback1 = input.int (16 ,'Lookback 1 ',group='Fibonacci ')
lookback2 = input.int (32 ,'Lookback 2 ',group='Fibonacci ')
Sigma = input.int (3 ,'ALMA Sigma ',group='Calc ')
Offset = input.float (.77 ,'ALMA Offset ',group='Calc ')
fib0236 = input.float (0.236 ,'Fibonacci Level 1 ',group='Fibonacci ')
fib0382 = input.float (0.382 ,'Fibonacci Level 2 ',group='Fibonacci ')
fib05 = input.float (0.5 ,'Fibonacci Level 3 ',group='Fibonacci ')
fib0786 = input.float (0.786 ,'Fibonacci Level 4 ',group='Fibonacci ')
fib0618 = input.float (0.618 ,'Fibonacci Level 5 ',group='Fibonacci ')
fib1236 = input.float (1.236 ,'Fibonacci Level 6 ',group='Fibonacci ')
fib1382 = input.float (1.382 ,'Fibonacci Level 7 ',group='Fibonacci ')
fib1618 = input.float (1.618 ,'Fibonacci Level 8 ',group='Fibonacci ')
rsio=request.security(syminfo.ticker,tf,ta.rsi(ta.linreg(open ,(ta.rsi(hl2,8)>50?(12):A1Length),0),16))-50
rsih=request.security(syminfo.ticker,tf,ta.rsi(ta.linreg(high ,(ta.rsi(hl2,8)>50?(12):A1Length),0),16))-50
rsil=request.security(syminfo.ticker,tf,ta.rsi(ta.linreg(low ,(ta.rsi(hl2,8)>50?(12):A1Length),0),16))-50
rsic=request.security(syminfo.ticker,tf,ta.rsi(ta.linreg(close,(ta.rsi(hl2,8)>50?(12):A1Length),0),16))-50
ccio=request.security(syminfo.ticker,tf,ta.cci(ta.linreg(open ,(ta.cci(hl2,8)>50?(48):A3Length ),0),A1Length))/4
ccih=request.security(syminfo.ticker,tf,ta.cci(ta.linreg(high ,(ta.cci(hl2,8)>50?(48):A3Length ),0),A1Length))/4
ccil=request.security(syminfo.ticker,tf,ta.cci(ta.linreg(low ,(ta.cci(hl2,8)>50?(48):A3Length ),0),A1Length))/4
ccic=request.security(syminfo.ticker,tf,ta.cci(ta.linreg(close,(ta.cci(hl2,8)>50?(48):A3Length ),0),A1Length))/4
ccrsiav=math.avg(rsio,rsih,rsil,rsic,ccio,ccih,ccil,ccic)
o = ccrsiav>ccrsiav[1]?math.min(rsio,ccio):math.max(rsio,ccio)
h = math.max(rsih,ccih)
l = math.min(rsil,ccil)
c = ccrsiav>ccrsiav[1]?math.max(rsic,ccic):math.min(rsic,ccic)
ohlc=math.avg(o,h,l,c)
hl=ta.sma(ta.highest(h,A5Length)-ta.lowest(l,A5Length),A8Length)
hlx=ta.sma(ta.highest(h,A1Length)-ta.lowest(l,A1Length),A1Length)
ma1 = ta.sma(ohlc,A1Length)
ma2 = ta.ema(ohlc,A3Length)
ma3 = ta.wma(ohlc,A7Length)
ma3a = ta.sma(ma3+(hl/2.68),A3Length)
ma3b = ta.sma(ma3-(hl/2.68),A3Length)
ma3c = math.avg(ma3a,ma3b)
ma4a = ta.sma(ma3+(hl/1.68),A3Length)
ma4b = ta.sma(ma3-(hl/1.68),A3Length)
ma5 = ta.linreg(ohlc,A5Length,0)
coppock1 =ta.wma(ta.roc(hl2,11)+ta.roc(hl2,14),10)
coppock2 =coppock1>100 ?coppock1-(coppock1-100): coppock1<-100?coppock1-(coppock1+100):coppock1
loppock1 =ta.swma(ta.linreg(ta.roc(ta.cci(ta.highest(high,4)-ta.lowest(low,4),momLen),11)+ta.roc(ta.cci(ta.highest(high,4)-ta.lowest(low,4),momLen),14),10,0))/2
loppock2 =loppock1>100 ?loppock1-(loppock1-100): loppock1<-100?loppock1-(loppock1+100):loppock1
curve1 = ta.alma(ta.ema(c,(A1Length/2)),A1Length ,Offset,Sigma)
curve1a = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5 ,Offset,Sigma)
curve1b = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5*2,Offset,Sigma)
curve1c = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5*3,Offset,Sigma)
curve1d = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5*4,Offset,Sigma)
curve1e = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5*5,Offset,Sigma)
curve1f = ta.alma(ta.ema(c,(A1Length/2)),A1Length + (A2Length - A1Length) / 5*6,Offset,Sigma)
curve3 = ta.alma(ta.ema(c,(A1Length/2)),A3Length ,Offset,Sigma)
curve3a = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5 ,Offset,Sigma)
curve3b = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5*2,Offset,Sigma)
curve3c = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5*3,Offset,Sigma)
curve3d = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5*4,Offset,Sigma)
curve3e = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5*5,Offset,Sigma)
curve3f = ta.alma(ta.ema(c,(A1Length/2)),A3Length + (A4Length - A3Length) / 5*6,Offset,Sigma)
curve5 = ta.alma(ta.ema(c,(A1Length/2)),A5Length ,Offset,Sigma)
curve5a = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5 ,Offset,Sigma)
curve5b = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5*2,Offset,Sigma)
curve5c = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5*3,Offset,Sigma)
curve5d = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5*4,Offset,Sigma)
curve5e = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5*5,Offset,Sigma)
curve5f = ta.alma(ta.ema(c,(A1Length/2)),A5Length + (A6Length - A5Length) / 5*6,Offset,Sigma)
curve7 = ta.alma(ta.ema(c,(A1Length/2)),A7Length ,Offset,Sigma)
curve7a = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5 ,Offset,Sigma)
curve7b = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5*2,Offset,Sigma)
curve7c = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5*3,Offset,Sigma)
curve7d = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5*4,Offset,Sigma)
curve7e = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5*5,Offset,Sigma)
curve7f = ta.alma(ta.ema(c,(A1Length/2)),A7Length + (A8Length - A7Length) / 5*6,Offset,Sigma)
curve9 = ta.alma(ta.ema(c,(A1Length/2)),A9Length ,Offset,Sigma)
curve9a = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5 ,Offset,Sigma)
curve9b = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5*2,Offset,Sigma)
curve9c = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5*3,Offset,Sigma)
curve9d = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5*4,Offset,Sigma)
curve9e = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5*5,Offset,Sigma)
curve9f = ta.alma(ta.ema(c,(A1Length/2)),A9Length + (A10Length - A9Length) / 5*6,Offset,Sigma)
xcurve1 = ta.alma(coppock1 ,A1Length ,Offset,Sigma)
xcurve1a = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5 ,Offset,Sigma)
xcurve1b = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5*2,Offset,Sigma)
xcurve1c = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5*3,Offset,Sigma)
xcurve1d = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5*4,Offset,Sigma)
xcurve1e = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5*5,Offset,Sigma)
xcurve1f = ta.alma(coppock1 ,A1Length + (A2Length - A1Length) / 5*6,Offset,Sigma)
xcurve3 = ta.alma(coppock1 ,A3Length ,Offset,Sigma)
xcurve3a = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5 ,Offset,Sigma)
xcurve3b = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5*2,Offset,Sigma)
xcurve3c = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5*3,Offset,Sigma)
xcurve3d = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5*4,Offset,Sigma)
xcurve3e = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5*5,Offset,Sigma)
xcurve3f = ta.alma(coppock1 ,A3Length + (A4Length - A3Length) / 5*6,Offset,Sigma)
xcurve5 = ta.alma(coppock1 ,A5Length ,Offset,Sigma)
xcurve5a = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5 ,Offset,Sigma)
xcurve5b = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5*2,Offset,Sigma)
xcurve5c = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5*3,Offset,Sigma)
xcurve5d = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5*4,Offset,Sigma)
xcurve5e = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5*5,Offset,Sigma)
xcurve5f = ta.alma(coppock1 ,A5Length + (A6Length - A5Length) / 5*6,Offset,Sigma)
xcurve7 = ta.alma(coppock1 ,A7Length ,Offset,Sigma)
xcurve7a = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5 ,Offset,Sigma)
xcurve7b = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5*2,Offset,Sigma)
xcurve7c = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5*3,Offset,Sigma)
xcurve7d = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5*4,Offset,Sigma)
xcurve7e = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5*5,Offset,Sigma)
xcurve7f = ta.alma(coppock1 ,A7Length + (A8Length - A7Length) / 5*6,Offset,Sigma)
xcurve9 = ta.alma(coppock1 ,A9Length ,Offset,Sigma)
xcurve9a = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5 ,Offset,Sigma)
xcurve9b = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5*2,Offset,Sigma)
xcurve9c = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5*3,Offset,Sigma)
xcurve9d = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5*4,Offset,Sigma)
xcurve9e = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5*5,Offset,Sigma)
xcurve9f = ta.alma(coppock1 ,A9Length + (A10Length - A9Length) / 5*6,Offset,Sigma)
av1 = ta.rsi(math.avg(curve1 , curve1a , curve1b , curve1c , curve1d , curve1e),A1Length)-50
av3 = ta.rsi(math.avg(curve3 , curve3a , curve3b , curve3c , curve3d , curve3e),A1Length)-50
av5 = ta.rsi(math.avg(curve5 , curve5a , curve5b , curve5c , curve5d , curve5e),A1Length)-50
av7 = ta.rsi(math.avg(curve7 , curve7a , curve7b , curve7c , curve7d , curve7e),A1Length)-50
av9 = ta.rsi(math.avg(curve9 , curve9a , curve9b , curve9c , curve9d , curve9e),A1Length)-50
xav1 = ta.cci(math.avg(xcurve1 , xcurve1a , xcurve1b , xcurve1c , xcurve1d , xcurve1e),A1Length) /5
xav3 = ta.cci(math.avg(xcurve3 , xcurve3a , xcurve3b , xcurve3c , xcurve3d , xcurve3e),A1Length) /5
xav5 = ta.cci(math.avg(xcurve5 , xcurve5a , xcurve5b , xcurve5c , xcurve5d , xcurve5e),A1Length) /5
xav7 = ta.cci(math.avg(xcurve7 , xcurve7a , xcurve7b , xcurve7c , xcurve7d , xcurve7e),A1Length) /5
xav9 = ta.cci(math.avg(xcurve9 , xcurve9a , xcurve9b , xcurve9c , xcurve9d , xcurve9e),A1Length) /5
max1= ta.linreg(math.max(xav1 ,av1 ),c>hl?A1Length:(12),0)
max3= ta.linreg(math.max(xav3 ,av3 ),c>hl?A1Length:(12),0)
max5= ta.linreg(math.max(xav5 ,av5 ),c>hl?A1Length:(12),0)
max7= ta.linreg(math.max(xav7 ,av7 ),c>hl?A1Length:(12),0)
max9= ta.linreg(math.max(xav9 ,av9 ),c>hl?A1Length:(12),0)
min1= ta.linreg(math.min(xav1 ,av1 ),c>hl?A1Length:(12),0)
min3= ta.linreg(math.min(xav3 ,av3 ),c>hl?A1Length:(12),0)
min5= ta.linreg(math.min(xav5 ,av5 ),c>hl?A1Length:(12),0)
min7= ta.linreg(math.min(xav7 ,av7 ),c>hl?A1Length:(12),0)
min9= ta.linreg(math.min(xav9 ,av9 ),c>hl?A1Length:(12),0)
BullOverbought = ta.highest(c[FibOffset] ,h>hl?lookback1:lookback2)
BearOversold = ta.lowest (c[FibOffset] ,l<hl?lookback1:lookback2)
minav=ta.ema(math.avg(min1,min9,c,BearOversold )-(.382*hl),A1Length)
maxav=ta.ema(math.avg(max1,max9,c,BullOverbought)+(.382*hl),A1Length)
max=ta.sma(math.max(xav1,av1,xav3,av3,xav5,av5,xav7,av7,xav9,av9)+ta.wma((maxav-h)/1.618,32),64)
min=ta.sma(math.min(xav1,av1,xav3,av3,xav5,av5,xav7,av7,xav9,av9)-ta.wma((l-minav)/1.618,32),64)
mid=math.avg(max,min)
maxx=max>maxav
minn=min<minav
BullOverbought0 = SmoothFib?ta.ema(BullOverbought*fib0236,SmoothLen) :(BullOverbought*fib0236)
BearOversold0 = SmoothFib?ta.ema(BearOversold *fib0236,SmoothLen) :(BearOversold *fib0236)
FibOverbought1 = SmoothFib?ta.ema(BullOverbought*fib0382,SmoothLen) :(BullOverbought*fib0382)
FibOversold1 = SmoothFib?ta.ema(BearOversold *fib0382,SmoothLen) :(BearOversold *fib0382)
FibOverbought2 = SmoothFib?ta.ema(BullOverbought*fib05 ,SmoothLen) :(BullOverbought*fib05 )
FibOversold2 = SmoothFib?ta.ema(BearOversold *fib05 ,SmoothLen) :(BearOversold *fib05 )
FibOverbought3 = SmoothFib?ta.ema(BullOverbought*fib0618,SmoothLen) :(BullOverbought*fib0786)
FibOversold3 = SmoothFib?ta.ema(BearOversold *fib0618,SmoothLen) :(BearOversold *fib0786)
FibOverbought4 = SmoothFib?ta.ema(BullOverbought*fib0786,SmoothLen) :(BullOverbought*fib0618)
FibOversold4 = SmoothFib?ta.ema(BearOversold *fib0786,SmoothLen) :(BearOversold *fib0618)
FibOverbought5 = SmoothFib?ta.ema(BullOverbought*fib1236,SmoothLen) :(BullOverbought*fib1236)
FibOversold5 = SmoothFib?ta.ema(BearOversold *fib1236,SmoothLen) :(BearOversold *fib1236)
//FibOverbought6 = SmoothFib?ta.ema(BullOverbought*fib1382,SmoothLen) :(BullOverbought*fib1382)
//FibOversold6 = SmoothFib?ta.ema(BearOversold *fib1382,SmoothLen) :(BearOversold *fib1382)
//FibOverbought7 = SmoothFib?ta.ema(BullOverbought*fib1618,SmoothLen) :(BullOverbought*fib1618)
//FibOversold7 = SmoothFib?ta.ema(BearOversold *fib1618,SmoothLen) :(BearOversold *fib1618)
//colors
rsi_colors = color.new(rsio<rsic?input.color(#acfb00 ,'Up' ,group='RSI' ):input.color(#ff0000 ,'Down' ,group='RSI' ),0)
cci_colors = color.new(ccio<ccic?input.color(#acfb00 ,'Up' ,group='CCI' ):input.color(#ff0000 ,'Down' ,group='CCI' ),0)
span_colors = color.new(o<c ?input.color(color.olive,'SpanUp',group='Span'):input.color(#7d0909 ,'SpanDown',group='Span'),0)
fib_color = color.new(input.color(#ffffff,'Fib Color ' ),80),
Overbought_color= color.new(input.color(#ff0000,'Overbought Color' ),40),
Oversold_color = color.new(input.color(#acfb00,'Oversold Color ' ),40),
//FIB '
Oversoldplot = plot(Bound ? BearOversold : na,'Lower Boundary' ,color=color.new(Oversold_color ,40) ,linewidth=2,style=plot.style_linebr)
Oversold0plot = plot(Fib ? BearOversold0 : na,'Inner Fib Oversold(0.236)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Oversold1plot = plot(Fib ? FibOversold1 : na,'Inner Fib Oversold(0.382)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Oversold2plot = plot(Fib ? FibOversold2 : na,'Inner Fib Oversold(0.5 )' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Oversold3plot = plot(Fib ? FibOversold3 : na,'Inner Fib Oversold(0.618)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Oversold4plot = plot(Fib ? FibOversold4 : na,'Inner Fib Oversold(0.786)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Overboughtplot = plot(Bound ? BullOverbought : na,'Upper Boundary' ,color=color.new(Overbought_color,40) ,linewidth=2,style=plot.style_linebr)
Overbought0plot = plot(Fib ? BullOverbought0 : na,'Inner Fib Overbought(0.236)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Overbought1plot = plot(Fib ? FibOverbought1 : na,'Inner Fib Overbought(0.382)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Overbought2plot = plot(Fib ? FibOverbought2 : na,'Inner Fib Overbought(0.5 )' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Overbought3plot = plot(Fib ? FibOverbought3 : na,'Inner Fib Overbought(0.618)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
Overbought4plot = plot(Fib ? FibOverbought4 : na,'Inner Fib Overbought(0.786)' ,color=fib_color ,linewidth=1,style=plot.style_linebr)
ma3cplot = plot(ma3c,color=color.white,style=plot.style_linebr,linewidth=2)
ma5plot = plot(ma5,color=color.orange)
midplot = plot(mid ,'Mid' , color=color.new(color.gray,60 ))
minplot = plot(min ,'Min' , color=color.new(c<hl? Oversold_color :Overbought_color,60 ))
maxplot = plot(max ,'Max' , color=color.new(c<hl? Overbought_color:Oversold_color,60 ))
minavplot = plot(minav,'Min Average', color=color.new(Background?o<c?Oversold_color:Overbought_color:na,95),style=plot.style_areabr,histbase=-100)
maxavplot = plot(maxav,'Max Average', color=color.new(Background?o>c?Overbought_color:Oversold_color:na,95),style=plot.style_areabr,histbase=+100)
coppockplot = plot(coppock2*3 ,'Coppock Curve ',linewidth=3,color=color.blue)
loppockplot = plot(loppock2/5 ,'Loppock Momentum Curve',linewidth=2,color=color.new(loppock1/3>maxav or loppock1/3 < minav?color.fuchsia:color.purple,40))
fill(minavplot,maxavplot,color=color.new(color.gray,97))
fill(minplot,minavplot,color=minn and not maxx ?color.new(Background?#acfb00:na,80):color.new(color.gray,95))
fill(maxplot,maxavplot,color=maxx and not minn ?color.new(Background?#ff0000:na,80):color.new(color.gray,95))
plotcandle(o,h,l,c ,'Span Candles',color=color.new(span_colors,90),wickcolor=color.new(span_colors,10),bordercolor=color.new(span_colors,20))
plotcandle(rsio,rsih,rsil,rsic,'RSI Candles ',color=color.new(rsi_colors ,40),wickcolor=color.new(rsi_colors ,10),bordercolor=color.new(rsi_colors ,20))
plotcandle(ccio,ccih,ccil,ccic,'CCI Candles ',color=color.new(cci_colors ,40),wickcolor=color.new(cci_colors ,10),bordercolor=color.new(cci_colors ,20))
h0=hline(0 ,'Zero',linewidth=2,color=color.white)
h1=hline(30 ,'30 ',linewidth=2,color=Overbought_color)
h2=hline(-30,'-30 ',linewidth=2,color=Oversold_color)
//plot(ma1,color=color.purple)
//plot(ma2,color=color.navy)
//plot(ma3,color =color.gray)
//plot(ma3a,color=color.black)
//plot(ma3b,color=color.black)
//plot(ma4a,color=color.black)
//plot(ma4b,color=color.black) |
Candle Difference | https://www.tradingview.com/script/wyI2Kd2E-Candle-Difference/ | JaxonBest | https://www.tradingview.com/u/JaxonBest/ | 2 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ JaxonBest
//@version=5
indicator("Candle Difference")
plot(open - close, color=color.orange, title="Open Wick")
plot(low - close, color=color.red, title="Low Wick")
plot(high - close, color=color.green, title="High Wick") |
Moon Phases/Apogee & Perigee/Eclipses/North Node by BT | https://www.tradingview.com/script/1s3KLzTD-Moon-Phases-Apogee-Perigee-Eclipses-North-Node-by-BT/ | boratuncer | https://www.tradingview.com/u/boratuncer/ | 88 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ boratuncer
//@version=5
indicator(title="Moon Phases / Apogee & Perigee / Eclipses / North & South Nodes by BT", shorttitle="Moon by BT", overlay=true, max_lines_count=500, max_labels_count=500)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Inputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
ig1="Generic Inputs"
year1 = input.int(2021, "Start Year", group=ig1)
year2 = input.int(2022, "Stop Year", group=ig1)
ig2="Moon Phases"
showMoonF = input.bool(true, "Show Full Moons", group=ig2)
color colorMP_F = input.color(color.white, "Full Moon Color", group=ig2)
showMoonN = input.bool(true, "Show New Moons", group=ig2)
color colorMP_N = input.color(color.gray, "New Moon Color", group=ig2)
ig3="Apogee / Perigee"
showApogee = input.bool(false, "Show Apogees", group=ig3)
color colorAPO = input.color(color.yellow, "Apogee Color", group=ig3)
showPerigee = input.bool(false, "Show Perigees", group=ig3)
color colorPER = input.color(color.red, "Perigee Color", group=ig3)
ig4="North Node"
showNorth = input.bool(false, "Show North Node ", group=ig4)
color colorNorth = input.color(color.blue, "North Node Color", group=ig4)
ig5="Solar & Lunar Eclipses"
showSolarA = input.bool(false, "Show Solar Eclipses (Annular) ", group=ig5)
showSolarP = input.bool(false, "Show Solar Eclipses (Parial) ", group=ig5)
showSolarT = input.bool(false, "Show Solar Eclipses (Total) ", group=ig5)
color colorEclipseS = input.color(color.green, "Solar Eclipses Color", group=ig5)
showLunarPE = input.bool(false, "Show Lunar Eclipses (Penumbral) ", group=ig5)
showLunarP = input.bool(false, "Show Lunar Eclipses (Parial) ", group=ig5)
showLunarT = input.bool(false, "Show Lunar Eclipses (Total) ", group=ig5)
color colorEclipseL = input.color(color.purple, "Lunar Eclipses Color", group=ig5)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//color colorMP_N = color.new(color.gray, 20) // Moon phases new
//color colorMP_F = color.new(color.white, 20) // Moon phases full
//color colorAPO = color.new(color.yellow, 20) // Moon phases apogee
//color colorPER = color.new(color.red, 20) // Moon phases apogee
//color colorNorth = color.new(color.blue, 20) // North node
//color colorEclipseS = color.new(color.green, 20) // Solar eclipses
//color colorEclipseL = color.new(color.purple, 20) // Lunar eclipses
// Format as 2021-01-13T04:32
//var PHASES_N = array.from("2021-01-13")
string[] PHASES_N = array.from("2015-01-20", "2015-02-18", "2015-03-20", "2015-04-18", "2015-05-18", "2015-06-16", "2015-07-16", "2015-08-14", "2015-09-13", "2015-10-13", "2015-11-11", "2015-12-11",
"2016-01-10", "2016-01-08", "2016-03-09", "2016-04-07", "2016-05-06", "2016-06-05", "2016-07-04", "2016-08-02", "2016-09-01", "2016-10-01", "2016-10-30", "2016-11-29", "2016-12-29",
"2017-01-28", "2017-02-26", "2017-03-28", "2017-04-26", "2017-05-25", "2017-06-24", "2017-07-23", "2017-08-21", "2017-09-20", "2017-10-19", "2017-11-18", "2017-12-18",
"2018-01-17", "2018-02-15", "2018-03-17", "2018-04-16", "2018-05-15", "2018-06-13", "2018-07-13", "2018-08-11", "2018-09-09", "2018-10-09", "2018-11-07", "2018-12-07",
"2019-01-06", "2019-02-04", "2019-03-06", "2019-04-05", "2019-05-04", "2019-06-03", "2019-07-02", "2019-08-01", "2019-08-30", "2019-09-28", "2019-10-29", "2019-11-26", "2019-12-26",
"2020-01-24", "2020-02-23", "2020-03-24", "2020-04-23", "2020-05-22", "2020-06-21", "2020-07-20", "2020-08-19", "2020-09-17", "2020-10-16", "2020-11-15", "2020-12-14",
"2021-01-13", "2021-02-11", "2021-03-13", "2021-04-12", "2021-05-11", "2021-06-10", "2021-07-10", "2021-08-08", "2021-09-07", "2021-10-06", "2021-11-04", "2021-12-04",
"2022-01-02", "2022-02-01", "2022-03-02", "2022-04-01", "2022-04-30", "2022-05-30", "2022-06-29", "2022-07-28", "2022-08-27", "2022-09-25", "2022-10-25", "2022-11-23", "2022-12-23",
"2023-01-21", "2023-02-20", "2023-03-21", "2023-04-20", "2023-05-19", "2023-06-18", "2023-07-17", "2023-08-16", "2023-09-15", "2023-10-14", "2023-11-13", "2023-12-12")
string[] PHASES_F = array.from("2015-01-05", "2015-02-03", "2015-03-05", "2015-04-04", "2015-05-04", "2015-06-02", "2015-07-02", "2015-07-31", "2015-08-29", "2015-09-28", "2015-10-27", "2015-11-25", "2015-12-25",
"2016-01-24", "2016-01-22", "2016-03-23", "2016-04-22", "2016-05-21", "2016-06-20", "2016-07-19", "2016-08-10", "2016-09-16", "2016-10-06", "2016-11-14", "2016-12-14",
"2017-01-12", "2017-02-11", "2017-03-12", "2017-04-11", "2017-05-10", "2017-06-09", "2017-07-09", "2017-08-07", "2017-09-06", "2017-10-05", "2017-11-04", "2017-12-03",
"2018-01-02", "2018-01-31", "2018-03-02", "2018-03-31", "2018-04-30", "2018-05-29", "2018-06-28", "2018-07-27", "2018-08-26", "2018-09-25", "2018-10-24", "2018-11-23", "2018-12-22",
"2019-01-21", "2019-02-19", "2019-03-21", "2019-04-19", "2019-05-18", "2019-06-17", "2019-07-16", "2019-08-15", "2019-09-14", "2019-10-13", "2019-11-12", "2019-12-12",
"2020-01-10", "2020-02-09", "2020-03-09", "2020-04-08", "2020-05-07", "2020-06-05", "2020-07-05", "2020-08-03", "2020-09-02", "2020-10-01", "2020-10-31", "2020-11-30", "2020-12-30",
"2021-01-28", "2021-02-27", "2021-03-28", "2021-04-27", "2021-05-26", "2021-06-24", "2021-07-24", "2021-08-22", "2021-09-20", "2021-10-20", "2021-11-19", "2021-12-19",
"2022-01-17", "2022-02-16", "2022-03-18", "2022-04-16", "2022-05-16", "2022-06-14", "2022-07-13", "2022-08-12", "2022-09-10", "2022-10-09", "2022-11-08", "2022-12-08",
"2023-01-06", "2023-02-05", "2023-03-07", "2023-04-06", "2023-05-05", "2023-06-04", "2023-07-03", "2023-08-01", "2023-08-31", "2023-09-29", "2023-10-28", "2023-11-27", "2023-12-27")
string[] APOGEE = array.from("2015-01-09", "2015-02-06", "2015-03-05", "2015-04-01", "2015-04-29", "2015-05-26", "2015-06-23", "2015-07-21", "2015-08-18", "2015-09-14", "2015-10-11", "2015-11-07", "2015-12-05",
"2016-01-02", "2016-01-30", "2016-02-27", "2016-03-25", "2016-04-21", "2016-05-18", "2016-06-15", "2016-07-13", "2016-08-10", "2016-09-16", "2016-10-04", "2016-10-31", "2016-11-27", "2016-12-25",
"2017-01-22", "2017-02-18", "2017-03-18", "2017-04-15", "2017-05-12", "2017-06-08", "2017-07-06", "2017-08-02", "2017-08-30", "2017-09-27", "2017-10-25", "2017-11-21", "2017-12-19",
"2018-01-15", "2018-02-11", "2018-03-11", "2018-04-08", "2018-05-06", "2018-06-02", "2018-06-30", "2018-07-27", "2018-08-23", "2018-09-20", "2018-10-17", "2018-11-14", "2018-12-12",
"2019-01-09", "2019-02-05", "2019-03-04", "2019-04-01", "2019-04-28", "2019-05-26", "2019-06-23", "2019-07-21", "2019-08-17", "2019-09-13", "2019-10-10", "2019-11-07", "2019-12-05",
"2020-01-02", "2020-01-29", "2020-02-26", "2020-03-24", "2020-04-20", "2020-05-18", "2020-06-15", "2020-07-12", "2020-08-09", "2020-09-06", "2020-10-03", "2020-10-30", "2020-11-27", "2020-12-24",
"2021-01-21", "2021-02-18", "2021-03-18", "2021-04-14", "2021-05-11", "2021-06-08", "2021-07-05", "2021-08-02", "2021-08-30", "2021-09-26", "2021-10-24", "2021-11-21", "2021-12-18",
"2022-01-14", "2022-02-11", "2022-03-10", "2022-04-07", "2022-05-05", "2022-06-02", "2022-06-29", "2022-07-26", "2022-08-22", "2022-09-19", "2022-10-17", "2022-11-14", "2022-12-12",
"2023-01-08", "2023-02-04", "2023-03-03", "2023-03-31", "2023-04-28", "2023-05-26", "2023-06-22", "2023-07-20", "2023-08-16", "2023-09-12", "2023-10-10", "2023-11-06", "2023-12-04")
string[] PERIGEE = array.from("2015-01-21", "2015-02-19", "2015-03-19", "2015-04-17", "2015-05-15", "2015-06-10", "2015-07-05", "2015-08-02", "2015-08-30", "2015-09-28", "2015-10-26", "2015-11-23", "2015-12-21",
"2016-01-15", "2016-02-11", "2016-03-10", "2016-04-07", "2016-05-06", "2016-06-03", "2016-07-01", "2016-07-27", "2016-08-22", "2016-09-18", "2016-10-16", "2016-11-14", "2016-12-12",
"2017-01-10", "2017-02-06", "2017-03-03", "2017-03-30", "2017-04-27", "2017-05-26", "2017-06-23", "2017-07-21", "2017-08-18", "2017-09-13", "2017-10-09", "2017-11-06", "2017-12-04",
"2018-01-01", "2018-01-30", "2018-02-27", "2018-03-26", "2018-04-20", "2018-05-17", "2018-06-14", "2018-07-13", "2018-08-10", "2018-09-08", "2018-10-05", "2018-10-31", "2018-11-26", "2018-12-24",
"2019-01-21", "2019-02-19", "2019-03-19", "2019-04-16", "2019-05-13", "2019-06-07", "2019-07-05", "2019-08-02", "2019-08-30", "2019-09-28", "2019-10-26", "2019-11-23", "2019-12-18",
"2020-01-13", "2020-02-10", "2020-03-10", "2020-04-07", "2020-05-06", "2020-06-03", "2020-06-30", "2020-07-25", "2020-08-21", "2020-09-18", "2020-10-16", "2020-11-14", "2020-12-12",
"2021-01-09", "2021-02-03", "2021-03-02", "2021-03-30", "2021-04-27", "2021-05-26", "2021-06-23", "2021-07-21", "2021-08-17", "2021-09-11", "2021-10-08", "2021-11-05", "2021-12-04",
"2022-01-01", "2022-01-30", "2022-02-26", "2022-03-23", "2022-04-19", "2022-05-17", "2022-06-14", "2022-07-13", "2022-08-10", "2022-09-07", "2022-10-04", "2022-10-29", "2022-11-26", "2022-12-24",
"2023-01-21", "2023-02-19", "2023-03-19", "2023-04-16", "2023-05-11", "2023-06-06", "2023-07-04", "2023-08-02", "2023-08-30", "2023-09-28", "2023-10-26", "2023-11-21", "2023-12-16")
string[] NORTHN = array.from("2015-11-10", "2017-04-28", "2018-10-16", "2020-06-05", "2021-12-25", "2023-07-12", "2025-01-29", "2026-08-18", "2028-03-07", "2029-09-24", "2031-04-14")
string[] SOLAR_E_A = array.from("2020-06-21", "2021-06-10", "2023-10-14", "2024-10-02")
string[] SOLAR_E_P = array.from("2015-03-20", "2022-04-30","2022-10-25", "2025-03-29", "2025-09-21")
string[] SOLAR_E_T = array.from("2020-12-14", "2021-12-04", "2023-04-20", "2024-04-08")
string[] LUNAR_E_PE = array.from("2016-09-16", "2017-02-11", "2018-01-31", "2020-01-10", "2020-06-05", "2020-07-04", "2020-11-29", "2023-05-05", "2024-03-24")
string[] LUNAR_E_P = array.from("2017-08-07", "2019-07-16", "2021-11-18", "2023-10-29", "2024-10-17")
string[] LUNAR_E_T = array.from("2015-09-28", "2018-07-27", "2019-01-21", "2021-05-25", "2022-05-15", "2022-11-07", "2024-10-17", "2025-03-13", "2025-09-07")
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
debug(string labeltext) =>
if barstate.islast
label.new(bar_index, close, labeltext, style=label.style_label_left, textalign=text.align_left)
vlineTime(BarIndex, Color, LineStyle, LineWidth, Text) => // Verticle Line Function, โ50-54 lines maximum allowable per indicator
//m=ta.lowest(200) * 0.90
label.new(x=BarIndex, y=0, color=Color, text=Text, xloc=xloc.bar_time)
ret = line.new(BarIndex, low - ta.tr, BarIndex, high + ta.tr, xloc=xloc.bar_time, extend=extend.both, style=LineStyle, width=LineWidth, color=Color)
line.delete(ret[1])
drawLines(show, inputarray, year1, year2, colorLine, inputtext) =>
for i = 0 to array.size(inputarray) - 1
arr = str.split(array.get(inputarray, i), '-')
int y = math.round(str.tonumber(str.tostring(array.get(arr, 0))))
int m = math.round(str.tonumber(str.tostring(array.get(arr, 1))))
int d = math.round(str.tonumber(str.tostring(array.get(arr, 2))))
for var j=year1 to year2
if(y == j)
vlineTime((show) ? timestamp(y, m, d, 00, 00) : na, colorLine, line.style_dashed, 2, inputtext)
//debug(str.tostring(y))
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
// Script body
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
drawLines(showMoonN, PHASES_N, year1, year2, colorMP_N, "New Moon") // Draw new moons
drawLines(showMoonF, PHASES_F, year1, year2, colorMP_F, "Full Moon") // Draw full moons
drawLines(showApogee, APOGEE, year1, year2, colorAPO, "Apogee") // Draw apogee
drawLines(showPerigee, PERIGEE, year1, year2, colorPER, "Perigee") // Draw perigee
drawLines(showNorth, NORTHN, year1, year2, colorNorth, "North Node") // Draw north node
drawLines(showSolarA, SOLAR_E_A, year1, year2, colorEclipseS, "Solar Eclipses (Annular)") // Solar Exlipses (Annular)
drawLines(showSolarP, SOLAR_E_P, year1, year2, colorEclipseS, "Solar Eclipses (Partial)") // Solar Exlipses (Partial)
drawLines(showSolarT, SOLAR_E_T, year1, year2, colorEclipseS, "Solar Eclipses (Total)") // Solar Exlipses (Total)
drawLines(showLunarPE, LUNAR_E_PE, year1, year2, colorEclipseL, "Lunar Eclipses (Penumbral)") // Lunar Exlipses (Annular)
drawLines(showLunarP, LUNAR_E_P, year1, year2, colorEclipseL, "Lunar Eclipses (Partial)") // Lunar Exlipses (Partial)
drawLines(showLunarT, LUNAR_E_T, year1, year2, colorEclipseL, "Lunar Eclipses (Total)") // Lunar Exlipses (Total)
|
Variety RSI of Fast Discrete Cosine Transform [Loxx] | https://www.tradingview.com/script/Pokmm59g-Variety-RSI-of-Fast-Discrete-Cosine-Transform-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 118 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Variety RSI of Fast Discrete Cosine Transform [Loxx]",
shorttitle='VRSIFDCT [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxvarietyrsi/1
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crosses'
//==========================================================================================
//Fast Discrete Cosine Transform
//The algorithm performs a fast cosine transform of the real
//function defined by nn samples on the real axis.
//Depending on the passed parameters, it can be executed
//both direct and inverse conversion.
//Input parameters:
// tnn - Number of function values minus one. Should be 1024
// degree of two. The algorithm does not check
// correct value passed.
// a - array [0 .. nn] of Real 1025
// Function values.
// InverseFCT
// - the direction of the transformation.
// True if reverse, False if direct.
//
//Output parameters:
// a - the result of the transformation. For more details, see
// description on the site. https://www.alglib.net/fasttransforms/fft.php
//==========================================================================================
_fastcosinetransform(float[] a, int tnn, bool inversefct)=>
int j = 0
int n2 = 0
float sum = 0.
float y1 = 0.
float y2 = 0.
float theta = 0.
float wi = 0.
float wpi = 0.
float wr = 0.
float wpr = 0.
float wtemp = 0.
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int istep = 0
int isign = 0
float tempr = 0.
float tempi = 0.
while true
if (tnn == 1)
y1 := array.get(a, 0)
y2 := array.get(a, 1)
array.set(a, 0, 0.5 * (y1 + y2))
array.set(a, 1, 0.5 * (y1 - y2))
if inversefct
array.set(a, 0, array.get(a, 0) * 2)
array.set(a, 1, array.get(a, 1) * 2)
break
wi := 0
wr := 1
theta := math.pi / tnn
wtemp := math.sin(theta * 0.5)
wpr := -2.0 * wtemp * wtemp
wpi := math.sin(theta)
sum := 0.5 * (array.get(a, 0) - array.get(a, tnn))
array.set(a, 0, 0.5 * (array.get(a, 0) + array.get(a, tnn)))
n2 := tnn + 2
for jx = 2 to tnn / 2
wtemp := wr
wr := wtemp * wpr - wi * wpi + wtemp
wi := wi * wpr + wtemp * wpi + wi
y1 := 0.5 * (array.get(a, jx - 1) + array.get(a, n2 - jx - 1))
y2 := array.get(a, jx - 1) - array.get(a, n2 - jx - 1)
array.set(a, jx - 1, y1 - wi * y2)
array.set(a, n2 - jx - 1, y1 + wi * y2)
sum := sum + wr * y2
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
array.set(a, tnn, array.get(a, 1))
array.set(a, 1, sum)
j := 4
while (j <= tnn)
sum := sum + array.get(a, j - 1)
array.set(a, j - 1, sum)
j := j + 2
if (inversefct)
for jx = 0 to tnn
array.set(a, jx, array.get(a, jx) * 2 / tnn)
break
a
smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group= "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
//N specifies series length (power of two);
//SS - A smoothening coefficient in the resulting spectrum zeroes out frequency ratios exceeding set value. SS cannot exceed 2^N. Close series fully repeats itself if SS = 2^N.
windowper = input.string("256", "Window Period", options = ["16", "32", "64", "128", "256", "512", "1024", "2048"], group = "Basic Settings")
smthcutoff = input.int(12, "Smoothing Period", group = "Basic Settings")
arraylevl = input.int(0, "Output Level", group = "Basic Settings", minval = 0,
tooltip = "Experimental, default and utility is the 0 index default. Adjusting this value upward smooths the signal. This value is the index of the of the Inverse Fast Cosine Transform output array.")
rsiper = input.int(15, "RSI Period", group= "RSI Settings")
rsitype = input.string("Regular", "RSI Type", options = ["RSX", "Regular", "Slow", "Rapid", "Harris", "Cuttler", "Ehlers Smoothed"], group = "RSI Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
rsimode = switch rsitype
"RSX" => "rsi_rsx"
"Regular" => "rsi_rsi"
"Slow" => "rsi_slo"
"Rapid" => "rsi_rap"
"Harris" => "rsi_har"
"Cuttler" => "rsi_cut"
"Ehlers Smoothed" => "rsi_ehl"
=> "rsi_rsi"
Window = str.tonumber(windowper)
//check that indow is power of 2
n = int(math.log(Window) / math.log(2))
N = int(math.max(math.pow(2, n), 16))
var aa = array.new<float>(N + 1, 0.)
//fill caculation array with source values
for i = 0 to N - 1
array.set(aa, i, nz(src[i]))
M = array.size(aa)
end = M - 1
smthcutoff := int(math.min(smthcutoff, M))
//regular pass of FCT
_fastcosinetransform(aa, N, false)
//filter of FCT, values above smthcutoff are zeroed out
for k = 0 to end
if k >= smthcutoff
array.set(aa, k, 0.)
//inverse pass of FCT
_fastcosinetransform(aa, N, true)
//we are only interested in the first value; although accessing additional values can create ribbons and boundaries
arraylevlout = math.min(array.size(aa) - 1, arraylevl)
out = array.get(aa, arraylevlout)
out := loxxvarietyrsi.rsiVariety(rsimode, out, rsiper)
sig = nz(out[1])
mid = 50
state = 0.
if sigtype == SM02
if (out < sig)
state := -1
if (out > sig)
state := 1
else if sigtype == SM03
if (out < mid)
state := -1
if (out > mid)
state := 1
colorout = state == -1 ? redcolor : state == 1 ? greencolor : color.gray
plot(out, "RSI FDCT", color = colorout, linewidth = 2)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
barcolor(colorout)
goLong = sigtype == SM02 ? ta.crossover(out, sig) : ta.crossover(out, mid)
goShort = sigtype == SM02 ? ta.crossunder(out, sig) : ta.crossunder(out, mid)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Variety RSI of Fast Discrete Cosine Transform [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Variety RSI of Fast Discrete Cosine Transform [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
True_Range_% | https://www.tradingview.com/script/i0L0rKMB-True-Range/ | Teji_Singh | https://www.tradingview.com/u/Teji_Singh/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Teji_Singh
//@version=5
indicator("True_Range_%", "TR_%")
True_Range_Avg = input(100)
High_True_Range_Value = input.float(1.5,step=0.5)
Low_True_Range_Value = input.float(0.7, step=0.1, maxval = 1)
Latest_True_Range = ta.tr(1)
volatility = Latest_True_Range / close[1] * 100
Volatility_Avg = ta.sma(volatility,True_Range_Avg)
HIGH_Significance = volatility >= Volatility_Avg * High_True_Range_Value
LOW_Significance = volatility >= Volatility_Avg * Low_True_Range_Value
plot(volatility,title = "True_Range_%", style = plot.style_columns,color = HIGH_Significance ? color.red : LOW_Significance ? color.blue : color.white)
plot(Volatility_Avg, title = "True_Range_Avg_1", color = color.yellow) |
Real-Fast Fourier Transform of Price w/ Linear Regression [Loxx] | https://www.tradingview.com/script/19wyKiYV-Real-Fast-Fourier-Transform-of-Price-w-Linear-Regression-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 217 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Real-Fast Fourier Transform of Price w/ Linear Regression [Loxx]",
shorttitle = "RFFTP [Loxx]",
overlay = true,
max_lines_count = 500)
greencolor = #2DD204
redcolor = #D2042D
//+-------------------------------------------------------------------------+
//| Real Fast Fourier Transform |
///+-------------------------------------------------------------------------+
//The algorithm performs a fast Fourier transform of a real
//function defined by n samples on the real axis.
//
//Depending on the passed parameters, it can be executed
//both direct and inverse conversion.
//
// Input parameters:
// tnn - Number of function values. Must be degree
// deuces. Algorithm does not validate
// passed value.
// a - array [0 .. nn-1] of Real
// Function values.
// InverseFFT
// - the direction of the transformation.
// True if reverse, False if direct.
//
// Output parameters:
// a - the result of the transformation.
//
// For more details, see description on the site:
// https://www.alglib.net/fasttransforms/fft.php
// https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.205.4523&rep=rep1&type=pdf
//+-------------------------------------------------------------------------+
_realFastFourierTransform(float[] a, int tnn, bool inversefft)=>
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int j = 0
int istep = 0
int isign = 0
float wtemp = 0.
float wr = 0.
float wpr = 0.
float wpi = 0.
float wi = 0.
float theta = 0.
float tempr = 0.
float tempi = 0.
if (tnn != 1)
if (not inversefft)
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
else
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := 0.5
ttheta := -ttheta
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, c1 * (h1r + array.get(a, 1)))
array.set(a, 1, c1 * (h1r - array.get(a, 1)))
if (inversefft)
isign := -1
else
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
if (inversefft)
for ix = 1 to 2 * nn
array.set(a, ix - 1, array.get(a, ix - 1) / nn)
if (not inversefft)
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
a
//linear regression value
_iLRValue(float[] src, float period, float slope)=>
float SumXY = 0.
float SumY = 0.
float sumX = period * (period - 1) / 2.0
float sumXX = period * (period - 1) * (2.0 * period - 1.0) / 6.0
float divisor = math.pow(sumX, 2.0) - period * sumXX
slope1 = slope
for k = 0 to period - 1
SumXY += k * array.get(src, k)
SumY += array.get(src, k)
if (divisor != 0)
slope1 := (period * SumXY - sumX * SumY) / divisor
else
slope1 := 0
out = ((SumY - slope1 * sumX) / period + slope1 * (period - 1.0))
[out, slope1]
src = input.source(close, "Source", group = "Basic Settings")
uselreg = input.bool(true, "Use Linear Regression?", group = "Basic Settings")
Windowin = input.string("512", "Window", options = ["4", "8", "16", "32", "64", "128", "256", "512", "1024", "2048"], group = "Basic Settings")
Treshold = input.float(0.03, "Treshold", step = 0.001, group = "Basic Settings")
dtrendper = input.int(0, "Detrended Line Period", group = "Basic Settings")
barsback = input.int(30, "Last Bar", minval = 0, group = "Basic Settings")
mutebars = input.bool(true, "Bar color muting?", group = "Basic Settings")
//+------------------------------------------------------------------+
//| Initialize variables
//+------------------------------------------------------------------+
var pvlines = array.new_line(0)
var lrlines = array.new_line(0)
//+------------------------------------------------------------------+
//| Force input Window period to lowest nearest power of 2,
//| we alreadsy solved to make sure user can
//| only select powers of 2
//+------------------------------------------------------------------+
Window = str.tonumber(Windowin)
n = int(math.log(Window) / math.log(2))
N = int(math.max(math.pow(2, n), 16))
barcolor(mutebars ? last_bar_index - bar_index >= barsback and last_bar_index - bar_index < N ? color.gray : na : na)
//+------------------------------------------------------------------+
//| Initialize lines for drawing later
//+------------------------------------------------------------------+
countout = Window >= 256 ? 250 : Window
if barstate.isfirst
for i = 0 to countout - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(lrlines, line.new(na, na, na, na))
//+------------------------------------------------------------------+
//| Core compute
//+------------------------------------------------------------------+
if barstate.islast
//+------------------------------------------------------------------+
//| Initial variables
//+------------------------------------------------------------------+
dlLength = dtrendper > N or dtrendper < 1 ? N : dtrendper
work = array.new<float>(N, 0.)
price = array.new<float>(N, 0.)
lr = array.new<float>(N, 0.)
fft = array.new<float>(N, 0.)
for i = 0 to N - 1
array.set(price, i, nz(src[i + barsback]))
endValue = 0.
slope = 0.
//+------------------------------------------------------------------+
//| Apply Linear Regression and detrending
//+------------------------------------------------------------------+
if (uselreg)
[dv, slp] = _iLRValue(price, dlLength, slope)
endValue := dv
slope := slp
else
endValue := array.get(price, 0)
slope := (endValue - array.get(price, dlLength - 1)) / dlLength
for i = N - 1 to 0
array.set(lr, i, endValue - slope * i)
array.set(work, i, array.get(price, i) - array.get(lr, i))
//+------------------------------------------------------------------+
//| Apply Regular FFT and calculate powers and modified by threshhold
//+------------------------------------------------------------------+
_realFastFourierTransform(work, N, false)
for i = 1 to N / 2 - 1
amp = math.sqrt(math.pow(array.get(work, i * 2), 2) + math.pow(array.get(work, i * 2 + 1), 2))
add = 0.
if (not (array.get(work, i * 2) > 0))
add := math.pi
phase = math.atan(array.get(work, i * 2 + 1) / array.get(work, i * 2))
array.set(work, i * 2, amp * math.cos(phase + add))
array.set(work, i * 2 + 1, amp * math.sin(phase + add))
power = 0.
for i = 1 to N / 2 - 1
power += math.sqrt(math.pow(array.get(work, i * 2), 2) + math.pow(array.get(work, i * 2 + 1), 2))
treshold = power * Treshold
for i = 1 to N / 2 - 1
tmp = math.sqrt(math.pow(array.get(work, i * 2), 2) + math.pow(array.get(work, i * 2 + 1), 2))
if (tmp < treshold)
array.set(work, i * 2, 0)
array.set(work, i * 2 + 1, 0)
//+------------------------------------------------------------------+
//| Apply Inverse FFT and final output
//+------------------------------------------------------------------+
_realFastFourierTransform(work, N , true)
for i = 0 to N - 1
array.set(fft, i, array.get(work, i) + array.get(lr, i))
skipper = Window == 2048 ? 8 : Window == 1024 ? 4 : Window == 512 ? 2 : 1
int i = 0
int j = 0
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
while i < N and i < array.size(fft) - 2
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
colorout = i < array.size(fft) - 2 ? array.get(fft, i) > array.get(fft, i + skipper) ? greencolor : redcolor : na
line.set_xy1(pvline, bar_index - i - skipper - barsback, array.get(fft, i + skipper))
line.set_xy2(pvline, bar_index - i - barsback, array.get(fft, i))
line.set_color(pvline, colorout)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 5)
lrline = array.get(lrlines, j)
colorout2 = i < array.size(lr) - 2 ? array.get(lr, i) > array.get(lr, i + skipper) ? greencolor : redcolor : na
line.set_xy1(lrline, bar_index - i - skipper - barsback, array.get(lr, i + skipper))
line.set_xy2(lrline, bar_index - i - barsback, array.get(lr, i))
line.set_color(lrline, colorout2)
line.set_style(lrline, line.style_solid)
line.set_width(lrline, 2)
i += skipper
j += 1
|
DOW 30 - Market Breadth | https://www.tradingview.com/script/EBEkesQm-DOW-30-Market-Breadth/ | maplehunger123 | https://www.tradingview.com/u/maplehunger123/ | 35 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//Script Date 8/8/2022 : Script Version 1
// ยฉ maplehunger123
//Script Analalises All stocks within the DOW JONES INDUSTRIAL ADVERAGE as 8/9/2022, evaluating VWap, and EMA bands suggesting Overall intra-day Market Trends.
//This indicator main usage is for intraday analysis understanding current market centiment being bearish, or bullish.
//Current stocks: 3M, American Express, Amgen, Apple, Boeing, Caterpillar, Chevron, Cisco Systems, Coca-Cola, Disney, Dow, Goldman Sachs, Home Depot, Honeywell, IBM, Intel, Johnson & Johnson, JP Morgan Chase, McDonaldโs, Merck, Microsoft, Nike, Procter & Gamble, Salesforce, Travelers, UnitedHealth, Visa, Walgreens, and Walmart.
//THIS INDICATOR IS WEIGHTED BY DJI.
//@version=5
indicator("DOW 30 - Weight", overlay=false)
// OPTIONS OF SHORT TERM TIMEFRAME ------------------------------------------------------------------------Option TO BE ADDED----------------------------------------------------
//SHORT_TERM = -------------------------------------------------------------------------------------------Option To Be ADDED ---------------------------------------------------
// OPTIONS OF LONGER TERM TIMEFRAME -----------------------------------------------------------------------Option To Be ADDED ---------------------------------------------------
//LONGE_TERM = --------------------------------------------------------------------------------------------Option To Be ADDED ---------------------------------------------------
// 9 EMA REQUEST
// 20 EMA REQUEST
// Vwap Request
// Stock Price Request
AXPema9 = ta.ema(request.security("AXP", "1", close), 9)
AXPema = ta.ema(request.security("AXP", "1", close), 20)
AXPVwap = ta.vwap(request.security("AXP", "1", close))
AXP = (request.security("AXP", "1", close))
AMGNema9 = ta.ema(request.security("AMGN", "1", close), 9)
AMGNema = ta.ema(request.security("AMGN", "1", close), 20)
AMGNVwap = ta.vwap(request.security("AMGN", "1", close))
AMGN = (request.security("AMGN", "1", close))
AAPLema9 = ta.ema(request.security("AAPL", "1", close), 9)
AAPLema = ta.ema(request.security("AAPL", "1", close), 20)
AAPLVwap = ta.vwap(request.security("AAPL", "1", close))
AAPL = (request.security("AAPL", "1", close))
BAema9 = ta.ema(request.security("BA", "1", close), 9)
BAema = ta.ema(request.security("BA", "1", close), 20)
BAVwap = ta.vwap(request.security("BA", "1", close))
BA = (request.security("BA", "1", close))
CATema9 = ta.ema(request.security("CAT", "1", close), 9)
CATema = ta.ema(request.security("CAT", "1", close), 20)
CATVwap = ta.vwap(request.security("CAT", "1", close))
CAT = (request.security("CAT", "1", close))
CSCOema9 = ta.ema(request.security("CSCO", "1", close), 9)
CSCOema = ta.ema(request.security("CSCO", "1", close), 20)
CSCOVwap = ta.vwap(request.security("CSCO", "1", close))
CSCO = (request.security("CSCO", "1", close))
CVXema9 = ta.ema(request.security("CVX", "1", close), 9)
CVXema = ta.ema(request.security("CVX", "1", close), 20)
CVXVwap = ta.vwap(request.security("CVX", "1", close))
CVX = (request.security("CVX", "1", close))
GSema9 = ta.ema(request.security("GS", "1", close), 9)
GSema = ta.ema(request.security("GS", "1", close), 20)
GSWap = ta.vwap(request.security("GS", "1", close))
GS = (request.security("GS", "1", close))
HDema9 = ta.ema(request.security("HD", "1", close), 9)
HDema = ta.ema(request.security("HD", "1", close), 20)
HDVWap = ta.vwap(request.security("HD", "1", close))
HD = (request.security("HD", "1", close))
HONema9 = ta.ema(request.security("HON", "1", close), 9)
HONema = ta.ema(request.security("HON", "1", close), 20)
HONVWap = ta.vwap(request.security("HON", "1", close))
HON = (request.security("HON", "1", close))
IBMema9 = ta.ema(request.security("IBM", "1", close), 9)
IBMema = ta.ema(request.security("IBM", "1", close), 20)
IBMVWap = ta.vwap(request.security("IBM", "1", close))
IBM = (request.security("IBM", "1", close))
INTCema9 = ta.ema(request.security("INTC", "1", close), 9)
INTCema = ta.ema(request.security("INTC", "1", close), 20)
INTCVWap = ta.vwap(request.security("INTC", "1", close))
INTC = (request.security("INTC", "1", close))
JNJema9 = ta.ema(request.security("JNJ", "1", close), 9)
JNJema = ta.ema(request.security("JNJ", "1", close), 20)
JNJVWap = ta.vwap(request.security("JNJ", "1", close))
JNJ = (request.security("JNJ", "1", close))
KOema9 = ta.ema(request.security("KO", "1", close), 9)
KOema = ta.ema(request.security("KO", "1", close), 20)
KOVWap = ta.vwap(request.security("KO", "1", close))
KO = (request.security("KO", "1", close))
JPMema9 = ta.ema(request.security("JPM", "1", close), 9)
JPMema = ta.ema(request.security("JPM", "1", close), 20)
JPMVWap = ta.vwap(request.security("JPM", "1", close))
JPM = (request.security("JPM", "1", close))
MMMema9 = ta.ema(request.security("MMM", "1", close), 9)
MMMema = ta.ema(request.security("MMM", "1", close), 20)
MMMVWap = ta.vwap(request.security("MMM", "1", close))
MMM = (request.security("MMM", "1", close))
MRKema9 = ta.ema(request.security("MRK", "1", close), 9)
MRKema = ta.ema(request.security("MRK", "1", close), 20)
MRKVWap = ta.vwap(request.security("MRK", "1", close))
MRK = (request.security("MRK", "1", close))
MSFTema9 = ta.ema(request.security("MSFT", "1", close), 9)
MSFTema = ta.ema(request.security("MSFT", "1", close), 20)
MSFTVWap = ta.vwap(request.security("MSFT", "1", close))
MSFT = (request.security("MSFT", "1", close))
NKEema9 = ta.ema(request.security("MSFT", "1", close), 9)
NKEema = ta.ema(request.security("MSFT", "1", close), 20)
NKEVWap = ta.vwap(request.security("MSFT", "1", close))
NKE = (request.security("MSFT", "1", close))
PGema9 = ta.ema(request.security("MSFT", "1", close), 9)
PGema = ta.ema(request.security("MSFT", "1", close), 20)
PGVWap = ta.vwap(request.security("MSFT", "1", close))
PG = (request.security("MSFT", "1", close))
TRVema9 = ta.ema(request.security("TRV", "1", close), 9)
TRVema = ta.ema(request.security("TRV", "1", close), 20)
TRVVWap = ta.vwap(request.security("TRV", "1", close))
TRV = (request.security("TRV", "1", close))
UNHema9 = ta.ema(request.security("UNH", "1", close), 9)
UNHema = ta.ema(request.security("UNH", "1", close), 20)
UNHVWap = ta.vwap(request.security("UNH", "1", close))
UNH = (request.security("UNH", "1", close))
CRMema9 = ta.ema(request.security("CRM", "1", close), 9)
CRMema = ta.ema(request.security("CRM", "1", close), 20)
CRMVWap = ta.vwap(request.security("CRM", "1", close))
CRM = (request.security("CRM", "1", close))
VZema9 = ta.ema(request.security("VZ", "1", close), 9)
VZema = ta.ema(request.security("VZ", "1", close), 20)
VZVWap = ta.vwap(request.security("VZ", "1", close))
VZ = (request.security("VZ", "1", close))
Vema9 = ta.ema(request.security("V", "1", close), 9)
Vema = ta.ema(request.security("V", "1", close), 20)
VVWap = ta.vwap(request.security("V", "1", close))
V = (request.security("V", "1", close))
WBAema9 = ta.ema(request.security("WBA", "1", close), 9)
WBAema = ta.ema(request.security("WBA", "1", close), 20)
WBAVWap = ta.vwap(request.security("WBA", "1", close))
WBA = (request.security("WBA", "1", close))
WMTema9 = ta.ema(request.security("WMT", "1", close), 9)
WMTema = ta.ema(request.security("WMT", "1", close), 20)
WMTVWap = ta.vwap(request.security("WMT", "1", close))
WMT = (request.security("WMT", "1", close))
DISema9 = ta.ema(request.security("DIS", "1", close), 9)
DISema = ta.ema(request.security("DIS", "1", close), 20)
DISVWap = ta.vwap(request.security("DIS", "1", close))
DIS = (request.security("DIS", "1", close))
DOWema9 = ta.ema(request.security("DOW", "1", close), 9)
DOWema = ta.ema(request.security("DOW", "1", close), 20)
DOWVWap = ta.vwap(request.security("DOW", "1", close))
DOW = (request.security("DOW", "1", close))
MCDema9 = ta.ema(request.security("MCD", "1", close), 9)
MCDema = ta.ema(request.security("MCD", "1", close), 20)
MCDVWap = ta.vwap(request.security("MCD", "1", close))
MCD = (request.security("MCD", "1", close))
//STOCK GREATER THAN VWAP = BULL
//SET MAX VALUE OF BULLS TO 1
//SET MIN VALUE OF BULLS TO 0
//STOCK AXP || STOCK NUMBER 0
//STOCK GREATER THAN VWAP = BULLISH
float AXPB= 0
isabove = (AXP > AXPVwap)
if isabove
AXPB := 3.155847
else
AXPB := 0
//STOCK NUMBER 0
//BEARS
float AXPb = 0
isbelow = (AXP < AXPVwap)
if isbelow
AXPb := 3.155847
else
AXPb := 0
//STOCK AXP || STOCK NUMBER 0
//EMA CALCULATION
float AXPE= 0
above0 = (AXP > AXPema)
if above0
AXPE := 3.155847
else
AXPE := 0
//STOCK NUMBER 0
//BEARS EMA CALCULATION
float AXPe = 0
below0 = (AXP < AXPema)
if below0
AXPe := 3.155847
else
AXPe := 0
//STOCK AXP || STOCK NUMBER 0
//EMA CALCULATION 9
float AXPEE= 0
above00 = (AXP > AXPema9)
if above00
AXPEE := 3.155847
else
AXPEE := 0
//STOCK NUMBER 0
//BEARS EMA 9 CALCULATION
float AXPee = 0
below00 = (AXP < AXPema9)
if below00
AXPee := 3.155847
else
AXPee := 0
//STOCK AMGN || STOCK NUMBER 1
//STOCK GREATER THAN VWAP = BULLISH
float AMGNB= 0
isabove1 = (AMGN > AMGNVwap)
if isabove1
AMGNB := 4.961912
else
AMGNB := 0
//STOCK NUMBER 1
//BEARS
float AMGNb = 0
isbelow1 = (AMGN < AMGNVwap)
if isbelow1
AMGNb := 4.961912
else
AMGNb := 0
//STOCK AMGN || STOCK NUMBER 1
//EMA CALCULATION
float AMGNE= 0
above1 = (AMGN > AMGNema)
if above1
AMGNE := 4.961912
else
AMGNE := 0
//STOCK NUMBER 1
//BEARS EMA CALCULATION
float AMGNe = 0
below1 = (AMGN < AMGNema)
if below1
AMGNe := 4.961912
else
AMGNe := 0
//STOCK AMGN || STOCK NUMBER 1
//EMA 9 CALCULATION
float AMGNEE= 0
above01 = (AMGN > AMGNema9)
if above01
AMGNEE := 4.961912
else
AMGNEE := 0
//STOCK NUMBER 1
//BEARS EMA CALCULATION
float AMGNee = 0
below01 = (AMGN < AMGNema9)
if below01
AMGNee := 4.961912
else
AMGNee := 0
//STOCK AAPL || STOCK NUMBER 2
//STOCK GREATER THAN VWAP = BULLISH
float AAPLB= 0
isabove2 = (AAPL > AAPLVwap)
if isabove2
AAPLB := 3.308142
else
AAPLB := 0
//STOCK NUMBER 2
//BEARS
float AAPLb = 0
isbelow2 = (AAPL < AAPLVwap)
if isbelow2
AAPLb := 3.308142
else
AAPLb := 0
//STOCK AAPL || STOCK NUMBER 2
//EMA CALCULATION
float AAPLE= 0
above2 = (AAPL > AAPLema)
if above2
AAPLE := 3.308142
else
AAPLE := 0
//STOCK NUMBER 2
//BEARS EMA CALCULATION
float AAPLe = 0
below2 = (AAPL < AAPLema)
if below2
AAPLe := 3.308142
else
AAPLe := 0
//STOCK AAPL || STOCK NUMBER 2
//EMA 9 CALCULATION
float AAPLEE= 0
above02 = (AAPL > AAPLema9)
if above02
AAPLEE := 3.308142
else
AAPLEE := 0
//STOCK NUMBER 2
//BEARS EMA 9 CALCULATION
float AAPLee = 0
below02 = (AAPL < AAPLema9)
if below02
AAPLee := 3.308142
else
AAPLee := 0
//STOCK BA || STOCK NUMBER 3
//STOCK GREATER THAN VWAP = BULLISH
float BAB= 0
isabove3 = (BA > BAVwap)
if isabove3
BAB := 3.328608
else
BAB := 0
//STOCK NUMBER 3
//BEARS
float BAb = 0
isbelow3 = (BA < BAVwap)
if isbelow3
BAb := 3.328608
else
BAb := 0
//STOCK BA || STOCK NUMBER 3
//EMA CALCULATION
float BAE= 0
above3 = (BA > BAema)
if above3
BAE := 3.328608
else
BAE := 0
//STOCK NUMBER 3
//BEARS EMA CALCULATION
float BAe = 0
below3 = (BA < BAema)
if below3
BAe := 3.328608
else
BAe := 0
//STOCK BA || STOCK NUMBER 3
//EMA 9 CALCULATION
float BAEE= 0
above03 = (BA > BAema9)
if above03
BAEE := 3.328608
else
BAEE := 0
//STOCK NUMBER 3
//BEARS EMA CALCULATION
float BAee = 0
below03 = (BA < BAema9)
if below03
BAee := 3.328608
else
BAee := 0
//STOCK CAT || STOCK NUMBER 4
//STOCK GREATER THAN VWAP = BULLISH
float CATB= 0
isabove4 = (CAT > CATVwap)
if isabove4
CATB := 3.728306
else
CATB := 0
//STOCK NUMBER 4
//BEARS
float CATb = 0
isbelow4 = (CAT < CATVwap)
if isbelow4
CATb := 3.728306
else
CATb := 0
//STOCK CAT || STOCK NUMBER 4
//EMA CALCULATION
float CATE= 0
above4 = (CAT > CATema)
if above4
CATE := 3.728306
else
CATE := 0
//STOCK NUMBER 4
//BEARS EMA CALCULATION
float CATe = 0
below4 = (CAT < CATema)
if below4
CATe := 3.728306
else
CATe := 0
//STOCK CAT || STOCK NUMBER 4
//EMA CALCULATION
float CATEE= 0
above04 = (CAT > CATema9)
if above04
CATEE := 3.728306
else
CATEE := 0
//STOCK NUMBER 4
//BEARS EMA CALCULATION
float CATee = 0
below04 = (CAT < CATema9)
if below04
CATee := 3.728306
else
CATee := 0
//STOCK CSCO || STOCK NUMBER 5
//STOCK GREATER THAN VWAP = BULLISH
float CSCOB= 0
isabove5 = (CSCO > CSCOVwap)
if isabove5
CSCOB := 0.903333
else
CSCOB := 0
//STOCK NUMBER 5
//BEARS
float CSCOb = 0
isbelow5 = (CSCO < CSCOVwap)
if isbelow5
CSCOb := 0.903333
else
CSCOb := 0
//STOCK CSCO || STOCK NUMBER 5
//EMA CALCULATION
float CSCOE= 0
above5 = (CSCO > CSCOema)
if above5
CSCOE := 0.903333
else
CSCOE := 0
//STOCK NUMBER 5
//BEARS EMA CALCULATION
float CSCOe = 0
below5 = (CSCO < CSCOema)
if below5
CSCOe := 0.903333
else
CSCOe := 0
//STOCK CSCO || STOCK NUMBER 5
//EMA 9 CALCULATION
float CSCOEE= 0
above05 = (CSCO > CSCOema9)
if above05
CSCOEE := 0.903333
else
CSCOEE := 0
//STOCK NUMBER 5
//BEARS EMA CALCULATION
float CSCOee = 0
below05 = (CSCO < CSCOema9)
if below05
CSCOee := 0.903333
else
CSCOee := 0
//STOCK CVX || STOCK NUMBER 6
//STOCK GREATER THAN VWAP = BULLISH
float CVXB= 0
isabove6 = (CVX > CVXVwap)
if isabove6
CVXB := 3.078195
else
CVXB := 0
//STOCK NUMBER 6
//BEARS
float CVXb = 0
isbelow6 = (CVX < CVXVwap)
if isbelow6
CVXb := 3.078195
else
CVXb := 0
//STOCK CVX || STOCK NUMBER 6
//EMA CALCULATION
float CVXE= 0
above6 = (CVX > CVXema)
if above6
CVXE := 3.078195
else
CVXE := 0
//STOCK NUMBER 6
//BEARS EMA CALCULATION
float CVXe = 0
below6 = (CVX < CVXema)
if below6
CVXe := 3.078195
else
CVXe := 0
//STOCK CVX || STOCK NUMBER 6
//EMA 9 CALCULATION
float CVXEE= 0
above06 = (CVX > CVXema9)
if above06
CVXEE := 3.078195
else
CVXEE := 0
//STOCK NUMBER 6
//BEARS EMA CALCULATION
float CVXee = 0
below06 = (CVX < CVXema9)
if below06
CVXee := 3.078195
else
CVXee := 0
//STOCK GS || STOCK NUMBER 7
//STOCK GREATER THAN VWAP = BULLISH
float GSB= 0
isabove7 = (GS > GSWap)
if isabove7
GSB := 6.715406
else
GSB := 0
//STOCK NUMBER 7
//BEARS
float GSb = 0
isbelow7 = (GS < GSWap)
if isbelow7
GSb := 6.715406
else
GSb := 0
//STOCK GS || STOCK NUMBER 7
//EMA CALCULATION
float GSE= 0
above7 = (GS > GSema)
if above7
GSE := 6.715406
else
GSE := 0
//STOCK NUMBER 7
//BEARS EMA CALCULATION
float GSe = 0
below7 = (GS < GSema)
if below7
GSe := 6.715406
else
GSe := 0
//STOCK GS || STOCK NUMBER 7
//EMA CALCULATION
float GSEE= 0
above07 = (GS > GSema9)
if above07
GSEE := 6.715406
else
GSEE := 0
//STOCK NUMBER 7
//BEARS EMA CALCULATION
float GSee = 0
below07 = (GS < GSema9)
if below07
GSee := 6.715406
else
GSee := 0
//STOCK HD || STOCK NUMBER 8
//STOCK GREATER THAN VWAP = BULLISH
float HDB= 0
isabove8 = (HD > HDVWap)
if isabove8
HDB := 6.259726
else
HDB := 0
//STOCK NUMBER 8
//BEARS
float HDb = 0
isbelow8 = (HD < HDVWap)
if isbelow8
HDb := 6.259726
else
HDb := 0
//STOCK HD || STOCK NUMBER 8
//EMA CALCULATION
float HDE= 0
above8 = (HD > HDema)
if above8
HDE := 6.259726
else
HDE := 0
//STOCK NUMBER 8
//BEARS EMA CALCULATION
float HDe = 0
below8 = (HD < HDema)
if below8
HDe := 6.259726
else
HDe := 0
//STOCK HD || STOCK NUMBER 8
//EMA CALCULATION
float HDEE= 0
above08 = (HD > HDema9)
if above08
HDEE := 6.259726
else
HDEE := 0
//STOCK NUMBER 8
//BEARS EMA CALCULATION
float HDee = 0
below08 = (HD < HDema9)
if below08
HDee := 6.259726
else
HDee := 0
//STOCK HON || STOCK NUMBER 9
//STOCK GREATER THAN VWAP = BULLISH
float HONB= 0
isabove9 = (HON > HONVWap)
if isabove9
HONB := 3.892038
else
HONB := 0
//STOCK NUMBER 9
//BEARS
float HONb = 0
isbelow9 = (HON < HONVWap)
if isbelow9
HONb := 3.892038
else
HONb := 0
//STOCK HON || STOCK NUMBER 9
//EMA CALCULATION
float HONE= 0
above9 = (HON > HONema)
if above9
HONE := 3.892038
else
HONE := 0
//STOCK NUMBER 9
//BEARS EMA CALCULATION
float HONe = 0
below9 = (HON < HONema)
if below9
HONe := 3.892038
else
HONe := 0
//STOCK HON || STOCK NUMBER 9
//EMA CALCULATION
float HONEE= 0
above09 = (HON > HONema9)
if above09
HONEE := 3.892038
else
HONEE := 0
//STOCK NUMBER 9
//BEARS EMA CALCULATION
float HONee = 0
below09 = (HON < HONema9)
if below09
HONee := 3.892038
else
HONee := 0
//STOCK IBM || STOCK NUMBER 10
//STOCK GREATER THAN VWAP = BULLISH
float IBMB= 0
isabove10 = (IBM > IBMVWap)
if isabove10
IBMB := 2.66084
else
IBMB := 0
//STOCK NUMBER 10
//BEARS
float IBMb = 0
isbelow10 = (IBM < IBMVWap)
if isbelow10
IBMb := 2.66084
else
IBMb := 0
//STOCK IBM || STOCK NUMBER 10
//EMA CALCULATION
float IBME= 0
above10 = (IBM > IBMema)
if above10
IBME := 2.66084
else
IBME := 0
//STOCK NUMBER 10
//BEARS EMA CALCULATION
float IBMe = 0
below10 = (IBM < IBMema)
if below10
IBMe := 2.66084
else
IBMe := 0
//STOCK IBM || STOCK NUMBER 10
//EMA CALCULATION
float IBMEE= 0
above010 = (IBM > IBMema9)
if above010
IBMEE := 2.66084
else
IBMEE := 0
//STOCK NUMBER 10
//BEARS EMA CALCULATION
float IBMee = 0
below010 = (IBM < IBMema9)
if below010
IBMee := 2.66084
else
IBMee := 0
//STOCK INTC || STOCK NUMBER 11
//STOCK GREATER THAN VWAP = BULLISH
float INTCB= 0
isabove11 = (INTC > INTCVWap)
if isabove11
INTCB := 0.709905
else
INTCB := 0
//STOCK NUMBER 11
//BEARS
float INTCb = 0
isbelow11 = (INTC < INTCVWap)
if isbelow11
INTCb := 0.709905
else
INTCb := 0
//STOCK INTC || STOCK NUMBER 11
//EMA CALCULATION
float INTCE= 0
above11 = (INTC > INTCema)
if above11
INTCE := 0.709905
else
INTCE := 0
//STOCK NUMBER 11
//BEARS EMA CALCULATION
float INTCe = 0
below11 = (INTC < INTCema)
if below11
INTCe := 0.709905
else
INTCe := 0
//STOCK INTC || STOCK NUMBER 11
//EMA CALCULATION
float INTCEE= 0
above011 = (INTC > INTCema9)
if above011
INTCEE := 0.709905
else
INTCEE := 0
//STOCK NUMBER 11
//BEARS EMA CALCULATION
float INTCee = 0
below011 = (INTC < INTCema9)
if below011
INTCee := 0.709905
else
INTCee := 0
//STOCK JNJ || STOCK NUMBER 12
//STOCK GREATER THAN VWAP = BULLISH
float JNJB= 0
isabove12 = (JNJ > JNJVWap)
if isabove12
JNJB := 3.415089
else
JNJB := 0
//STOCK NUMBER 12
//BEARS
float JNJb = 0
isbelow12 = (JNJ < JNJVWap)
if isbelow12
JNJb := 3.415089
else
JNJb := 0
//STOCK JNJ || STOCK NUMBER 12
//EMA CALCULATION
float JNJE= 0
above12 = (JNJ > JNJema)
if above12
JNJE := 3.415089
else
JNJE := 0
//STOCK NUMBER 12
//BEARS EMA CALCULATION
float JNJe = 0
below12 = (JNJ < JNJema)
if below12
JNJe := 3.415089
else
JNJe := 0
//STOCK JNJ || STOCK NUMBER 12
//EMA CALCULATION
float JNJEE= 0
above012 = (JNJ > JNJema9)
if above12
JNJEE := 3.415089
else
JNJEE := 0
//STOCK NUMBER 12
//BEARS EMA CALCULATION
float JNJee = 0
below012 = (JNJ < JNJema9)
if below012
JNJee := 3.415089
else
JNJee := 0
//STOCK KO || STOCK NUMBER 13
//STOCK GREATER THAN VWAP = BULLISH
float KOB= 0
isabove13 = (KO > KOVWap)
if isabove13
KOB := 1.263503
else
KOB := 0
//STOCK NUMBER 13
//BEARS
float KOb = 0
isbelow13 = (KO < KOVWap)
if isbelow13
KOb := 1.263503
else
KOb := 0
//STOCK KO || STOCK NUMBER 13
//EMA CALCULATION
float KOE= 0
above13 = (KO > KOema)
if above13
KOE := 1.263503
else
KOE := 0
//STOCK NUMBER 13
//BEARS EMA CALCULATION
float KOe = 0
below13 = (KO < KOema)
if below13
KOe := 1.263503
else
KOe := 0
//STOCK KO || STOCK NUMBER 13
//EMA CALCULATION
float KOEE= 0
above013 = (KO > KOema9)
if above013
KOEE := 1.263503
else
KOEE := 0
//STOCK NUMBER 13
//BEARS EMA CALCULATION
float KOee = 0
below013 = (KO < KOema9)
if below013
KOee := 1.263503
else
KOee := 0
//STOCK JPM || STOCK NUMBER 14
//STOCK GREATER THAN VWAP = BULLISH
float JPMB= 0
isabove14 = (JPM > JPMVWap)
if isabove14
JPMB := 2.29445
else
JPMB := 0
//STOCK NUMBER 14
//BEARS
float JPMb = 0
isbelow14 = (JPM < JPMVWap)
if isbelow14
JPMb := 2.29445
else
JPMb := 0
//STOCK JPM || STOCK NUMBER 14
//EMA CALCULATION
float JPME= 0
above14 = (JPM > JPMema)
if above14
JPME := 2.29445
else
JPME := 0
//STOCK NUMBER 14
//BEARS EMA CALCULATION
float JPMe = 0
below14 = (JPM < JPMema)
if below14
JPMe := 2.29445
else
JPMe := 0
//STOCK JPM || STOCK NUMBER 14
//EMA CALCULATION
float JPMEE= 0
above014 = (JPM > JPMema9)
if above014
JPMEE := 2.29445
else
JPMEE := 0
//STOCK NUMBER 14
//BEARS EMA CALCULATION
float JPMee = 0
below014 = (JPM < JPMema9)
if below014
JPMee := 2.29445
else
JPMee := 0
//STOCK MMM || STOCK NUMBER 15
//STOCK GREATER THAN VWAP = BULLISH
float MMMB= 0
isabove15 = (MMM > MMMVWap)
if isabove15
MMMB := 2.979274
else
MMMB := 0
//STOCK NUMBER 15
//BEARS
float MMMb = 0
isbelow15 = (MMM < MMMVWap)
if isbelow15
MMMb := 2.979274
else
MMMb := 0
//STOCK MMM || STOCK NUMBER 15
//EMA CALCULATION
float MMME= 0
above15 = (MMM > MMMema)
if above15
MMME := 2.979274
else
MMME := 0
//STOCK NUMBER 15
//BEARS EMA CALCULATION
float MMMe = 0
below15 = (MMM < MMMema)
if below15
MMMe := 2.979274
else
MMMe := 0
//STOCK MMM || STOCK NUMBER 15
//EMA CALCULATION
float MMMEE= 0
above015 = (MMM > MMMema9)
if above015
MMMEE := 2.979274
else
MMMEE := 0
//STOCK NUMBER 15
//BEARS EMA CALCULATION
float MMMee = 0
below015 = (MMM < MMMema9)
if below015
MMMee := 2.979274
else
MMMee := 0
//STOCK MRK || STOCK NUMBER 16
//STOCK GREATER THAN VWAP = BULLISH
float MRKB= 0
isabove16 = (MRK > MRKVWap)
if isabove16
MRKB := 1.775565
else
MRKB := 0
//STOCK NUMBER 16
//BEARS
float MRKb = 0
isbelow16 = (MRK < MRKVWap)
if isbelow16
MRKb := 1.775565
else
MRKb := 0
//STOCK MRK || STOCK NUMBER 16
//EMA CALCULATION
float MRKE= 0
above16 = (MRK > MRKema)
if above16
MRKE := 1.775565
else
MRKE := 0
//STOCK NUMBER 16
//BEARS EMA CALCULATION
float MRKe = 0
below16 = (MRK < MRKema)
if below16
MRKe := 1.775565
else
MRKe := 0
//STOCK MRK || STOCK NUMBER 16
//EMA CALCULATION
float MRKEE= 0
above016 = (MRK > MRKema9)
if above016
MRKEE := 1.775565
else
MRKEE := 0
//STOCK NUMBER 16
//BEARS EMA CALCULATION
float MRKee = 0
below016 = (MRK < MRKema9)
if below016
MRKee := 1.775565
else
MRKee := 0
//STOCK MSFT || STOCK NUMBER 17
//STOCK GREATER THAN VWAP = BULLISH
float MSFTB= 0
isabove17 = (MSFT > MSFTVWap)
if isabove17
MSFTB := 5.624664
else
MSFTB := 0
//STOCK NUMBER 17
//BEARS
float MSFTb = 0
isbelow17 = (MSFT < MSFTVWap)
if isbelow17
MSFTb := 5.624664
else
MSFTb := 0
//STOCK MSFT || STOCK NUMBER 17
//EMA CALCULATION
float MSFTE= 0
above17 = (MSFT > MSFTema)
if above17
MSFTE := 5.624664
else
MSFTE := 0
//STOCK NUMBER 17
//BEARS EMA CALCULATION
float MSFTe = 0
below17 = (MSFT < MSFTema)
if below17
MSFTe := 5.624664
else
MSFTe := 0
//STOCK MSFT || STOCK NUMBER 17
//EMA CALCULATION
float MSFTEE= 0
above017 = (MSFT > MSFTema9)
if above017
MSFTEE := 5.624664
else
MSFTEE := 0
//STOCK NUMBER 17
//BEARS EMA CALCULATION
float MSFTee = 0
below017 = (MSFT < MSFTema9)
if below017
MSFTee := 5.624664
else
MSFTee := 0
//STOCK NKE || STOCK NUMBER 18
//STOCK GREATER THAN VWAP = BULLISH
float NKEB= 0
isabove18 = (NKE > NKEVWap)
if isabove18
NKEB := 2.287427
else
NKEB := 0
//STOCK NUMBER 18
//BEARS
float NKEb = 0
isbelow18 = (NKE < NKEVWap)
if isbelow18
NKEb := 2.287427
else
NKEb := 0
//STOCK NKE || STOCK NUMBER 18
//EMA CALCULATION
float NKEE= 0
above18 = (NKE > NKEema)
if above18
NKEE := 2.287427
else
NKEE := 0
//STOCK NUMBER 18
//BEARS EMA CALCULATION
float NKEe = 0
below18 = (NKE < NKEema)
if below18
NKEe := 2.287427
else
NKEe := 0
//STOCK NKE || STOCK NUMBER 18
//EMA CALCULATION
float NKEEE= 0
above018 = (NKE > NKEema9)
if above018
NKEEE := 2.287427
else
NKEEE := 0
//STOCK NUMBER 18
//BEARS EMA CALCULATION
float NKEee = 0
below018 = (NKE < NKEema9)
if below018
NKEee := 2.287427
else
NKEee := 0
//STOCK PG || STOCK NUMBER 19
//STOCK GREATER THAN VWAP = BULLISH
float PGB= 0
isabove19 = (PG > PGVWap)
if isabove19
PGB := 2.914865
else
PGB := 0
//STOCK NUMBER 19
//BEARS
float PGb = 0
isbelow19 = (PG < PGVWap)
if isbelow19
PGb := 2.914865
else
PGb := 0
//STOCK PG || STOCK NUMBER 19
//EMA CALCULATION
float PGE= 0
above19 = (PG > PGema)
if above19
PGE := 2.914865
else
PGE := 0
//STOCK NUMBER 19
//BEARS EMA CALCULATION
float PGe = 0
below19 = (PG < PGema)
if below19
PGe := 2.914865
else
PGe := 0
//STOCK PG || STOCK NUMBER 19
//EMA CALCULATION
float PGEE= 0
above019 = (PG > PGema9)
if above019
PGEE := 2.914865
else
PGEE := 0
//STOCK NUMBER 19
//BEARS EMA CALCULATION
float PGee = 0
below019 = (PG < PGema9)
if below019
PGee := 2.914865
else
PGee := 0
//STOCK TRV || STOCK NUMBER 20
//STOCK GREATER THAN VWAP = BULLISH
float TRVB= 0
isabove20 = (TRV > TRVVWap)
if isabove20
TRVB := 3.210023
else
TRVB := 0
//STOCK NUMBER 20
//BEARS
float TRVb = 0
isbelow20 = (TRV < TRVVWap)
if isbelow20
TRVb := 3.210023
else
TRVb := 0
//STOCK TRV || STOCK NUMBER 20
//EMA CALCULATION
float TRVE= 0
above20 = (TRV > TRVema)
if above20
TRVE := 3.210023
else
TRVE := 0
//STOCK NUMBER 20
//BEARS EMA CALCULATION
float TRVe = 0
below20 = (TRV < TRVema)
if below20
TRVe := 3.210023
else
TRVe := 0
//STOCK TRV || STOCK NUMBER 20
//EMA CALCULATION
float TRVEE= 0
above020 = (TRV > TRVema9)
if above020
TRVEE := 3.210023
else
TRVEE := 0
//STOCK NUMBER 20
//BEARS EMA CALCULATION
float TRVee = 0
below020 = (TRV < TRVema9)
if below020
TRVee := 3.210023
else
TRVee := 0
//STOCK UNH || STOCK NUMBER 21
//STOCK GREATER THAN VWAP = BULLISH
float UNHB= 0
isabove21 = (UNH > UNHVWap)
if isabove21
UNHB := 10.766961
else
UNHB := 0
//STOCK NUMBER 21
//BEARS
float UNHb = 0
isbelow21 = (UNH < UNHVWap)
if isbelow21
UNHb := 1
else
UNHb := 0
//STOCK UNH || STOCK NUMBER 21
//EMA CALCULATION
float UNHE= 0
above21 = (UNH > UNHema)
if above21
UNHE := 10.766961
else
UNHE := 0
//STOCK NUMBER 21
//BEARS EMA CALCULATION
float UNHe = 0
below21 = (UNH < UNHema)
if below21
UNHe := 10.766961
else
UNHe := 0
//STOCK UNH || STOCK NUMBER 21
//EMA CALCULATION
float UNHEE= 0
above021 = (UNH > UNHema9)
if above021
UNHEE := 10.766961
else
UNHEE := 0
//STOCK NUMBER 21
//BEARS EMA CALCULATION
float UNHee = 0
below021 = (UNH < UNHema9)
if below021
UNHee := 10.766961
else
UNHee := 0
//STOCK CRM || STOCK NUMBER 22
//STOCK GREATER THAN VWAP = BULLISH
float CRMB= 0
isabove22 = (CRM > CRMVWap)
if isabove22
CRMB := 3.807363
else
CRMB := 0
//STOCK NUMBER 22
//BEARS
float CRMb = 0
isbelow22 = (CRM < CRMVWap)
if isbelow22
CRMb := 3.807363
else
CRMb := 0
//STOCK CRM || STOCK NUMBER 22
//EMA CALCULATION
float CRME= 0
above22 = (CRM > CRMema)
if above22
CRME := 3.807363
else
CRME := 0
//STOCK NUMBER 22
//BEARS EMA CALCULATION
float CRMe = 0
below22 = (CRM < CRMema)
if below22
CRMe := 3.807363
else
CRMe := 0
//STOCK CRM || STOCK NUMBER 22
//EMA CALCULATION
float CRMEE= 0
above022 = (CRM > CRMema9)
if above022
CRMEE := 3.807363
else
CRMEE := 0
//STOCK NUMBER 22
//BEARS EMA CALCULATION
float CRMee = 0
below022 = (CRM < CRMema9)
if below022
CRMee := 3.807363
else
CRMee := 0
//STOCK VZ || STOCK NUMBER 23
//STOCK GREATER THAN VWAP = BULLISH
float VZB= 0
isabove23 = (VZ > VZVWap)
if isabove23
VZB := 0.893702
else
VZB := 0
//STOCK NUMBER 23
//BEARS
float VZb = 0
isbelow23 = (VZ < VZVWap)
if isbelow23
VZb := 0.893702
else
VZb := 0
//STOCK VZ || STOCK NUMBER 23
//EMA CALCULATION
float VZE= 0
above23 = (VZ > VZema)
if above23
VZE := 0.893702
else
VZE := 0
//STOCK NUMBER 23
//BEARS EMA CALCULATION
float VZe = 0
below23 = (VZ < VZema)
if below23
VZe := 0.893702
else
VZe := 0
//STOCK VZ || STOCK NUMBER 23
//EMA CALCULATION
float VZEE= 0
above023 = (VZ > VZema9)
if above023
VZEE := 0.893702
else
VZEE := 0
//STOCK NUMBER 23
//BEARS EMA CALCULATION
float VZee = 0
below023 = (VZ < VZema9)
if below023
VZee := 0.893702
else
VZee := 0
//STOCK V || STOCK NUMBER 24
//STOCK GREATER THAN VWAP = BULLISH
float VB= 0
isabove24 = (V > VVWap)
if isabove24
VB := 4.280299
else
VB := 0
//STOCK NUMBER 24
//BEARS
float Vb = 0
isbelow24 = (V < VVWap)
if isbelow24
Vb := 4.280299
else
Vb := 0
//STOCK V || STOCK NUMBER 24
//EMA CALCULATION
float VE= 0
above24 = (V > Vema)
if above24
VE := 4.280299
else
VE := 0
//STOCK NUMBER 24
//BEARS EMA CALCULATION
float Ve = 0
below24 = (V < Vema)
if below24
Ve := 4.280299
else
Ve := 0
//STOCK V || STOCK NUMBER 24
//EMA CALCULATION
float VEE= 0
above024 = (V > Vema9)
if above024
VEE := 4.280299
else
VEE := 0
//STOCK NUMBER 24
//BEARS EMA CALCULATION
float Vee = 0
below024 = (V < Vema9)
if below024
Vee := 4.280299
else
Vee := 0
//STOCK WBA || STOCK NUMBER 25
//STOCK GREATER THAN VWAP = BULLISH
float WBAB= 0
isabove25 = (WBA > WBAVWap)
if isabove25
WBAB := 0.792172
else
WBAB := 0
//STOCK NUMBER 25
//BEARS
float WBAb = 0
isbelow25 = (WBA < WBAVWap)
if isbelow25
WBAb := 0.792172
else
WBAb := 0
//STOCK WBA || STOCK NUMBER 25
//EMA CALCULATION
float WBAE= 0
above25 = (WBA > WBAema)
if above25
WBAE := 0.792172
else
WBAE := 0
//STOCK NUMBER 25
//BEARS EMA CALCULATION
float WBAe = 0
below25 = (WBA < WBAema)
if below25
WBAe := 0.792172
else
WBAe := 0
//STOCK WBA || STOCK NUMBER 25
//EMA CALCULATION
float WBAEE= 0
above025 = (WBA > WBAema9)
if above025
WBAEE := 0.792172
else
WBAEE := 0
//STOCK NUMBER 25
//BEARS EMA CALCULATION
float WBAee = 0
below025 = (WBA < WBAema9)
if below025
WBAee := 0.792172
else
WBAee := 0
//STOCK WMT || STOCK NUMBER 26
//STOCK GREATER THAN VWAP = BULLISH
float WMTB= 0
isabove26 = (WMT > WMTVWap)
if isabove26
WMTB := 2.560514
else
WMTB := 0
//STOCK NUMBER 26
//BEARS
float WMTb = 0
isbelow26 = (WMT < WMTVWap)
if isbelow26
WMTb := 2.560514
else
WMTb := 0
//STOCK WMT || STOCK NUMBER 26
//EMA CALCULATION
float WMTE= 0
above26 = (WMT > WMTema)
if above26
WMTE := 2.560514
else
WMTE := 0
//STOCK NUMBER 26
//BEARS EMA CALCULATION
float WMTe = 0
below26 = (WMT < WMTema)
if below26
WMTe := 2.560514
else
WMTe := 0
//STOCK WMT || STOCK NUMBER 26
//EMA CALCULATION
float WMTEE= 0
above026 = (WMT > WMTema9)
if above026
WMTEE := 2.560514
else
WMTEE := 0
//STOCK NUMBER 26
//BEARS EMA CALCULATION
float WMTee = 0
below026 = (WMT < WMTema9)
if below026
WMTee := 2.560514
else
WMTee := 0
//STOCK DIS || STOCK NUMBER 27
//STOCK GREATER THAN VWAP = BULLISH
float DISB= 0
isabove27 = (DIS > DISVWap)
if isabove27
DISB := 2.189309
else
DISB := 0
//STOCK NUMBER 27
//BEARS
float DISb = 0
isbelow27 = (DIS < DISVWap)
if isbelow27
DISb := 2.189309
else
DISb := 0
//STOCK DIS || STOCK NUMBER 27
//EMA CALCULATION
float DISE= 0
above27 = (DIS > DISema)
if above27
DISE := 2.189309
else
DISE := 0
//STOCK NUMBER 27
//BEARS EMA CALCULATION
float DISe = 0
below27 = (DIS < DISema)
if below27
DISe := 2.189309
else
DISe := 0
//STOCK DIS || STOCK NUMBER 27
//EMA CALCULATION
float DISEE= 0
above027 = (DIS > DISema9)
if above027
DISEE := 2.189309
else
DISEE := 0
//STOCK NUMBER 27
//BEARS EMA CALCULATION
float DISee = 0
below027 = (DIS < DISema9)
if below027
DISee := 2.189309
else
DISee := 0
//STOCK DOW || STOCK NUMBER 28
//STOCK GREATER THAN VWAP = BULLISH
float DOWB= 0
isabove28 = (DOW > DOWVWap)
if isabove28
DOWB := 1.046403
else
DOWB := 0
//STOCK NUMBER 28
//BEARS
float DOWb = 0
isbelow28 = (DOW < DOWVWap)
if isbelow28
DOWb := 1.046403
else
DOWb := 0
//STOCK DOW || STOCK NUMBER 28
//EMA CALCULATION
float DOWE= 0
above28 = (DOW > DOWema)
if above28
DOWE := 1.046403
else
DOWE := 0
//STOCK NUMBER 28
//BEARS EMA CALCULATION
float DOWe = 0
below28 = (DOW < DOWema)
if below28
DOWe := 1.046403
else
DOWe := 0
//STOCK DOW || STOCK NUMBER 28
//EMA CALCULATION
float DOWEE= 0
above028 = (DOW > DOWema9)
if above028
DOWEE := 1.046403
else
DOWEE := 0
//STOCK NUMBER 28
//BEARS EMA CALCULATION
float DOWee = 0
below028 = (DOW < DOWema9)
if below028
DOWee := 1.046403
else
DOWee := 0
//STOCK MCD || STOCK NUMBER 29
//STOCK GREATER THAN VWAP = BULLISH
float MCDB= 0
isabove29 = (MCD > MCDVWap)
if isabove29
MCDB := 5.152731
else
MCDB := 0
//STOCK NUMBER 29
//BEARS
float MCDb = 0
isbelow29 = (MCD < MCDVWap)
if isbelow29
MCDb := 5.152731
else
MCDb := 0
//STOCK MCD || STOCK NUMBER 29
//EMA CALCULATION
float MCDE= 0
above29 = (MCD > MCDema)
if above29
MCDE := 5.152731
else
MCDE := 0
//STOCK NUMBER 29
//BEARS EMA CALCULATION
float MCDe = 0
below29 = (MCD < MCDema)
if below29
MCDe := 5.152731
else
MCDe := 0
//STOCK MCD || STOCK NUMBER 29
//EMA CALCULATION
float MCDEE= 0
above029 = (MCD > MCDema9)
if above029
MCDEE := 5.152731
else
MCDEE := 0
//STOCK NUMBER 29
//BEARS EMA CALCULATION
float MCDee = 0
below029 = (MCD < MCDema9)
if below029
MCDee := 5.152731
else
MCDee := 0
//PLOTS ALL STOCKS ABOVE 20 EMA = BULLema20
//PLOTS ALL STOCKS BELOW 20 EMA = BEARema20
BULLema20 = AXPE + AMGNE + AAPLE + BAE + CATE + CSCOE + CVXE + GSE + HDE + HONE + IBME + INTCE + JNJE + KOE + JPME + MMME + MRKE + MSFTE + NKEE + PGE + TRVE + UNHE + CRME + VZE + VE + WBAE + WMTE + DISE + DOWE + MCDE
BEARema20 = AXPe + AMGNe + AAPLe + BAe + CATe + CSCOe + CVXe + GSe + HDe + HONe + IBMe + INTCe + JNJe + KOe + JPMe + MMMe + MRKe + MSFTe + NKEe + PGe + TRVe + UNHe + CRMe + VZe + Ve + WBAe + WMTe + DISe + DOWe + MCDe
//plot(BULLema20, "20ema.BULLS", color.blue,1)
//plot(BEARema20, "20ema.BEARS", color.orange,1)
//PLOT ALL STOCKS ABOVE 9 EMA = BULLema9
//PLOT ALL STOCKS BELOW 9 EMA = BULLema9
BULLema9 = AXPEE + AMGNEE + AAPLEE + BAEE + CATEE + CSCOEE + CVXEE + GSEE + HDEE + HONEE + IBMEE + INTCEE + JNJEE + KOEE + JPMEE + MMMEE + MRKEE + MSFTEE + NKEEE + PGEE + TRVEE + UNHEE + CRMEE + VZEE + VEE + WBAEE + WMTEE + DISEE + DOWEE + MCDEE
BEARema9 = AXPee + AMGNee + AAPLee + BAee + CATee + CSCOee + CVXee + GSee + HDee + HONee + IBMee + INTCee + JNJee + KOee + JPMee + MMMee + MRKee + MSFTee + NKEee + PGee + TRVee + UNHee + CRMee + VZee + Vee + WBAee + WMTee + DISee + DOWee + MCDee
//plot(BULLema9, "9ema.BULLS", color.blue,1)
//plot(BEARema9, "9ema.BEARS", color.orange,1)
//Total Bull EMA = All Bullish EMA Values /Divided/ by 2
TotalBULLema = (BULLema20 + BULLema9) / 2
plot(TotalBULLema, "ema.BULLS", color = color.rgb(131, 171, 230, 80),linewidth = 1, style = plot.style_area)
//Total Bear EMA = ALL Bearish EMA Values /Divided/ by 2
TotalBEARema = (BEARema20 + BEARema9) / 2
plot(TotalBEARema, "ema.BEARS", color = color.rgb(255, 0, 0, 95), linewidth = 1, style = plot.style_area)
//PLOTS ALL STOCKS ABOVE VWAP = TOTAL BULLS
//PLOTS ALL STOCKS BELOW VWAP = TOTAL BEARS
TOTALBULLS = AXPB + AMGNB + AAPLB + BAB + CATB + CSCOB + CVXB + GSB + HONB + HDB + IBMB + INTCB + JNJB + KOB + JPMB + MMMB + MRKB + MSFTB + NKEB + PGB + TRVB + UNHB + CRMB + VZB + VB + WBAB + WMTB + DISB + DOWB + MCDB
TOTALBEARS = AXPb + AMGNb + AAPLb + BAb + CATb + CSCOb + CVXb + GSb + HONb + HDb + IBMb + INTCb + JNJb + KOb + JPMb + MMMb + MRKb + MSFTb + NKEb + PGb + TRVb + UNHb + CRMb + VZb + Vb + WBAb + WMTb + DISb + DOWb + MCDb
plot(TOTALBULLS, "Vwap.BULLS", color.green,3)
plot(TOTALBEARS, "Vwap.BEARS", color.red,3)
// Request SIMPLE ADVANCED/DECLINE DOW JONES
ADVDEC = request.security("ADVDEC.DJ", "1", close)
ADVDEC0 = ADVDEC * 1.666666666666666666666666666666666666666666667
ADVDEC1 = ADVDEC0 +50
//PLOT SIMPLE ADVANCED/ DECLINE DOW JONES
plot(ADVDEC1, "ADVDEC.DJ", color = color.rgb(0, 0, 0, 90), linewidth = 2)
//Horizontal Line at 30 = MAX BULL LINE
hline(100, "MAX", color.black, linestyle = hline.style_dashed, linewidth = 2)
//Horizontal Line at 30 = MAX BEAR LINE
hline(0, "MIN", color.black, linestyle = hline.style_dashed, linewidth = 2)
//Horizontal Line at 30 = Neutral
hline(60, "60Neutral", color.black, linestyle = hline.style_dashed, linewidth = 1)
hline(50, "50Neutral", color.black, linestyle = hline.style_dotted, linewidth = 1)
hline(40, "40Neutral", color.black, linestyle = hline.style_dashed, linewidth = 1)
|
Stoch/RSI with EMA50 Cross & HHLL | https://www.tradingview.com/script/mEulOGBe-Stoch-RSI-with-EMA50-Cross-HHLL/ | Degen_Crypto | https://www.tradingview.com/u/Degen_Crypto/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Demha_MCX
//@version=5
indicator("Oscillators", "RSI+SRSI+HHLL+EMA50Crosover", false)
//////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////Plotting RSI//////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
rsi = ta.rsi(close,14)
plot(rsi, color=color.white, title="RSI",linewidth=2)
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////Plotting SRSI/////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Input data to configure on chart
smoothK = input.int (defval=3, title = "Stochastic %K", minval=1,maxval=100, step=1)
smoothD = input.int (defval=3, title = "Stochastic %D", minval=1,maxval=100, step=1)
lengthRSI = input.int (defval=14, title = "RSI Length", minval=1, maxval=100,step=1)
lengthStoch = input.int (defval=14, title = "Stochastic Length",maxval=100, minval=1, step=1)
src4 = input(close, title="RSI Source")
// Calculate indicator
rsi1 = ta.rsi(src4, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
// Drawing - plot on chart
plot(k, color=color.blue,title = "%k")
plot(d, color=color.red,title = "%d")
h0 = hline(80, linestyle=hline.style_dotted,title = "Oscillator Upper Band")
h1 = hline(20, linestyle=hline.style_dotted,title = "Oscillator Lower Band")
fill(h0, h1, color.new(color.purple, 80),title = "Oscillator Background")
/////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////Plotting Crossover of EMA50 with CMP//////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
ema50CrossOver = ta.crossover(close,ta.ema(close,50))
ema50CrossUnder = ta.crossunder(close,ta.ema(close,50))
bgcolor(title="ema50_CrossOver",color= ema50CrossOver ? color.new(color.green,80) : na)
bgcolor(title="ema50_CrossUnder",color=ema50CrossUnder ? color.new(color.red,80) : na)
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////Plotting HH & LL////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// ||--- Fractal Recognition:
filterBW = input(false, title="filter Bill Williams Fractals:")
// ||--- Fractal Recognition Functions: ---------------------------------------------------------------||
isRegularFractal(mode) =>
ret = mode == 1 ? high[4] < high[3] and high[3] < high[2] and high[2] > high[1] and high[1] > high[0] : mode == -1 ? low[4] > low[3] and low[3] > low[2] and low[2] < low[1] and low[1] < low[0] : false
isBWFractal(mode) =>
ret = mode == 1 ? high[4] < high[2] and high[3] <= high[2] and high[2] >= high[1] and high[2] > high[0] : mode == -1 ? low[4] > low[2] and low[3] >= low[2] and low[2] <= low[1] and low[2] < low[0] : false
filteredtopf = filterBW ? isRegularFractal(1) : isBWFractal(1)
filteredbotf = filterBW ? isRegularFractal(-1) : isBWFractal(-1)
ShowHHLL = input(true)
higherhigh = filteredtopf == false ? false : (ta.valuewhen(filteredtopf == true, high[2], 1) < ta.valuewhen(filteredtopf == true, high[2], 0) and ta.valuewhen(filteredtopf == true, high[2], 2) < ta.valuewhen(filteredtopf == true, high[2], 0))
lowerhigh = filteredtopf == false ? false : (ta.valuewhen(filteredtopf == true, high[2], 1) > ta.valuewhen(filteredtopf == true, high[2], 0) and ta.valuewhen(filteredtopf == true, high[2], 2) > ta.valuewhen(filteredtopf == true, high[2], 0))
higherlow = filteredbotf == false ? false : (ta.valuewhen(filteredbotf == true, low[2], 1) < ta.valuewhen(filteredbotf == true, low[2], 0) and ta.valuewhen(filteredbotf == true, low[2], 2) < ta.valuewhen(filteredbotf == true, low[2], 0) )
lowerlow = filteredbotf == false ? false : (ta.valuewhen(filteredbotf == true, low[2], 1) > ta.valuewhen(filteredbotf == true, low[2], 0) and ta.valuewhen(filteredbotf == true, low[2], 2) > ta.valuewhen(filteredbotf == true, low[2], 0))
plotshape(ShowHHLL ? higherhigh : na, title='Higher High', style=shape.square, location=location.top, color=color.green, text="[HH]",textcolor=color.green, offset=-2)
plotshape(ShowHHLL ? higherlow : na, title='Higher Low', style=shape.circle, location=location.top, color=color.yellow, text="[HL]",textcolor=color.yellow, offset=-2)
plotshape(ShowHHLL ? lowerhigh : na, title='Lower High', style=shape.circle, location=location.bottom, color=color.yellow, text="[LH]",textcolor=color.yellow, offset=-2)
plotshape(ShowHHLL ? lowerlow : na, title='Lower Low', style=shape.square, location=location.bottom, color=color.red, text="[LL]",textcolor=color.red, offset=-2)
alertcondition(higherhigh, title='Higher High', message='{{ticker}} - Higher High on the {{interval}}')
alertcondition(lowerlow, title='Lower Low', message='{{ticker}} - Lower Low on the {{interval}}')
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////END OF FILE/////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
Moving Averages Proximity Oscillator [LuxAlgo] | https://www.tradingview.com/script/HGlMiFRz-Moving-Averages-Proximity-Oscillator-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,440 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ LuxAlgo
//@version=5
indicator("Moving Averages Proximity Oscillator [LuxAlgo]", "MAPO [LuxAlgo]")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
min = input.int(10, "Minimum Length"
, minval = 1)
max = input.int(100, "Maximum Length"
, minval = 1)
smooth = input.int(9
, minval = 1)
normalized = input(true)
src = input(close)
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
csum = ta.cum(src)
len = 0.
per = 0.
max_min = math.abs(src - (csum - csum[min]) / min)
for i = min to max
ma = (csum - csum[i])/i
per += src > ma ? 1 : 0
ae = math.abs(src - ma)
max_min := math.min(ae, max_min)
len := ae == max_min ? i : len
len := ta.sma(len, smooth)
per := ta.sma(per, smooth)
if normalized
len := (len - min) / (max - min + 1) * 100
per := per / (max - min + 1) * 100
else
per := per + min
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
var lvl = normalized ? 50 : (max + min + 1) / 2
var ob = normalized ? 80 : 0.8 * max + 0.2 * min
var os = normalized ? 20 : 0.8 * min + 0.2 * max
plot(per, "Price Above MA's"
, color = per > lvl ? color.teal : color.red
, transp = 50
, style = plot.style_columns
, histbase = lvl)
plot(len, "Proximity Index"
, color = #5b9cf6)
hline(ob)
hline(os)
//-----------------------------------------------------------------------------}
|
Real-Fast Fourier Transform of Price Oscillator [Loxx] | https://www.tradingview.com/script/ueFBjctp-Real-Fast-Fourier-Transform-of-Price-Oscillator-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 98 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Real-Fast Fourier Transform Oscillator [Loxx]",
shorttitle = "RFFTO [Loxx]",
overlay = false,
max_lines_count = 500)
greencolor = #2DD204
redcolor = #D2042D
//+-------------------------------------------------------------------------+
//| Real Fast Fourier Transform |
///+-------------------------------------------------------------------------+
//The algorithm performs a fast Fourier transform of a real
//function defined by n samples on the real axis.
//
//Depending on the passed parameters, it can be executed
//both direct and inverse conversion.
//
// Input parameters:
// tnn - Number of function values. Must be degree
// deuces. Algorithm does not validate
// passed value.
// a - array [0 .. nn-1] of Real
// Function values.
// InverseFFT
// - the direction of the transformation.
// True if reverse, False if direct.
//
// Output parameters:
// a - the result of the transformation.
//
// For more details, see description on the site:
// https://www.alglib.net/fasttransforms/fft.php
// https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.205.4523&rep=rep1&type=pdf
//+-------------------------------------------------------------------------+
_realFastFourierTransform(float[] a, int tnn, bool inversefft)=>
float twr = 0.
float twi = 0.
float twpr = 0.
float twpi = 0.
float twtemp = 0.
float ttheta = 0.
int i = 0
int i1 = 0
int i2 = 0
int i3 = 0
int i4 = 0
float c1 = 0.
float c2 = 0.
float h1r = 0.
float h1i = 0.
float h2r = 0.
float h2i = 0.
float wrs = 0.
float wis = 0.
int nn = 0
int n = 0
int mmax = 0
int m = 0
int j = 0
int istep = 0
int isign = 0
float wtemp = 0.
float wr = 0.
float wpr = 0.
float wpi = 0.
float wi = 0.
float theta = 0.
float tempr = 0.
float tempi = 0.
if (tnn != 1)
if (not inversefft)
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := -0.5
else
ttheta := 2.0 * math.pi / tnn
c1 := 0.5
c2 := 0.5
ttheta := -ttheta
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, c1 * (h1r + array.get(a, 1)))
array.set(a, 1, c1 * (h1r - array.get(a, 1)))
if (inversefft)
isign := -1
else
isign := 1
n := tnn
nn := tnn / 2
j := 1
for ii = 1 to nn
i := 2 * ii - 1
if (j > i)
tempr := array.get(a, j - 1)
tempi := array.get(a, j)
array.set(a, j - 1, array.get(a, i - 1))
array.set(a, j, array.get(a, i))
array.set(a, i - 1, tempr)
array.set(a, i, tempi)
m := n / 2
while (m >= 2 and j > m)
j := j - m
m := m / 2
j := j + m
mmax := 2
while (n > mmax)
istep := 2 * mmax
theta := 2.0 * math.pi / (isign * mmax)
wpr := -2.0 * math.pow(math.sin(0.5 * theta), 2)
wpi := math.sin(theta)
wr := 1.0
wi := 0.0
for ii = 1 to mmax / 2
m := 2 * ii - 1
for jj = 0 to (n - m) / istep
i := m + jj * istep
j := i + mmax
tempr := wr * array.get(a, j - 1) - wi * array.get(a, j)
tempi := wr * array.get(a, j) + wi * array.get(a, j - 1)
array.set(a, j - 1, array.get(a, i - 1) - tempr)
array.set(a, j, array.get(a, i) - tempi)
array.set(a, i - 1, array.get(a, i - 1) + tempr)
array.set(a, i, array.get(a, i) + tempi)
wtemp := wr
wr := wr * wpr - wi * wpi + wr
wi := wi * wpr + wtemp * wpi + wi
mmax := istep
if (inversefft)
for ix = 1 to 2 * nn
array.set(a, ix - 1, array.get(a, ix - 1) / nn)
if (not inversefft)
twpr := -2.0 * math.pow(math.sin(0.5 * ttheta), 2)
twpi := math.sin(ttheta)
twr := 1.0 + twpr
twi := twpi
for ix = 2 to tnn / 4 + 1
i1 := ix + ix - 2
i2 := i1 + 1
i3 := tnn + 1 - i2
i4 := i3 + 1
wrs := twr
wis := twi
h1r := c1 * (array.get(a, i1) + array.get(a, i3))
h1i := c1 * (array.get(a, i2) - array.get(a, i4))
h2r := -c2 * (array.get(a, i2) + array.get(a, i4))
h2i := c2 * (array.get(a, i1) - array.get(a, i3))
array.set(a, i1, h1r + wrs * h2r - wis * h2i)
array.set(a, i2, h1i + wrs * h2i + wis * h2r)
array.set(a, i3, h1r - wrs * h2r + wis * h2i)
array.set(a, i4, -h1i + wrs * h2i + wis * h2r)
twtemp := twr
twr := twr * twpr - twi * twpi + twr
twi := twi * twpr + twtemp * twpi + twi
h1r := array.get(a, 0)
array.set(a, 0, h1r + array.get(a, 1))
array.set(a, 1, h1r - array.get(a, 1))
a
//Normalize data
_InSigNormalize(float[] aa)=>
float sum_sqrt = 0.
int element_count = array.size(aa)
for i = 0 to element_count - 1
sum_sqrt += math.pow(array.get(aa, i), 2)
sum_sqrt := math.sqrt(sum_sqrt)
if (sum_sqrt != 0)
for i = 0 to element_count - 1
array.set(aa, i, array.get(aa, i) / sum_sqrt)
aa
src = input.source(open, "Source")
n = input.int(9, "Window Period")
Fmin1 = input.int(3, "Minimum Filter")
Fmax1 = input.int(21, "Maximum Filter")
barsback = input.int(30, "Last Bar", minval = 0)
Inverse = input.bool(true, "Add inverse step?")
int N = int(math.pow(2, n))
var aa = array.new<float>(N, 0.)
var pvlines = array.new_line(0)
countout = N >= 256 ? 250 : N
if barstate.isfirst
for i = 0 to countout - 1
array.push(pvlines, line.new(na, na, na, na))
if barstate.islast
for i = 0 to N - 1
array.set(aa, i, nz(src[i + barsback]))
_InSigNormalize(aa)
_realFastFourierTransform(aa, N, false)
N := array.size(aa)
Fmax1 := math.min(Fmax1, N - 1)
for i = 0 to N - 1
if i < Fmin1 or i > Fmax1
array.set(aa, i, 0.)
if (Inverse)
_realFastFourierTransform(aa, N, true)
xm = array.copy(aa)
skipper = N >= 2048 ? 8 : N >= 1024 ? 4 : N == 512 ? 2 : 1
int i = 0
int j = 0
while i < N and i < array.size(xm) - 2
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
colorout = i < array.size(xm) - 2 ? array.get(xm, i) > array.get(xm, i + skipper) ? greencolor : redcolor : na
line.set_xy1(pvline, bar_index - i - skipper - barsback, array.get(xm, i + skipper))
line.set_xy2(pvline, bar_index - i - barsback, array.get(xm, i))
line.set_color(pvline, colorout)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 2)
i += skipper
j += 1
plot(0, color = bar_index % 2 ? color.gray : na)
|
Price Pivots for NASDQ 100 Stocks | https://www.tradingview.com/script/Gxjb7lmg-Price-Pivots-for-NASDQ-100-Stocks/ | Arun_K_Bhaskar | https://www.tradingview.com/u/Arun_K_Bhaskar/ | 107 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Arun_K_Bhaskar
//@version=5
// Updated on 7 August 2022
// Included Equities: NASDQ 100 listed stocks as per the updated date.
// Formula Reference: Intrangle - Straddle / Strangle By Saravanan_Ragavan
// Source Link: https://in.tradingview.com/script/BWsF0S4k-Intrangle-Straddle-Strangle/
indicator(title="Price Pivots for NASDQ 100 Stocks", shorttitle="Price Pivots NASDQ 100", overlay=true)
////////////////////////////////////////////////////////// F&O Index & Equity Symbols
// Symbols of Strike Price Difference 0.25
sym_001_spd_0_25 = "GOOG"
sym_002_spd_0_25 = "GOOGL"
// Symbols of Strike Price Difference 0.5
sym_003_spd_0_5 = "CMCSA"
sym_004_spd_0_5 = "CSCO"
sym_005_spd_0_5 = "CSX"
sym_006_spd_0_5 = "INTC"
sym_007_spd_0_5 = "KHC"
sym_008_spd_0_5 = "LCID"
sym_009_spd_0_5 = "SIRI"
sym_010_spd_0_5 = "WBA"
// Symbols of Strike Price Difference 1
sym_011_spd_1 = "ABNB"
sym_012_spd_1 = "AMAT"
sym_013_spd_1 = "AMD"
sym_014_spd_1 = "AMZN"
sym_015_spd_1 = "ATVI"
sym_016_spd_1 = "AZN"
sym_017_spd_1 = "BIDU"
sym_018_spd_1 = "DDOG"
sym_019_spd_1 = "DOCU"
sym_020_spd_1 = "EA"
sym_021_spd_1 = "EBAY"
sym_022_spd_1 = "EXC"
sym_023_spd_1 = "FISV"
sym_024_spd_1 = "FTNT"
sym_025_spd_1 = "GILD"
sym_026_spd_1 = "JD"
sym_027_spd_1 = "KDP"
sym_028_spd_1 = "MCHP"
sym_029_spd_1 = "MDLZ"
sym_030_spd_1 = "MNST"
sym_031_spd_1 = "MRVL"
sym_032_spd_1 = "MTCH"
sym_033_spd_1 = "MU"
sym_034_spd_1 = "NTES"
sym_035_spd_1 = "OKTA"
sym_036_spd_1 = "PDD"
sym_037_spd_1 = "PYPL"
sym_038_spd_1 = "ROST"
sym_039_spd_1 = "SBUX"
sym_040_spd_1 = "SPLK"
sym_041_spd_1 = "SWKS"
sym_042_spd_1 = "TMUS"
sym_043_spd_1 = "ZM"
// Symbols of Strike Price Difference 2.5
sym_044_spd_2_5 = "AAPL"
sym_045_spd_2_5 = "ADBE"
sym_046_spd_2_5 = "ADI"
sym_047_spd_2_5 = "ADP"
sym_048_spd_2_5 = "ADSK"
sym_049_spd_2_5 = "AEP"
sym_050_spd_2_5 = "ALGN"
sym_051_spd_2_5 = "AMGN"
sym_052_spd_2_5 = "AVGO"
sym_053_spd_2_5 = "BIIB"
sym_054_spd_2_5 = "COST"
sym_055_spd_2_5 = "CRWD"
sym_056_spd_2_5 = "CTSH"
sym_057_spd_2_5 = "DLTR"
sym_058_spd_2_5 = "FAST"
sym_059_spd_2_5 = "HON"
sym_060_spd_2_5 = "ISRG"
sym_061_spd_2_5 = "MAR"
sym_062_spd_2_5 = "META"
sym_063_spd_2_5 = "MRNA"
sym_064_spd_2_5 = "MSFT"
sym_065_spd_2_5 = "NFLX"
sym_066_spd_2_5 = "NVDA"
sym_067_spd_2_5 = "NXPI"
sym_068_spd_2_5 = "PCAR"
sym_069_spd_2_5 = "PEP"
sym_070_spd_2_5 = "QCOM"
sym_071_spd_2_5 = "TEAM"
sym_072_spd_2_5 = "TXN"
sym_073_spd_2_5 = "VRTX"
sym_074_spd_2_5 = "WDAY"
sym_075_spd_2_5 = "ZS"
// Symbols of Strike Price Difference 5
sym_076_spd_5 = "ASML"
sym_077_spd_5 = "BKNG"
sym_078_spd_5 = "CDNS"
sym_079_spd_5 = "CEG"
sym_080_spd_5 = "CHTR"
sym_081_spd_5 = "CPRT"
sym_082_spd_5 = "DXCM"
sym_083_spd_5 = "ILMN"
sym_084_spd_5 = "INTU"
sym_085_spd_5 = "KLAC"
sym_086_spd_5 = "LRCX"
sym_087_spd_5 = "LULU"
sym_088_spd_5 = "MELI"
sym_089_spd_5 = "PANW"
sym_090_spd_5 = "PAYX"
sym_091_spd_5 = "REGN"
sym_092_spd_5 = "SGEN"
sym_093_spd_5 = "TSLA"
sym_094_spd_5 = "VRSK"
sym_095_spd_5 = "VRSN"
sym_096_spd_5 = "XEL"
// Symbols of Strike Price Difference 10
sym_097_spd_10 = "ANSS"
sym_098_spd_10 = "CTAS"
sym_099_spd_10 = "IDXX"
sym_100_spd_10 = "ODFL"
sym_101_spd_10 = "ORLY"
sym_102_spd_10 = "SNPS"
////////////////////////////////////////////////////////// Common Strike Price Difference in NSE F&O
spd_0_25 = 0.25
spd_0_5 = 0.5
spd_1 = 1
spd_2_5 = 2.5
spd_5 = 5
spd_10 = 10
////////////////////////////////////////////////////////// Price Pivots
ttSrc = "โข Custom: Enter the price manually after choosing the Source as Custom to show the Pivots at that price.\nโข LTP: Pivot is calculated based on Last Traded Price.\nโข Day Open: Pivot is calculated based on current day opening price.\nโข PD Close: Pivot is calculated based on previous day closing price.\nโข PD HL2: Pivot is calculated based on previous day average of High and Low.\nโข PD HLC3: Pivot is calculated based on previous day average of High, Low and Close."
ttHis = "Increase numbers for prevoius pivots"
ttCus = "Enter price manually to calculate pivots of that price level"
gpPP = "Price Pivots"
show_pp = input.bool(true, title="Show Price Pivots", group=gpPP, inline="01")
show_pp_label = input.bool(true, title="Price Labels", group=gpPP, inline="01")
i_timeframe = input.string("D", title="Timeframe", options=["1", "3", "5", "15", "30", "45", "60", "120", "180", "240", "D", "5D", "W", "2W", "3W", "M", "3M", "6M", "12M"], group=gpPP)
i_source = input.string("PD Close", title="Source", options=["Custom", "LTP","Day Open", "PD Close", "PD HL2", "PD HLC3"], group=gpPP, tooltip=ttSrc)
i_pd_ltp_o = input.int(0, title="Historical (If Source is Day Open)", minval=0, group=gpPP, tooltip=ttHis)
i_pd_c_hl2_hlc3 = input.int(1, title="Historical (If Source is PD Close, HL2, HLC3)", minval=1, group=gpPP, tooltip=ttHis)
i_custom = input.float(0, title="Enter Price (If Source is Custom)", minval=0, group=gpPP, tooltip=ttCus)
////////////////////////////////////////////////////// OHLC
day_open = request.security(syminfo.tickerid, i_timeframe, open[i_pd_ltp_o], lookahead=barmerge.lookahead_on)
pd_high = request.security(syminfo.tickerid, i_timeframe, high[i_pd_c_hl2_hlc3], lookahead=barmerge.lookahead_on)
pd_low = request.security(syminfo.tickerid, i_timeframe, low[i_pd_c_hl2_hlc3], lookahead=barmerge.lookahead_on)
pd_close = request.security(syminfo.tickerid, i_timeframe, close[i_pd_c_hl2_hlc3], lookahead=barmerge.lookahead_on)
get_high = request.security(syminfo.tickerid, "60", high)
get_low = request.security(syminfo.tickerid, "60", low)
////////////////////////////////////////////////////// Source
price_input = i_source == "LTP" ? close[i_pd_ltp_o] :
i_source == "Day Open" ? day_open :
i_source == "PD Close" ? pd_close :
i_source == "PD HL2" ? math.avg(pd_high, pd_low) :
i_source == "PD HLC3" ? math.avg(pd_high, pd_low, pd_close) : i_custom
price_option = i_source == "Custom" ? i_custom : price_input
////////////////////////////////////////////////////// Price Levels Settings
ttR5 = "This number is for R5 which can be adjusted for extended price pivots"
ttS5 = "This number is for S5 which can be adjusted for extended price pivots"
i_r_col = input.color(color.silver, title="", group=gpPP, inline="05")
show_r_1 = input.bool(true, title="R1", group=gpPP, inline="05")
show_r_2 = input.bool(true, title="R2", group=gpPP, inline="05")
show_r_3 = input.bool(false, title="R3", group=gpPP, inline="05")
show_r_4 = input.bool(false, title="R4", group=gpPP, inline="05")
show_r_5 = input.bool(false, title="R5", group=gpPP, inline="05")
i_r_5x_level = input.int(4, minval=4, title="", group=gpPP, inline="05", tooltip=ttR5)
i_s_col = input.color(color.silver, title="", group=gpPP, inline="06")
show_s_1 = input.bool(true, title="S1", group=gpPP, inline="06")
show_s_2 = input.bool(true, title="S2", group=gpPP, inline="06")
show_s_3 = input.bool(false, title="S3", group=gpPP, inline="06")
show_s_4 = input.bool(false, title="S4", group=gpPP, inline="06")
show_s_5 = input.bool(false, title="S5", group=gpPP, inline="06")
i_s_5x_level = input.int(4, minval=4, title="", group=gpPP, inline="06", tooltip=ttS5)
i_pp_style = input.string(line.style_solid, title = "", options = [line.style_solid, line.style_dashed, line.style_dotted], group=gpPP, inline="07")
i_pp_width = input.int(1, title = "", minval=1, group=gpPP, inline="07")
show_avg = input.bool(false, title="Average Levels", group=gpPP, inline="08")
i_pp_avg_style = input.string(line.style_dashed, title = "", options = [line.style_solid, line.style_dashed, line.style_dotted], group=gpPP, inline="08")
i_pp_avg_width = input.int(1, title = "", minval=1, group=gpPP, inline="08")
i_extend = input.string("None", title="Extend Lines", options=["None", "Left", "Right", "Both"], group=gpPP, inline="09")
ext_option = i_extend == "None" ? extend.none : i_extend == "Left" ? extend.left : i_extend == "Right" ? extend.right : i_extend == "Both" ? extend.both : na
////////////////////////////////////////////////////////// Strike Price Difference Formula
// Strike Price Difference 0.25
upper_val_spd_0_25 = math.round(price_input[i_pd_ltp_o] / spd_0_25, 0) * spd_0_25
lower_val_spd_0_25 = math.round(price_input[i_pd_ltp_o] / spd_0_25, 0) * spd_0_25
upper_spd_0_25 = upper_val_spd_0_25 < price_input[i_pd_ltp_o] ? upper_val_spd_0_25 + spd_0_25 : upper_val_spd_0_25
lower_spd_0_25 = lower_val_spd_0_25 > price_input[i_pd_ltp_o] ? lower_val_spd_0_25 - spd_0_25 : lower_val_spd_0_25
// Strike Price Difference 0.5
upper_val_spd_0_5 = math.round(price_input[i_pd_ltp_o] / spd_0_5, 0) * spd_0_5
lower_val_spd_0_5 = math.round(price_input[i_pd_ltp_o] / spd_0_5, 0) * spd_0_5
upper_spd_0_5 = upper_val_spd_0_5 < price_input[i_pd_ltp_o] ? upper_val_spd_0_5 + spd_0_5 : upper_val_spd_0_5
lower_spd_0_5 = lower_val_spd_0_5 > price_input[i_pd_ltp_o] ? lower_val_spd_0_5 - spd_0_5 : lower_val_spd_0_5
// Strike Price Difference 1
upper_val_spd_1 = math.round(price_input[i_pd_ltp_o] / spd_1, 0) * spd_1
lower_val_spd_1 = math.round(price_input[i_pd_ltp_o] / spd_1, 0) * spd_1
upper_spd_1 = upper_val_spd_1 < price_input[i_pd_ltp_o] ? upper_val_spd_1 + spd_1 : upper_val_spd_1
lower_spd_1 = lower_val_spd_1 > price_input[i_pd_ltp_o] ? lower_val_spd_1 - spd_1 : lower_val_spd_1
// Strike Price Difference 2.5
upper_val_spd_2_5 = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
lower_val_spd_2_5 = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
upper_spd_2_5 = upper_val_spd_2_5 < price_input[i_pd_ltp_o] ? upper_val_spd_2_5 + spd_2_5 : upper_val_spd_2_5
lower_spd_2_5 = lower_val_spd_2_5 > price_input[i_pd_ltp_o] ? lower_val_spd_2_5 - spd_2_5 : lower_val_spd_2_5
// Strike Price Difference 5
upper_val_spd_5 = math.round(price_input[i_pd_ltp_o] / spd_5, 0) * spd_5
lower_val_spd_5 = math.round(price_input[i_pd_ltp_o] / spd_5, 0) * spd_5
upper_spd_5 = upper_val_spd_5 < price_input[i_pd_ltp_o] ? upper_val_spd_5 + spd_5 : upper_val_spd_5
lower_spd_5 = lower_val_spd_5 > price_input[i_pd_ltp_o] ? lower_val_spd_5 - spd_5 : lower_val_spd_5
// Strike Price Difference 10
upper_val_spd_10 = math.round(price_input[i_pd_ltp_o] / spd_10, 0) * spd_10
lower_val_spd_10 = math.round(price_input[i_pd_ltp_o] / spd_10, 0) * spd_10
upper_spd_10 = upper_val_spd_10 < price_input[i_pd_ltp_o] ? upper_val_spd_10 + spd_10 : upper_val_spd_10
lower_spd_10 = lower_val_spd_10 > price_input[i_pd_ltp_o] ? lower_val_spd_10 - spd_10 : lower_val_spd_10
////////////////////////////////////////////////////////// Upper & Lower Strikes
upper_strike = syminfo.root == sym_001_spd_0_25 ? upper_spd_0_25 : syminfo.root == sym_002_spd_0_25 ? upper_spd_0_25 :
syminfo.root == sym_003_spd_0_5 ? upper_spd_0_5 : syminfo.root == sym_004_spd_0_5 ? upper_spd_0_5 : syminfo.root == sym_005_spd_0_5 ? upper_spd_0_5 :
syminfo.root == sym_006_spd_0_5 ? upper_spd_0_5 : syminfo.root == sym_007_spd_0_5 ? upper_spd_0_5 : syminfo.root == sym_008_spd_0_5 ? upper_spd_0_5 :
syminfo.root == sym_009_spd_0_5 ? upper_spd_0_5 : syminfo.root == sym_010_spd_0_5 ? upper_spd_0_5 :
syminfo.root == sym_011_spd_1 ? upper_spd_1 : syminfo.root == sym_012_spd_1 ? upper_spd_1 : syminfo.root == sym_013_spd_1 ? upper_spd_1 :
syminfo.root == sym_014_spd_1 ? upper_spd_1 : syminfo.root == sym_015_spd_1 ? upper_spd_1 : syminfo.root == sym_016_spd_1 ? upper_spd_1 :
syminfo.root == sym_017_spd_1 ? upper_spd_1 : syminfo.root == sym_018_spd_1 ? upper_spd_1 : syminfo.root == sym_019_spd_1 ? upper_spd_1 :
syminfo.root == sym_020_spd_1 ? upper_spd_1 : syminfo.root == sym_021_spd_1 ? upper_spd_1 : syminfo.root == sym_022_spd_1 ? upper_spd_1 :
syminfo.root == sym_023_spd_1 ? upper_spd_1 : syminfo.root == sym_024_spd_1 ? upper_spd_1 : syminfo.root == sym_025_spd_1 ? upper_spd_1 :
syminfo.root == sym_026_spd_1 ? upper_spd_1 : syminfo.root == sym_027_spd_1 ? upper_spd_1 : syminfo.root == sym_028_spd_1 ? upper_spd_1 :
syminfo.root == sym_029_spd_1 ? upper_spd_1 : syminfo.root == sym_030_spd_1 ? upper_spd_1 : syminfo.root == sym_031_spd_1 ? upper_spd_1 :
syminfo.root == sym_032_spd_1 ? upper_spd_1 : syminfo.root == sym_033_spd_1 ? upper_spd_1 : syminfo.root == sym_034_spd_1 ? upper_spd_1 :
syminfo.root == sym_035_spd_1 ? upper_spd_1 : syminfo.root == sym_036_spd_1 ? upper_spd_1 : syminfo.root == sym_037_spd_1 ? upper_spd_1 :
syminfo.root == sym_038_spd_1 ? upper_spd_1 : syminfo.root == sym_039_spd_1 ? upper_spd_1 : syminfo.root == sym_040_spd_1 ? upper_spd_1 :
syminfo.root == sym_041_spd_1 ? upper_spd_1 : syminfo.root == sym_042_spd_1 ? upper_spd_1 : syminfo.root == sym_043_spd_1 ? upper_spd_1 :
syminfo.root == sym_044_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_045_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_046_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_047_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_048_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_049_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_050_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_051_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_052_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_053_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_054_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_055_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_056_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_057_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_058_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_059_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_060_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_061_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_062_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_063_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_064_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_065_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_066_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_067_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_068_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_069_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_070_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_071_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_072_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_073_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_074_spd_2_5 ? upper_spd_2_5 : syminfo.root == sym_075_spd_2_5 ? upper_spd_2_5 :
syminfo.root == sym_076_spd_5 ? upper_spd_5 : syminfo.root == sym_077_spd_5 ? upper_spd_5 : syminfo.root == sym_078_spd_5 ? upper_spd_5 :
syminfo.root == sym_079_spd_5 ? upper_spd_5 : syminfo.root == sym_080_spd_5 ? upper_spd_5 : syminfo.root == sym_081_spd_5 ? upper_spd_5 :
syminfo.root == sym_082_spd_5 ? upper_spd_5 : syminfo.root == sym_083_spd_5 ? upper_spd_5 : syminfo.root == sym_084_spd_5 ? upper_spd_5 :
syminfo.root == sym_085_spd_5 ? upper_spd_5 : syminfo.root == sym_086_spd_5 ? upper_spd_5 : syminfo.root == sym_087_spd_5 ? upper_spd_5 :
syminfo.root == sym_088_spd_5 ? upper_spd_5 : syminfo.root == sym_089_spd_5 ? upper_spd_5 : syminfo.root == sym_090_spd_5 ? upper_spd_5 :
syminfo.root == sym_091_spd_5 ? upper_spd_5 : syminfo.root == sym_092_spd_5 ? upper_spd_5 : syminfo.root == sym_093_spd_5 ? upper_spd_5 :
syminfo.root == sym_094_spd_5 ? upper_spd_5 : syminfo.root == sym_095_spd_5 ? upper_spd_5 : syminfo.root == sym_096_spd_5 ? upper_spd_5 :
syminfo.root == sym_097_spd_10 ? upper_spd_10 : syminfo.root == sym_098_spd_10 ? upper_spd_10 : syminfo.root == sym_099_spd_10 ? upper_spd_10 :
syminfo.root == sym_100_spd_10 ? upper_spd_10 : syminfo.root == sym_101_spd_10 ? upper_spd_10 : syminfo.root == sym_102_spd_10 ? upper_spd_10 : na
lower_strike = syminfo.root == sym_001_spd_0_25 ? lower_spd_0_25 : syminfo.root == sym_002_spd_0_25 ? lower_spd_0_25 :
syminfo.root == sym_003_spd_0_5 ? lower_spd_0_5 : syminfo.root == sym_004_spd_0_5 ? lower_spd_0_5 : syminfo.root == sym_005_spd_0_5 ? lower_spd_0_5 :
syminfo.root == sym_006_spd_0_5 ? lower_spd_0_5 : syminfo.root == sym_007_spd_0_5 ? lower_spd_0_5 : syminfo.root == sym_008_spd_0_5 ? lower_spd_0_5 :
syminfo.root == sym_009_spd_0_5 ? lower_spd_0_5 : syminfo.root == sym_010_spd_0_5 ? lower_spd_0_5 :
syminfo.root == sym_011_spd_1 ? lower_spd_1 : syminfo.root == sym_012_spd_1 ? lower_spd_1 : syminfo.root == sym_013_spd_1 ? lower_spd_1 :
syminfo.root == sym_014_spd_1 ? lower_spd_1 : syminfo.root == sym_015_spd_1 ? lower_spd_1 : syminfo.root == sym_016_spd_1 ? lower_spd_1 :
syminfo.root == sym_017_spd_1 ? lower_spd_1 : syminfo.root == sym_018_spd_1 ? lower_spd_1 : syminfo.root == sym_019_spd_1 ? lower_spd_1 :
syminfo.root == sym_020_spd_1 ? lower_spd_1 : syminfo.root == sym_021_spd_1 ? lower_spd_1 : syminfo.root == sym_022_spd_1 ? lower_spd_1 :
syminfo.root == sym_023_spd_1 ? lower_spd_1 : syminfo.root == sym_024_spd_1 ? lower_spd_1 : syminfo.root == sym_025_spd_1 ? lower_spd_1 :
syminfo.root == sym_026_spd_1 ? lower_spd_1 : syminfo.root == sym_027_spd_1 ? lower_spd_1 : syminfo.root == sym_028_spd_1 ? lower_spd_1 :
syminfo.root == sym_029_spd_1 ? lower_spd_1 : syminfo.root == sym_030_spd_1 ? lower_spd_1 : syminfo.root == sym_031_spd_1 ? lower_spd_1 :
syminfo.root == sym_032_spd_1 ? lower_spd_1 : syminfo.root == sym_033_spd_1 ? lower_spd_1 : syminfo.root == sym_034_spd_1 ? lower_spd_1 :
syminfo.root == sym_035_spd_1 ? lower_spd_1 : syminfo.root == sym_036_spd_1 ? lower_spd_1 : syminfo.root == sym_037_spd_1 ? lower_spd_1 :
syminfo.root == sym_038_spd_1 ? lower_spd_1 : syminfo.root == sym_039_spd_1 ? lower_spd_1 : syminfo.root == sym_040_spd_1 ? lower_spd_1 :
syminfo.root == sym_041_spd_1 ? lower_spd_1 : syminfo.root == sym_042_spd_1 ? lower_spd_1 : syminfo.root == sym_043_spd_1 ? lower_spd_1 :
syminfo.root == sym_044_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_045_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_046_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_047_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_048_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_049_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_050_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_051_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_052_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_053_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_054_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_055_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_056_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_057_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_058_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_059_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_060_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_061_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_062_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_063_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_064_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_065_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_066_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_067_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_068_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_069_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_070_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_071_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_072_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_073_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_074_spd_2_5 ? lower_spd_2_5 : syminfo.root == sym_075_spd_2_5 ? lower_spd_2_5 :
syminfo.root == sym_076_spd_5 ? lower_spd_5 : syminfo.root == sym_077_spd_5 ? lower_spd_5 : syminfo.root == sym_078_spd_5 ? lower_spd_5 :
syminfo.root == sym_079_spd_5 ? lower_spd_5 : syminfo.root == sym_080_spd_5 ? lower_spd_5 : syminfo.root == sym_081_spd_5 ? lower_spd_5 :
syminfo.root == sym_082_spd_5 ? lower_spd_5 : syminfo.root == sym_083_spd_5 ? lower_spd_5 : syminfo.root == sym_084_spd_5 ? lower_spd_5 :
syminfo.root == sym_085_spd_5 ? lower_spd_5 : syminfo.root == sym_086_spd_5 ? lower_spd_5 : syminfo.root == sym_087_spd_5 ? lower_spd_5 :
syminfo.root == sym_088_spd_5 ? lower_spd_5 : syminfo.root == sym_089_spd_5 ? lower_spd_5 : syminfo.root == sym_090_spd_5 ? lower_spd_5 :
syminfo.root == sym_091_spd_5 ? lower_spd_5 : syminfo.root == sym_092_spd_5 ? lower_spd_5 : syminfo.root == sym_093_spd_5 ? lower_spd_5 :
syminfo.root == sym_094_spd_5 ? lower_spd_5 : syminfo.root == sym_095_spd_5 ? lower_spd_5 : syminfo.root == sym_096_spd_5 ? lower_spd_5 :
syminfo.root == sym_097_spd_10 ? lower_spd_10 : syminfo.root == sym_098_spd_10 ? lower_spd_10 : syminfo.root == sym_099_spd_10 ? lower_spd_10 :
syminfo.root == sym_100_spd_10 ? lower_spd_10 : syminfo.root == sym_101_spd_10 ? lower_spd_10 : syminfo.root == sym_102_spd_10 ? lower_spd_10 : na
////////////////////////////////////////////////////////// Strike Price Difference
spd = upper_strike - lower_strike
////////////////////////////////////////////////////////// Higher Strikes
upper_strike_2 = upper_strike + spd
upper_strike_3 = upper_strike + (2 * spd)
upper_strike_4 = upper_strike + (3 * spd)
upper_strike_5 = upper_strike + (i_r_5x_level * spd)
lower_strike_2 = lower_strike - spd
lower_strike_3 = lower_strike - (2 * spd)
lower_strike_4 = lower_strike - (3 * spd)
lower_strike_5 = lower_strike - (i_s_5x_level * spd)
////////////////////////////////////////////////////////// Average Levels
up_lo_avg = math.avg(upper_strike, lower_strike)
up_avg_2 = math.avg(upper_strike, upper_strike_2)
up_avg_3 = math.avg(upper_strike_2, upper_strike_3)
up_avg_4 = math.avg(upper_strike_3, upper_strike_4)
up_avg_5 = math.avg(upper_strike_4, upper_strike_5)
lo_avg_2 = math.avg(lower_strike, lower_strike_2)
lo_avg_3 = math.avg(lower_strike_2, lower_strike_3)
lo_avg_4 = math.avg(lower_strike_3, lower_strike_4)
lo_avg_5 = math.avg(lower_strike_4, lower_strike_5)
////////////////////////////////////////////////////////// Percentage from Close
up_percent_1 = ((close - upper_strike)/close)*100
up_percent_2 = ((close - upper_strike_2)/close)*100
up_percent_3 = ((close - upper_strike_3)/close)*100
up_percent_4 = ((close - upper_strike_4)/close)*100
up_percent_5 = ((close - upper_strike_5)/close)*100
lo_percent_1 = ((close - lower_strike)/close)*100
lo_percent_2 = ((close - lower_strike_2)/close)*100
lo_percent_3 = ((close - lower_strike_3)/close)*100
lo_percent_4 = ((close - lower_strike_4)/close)*100
lo_percent_5 = ((close - lower_strike_5)/close)*100
////////////////////////////////////////////////////////// Points from Close
up_points_1 = upper_strike - close
up_points_2 = upper_strike_2 - close
up_points_3 = upper_strike_3 - close
up_points_4 = upper_strike_4 - close
up_points_5 = upper_strike_5 - close
lo_points_1 = lower_strike - close
lo_points_2 = lower_strike_2 - close
lo_points_3 = lower_strike_3 - close
lo_points_4 = lower_strike_4 - close
lo_points_5 = lower_strike_5 - close
////////////////////////////////////////////////////////// Draw Lines & Labels
// Narest Strike Price
if show_pp
var line upper_line_1 = na
upper_line_1 := line.new(x1=bar_index - 225, y1=upper_strike, x2=bar_index + 10, y2=upper_strike, color=i_r_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(upper_line_1[1])
if show_pp_label
var label upper_label_1 = na
upper_label_1 := label.new(x=bar_index + 10, y=upper_strike, text=str.tostring(upper_strike, "#.## (") + str.tostring(up_percent_1, "#.##") + "%๏ฝ" + str.tostring(up_points_1, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_r_col)
label.delete(upper_label_1[1])
var line lower_line_1 = na
lower_line_1 := line.new(x1=bar_index - 225, y1=lower_strike, x2=bar_index + 10, y2=lower_strike, color=i_s_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(lower_line_1[1])
if show_pp_label
var label lower_label_1 = na
lower_label_1 := label.new(x=bar_index + 10, y=lower_strike, text=str.tostring(lower_strike, "#.## (") + str.tostring(lo_percent_1, "#.##") + "%๏ฝ" + str.tostring(lo_points_1, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_s_col)
label.delete(lower_label_1[1])
linefill.new(upper_line_1, lower_line_1, color.new(color.silver, 95))
if show_avg and show_pp
var line up_lo_line = na
up_lo_line := line.new(x1=bar_index - 225, y1=up_lo_avg, x2=bar_index + 10, y2=up_lo_avg, color=color.silver, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(up_lo_line[1])
// Upper Lines
if show_r_2 and show_pp
var line upper_line_2 = na
upper_line_2 := line.new(x1=bar_index - 225, y1=upper_strike_2, x2=bar_index + 10, y2=upper_strike_2, color=i_r_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(upper_line_2[1])
if show_pp_label
var label upper_label_2 = na
upper_label_2 := label.new(x=bar_index + 10, y=upper_strike_2, text=str.tostring(upper_strike_2, "#.## (") + str.tostring(up_percent_2, "#.##") + "%๏ฝ" + str.tostring(up_points_2, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_r_col)
label.delete(upper_label_2[1])
if show_avg
var line up_avg_2_line = na
up_avg_2_line := line.new(x1=bar_index - 225, y1=up_avg_2, x2=bar_index + 10, y2=up_avg_2, color=i_r_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(up_avg_2_line[1])
if show_r_3 and show_pp
var line upper_line_3 = na
upper_line_3 := line.new(x1=bar_index - 225, y1=upper_strike_3, x2=bar_index + 10, y2=upper_strike_3, color=i_r_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(upper_line_3[1])
if show_pp_label
var label upper_label_3 = na
upper_label_3 := label.new(x=bar_index + 10, y=upper_strike_3, text=str.tostring(upper_strike_3, "#.## (") + str.tostring(up_percent_3, "#.##") + "%๏ฝ" + str.tostring(up_points_3, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_r_col)
label.delete(upper_label_3[1])
if show_avg
var line up_avg_3_line = na
up_avg_3_line := line.new(x1=bar_index - 225, y1=up_avg_3, x2=bar_index + 10, y2=up_avg_3, color=i_r_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(up_avg_3_line[1])
if show_r_4 and show_pp
var line upper_line_4 = na
upper_line_4 := line.new(x1=bar_index - 225, y1=upper_strike_4, x2=bar_index + 10, y2=upper_strike_4, color=i_r_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(upper_line_4[1])
if show_pp_label
var label upper_label_4 = na
upper_label_4 := label.new(x=bar_index + 10, y=upper_strike_4, text=str.tostring(upper_strike_4, "#.## (") + str.tostring(up_percent_4, "#.##") + "%๏ฝ" + str.tostring(up_points_4, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_r_col)
label.delete(upper_label_4[1])
if show_avg
var line up_avg_4_line = na
up_avg_4_line := line.new(x1=bar_index - 225, y1=up_avg_4, x2=bar_index + 10, y2=up_avg_4, color=i_r_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(up_avg_4_line[1])
if show_r_5 and show_pp
var line upper_line_5 = na
upper_line_5 := line.new(x1=bar_index - 225, y1=upper_strike_5, x2=bar_index + 10, y2=upper_strike_5, color=i_r_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(upper_line_5[1])
if show_pp_label
var label upper_label_5 = na
upper_label_5 := label.new(x=bar_index + 10, y=upper_strike_5, text=str.tostring(upper_strike_5, "#.## (") + str.tostring(up_percent_5, "#.##") + "%๏ฝ" + str.tostring(up_points_5, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_r_col)
label.delete(upper_label_5[1])
if show_avg
var line up_avg_5_line = na
up_avg_5_line := line.new(x1=bar_index - 225, y1=up_avg_5, x2=bar_index + 10, y2=up_avg_5, color=i_r_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(up_avg_5_line[1])
// Lower Lines
if show_s_2 and show_pp
var line lower_line_2 = na
lower_line_2 := line.new(x1=bar_index - 225, y1=lower_strike_2, x2=bar_index + 10, y2=lower_strike_2, color=i_s_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(lower_line_2[1])
if show_pp_label
var label lower_label_2 = na
lower_label_2 := label.new(x=bar_index + 10, y=lower_strike_2, text=str.tostring(lower_strike_2, "#.## (") + str.tostring(lo_percent_2, "#.##") + "%๏ฝ" + str.tostring(lo_points_2, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_s_col)
label.delete(lower_label_2[1])
if show_avg
var line lo_avg_2_line = na
lo_avg_2_line := line.new(x1=bar_index - 225, y1=lo_avg_2, x2=bar_index + 10, y2=lo_avg_2, color=i_s_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(lo_avg_2_line[1])
if show_s_3 and show_pp
var line lower_line_3 = na
lower_line_3 := line.new(x1=bar_index - 225, y1=lower_strike_3, x2=bar_index + 10, y2=lower_strike_3, color=i_s_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(lower_line_3[1])
if show_pp_label
var label lower_label_3 = na
lower_label_3 := label.new(x=bar_index + 10, y=lower_strike_3, text=str.tostring(lower_strike_3, "#.## (") + str.tostring(lo_percent_3, "#.##") + "%๏ฝ" + str.tostring(lo_points_3, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_s_col)
label.delete(lower_label_3[1])
if show_avg
var line lo_avg_3_line = na
lo_avg_3_line := line.new(x1=bar_index - 225, y1=lo_avg_3, x2=bar_index + 10, y2=lo_avg_3, color=i_s_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(lo_avg_3_line[1])
if show_s_4 and show_pp
var line lower_line_4 = na
lower_line_4 := line.new(x1=bar_index - 225, y1=lower_strike_4, x2=bar_index + 10, y2=lower_strike_4, color=i_s_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(lower_line_4[1])
if show_pp_label
var label lower_label_4 = na
lower_label_4 := label.new(x=bar_index + 10, y=lower_strike_4, text=str.tostring(lower_strike_4, "#.## (") + str.tostring(lo_percent_4, "#.##") + "%๏ฝ" + str.tostring(lo_points_4, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_s_col)
label.delete(lower_label_4[1])
if show_avg
var line lo_avg_4_line = na
lo_avg_4_line := line.new(x1=bar_index - 225, y1=lo_avg_4, x2=bar_index + 10, y2=lo_avg_4, color=i_s_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(lo_avg_4_line[1])
if show_s_5 and show_pp
var line lower_line_5 = na
lower_line_5 := line.new(x1=bar_index - 225, y1=lower_strike_5, x2=bar_index + 10, y2=lower_strike_5, color=i_s_col, width=i_pp_width, style=i_pp_style, extend=ext_option)
line.delete(lower_line_5[1])
if show_pp_label
var label lower_label_5 = na
lower_label_5 := label.new(x=bar_index + 10, y=lower_strike_5, text=str.tostring(lower_strike_5, "#.## (") + str.tostring(lo_percent_5, "#.##") + "%๏ฝ" + str.tostring(lo_points_5, "#.##") + ")", style=label.style_label_left, color=color.new(color.white, 100), textcolor=i_s_col)
label.delete(lower_label_5[1])
if show_avg
var line lo_avg_5_line = na
lo_avg_5_line := line.new(x1=bar_index - 225, y1=lo_avg_5, x2=bar_index + 10, y2=lo_avg_5, color=i_s_col, width=i_pp_avg_width, style=i_pp_avg_style, extend=ext_option)
line.delete(lo_avg_5_line[1])
////////////////////////////////////////////////////////// Important Pivots
high_low_time = time(timeframe.period, "1030-1031")
pivot_time = time(timeframe.period, "1030-1600")
no_trade_time = time(timeframe.period, "0930-1029")
high_1hr = ta.valuewhen(no_trade_time, get_high, 0)
low_1hr = ta.valuewhen(no_trade_time, get_low, 0)
////////////////////////////////////////////////////// Price Levels Settings
gpL = "Important Pivots"
//i_r_col = input.color(color.rgb(240, 83, 80), title="", group=gpL, inline="01")
show_rz_1 = input.bool(true, title="R1", group=gpL, inline="01")
show_rz_2 = input.bool(false, title="R2", group=gpL, inline="01")
//s_color = input.color(color.rgb(38, 166, 154), title="", group=gpL, inline="02")
show_sz_1 = input.bool(true, title="S1", group=gpL, inline="01")
show_sz_2 = input.bool(false, title="S2", group=gpL, inline="01")
//show_last = input.bool(true, title="Hide Historical", group=gpL, inline="02")
//islast = show_last ? request.security(syminfo.tickerid, i_timeframe, barstate.islast, lookahead=barmerge.lookahead_on) : true
////////////////////////////////////////////////////////// Strike Price Difference Formula
// Strike Price Difference 0.25
upper_val_spd_0_25_plot_plot = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
lower_val_spd_0_25_plot_plot = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
upper_spd_0_25_plot = upper_val_spd_0_25_plot_plot < price_input[i_pd_ltp_o] ? upper_val_spd_0_25_plot_plot + spd_2_5 : upper_val_spd_0_25_plot_plot
lower_spd_0_25_plot = lower_val_spd_0_25_plot_plot > price_input[i_pd_ltp_o] ? lower_val_spd_0_25_plot_plot - spd_2_5 : lower_val_spd_0_25_plot_plot
// Strike Price Difference 0.5
upper_val_spd_0_5_plot = math.round(price_input[i_pd_ltp_o] / spd_0_5, 0) * spd_0_5
lower_val_spd_0_5_plot = math.round(price_input[i_pd_ltp_o] / spd_0_5, 0) * spd_0_5
upper_spd_0_5_plot = upper_val_spd_0_5_plot < price_input[i_pd_ltp_o] ? upper_val_spd_0_5_plot + spd_0_5 : upper_val_spd_0_5_plot
lower_spd_0_5_plot = lower_val_spd_0_5_plot > price_input[i_pd_ltp_o] ? lower_val_spd_0_5_plot - spd_0_5 : lower_val_spd_0_5_plot
// Strike Price Difference 1
upper_val_spd_1_plot = math.round(price_input[i_pd_ltp_o] / spd_1, 0) * spd_1
lower_val_spd_1_plot = math.round(price_input[i_pd_ltp_o] / spd_1, 0) * spd_1
upper_spd_1_plot = upper_val_spd_1_plot < price_input[i_pd_ltp_o] ? upper_val_spd_1_plot + spd_1 : upper_val_spd_1_plot
lower_spd_1_plot = lower_val_spd_1_plot > price_input[i_pd_ltp_o] ? lower_val_spd_1_plot - spd_1 : lower_val_spd_1_plot
// Strike Price Difference 2.5
upper_val_spd_2_5_plot = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
lower_val_spd_2_5_plot = math.round(price_input[i_pd_ltp_o] / spd_2_5, 0) * spd_2_5
upper_spd_2_5_plot = upper_val_spd_2_5_plot < price_input[i_pd_ltp_o] ? upper_val_spd_2_5_plot + spd_2_5 : upper_val_spd_2_5_plot
lower_spd_2_5_plot = lower_val_spd_2_5_plot > price_input[i_pd_ltp_o] ? lower_val_spd_2_5_plot - spd_2_5 : lower_val_spd_2_5_plot
// Strike Price Difference 5
upper_val_spd_5_plot = math.round(price_input[i_pd_ltp_o] / spd_5, 0) * spd_5
lower_val_spd_5_plot = math.round(price_input[i_pd_ltp_o] / spd_5, 0) * spd_5
upper_spd_5_plot = upper_val_spd_5_plot < price_input[i_pd_ltp_o] ? upper_val_spd_5_plot + spd_5 : upper_val_spd_5_plot
lower_spd_5_plot = lower_val_spd_5_plot > price_input[i_pd_ltp_o] ? lower_val_spd_5_plot - spd_5 : lower_val_spd_5_plot
// Strike Price Difference 10
upper_val_spd_10_plot = math.round(price_input[i_pd_ltp_o] / spd_10, 0) * spd_10
lower_val_spd_10_plot = math.round(price_input[i_pd_ltp_o] / spd_10, 0) * spd_10
upper_spd_10_plot = upper_val_spd_10_plot < price_input[i_pd_ltp_o] ? upper_val_spd_10_plot + spd_10 : upper_val_spd_10_plot
lower_spd_10_plot = lower_val_spd_10_plot > price_input[i_pd_ltp_o] ? lower_val_spd_10_plot - spd_10 : lower_val_spd_10_plot
////////////////////////////////////////////////////////// Upper & Lower Strikes
upper_strike_plot = syminfo.root == sym_001_spd_0_25 ? upper_spd_0_25_plot : syminfo.root == sym_002_spd_0_25 ? upper_spd_0_25_plot :
syminfo.root == sym_003_spd_0_5 ? upper_spd_0_5_plot : syminfo.root == sym_004_spd_0_5 ? upper_spd_0_5_plot : syminfo.root == sym_005_spd_0_5 ? upper_spd_0_5_plot :
syminfo.root == sym_006_spd_0_5 ? upper_spd_0_5_plot : syminfo.root == sym_007_spd_0_5 ? upper_spd_0_5_plot : syminfo.root == sym_008_spd_0_5 ? upper_spd_0_5_plot :
syminfo.root == sym_009_spd_0_5 ? upper_spd_0_5_plot : syminfo.root == sym_010_spd_0_5 ? upper_spd_0_5_plot :
syminfo.root == sym_011_spd_1 ? upper_spd_1_plot : syminfo.root == sym_012_spd_1 ? upper_spd_1_plot : syminfo.root == sym_013_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_014_spd_1 ? upper_spd_1_plot : syminfo.root == sym_015_spd_1 ? upper_spd_1_plot : syminfo.root == sym_016_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_017_spd_1 ? upper_spd_1_plot : syminfo.root == sym_018_spd_1 ? upper_spd_1_plot : syminfo.root == sym_019_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_020_spd_1 ? upper_spd_1_plot : syminfo.root == sym_021_spd_1 ? upper_spd_1_plot : syminfo.root == sym_022_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_023_spd_1 ? upper_spd_1_plot : syminfo.root == sym_024_spd_1 ? upper_spd_1_plot : syminfo.root == sym_025_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_026_spd_1 ? upper_spd_1_plot : syminfo.root == sym_027_spd_1 ? upper_spd_1_plot : syminfo.root == sym_028_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_029_spd_1 ? upper_spd_1_plot : syminfo.root == sym_030_spd_1 ? upper_spd_1_plot : syminfo.root == sym_031_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_032_spd_1 ? upper_spd_1_plot : syminfo.root == sym_033_spd_1 ? upper_spd_1_plot : syminfo.root == sym_034_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_035_spd_1 ? upper_spd_1_plot : syminfo.root == sym_036_spd_1 ? upper_spd_1_plot : syminfo.root == sym_037_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_038_spd_1 ? upper_spd_1_plot : syminfo.root == sym_039_spd_1 ? upper_spd_1_plot : syminfo.root == sym_040_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_041_spd_1 ? upper_spd_1_plot : syminfo.root == sym_042_spd_1 ? upper_spd_1_plot : syminfo.root == sym_043_spd_1 ? upper_spd_1_plot :
syminfo.root == sym_044_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_045_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_046_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_047_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_048_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_049_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_050_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_051_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_052_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_053_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_054_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_055_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_056_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_057_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_058_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_059_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_060_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_061_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_062_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_063_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_064_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_065_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_066_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_067_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_068_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_069_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_070_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_071_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_072_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_073_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_074_spd_2_5 ? upper_spd_2_5_plot : syminfo.root == sym_075_spd_2_5 ? upper_spd_2_5_plot :
syminfo.root == sym_076_spd_5 ? upper_spd_5_plot : syminfo.root == sym_077_spd_5 ? upper_spd_5_plot : syminfo.root == sym_078_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_079_spd_5 ? upper_spd_5_plot : syminfo.root == sym_080_spd_5 ? upper_spd_5_plot : syminfo.root == sym_081_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_082_spd_5 ? upper_spd_5_plot : syminfo.root == sym_083_spd_5 ? upper_spd_5_plot : syminfo.root == sym_084_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_085_spd_5 ? upper_spd_5_plot : syminfo.root == sym_086_spd_5 ? upper_spd_5_plot : syminfo.root == sym_087_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_088_spd_5 ? upper_spd_5_plot : syminfo.root == sym_089_spd_5 ? upper_spd_5_plot : syminfo.root == sym_090_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_091_spd_5 ? upper_spd_5_plot : syminfo.root == sym_092_spd_5 ? upper_spd_5_plot : syminfo.root == sym_093_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_094_spd_5 ? upper_spd_5_plot : syminfo.root == sym_095_spd_5 ? upper_spd_5_plot : syminfo.root == sym_096_spd_5 ? upper_spd_5_plot :
syminfo.root == sym_097_spd_10 ? upper_spd_10_plot : syminfo.root == sym_098_spd_10 ? upper_spd_10_plot : syminfo.root == sym_099_spd_10 ? upper_spd_10_plot :
syminfo.root == sym_100_spd_10 ? upper_spd_10_plot : syminfo.root == sym_101_spd_10 ? upper_spd_10_plot : syminfo.root == sym_102_spd_10 ? upper_spd_10_plot : na
lower_strike_plot = syminfo.root == sym_001_spd_0_25 ? lower_spd_0_25_plot : syminfo.root == sym_002_spd_0_25 ? lower_spd_0_25_plot :
syminfo.root == sym_003_spd_0_5 ? lower_spd_0_5_plot : syminfo.root == sym_004_spd_0_5 ? lower_spd_0_5_plot : syminfo.root == sym_005_spd_0_5 ? lower_spd_0_5_plot :
syminfo.root == sym_006_spd_0_5 ? lower_spd_0_5_plot : syminfo.root == sym_007_spd_0_5 ? lower_spd_0_5_plot : syminfo.root == sym_008_spd_0_5 ? lower_spd_0_5_plot :
syminfo.root == sym_009_spd_0_5 ? lower_spd_0_5_plot : syminfo.root == sym_010_spd_0_5 ? lower_spd_0_5_plot :
syminfo.root == sym_011_spd_1 ? lower_spd_1_plot : syminfo.root == sym_012_spd_1 ? lower_spd_1_plot : syminfo.root == sym_013_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_014_spd_1 ? lower_spd_1_plot : syminfo.root == sym_015_spd_1 ? lower_spd_1_plot : syminfo.root == sym_016_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_017_spd_1 ? lower_spd_1_plot : syminfo.root == sym_018_spd_1 ? lower_spd_1_plot : syminfo.root == sym_019_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_020_spd_1 ? lower_spd_1_plot : syminfo.root == sym_021_spd_1 ? lower_spd_1_plot : syminfo.root == sym_022_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_023_spd_1 ? lower_spd_1_plot : syminfo.root == sym_024_spd_1 ? lower_spd_1_plot : syminfo.root == sym_025_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_026_spd_1 ? lower_spd_1_plot : syminfo.root == sym_027_spd_1 ? lower_spd_1_plot : syminfo.root == sym_028_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_029_spd_1 ? lower_spd_1_plot : syminfo.root == sym_030_spd_1 ? lower_spd_1_plot : syminfo.root == sym_031_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_032_spd_1 ? lower_spd_1_plot : syminfo.root == sym_033_spd_1 ? lower_spd_1_plot : syminfo.root == sym_034_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_035_spd_1 ? lower_spd_1_plot : syminfo.root == sym_036_spd_1 ? lower_spd_1_plot : syminfo.root == sym_037_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_038_spd_1 ? lower_spd_1_plot : syminfo.root == sym_039_spd_1 ? lower_spd_1_plot : syminfo.root == sym_040_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_041_spd_1 ? lower_spd_1_plot : syminfo.root == sym_042_spd_1 ? lower_spd_1_plot : syminfo.root == sym_043_spd_1 ? lower_spd_1_plot :
syminfo.root == sym_044_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_045_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_046_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_047_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_048_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_049_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_050_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_051_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_052_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_053_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_054_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_055_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_056_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_057_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_058_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_059_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_060_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_061_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_062_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_063_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_064_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_065_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_066_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_067_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_068_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_069_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_070_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_071_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_072_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_073_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_074_spd_2_5 ? lower_spd_2_5_plot : syminfo.root == sym_075_spd_2_5 ? lower_spd_2_5_plot :
syminfo.root == sym_076_spd_5 ? lower_spd_5_plot : syminfo.root == sym_077_spd_5 ? lower_spd_5_plot : syminfo.root == sym_078_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_079_spd_5 ? lower_spd_5_plot : syminfo.root == sym_080_spd_5 ? lower_spd_5_plot : syminfo.root == sym_081_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_082_spd_5 ? lower_spd_5_plot : syminfo.root == sym_083_spd_5 ? lower_spd_5_plot : syminfo.root == sym_084_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_085_spd_5 ? lower_spd_5_plot : syminfo.root == sym_086_spd_5 ? lower_spd_5_plot : syminfo.root == sym_087_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_088_spd_5 ? lower_spd_5_plot : syminfo.root == sym_089_spd_5 ? lower_spd_5_plot : syminfo.root == sym_090_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_091_spd_5 ? lower_spd_5_plot : syminfo.root == sym_092_spd_5 ? lower_spd_5_plot : syminfo.root == sym_093_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_094_spd_5 ? lower_spd_5_plot : syminfo.root == sym_095_spd_5 ? lower_spd_5_plot : syminfo.root == sym_096_spd_5 ? lower_spd_5_plot :
syminfo.root == sym_097_spd_10 ? lower_spd_10_plot : syminfo.root == sym_098_spd_10 ? lower_spd_10_plot : syminfo.root == sym_099_spd_10 ? lower_spd_10_plot :
syminfo.root == sym_100_spd_10 ? lower_spd_10_plot : syminfo.root == sym_101_spd_10 ? lower_spd_10_plot : syminfo.root == sym_102_spd_10 ? lower_spd_10_plot : na
////////////////////////////////////////////////////////// Strike Price Difference
spd_plot = upper_strike_plot - lower_strike_plot
////////////////////////////////////////////////////////// Higher Strikes
upper_strike_2_plot = upper_strike_plot + spd_plot
upper_strike_3_plot = upper_strike_plot + (2 * spd_plot)
lower_strike_2_plot = lower_strike_plot - spd_plot
lower_strike_3_plot = lower_strike_plot - (2 * spd_plot)
////////////////////////////////////////////////////////// First One Hour Highlight
//bgcolor(no_trade_time ? color.new(color.silver, 95) : na)
////////////////////////////////////////////////////////// Plot Important Pivots
rz_1_2_line = plot(pivot_time and show_rz_1 ? upper_strike_plot : na, "R1", style=plot.style_linebr, color=color.new(#EF5350, 0), linewidth=3)
rz_2_2_line = plot(pivot_time and show_rz_2 ? upper_strike_2_plot : na, "R2", style=plot.style_linebr, color=color.new(#EF5350, 0), linewidth=3)
sz_1_2_line = plot(pivot_time and show_sz_1 ? lower_strike_plot : na, "S1", style=plot.style_linebr, color=color.new(#26A69A, 0), linewidth=3)
sz_2_2_line = plot(pivot_time and show_sz_2 ? lower_strike_2_plot : na, "S2", style=plot.style_linebr, color=color.new(#26A69A, 0), linewidth=3)
////////////////////////////////////////////////////////// Time Markers
gpT = "Time (IST) (Vertical)"
show_time_01 = input.bool(false, title="", group=gpT, inline="_01")
i_hour_01 = input.int(10, minval=0, title="", group=gpT, inline="_01")
i_minute_01 = input.int(30, minval=0, title=":", group=gpT, inline="_01")
i_t_col_01 = input.color(color.silver, title="", group=gpT, inline="_01")
show_time_02 = input.bool(true, title="", group=gpT, inline="_02")
i_hour_02 = input.int(11, minval=0, title="", group=gpT, inline="_02")
i_minute_02 = input.int(30, minval=0, title=":", group=gpT, inline="_02")
i_t_col_02 = input.color(color.silver, title="", group=gpT, inline="_02")
show_time_03 = input.bool(false, title="", group=gpT, inline="_03")
i_hour_03 = input.int(12, minval=0, title="", group=gpT, inline="_03")
i_minute_03 = input.int(30, minval=0, title=":", group=gpT, inline="_03")
i_t_col_03 = input.color(color.silver, title="", group=gpT, inline="_03")
show_time_04 = input.bool(false, title="", group=gpT, inline="_04")
i_hour_04 = input.int(13, minval=0, title="", group=gpT, inline="_04")
i_minute_04 = input.int(30, minval=0, title=":", group=gpT, inline="_04")
i_t_col_04 = input.color(color.silver, title="", group=gpT, inline="_04")
show_time_05 = input.bool(false, title="", group=gpT, inline="_05")
i_hour_05 = input.int(14, minval=0, title="", group=gpT, inline="_05")
i_minute_05 = input.int(30, minval=0, title=":", group=gpT, inline="_05")
i_t_col_05 = input.color(color.silver, title="", group=gpT, inline="_05")
show_time_06 = input.bool(false, title="", group=gpT, inline="_06")
i_hour_06 = input.int(15, minval=0, title="", group=gpT, inline="_06")
i_minute_06 = input.int(30, minval=0, title=":", group=gpT, inline="_06")
i_t_col_06 = input.color(color.silver, title="", group=gpT, inline="_06")
i_t_style = input.string(line.style_dotted, title = "", options = [line.style_solid, line.style_dashed, line.style_dotted], group=gpT, inline="_07")
i_t_width = input.int(1, title = "", minval=1, group=gpT, inline="_07")
show_time_label = input.bool(false, title="Time Label", group=gpT, inline="_08")
if show_time_01
time_01 = timestamp("GMT-0400", year, month, dayofmonth, i_hour_01, i_minute_01, 00)
time_01_line = line.new(x1=time_01, y1=open, x2=time_01, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_01, style=i_t_style, width=i_t_width)
line.delete(time_01_line[1])
if show_time_label
var label time_01_label = na
time_01_label := label.new(x=time_01, y=high, text=str.tostring(i_hour_01) + ":" + str.tostring(i_minute_01), textcolor=i_t_col_01, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_01_label[1])
// nd_time_01 = timestamp("GMT-0400", year, month , dayofmonth + 1, i_hour_01, i_minute_01, 00)
// nd_time_01_line = line.new(x1=nd_time_01, y1=open, x2=nd_time_01, y2=close, xloc=xloc.bar_time, extend=extend.both, color=color.new(color.silver, 0), style=i_t_style, width=i_t_width)
// line.delete(nd_time_01_line[1])
pd_time_02 = timestamp("GMT-0400", year, month , dayofmonth - 1, i_hour_05, i_minute_05, 00)
pd_time_02_line = line.new(x1=pd_time_02, y1=open, x2=pd_time_02, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_05, style=i_t_style, width=i_t_width)
line.delete(pd_time_02_line[1])
if show_time_label
var label pd_time_02_label = na
pd_time_02_label := label.new(x=pd_time_02, y=high, text=str.tostring(i_hour_05) + ":" + str.tostring(i_minute_05), textcolor=i_t_col_05, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(pd_time_02_label[1])
if show_time_02
time_02 = timestamp("GMT-0400", year, month , dayofmonth, i_hour_02, i_minute_02, 00)
time_02_line = line.new(x1=time_02, y1=open, x2=time_02, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_02, style=i_t_style, width=i_t_width)
line.delete(time_02_line[1])
if show_time_label
var label time_02_label = na
time_02_label := label.new(x=time_02, y=high, text=str.tostring(i_hour_02) + ":" + str.tostring(i_minute_02), textcolor=i_t_col_02, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_02_label[1])
if show_time_03
time_03 = timestamp("GMT-0400", year, month , dayofmonth, i_hour_03, i_minute_03, 00)
time_03_line = line.new(x1=time_03, y1=open, x2=time_03, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_03, style=i_t_style, width=i_t_width)
line.delete(time_03_line[1])
if show_time_label
var label time_03_label = na
time_03_label := label.new(x=time_03, y=high, text=str.tostring(i_hour_03) + ":" + str.tostring(i_minute_03), textcolor=i_t_col_03, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_03_label[1])
if show_time_04
time_04 = timestamp("GMT-0400", year, month , dayofmonth, i_hour_04, i_minute_04, 00)
time_04_line = line.new(x1=time_04, y1=open, x2=time_04, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_04, style=i_t_style, width=i_t_width)
line.delete(time_04_line[1])
if show_time_label
var label time_04_label = na
time_04_label := label.new(x=time_04, y=high, text=str.tostring(i_hour_04) + ":" + str.tostring(i_minute_04), textcolor=i_t_col_04, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_04_label[1])
if show_time_05
time_05 = timestamp("GMT-0400", year, month , dayofmonth, i_hour_05, i_minute_05, 00)
time_05_line = line.new(x1=time_05, y1=open, x2=time_05, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_05, style=i_t_style, width=i_t_width)
line.delete(time_05_line[1])
if show_time_label
var label time_05_label = na
time_05_label := label.new(x=time_05, y=high, text=str.tostring(i_hour_05) + ":" + str.tostring(i_minute_05), textcolor=i_t_col_05, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_05_label[1])
if show_time_06
time_06 = timestamp("GMT-0400", year, month , dayofmonth, i_hour_06, i_minute_06, 00)
time_06_line = line.new(x1=time_06, y1=open, x2=time_06, y2=close, xloc=xloc.bar_time, extend=extend.both, color=i_t_col_06, style=i_t_style, width=i_t_width)
line.delete(time_06_line[1])
if show_time_label
var label time_06_label = na
time_06_label := label.new(x=time_06, y=high, text=str.tostring(i_hour_06) + ":" + str.tostring(i_minute_06), textcolor=i_t_col_06, textalign=text.align_center, color=color.new(color.white, 100), style=label.style_label_down, size=size.normal, xloc=xloc.bar_time, yloc=yloc.abovebar)
label.delete(time_06_label[1])
//linefill.new(pd_time_02_line, time_01_line, color.new(color.black, 95))
////////////////////////////////////////////////////////// END |
Opening Price Change | https://www.tradingview.com/script/yKudUaUB-Opening-Price-Change/ | marceloelgringo | https://www.tradingview.com/u/marceloelgringo/ | 93 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ marceloelgringo
//@version=5
indicator("Opening Price Change", overlay=true)
closePreviousDay = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
openCurrentDay = request.security(syminfo.tickerid, "D", open, barmerge.gaps_off, barmerge.lookahead_on)
calculateChange(previousDay, currentDay) =>
isPositive = currentDay > previousDay
if isPositive
increase = currentDay - previousDay
increase / previousDay * 100
else
decrease = previousDay - currentDay
decrease / previousDay * 100
if session.isfirstbar_regular
isOpenPositive = openCurrentDay > closePreviousDay
isChangeZero = openCurrentDay == closePreviousDay
openMarketChangeLabel = label.new(bar_index, na)
label.set_color(openMarketChangeLabel, isChangeZero ? color.silver : (isOpenPositive ? color.green : color.red))
label.set_text(openMarketChangeLabel, (isChangeZero ? "" : isOpenPositive ? "+" : "-") + str.tostring(calculateChange(closePreviousDay, openCurrentDay), format.percent))
label.set_yloc(openMarketChangeLabel, yloc.abovebar)
|
Itakura-Saito Autoregressive Extrapolation of Price [Loxx] | https://www.tradingview.com/script/BKC6dFUY-Itakura-Saito-Autoregressive-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 388 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Itakura-Saito Autoregressive Extrapolation of Price [Loxx]",
shorttitle = "ISAGEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
bluecolor = #042dd2
_Geom(float[] x, int p)=>
int n = array.size(x)
float[] df = array.new<float>(n, 0.)
float[] db = array.new<float>(n, 0.)
float[] result = array.new<float>(n, 0.)
int kh = 0
int ki = 0
float tmp = 0.
float num = 0.
float denf = 0.
float denb = 0.
float r = 0.
for i = 0 to n - 1
array.set(df, i, array.get(x, i))
array.set(db, i, array.get(x, i))
//Main loop
for k = 1 to p
num := 0.
denf := 0.
denb := 0.
for i = k to n - 1
num += array.get(df, i) * array.get(db, i - 1)
denf += math.pow(array.get(df, i), 2)
denb += math.pow(array.get(db, i - 1), 2)
r := -num / math.sqrt(denf) / math.sqrt(denb)
//Calculate prediction coefficients
array.set(result, k, r)
kh := k / 2
for i = 1 to kh
ki := k - i
tmp := array.get(result, i)
array.set(result, i, array.get(result, i) + r * array.get(result, ki))
if (i != ki)
array.set(result, ki, array.get(result, ki) + r * tmp)
if (k < p)
for i = n - 1 to k
tmp1 = array.get(df, i)
array.set(df, i, array.get(df, i) + r * array.get(db, i - 1))
array.set(db, i, array.get(db, i - 1) + r * tmp1)
result
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(300, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.6, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
FutBars = input.int(100, "Future Bars", group = "Basic Settings", maxval = 500)
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
cnp = np >= 250 ? 250 : np
cnf = nf >= 250 ? 250 : nf
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction _Geom
float[] result = _Geom(x, no)
//Calculate linear predictions
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1 |
Crypto Breakout Indicator | https://www.tradingview.com/script/Md4AtZUt-Crypto-Breakout-Indicator/ | FittestTrader | https://www.tradingview.com/u/FittestTrader/ | 113 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ FittestTrader
//@version=5
indicator("Crypto Breakout Indicator", overlay=true)
//INPUTS
Bars = input (6)
minimum = input.int(1, "Min Breakout %")
maximum = input.int(20, "Max Breakout %")
Volume = input.int(10, "Min Volume Breakout %")
MovingAverage = input (200)
Consolidation = input.int(15, "Consolidation Range")
RSIOS = input.int(75, "Maximum Allowed RSI for Entry")
RSIEntry = input.int(50, "Minimum Allowed RSI for Entry")
BBR = input.int(1, "Maximum Allowed BB% for Entry")
//INPUTS
//Calculation
highest=ta.highest(high, Bars)[1]
lowest=ta.lowest(low,Bars) [1]
diff= ((highest/lowest) - 1)*100
minbo = highest * ((minimum/100)+1)
maxbo = highest * ((maximum/100)+1)
Vol = ((volume / volume[1]) - 1) * 100
MA = ta.ema(close,MovingAverage)
RSI=ta.rsi(close,14)
//Calculation
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
bbr = (src - lower)/(upper - lower)
Breakout = diff < Consolidation and close > minbo and close < maxbo and Vol > Volume and close > MA and bbr<=BBR
plotshape(Breakout,"Breakout",shape.labelup ,location.belowbar ,#26a69a,text="B",textcolor=color.white,size=size.normal)
alertcondition(Breakout,'Upper Breakout','Price Broke Out')
|
REJHAM | https://www.tradingview.com/script/Xp8Hl0LV-REJHAM/ | kutti2020 | https://www.tradingview.com/u/kutti2020/ | 22 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Kliphten
//@version=4
study(title="REJHAM", overlay=true)
range = high - low
candlecheck = (close > open) ? 1 : 0
UpWick = candlecheck == 1 ? (high - close) : (high - open)
DownWick = candlecheck == 0 ? (close - low) : (open - low)
isCandleOpenCloseEqual = (open == close) ? 1 : 0
tbl = table.new(position.top_right, 2, 4)
table.cell(tbl, 0, 0, "C.Key", bgcolor = #aaaaaa, width = 7, height = 6)
table.cell(tbl, 1, 0, "C.Value", bgcolor = #aaaaaa, width = 7, height = 6)
table.cell(tbl, 0, 1, "Time Period", bgcolor = color.green, width = 7, height = 6)
table.cell(tbl, 1, 1, timeframe.period + " Mins", bgcolor = color.red, width = 7, height = 6)
table.cell(tbl, 0, 2, "Up Wick", bgcolor = color.green, width = 7, height = 6)
table.cell(tbl, 1, 2, tostring(UpWick), bgcolor = color.red, width = 7, height = 6)
table.cell(tbl, 0, 3, "Down Wick", bgcolor = color.green, width = 7, height = 6)
table.cell(tbl, 1, 3, tostring(DownWick), bgcolor = color.red, width = 7, height = 6)
isRejectionExists = (UpWick > 0.001 and DownWick > 0.001) ? 1 : 0
timeperiod = timeframe.period
isBuyHammerexists = (isRejectionExists == 1 and candlecheck == 1) ? (DownWick > 2.1 * UpWick) ? (isCandleOpenCloseEqual == 1) ? 0 : 1 : 0 : 0
isSellHammerExists = (isRejectionExists == 1 and candlecheck == 0) ? (UpWick > 2.1 * DownWick) ? (isCandleOpenCloseEqual == 1) ? 0 : 1 : 0 : 0
//isAnyHammerexists = (isBuyHammerexists == 1 and timeperiod >= 15) ? 1 : (isSellHammerExists == 1 and timeperiod >= 15) ? 1 : 0
plotshape(isBuyHammerexists,location=location.belowbar,color= color.green , style=shape.triangleup)
plotshape(isSellHammerExists,location=location.abovebar,color= color.red , style=shape.triangledown)
//plotshape(isAnyHammerexists,location=location.belowbar,color= color.orange , style=shape.triangleup) |
Value At Risk Channel [AstrideUnicorn] | https://www.tradingview.com/script/i2FVkAEv-Value-At-Risk-Channel-AstrideUnicorn/ | AstrideUnicorn | https://www.tradingview.com/u/AstrideUnicorn/ | 70 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ AstrideUnicorn
//@version=5
indicator(title ="Value At Risk Channel", shorttitle="VaR Channel" , timeframe = "D", overlay = true)
// Script inputs
Percentile = input(5.0 , title = "Probability")
Window = input(200, title = "Window")
// Calculate the reurns
Returns = (close - close[1])/close[1]
// Calculate the calues of VaR - positive and negative returns in the percentiles
// determined by the Percentile parameter
VarLower = ta.percentile_linear_interpolation(Returns, Window, Percentile)
VarUpper = ta.percentile_linear_interpolation(Returns, Window, 100 - Percentile)
// Calculate the upper and lower lines of the VaR Channel
LowerLine = close*(1+VarLower)
UpperLine = close*(1+VarUpper)
// Plot upper and lower lines
plot(LowerLine, style = plot.style_stepline, linewidth = 3, title = "Upper line", color = color.blue)
plot(UpperLine, style = plot.style_stepline, linewidth = 3, title = "Lower line", color = color.blue)
|
Price Action Signals V2 | https://www.tradingview.com/script/CvM3K9lf-Price-Action-Signals-V2/ | sonnyparlin | https://www.tradingview.com/u/sonnyparlin/ | 99 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ sonnyparlin
// Chart update (8/7/2022)
// Note purple arrows denote weakness in price action and possible reversals
// red and green candles are considered to be stronger moves.
// New chart
// New chart
// removed indicator, new chart
//@version=5
indicator("Price Action Signals V2", overlay=true)
largeSpread = input.float(0.50, title="Large Spread candle if body > x", step=0.01)
irregularBody = input.float(.25, title="Mark irregular if candle spread is less than x on high volume", step=0.01)
irregularArrowColor = input(color.purple, title="Irregular Arrow Color")
volumeMA = input(12, title="Volume moving average length")
showIrregularArrows = input.bool(false)
lowerTail = 0.0
upperTail = 0.0
if (close > open)
upperTail := (high - close)
lowerTail := (open - low)
else
upperTail := (high - open)
lowerTail := (close - low)
candleBody = math.abs(close-open)
goodVolume = volume >= ta.sma(volume, volumeMA) * 2
cond2 = ((lowerTail > upperTail) and goodVolume and lowerTail > candleBody / 2 and candleBody > irregularBody)
cond3 = ((upperTail > lowerTail) and goodVolume and upperTail > candleBody / 2 and candleBody > irregularBody)
largeBodyGoodVolumeUp = close > open and candleBody > largeSpread and goodVolume
largeBodyGoodVolumeDown = close < open and candleBody > largeSpread and goodVolume
redPlot = 0.0
greenPlot = 0.0
if largeBodyGoodVolumeUp or cond2
greenPlot := close
if largeBodyGoodVolumeDown or cond3
redPlot := close
irregularUp = (candleBody < irregularBody and lowerTail > upperTail and close > open and goodVolume)
irregularDown = (candleBody < irregularBody and upperTail > lowerTail and open > close and goodVolume)
if irregularUp and showIrregularArrows
greenPlot := close
if irregularDown and showIrregularArrows
redPlot := close
if redPlot and greenPlot
if close > open
redPlot := 0
else
greenPlot := 0
plotshape(redPlot > 0.0, style=shape.triangledown,
location=location.abovebar, color=irregularDown ? color.purple : color.red)
plotshape(greenPlot > 0.0, style=shape.triangleup,
location=location.belowbar, color=irregularUp ? color.purple : color.green) |
OHLC MTF | https://www.tradingview.com/script/MkehSkui-OHLC-MTF/ | GhostTraderx1 | https://www.tradingview.com/u/GhostTraderx1/ | 248 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ GhostTraderx1
//@version=5
indicator("Previous OHLC", "OHLC MTF", true)
group1 = "General Settings"
string tf = input.timeframe("D", "Time Frame", group=group1)
int offset = input.int(1, "Offset", group=group1)
group2 = "Display Settings"
bool showLast = input.bool(false, "Show last OHLC levels only", group=group2)
bool extendLines = input.bool(false, "Extend OHLC levels", group=group2)
color bgcolor = input.color(color.new(color.silver, 80), "Background fill color", group=group2)
group3 = "Previous Open Level"
string openStyle = input.string(line.style_dashed, "Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group3)
color openColor = input.color(color.blue, "Previous High", group=group3)
int openWidth = input.int(1, "Thickness", group=group3)
group4 = "Previous High Level"
string highStyle = input.string(line.style_solid, "Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group4)
color highColor = input.color(color.green, "Previous High", group=group4)
int highWidth = input.int(1, "Thickness", group=group4)
group5 = "Previous Low Level"
string lowStyle = input.string(line.style_solid, "Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group5)
color lowColor = input.color(color.red, "Previous High", group=group5)
int lowWidth = input.int(1, "Thickness", group=group5)
group6 = "Previous Close Level"
string closeStyle = input.string(line.style_dashed, "Style", options=[line.style_solid, line.style_dashed, line.style_dotted], group=group6)
color closeColor = input.color(color.blue, "Previous High", group=group6)
int closeWidth = input.int(1, "Thickness", group=group6)
bool newSession = ta.change(time(tf))
op = request.security(syminfo.tickerid, tf, open[offset - 1])
hi = request.security(syminfo.tickerid, tf, high[offset - 1])
lo = request.security(syminfo.tickerid, tf, low[offset - 1])
cl = request.security(syminfo.tickerid, tf, close[offset - 1])
x = request.security(syminfo.tickerid, tf, time)
var line openLine = na
var line highLine = na
var line lowLine = na
var line closeLine = na
var linefill ohlc = na
displayLabels(x1, x2, x3, x4) =>
openLabel = label.new(line.get_x2(x1), line.get_y2(x1), "Prev. Open", xloc.bar_time, color=openColor, style=label.style_label_left, textcolor=color.white, size=size.tiny)
highLabel = label.new(line.get_x2(x2), line.get_y2(x2), "Prev. High", xloc.bar_time, color=highColor, style=label.style_label_left, textcolor=color.white, size=size.tiny)
lowLabel = label.new(line.get_x2(x3), line.get_y2(x3), "Prev. Low", xloc.bar_time, color=lowColor, style=label.style_label_left, textcolor=color.white, size=size.tiny)
closeLabel = label.new(line.get_x2(x4), line.get_y2(x4), "Prev. Close", xloc.bar_time, color=closeColor, style=label.style_label_left, textcolor=color.white, size=size.tiny)
label.delete(openLabel[1])
label.delete(highLabel[1])
label.delete(lowLabel[1])
label.delete(closeLabel[1])
displayLines(x1, x2) =>
opLine = line.new(x1, op[1], x2, op[1], xloc.bar_time, color=openColor, style=openStyle, width=openWidth)
hiLine = line.new(x1, hi[1], x2, hi[1], xloc.bar_time, color=highColor, style=highStyle, width=highWidth)
loLine = line.new(x1, lo[1], x2, lo[1], xloc.bar_time, color=lowColor, style=lowStyle, width=lowWidth)
clLine = line.new(x1, cl[1], x2, cl[1], xloc.bar_time, color=closeColor, style=closeStyle, width=closeWidth)
line.delete(opLine[1])
line.delete(hiLine[1])
line.delete(loLine[1])
line.delete(clLine[1])
[opLine, hiLine, loLine, clLine]
if newSession and not showLast
openLine := line.new(x[1], op, time, op, xloc.bar_time, color=openColor, style=openStyle, width=openWidth)
highLine := line.new(x[1], hi, time, hi, xloc.bar_time, color=highColor, style=highStyle, width=highWidth)
lowLine := line.new(x[1], lo, time, lo, xloc.bar_time, color=lowColor, style=lowStyle, width=lowWidth)
closeLine := line.new(x[1], cl, time, cl, xloc.bar_time, color=closeColor, style=closeStyle, width=closeWidth)
ohlc := linefill.new(highLine, lowLine, bgcolor)
if not extendLines
displayLabels(openLine, highLine, lowLine, closeLine)
if showLast
[openLine2, highLine2, lowLine2, closeLine2] = displayLines(x[1], x)
if not extendLines
displayLabels(openLine2, highLine2, lowLine2, closeLine2)
linefill.new(highLine2, lowLine2, bgcolor)
if extendLines
[openLine3, highLine3, lowLine3, closeLine3] = displayLines(x, time)
displayLabels(openLine3, highLine3, lowLine3, closeLine3)
linefill.new(highLine3, lowLine3, bgcolor)
|
Impactful pattern and candles pattern Alert | https://www.tradingview.com/script/DxfG9BsT-Impactful-pattern-and-candles-pattern-Alert/ | erfan_abedi | https://www.tradingview.com/u/erfan_abedi/ | 324 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ erfan_abedi
//@version=5
indicator("Impactful pattern and candles pattern Alert", shorttitle='Impactful pattern n Candles Alert', overlay=true , max_bars_back=5000)
//inputs
iptf = input.timeframe('60', title='IP:', group='timeframe', inline='tm', confirm = true, tooltip='choose timeframe for impactful patterns.')
sbuf = input.float(0.0 , 'stoploss:', group='buffering', inline='buff' , tooltip='amount of percent lower than real entry price or upper than stoploss in short position')
ebuf = input.float(0.0 , 'entry:', group='buffering', inline='buff', tooltip='amount of percent lower than real entry price or upper than stoploss in short position')
ipal = input.bool(true, title='ip alert', group='alertions', inline='al')
cal = input.bool(true, title='candle alert' , group='alertions', inline='al')
ibalt = input.bool(true, title= 'inside and outside bar', group='alertions', inline='al')
short = input.bool(false,title='Short position', confirm=true, group='timeframe', inline='tm')
txt = input.text_area('', title='type your text for alert')
perbar = input.string(alert.freq_once_per_bar, title= 'Ip alert frequency option: ', options=[alert.freq_once_per_bar ,alert.freq_once_per_bar_close,alert.freq_all], group='advance')
ipoff =input.int(4, title='IP pivot left and rightbars', group='advance', minval=1)
off = input.int(3, title='candle pivot left and rightbars' , group='advance', minval=1)
sym = syminfo.tickerid
//.................................................................................................
//candle
hi = high
lo =low
cl = close
op = open
bar_inde = bar_index
//ip pattern
bar_indexx = request.security(sym, iptf, bar_index)
//......................................................................................
//rally or drop or base?
hf = if open > close
(high - open + close - low) / (open - close) * -1
else if close > open
(high - close + open - low) / (close - open)
h = if hf == na
2.6
else
hf
s = if open > close
high - open + close - low - (open - close)
else if close > open
high - close + open - low - (close - open)
rally = h > 0 and h < 1 and s<0
drop = h < 0 and h > -1 and s<0
base= s>0
//......................................................
//legal for candle pattern
rbup = (lo[off]<lo[off+1] and cl[off]>cl[off+1]) and ta.pivotlow(lo,off,off) and short==false
rbdw = (hi[off]>hi[off+1] and cl[off]<cl[off+1]) and ta.pivothigh(hi,off,off) and short
krbup = cl[off]>hi[off+1] and op[off]<lo[off+1] and ta.pivotlow(lo,off,off) and short==false
krbdw = cl[off]<lo[off+1] and op[off]>hi[off+1] and ta.pivothigh(hi,off,off) and short
ebup = hi[off]<lo[off+1] and cl[off]>op[off] and ta.pivotlow(lo,off,off) and short==false
ebdw = lo[off]>hi[off+1] and cl[off]<op[off] and ta.pivothigh(hi,off,off) and short
pinup = (op[off] > cl[off] ? (cl[off]-lo[off])/(hi[off]-lo[off]) >= 2/3 : (op[off]-lo[off])/(hi[off]-lo[off]) >=2/3) and ta.pivotlow(lo,off,off) and short==false
pindw = (op[off] > cl[off] ? (hi[off]-op[off])/(hi[off]-lo[off]) >= 2/3 : (hi[off]-cl[off])/(hi[off]-lo[off]) >=2/3) and ta.pivothigh(hi,off,off) and short
tbrup = rally[off] and drop[off+1] and ta.pivotlow(lo,off,off) and short==false
tbrdw = drop[off] and rally[off+1] and ta.pivothigh(hi,off,off) and short
cup = cl[off+1]<op[off+1] and lo[off]<lo[off+1] and lo[off-1]>lo[off] and cl[off-1] > hi[off] and ta.pivotlow(lo,off,off) and short==false
cdw = cl[off+1]>op[off+1] and hi[off]>hi[off+1] and hi[off-1]<hi[off] and cl[off-1] < lo[off] and ta.pivothigh(hi,off,off) and short
ib= hi[off-1]<hi[off] and lo[off-1]>lo[off] and (ta.pivotlow(lo,off,off) or ta.pivothigh(hi,off,off) )
ob= hi[off]>hi[off+1] and lo[off]<lo[off+1] and (ta.pivotlow(lo,off,off) or ta.pivothigh(hi,off,off) )
//.............................................................................................................................
//-------------------ip pivots------------------------
pivot(a) =>
hh = request.security(sym, iptf, ta.valuewhen(ta.pivothigh(high,ipoff,ipoff),high[ipoff], a))
ll = request.security(sym, iptf, ta.valuewhen(ta.pivotlow(low,ipoff,ipoff),low[ipoff], a))
barl = request.security(sym, iptf, ta.valuewhen(ta.pivotlow(low,ipoff,ipoff),bar_index-ipoff, a))
barh= request.security(sym, iptf, ta.valuewhen(ta.pivothigh(high,ipoff,ipoff),bar_index-ipoff, a))
[hh,ll,barl,barh]
[ph0,pl0,pbl0,pbh0] = pivot(0)
[ph1,pl1,pbl1,pbh1] = pivot(1)
[ph2,pl2,pbl2,pbh2] = pivot(2)
basen = ta.valuewhen(base,bar_index, 0)
basennhi = ta.valuewhen(base,high, 0)
basennlo = ta.valuewhen(base,low, 0)
//--------------------------base finder----------------------------
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
basebuu() =>
basebu1 = 0
for i= ipoff to 0
if basen[i] <pbh0
basebu1 := basen[i]
basebu1
basebdd() =>
basebd1 = 0
for i= ipoff to 0
if basen[i] <pbl0
basebd1 := basen[i]
basebd1
basebu = request.security(sym, iptf, ta.valuewhen(basebuu()>0 , basebuu(), 0) )
basebd = request.security(sym, iptf, ta.valuewhen(basebdd()>0 , basebdd(), 0) )
basehiu = request.security(sym, iptf, high[bar_index - basebu])
baselou = request.security(sym, iptf,low[bar_index - basebu])
basehid = request.security(sym, iptf,high[bar_index - basebd])
baselod = request.security(sym, iptf, low[bar_index - basebd])
//...........................................................................
//legal for ip
//HnS and qm and we
hnsup = pl2<pl1 and ph0>ph1 and pl0>pl1 and ph1>pl1 and pl0<ph0 and pl0<ph1 and pbl0>pbh0 and pbh0>pbl1 and pbl1>pbh1 and pbl2<pbh1 and short
hnsdw = ph2>ph1 and ph0<ph1 and pl0<pl1 and ph1>pl1 and pl0<ph0 and pl0<ph1 and ph0>pl1 and pbl0<pbh0 and pbl1<pbh1 and pbl0>pbh1 and pbh2<pbl1 and short==false
qmup = pl2<pl0 and ph0>ph1 and pl0<pl1 and ph1>pl1 and pl0<ph0 and pl0<ph1 and pbl0>pbh0 and pbh0>pbl1 and pbl1>pbh1 and pbl2<pbh1 and short
qmdw = ph2>ph0 and ph0>ph1 and pl0<pl1 and ph1>pl1 and pl0<ph0 and pl0<ph1 and ph0>pl1 and pbl0<pbh0 and pbl1<pbh1 and pbl0>pbh1 and pbh2<pbl1 and short==false
weup = pl1 < baselou and basehiu<ph0 and baselou>pl0 and basebu<pbh0 and pbh0<pbl0 and pbl1>pbh1 and basebu>pbl1 and short
wedw = ph1>basehid and basehid<ph0 and baselod>pl0 and basebd<pbl0 and pbh0>pbl0 and basebd>pbh1 and pbl1<pbh1 and short==false
//.............................................................................................................................................
//lines
if (weup and iptf==timeframe.period)
line.new(pbl1, pl1, basebu, basehiu, color=color.red, width=5)
line.new(basebu, basehiu, basebu, baselou, color=color.red, width=5)
line.new(basebu, baselou, pbh0, ph0, color=color.red, width=5)
line.new(pbh0, ph0, pbl0, pl0, color=color.red, style=line.style_solid, width=5)
if (wedw and iptf==timeframe.period)
line.new(pbh1, ph1, basebd, baselod, color=color.green, width=5)
line.new(basebd, baselod, basebd, basehid, color=color.green, width=5)
line.new(basebd, basehid, pbl0, pl0, color=color.green, width=5)
line.new(pbl0, pl0, pbh0, ph0, color=color.green, style=line.style_solid, width=5)
if ((qmup or hnsup) and iptf==timeframe.period)
line.new(pbl2, pl2, pbh1, ph1, color=color.red, width=5)
line.new(pbh1, ph1, pbl1, pl1, color=color.red, width=5)
line.new(pbl1, pl1, pbh0, ph0, color=color.red, style=line.style_solid, width=5)
line.new(pbh0, ph0, pbl0, pl0, color=color.red, style=line.style_solid, width=5)
if ((qmdw or hnsdw) and iptf==timeframe.period)
line.new(pbh2, ph2, pbl1, pl1, color=color.green, width=5)
line.new(pbl1, pl1, pbh1, ph1, color=color.green, width=5)
line.new(pbh1, ph1, pbl0, pl0, color=color.green, style=line.style_solid, width=5)
line.new(pbl0, pl0, pbh0, ph0, color=color.green, style=line.style_solid, width=5)
//............................................................................................................................
//plots
plotshape(rbdw and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Bearish reversal bar', textcolor=color.red, editable = false, display =display.pane)
plotshape(krbdw and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Key reversal bar', textcolor=color.red , editable = false, display =display.pane)
plotshape(ebdw and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Bearish exhaustion bar', textcolor=color.red, editable = false, display =display.pane)
plotshape(pindw and short? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Bearish pin bar', textcolor=color.red, editable = false, display =display.pane)
plotshape(tbrdw and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Bearish two-bar reversal', textcolor=color.red, editable = false, display =display.pane)
plotshape(cdw and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Bearish tree-bar riversal', textcolor=color.red, editable = false, display =display.pane)
plotshape(ib and short ? close-open:na, offset= -1 * off +1, style=shape.arrowdown, color=color.red, text='Inside bar', textcolor=color.red, editable = false, display =display.pane)
plotshape(ob and short ? close-open:na, offset= -1 * off, style=shape.arrowdown, color=color.red, text='Outside bar', textcolor=color.red, editable = false , display =display.pane)
plotshape(rbup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Bullish reversal bar', textcolor=color.green,location=location.belowbar, editable = false, display =display.pane)
plotshape(krbup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Key reversal bar', textcolor=color.green,location=location.belowbar, editable = false, display =display.pane)
plotshape(ebup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Bullish exhaustion bar', textcolor=color.green,location=location.belowbar, editable = false,display =display.pane)
plotshape(pinup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Bullish pin bar', textcolor=color.green,location=location.belowbar, editable = false,display =display.pane)
plotshape(tbrup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Bullish two-bar reversal', textcolor=color.green,location=location.belowbar, editable = false,display =display.pane)
plotshape(cup and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Bullish three-bar riversal', textcolor=color.green,location=location.belowbar, editable = false,display =display.pane)
plotshape(ib and short==false ? close-open:na, offset= -1 * off +1, style=shape.arrowup, color=color.green, text='Inside bar', textcolor=color.green,location=location.belowbar, editable = false,display =display.pane)
plotshape(ob and short==false ? close-open:na, offset= -1 * off, style=shape.arrowup, color=color.green, text='Outside bar', textcolor=color.green,location=location.belowbar, editable = false,display = display.pane)
//............................................................................................................................................................................
//------------------------inside and outsidebar alerts-------------------------------------------------
bariu = ta.valuewhen(ta.crossover(close, ta.valuewhen(ib , high[off-1], 0)), bar_index, 0)
barou = ta.valuewhen(ta.crossover(close, ta.valuewhen(ob , high[off], 0)), bar_index, 0)
barid = ta.valuewhen(ta.crossunder(close, ta.valuewhen(ib , low[off-1], 0)), bar_index, 0)
barod = ta.valuewhen(ta.crossunder(close, ta.valuewhen(ob, low[off], 0)), bar_index, 0)
bari = ta.valuewhen(ib , bar_index[off-1], 0)
baro = ta.valuewhen(ob, bar_index[off], 0)
bardib = bari > baro ? bar_inde - bari : bar_inde - baro
ibal = ''
if bari>baro and bari>bariu[1] and bari>=barid and ta.crossover(close, ta.valuewhen(ib , high[off-1], 0))
if ibalt
alert( 'inside_bar just engulfed up.' + '\n' + 'good for long position.' + '\n' + txt)
ibal := 'insidebar engulfed up at '
else if bari<baro and baro>barou[1] and baro>=barod and ta.crossover(close, ta.valuewhen(ob , high[off], 0))
if ibalt
alert('outside_bar just engulfed up.' + '\n' + 'good for long position.'+ '\n' + txt)
ibal := 'outsidebar engulfed up at '
else if bari>baro and bari>barid[1] and bari>=bariu and ta.crossunder(close, ta.valuewhen(ib , low[off-1], 0))
if ibalt
alert( 'inside_bar just engulfed down.' + '\n' + 'good for short position.'+ '\n' + txt)
ibal := 'insidebar engulfed down at '
else if bari<baro and baro>barod[1] and baro>=barou and ta.crossunder(close, ta.valuewhen(ob , low[off], 0))
if ibalt
alert('outside_bar just engulfed down.' + '\n' + 'good for short position.'+ '\n' + txt)
ibal := 'outsidebar engulfed down at '
if ibal == ''
ibal := ibal[1]
//---------------------------------------------------------------------------------------------------
//alerts
alertip = if qmup
'Open your position!' + '\n' + 'IP pattern is Quasimodo for short position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring(ph1 - ((ebuf/100)*ph1)) + '\n' + 'stop loss:' +str.tostring(ph0 + ((sbuf/100)*ph0))
else if qmdw
'Open your position!' + '\n' + 'IP pattern is Quasimodo for long position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring(pl1 + ((ebuf/100)*pl1)) + '\n' + 'stop loss:' +str.tostring(pl0 - ((sbuf/100)*pl0))
else if hnsup
'Open your position!' + '\n' + 'IP pattern is Head and Shoulder for short position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring(ph1 - ((ebuf/100)*ph1)) + '\n' + 'stop loss:' +str.tostring(ph0 + ((sbuf/100)*ph0))
else if hnsdw
'Open your position!' + '\n' + 'IP pattern is Head and Shoulder for long position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring(pl1 + ((ebuf/100)*pl1)) + '\n' + 'stop loss:' +str.tostring(pl0 - ((sbuf/100)*pl0))
else if weup
'Open your position!' + '\n' + 'IP pattern is whipsaw engulfing for short position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring( baselou - ((ebuf/100)*baselou)) + '\n' + 'stop loss:' + str.tostring(ph0 + ((sbuf/100)*ph0))
else if wedw
'Open your position!' + '\n' + 'IP pattern is whipsaw engulfing for long position in the .' + str.tostring(iptf) + ' timeframe' + '\n' + 'entery price:' + str.tostring(basehid + ((ebuf/100)*basehid)) + '\n' + 'stop loss:' +str.tostring(pl0 - ((sbuf/100)*pl0))
else
'na'
barc = (bar_inde - ta.valuewhen(rbup or rbdw or krbup or krbdw or ebdw or ebup or pindw or pinup or tbrup or tbrdw or cup or cdw,bar_inde,0) ) + off
alertc = 'hi'
if rbup or rbdw
alertc :='reversal bar detected at '
else if krbup or krbdw
alertc :='key reversal bar detected at '
else if ebdw or ebup
alertc :='exhaustion bar detected at '
else if pindw or pinup
alertc :='pin bar detected at '
else if tbrup or tbrdw
alertc :='two-bar riversal detected at '
else if cup or cdw
alertc :='three-bar riversal detected at '
else
alertc:=alertc[1]
altimc = timeframe.period == 'D' ? 'Days ago' : timeframe.period== 'W' ? 'Weeks ago' : timeframe.period=='M' ? 'Mounth ago' : timeframe.period=='240' ?
'4h ago' : timeframe.period=='180' ? '3h ago' : timeframe.period=='120' ? '2h ago' : timeframe.period=='60' ? '1h ago' : timeframe.period=='45'
? '45minutes ago' : timeframe.period=='30' ? '30minutes ago' : timeframe.period=='15' ? '15minutes ago' : timeframe.period=='5' ? '5minutes ago' : timeframe.period=='3' ? '3minutes ago' :
timeframe.period=='1' ? '1minutes ago' : na
if (rbup or rbdw or krbup or krbdw or ebdw or ebup or pindw or pinup or tbrup or tbrdw or cup or cdw) and cal
alert(alertc + str.tostring(barc ) +' *' + altimc )
if (qmup or qmdw or wedw or weup or hnsup or hnsdw) and ipal
alert(alertip + '\n'+ alertc + str.tostring(barc ) +' *' + altimc + '\n' + ibal + str.tostring(bardib) + ' *' + altimc + '\n' + 'now price: ' + str.tostring(close) + '\n' + txt, perbar )
//-----------------------------------------------------------------------------------------
|
CDC Fibonacci Retracement and Extension | https://www.tradingview.com/script/Qd2blmLI-CDC-Fibonacci-Retracement-and-Extension/ | piriya33 | https://www.tradingview.com/u/piriya33/ | 375 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ piriya33
// Iteration of Kitti-Playbook Fibonacci Re-Extension 2Clicks R0.0
//@version=5
indicator("CDC Fibonacci Retracement and Extension","CDC Fib retrace/extend",
overlay = true)
// This indicator is meant to be used as a tool to quickly identify
// fibonacci retracements and projections in multiple charts during
// the same date range.
// Users can set the calculation date range and quickly flip through
// different charts for comparisons
//
// Steps for using this indicator is as follows:
// 1. Specify Start Date and End Date for calculations
// 2. Choose Open-ended mode for just retracements, this will disregard
// end date in calculations.
// 3. Select price source, if Use Highs/Lows is selected, the indicator will
// use high and low prices for calculation, if not, closing price eill
// be used instead
// 4. Select and/or modify retracement / projection lines as you see fit.
// 5. Enjoy the result!
dateSet = "Date and Data Setup"
levels = "Retracement Levels"
plevels = "Projection Levels"
labels = "Retracement Level Labels Setup"
startDate = input.time(timestamp("1 Jan 2014"),"Start Date",group=dateSet,
confirm = true)
endDate = input.time(timestamp("14 Nov 2021"), "End Date",inline = "end",
group=dateSet, confirm = true)
openEnd = input.bool(false,"Open ended?",inline = "end", group=dateSet)
sourceType = input.bool(true,"Use High/Low?",
inline = "toggle", group=dateSet)
labelSw = input.bool(true,"Show Labels",
inline = "toggle", group=dateSet)
// Inputs for Retracement Levels Calculations
lvl01 = input(0.236,"Retracement LV1",inline="lvl01",group=levels)
lvl02 = input(0.382,"Retracement LV2",inline="lvl02",group=levels)
lvl03 = input(0.618,"Retracement LV3",inline="lvl03",group=levels)
lvl04 = input(0.786,"Retracement LV4",inline="lvl04",group=levels)
lvl05 = input(0.887,"Retracement LV5",inline="lvl05",group=levels)
lvl06 = input(0.942,"Retracement LV6",inline="lvl06",group=levels)
lvl01sw = input.bool(false,"show",inline="lvl01",group=levels)
lvl02sw = input.bool(false,"show",inline="lvl02",group=levels)
lvl03sw = input.bool(true,"show",inline="lvl03",group=levels)
lvl04sw = input.bool(true,"show",inline="lvl04",group=levels)
lvl05sw = input.bool(true,"show",inline="lvl05",group=levels)
lvl06sw = input.bool(false,"show",inline="lvl06",group=levels)
lvl01cl = input.color(color.rgb(194, 141, 17, 50),inline="lvl01",group=levels)
lvl02cl = input.color(color.rgb(17, 194, 106, 50),inline="lvl02",group=levels)
lvl03cl = input.color(color.rgb(17, 147, 194, 50),inline="lvl03",group=levels)
lvl04cl = input.color(color.rgb(12, 86, 166, 50),inline="lvl04",group=levels)
lvl05cl = input.color(color.rgb(11, 36, 115, 50),inline="lvl05",group=levels)
lvl06cl = input.color(color.rgb(97, 13, 24, 50),inline="lvl06",group=levels)
// Inputs for projection levels calculations
plv01 = input(0.618,"Projection LV1",inline="plv01",group=plevels)
plv02 = input(0.786,"Projection LV2",inline="plv02",group=plevels)
plv03 = input(1.130,"Projection LV3",inline="plv03",group=plevels)
plv04 = input(1.618,"Projection LV4",inline="plv04",group=plevels)
plv05 = input(2.618,"Projection LV4",inline="plv05",group=plevels)
plv06 = input(4.236,"Projection LV4",inline="plv06",group=plevels)
plv01sw = input.bool(false,"show",inline="plv01",group=plevels)
plv02sw = input.bool(true,"show",inline="plv02",group=plevels)
plv03sw = input.bool(false,"show",inline="plv03",group=plevels)
plv04sw = input.bool(true,"show",inline="plv04",group=plevels)
plv05sw = input.bool(true,"show",inline="plv05",group=plevels)
plv06sw = input.bool(true,"show",inline="plv06",group=plevels)
plv01cl = input.color(color.rgb(189, 150, 0, 50),"",inline="plv01",group=plevels)
plv02cl = input.color(color.rgb(189, 120, 0, 50),"",inline="plv02",group=plevels)
plv03cl = input.color(color.rgb(189, 100, 0, 50),"",inline="plv03",group=plevels)
plv04cl = input.color(color.rgb(189, 70, 0, 50),"",inline="plv04",group=plevels)
plv05cl = input.color(color.rgb(189, 30, 0, 50),"",inline="plv05",group=plevels)
plv06cl = input.color(color.rgb(189, 0, 0, 50),"",inline="plv06",group=plevels)
strFormatSw = input.int(2,"Labels Precision",2,8, group=labels)
// Check if in calculation session
inSession = not openEnd ?
time >= startDate and time <= endDate :
time >= startDate
// Check if session has ended, if yes, start Projection calculations
outSession = not inSession and inSession[1]
// Declare Analysis Variables
float highSource = sourceType ? high : close
float lowSource = sourceType ? low : close
float pBase = ta.valuewhen(outSession,lowSource,0)
float maxINT = 2147483647.0
var lowestVal = maxINT
var highestVal = 0.0
var Range = 0.0
var pRange = 0.0
// Check for Lowest Price from Start Date then
// Check for Highest Price from Start Sate then
// Check for Highest Price again when new low is established within Range
if inSession
if lowSource < lowestVal
lowestVal := lowSource
if highSource > highestVal
highestVal := highSource
if lowestVal < lowestVal[1]
highestVal := highSource
Range := highestVal - lowestVal
// Calculate Retracement Levels
lvl01Line = highestVal - Range * lvl01
lvl02Line = highestVal - Range * lvl02
lvl03Line = highestVal - Range * lvl03
lvl04Line = highestVal - Range * lvl04
lvl05Line = highestVal - Range * lvl05
lvl06Line = highestVal - Range * lvl06
// Calculate Projection Levels
plv01Line = pBase + Range * plv01
plv02Line = pBase + Range * plv02
plv03Line = pBase + Range * plv03
plv04Line = pBase + Range * plv04
plv05Line = pBase + Range * plv05
plv06Line = pBase + Range * plv06
// Plot Levels
boundColor = color.gray
lowestBound = plot(inSession ? lowestVal : na,"Highest Value",boundColor)
highestBound = plot(inSession ? highestVal : na,"Lowest Value",boundColor)
lowSourceP = plot(lowSource,"Current low price source",display=display.none)
highSourceP = plot(highSource,"Current high price source",display=display.none)
lvlp01 = plot(inSession ? lvl01sw ? lvl01Line : na : na,"lvl01",lvl01cl)
lvlp02 = plot(inSession ? lvl02sw ? lvl02Line : na : na,"lvl02",lvl02cl)
lvlp03 = plot(inSession ? lvl03sw ? lvl03Line : na : na,"lvl03",lvl03cl)
lvlp04 = plot(inSession ? lvl04sw ? lvl04Line : na : na,"lvl04",lvl04cl)
lvlp05 = plot(inSession ? lvl05sw ? lvl05Line : na : na,"lvl05",lvl05cl)
lvlp06 = plot(inSession ? lvl06sw ? lvl06Line : na : na,"lvl06",lvl06cl)
plvpbase= plot(plv01sw or plv02sw or plv03sw or plv04sw ? pBase : na,
"Projection Base", color.gray)
plvp00 = plot(plv01sw or plv02sw or plv03sw or plv04sw ? pBase + Range : na,
"Projection 100%", color.gray)
plvp01 = plot(plv01sw ? plv01Line : na,"Projection 01",plv01cl)
plvp02 = plot(plv02sw ? plv02Line : na,"Projection 02",plv02cl)
plvp03 = plot(plv03sw ? plv03Line : na,"Projection 03",plv03cl)
plvp04 = plot(plv04sw ? plv04Line : na,"Projection 04",plv04cl)
plvp05 = plot(plv05sw ? plv05Line : na,"Projection 05",plv05cl)
plvp06 = plot(plv06sw ? plv06Line : na,"Projection 06",plv06cl)
fillColor01 = lvl01sw ? lowSource < lvl01Line ? color.new(lvl01cl,80) : na : na
fillColor02 = lvl02sw ? lowSource < lvl02Line ? color.new(lvl02cl,80) : na : na
fillColor03 = lvl03sw ? lowSource < lvl03Line ? color.new(lvl03cl,50) : na : na
fillColor04 = lvl04sw ? lowSource < lvl04Line ? color.new(lvl04cl,50) : na : na
fillColor05 = lvl05sw ? lowSource < lvl05Line ? color.new(lvl05cl,50) : na : na
fillColor06 = lvl06sw ? lowSource < lvl06Line ? color.new(lvl06cl,80) : na : na
fillColorP1 = plv01sw ? highSource > plv01Line ? color.new(plv01cl,85): na : na
fillColorP2 = plv02sw ? highSource > plv02Line ? color.new(plv02cl,85): na : na
fillColorP3 = plv03sw ? highSource > plv03Line ? color.new(plv03cl,70): na : na
fillColorP4 = plv04sw ? highSource > plv04Line ? color.new(plv04cl,60): na : na
fillColorP5 = plv05sw ? highSource > plv05Line ? color.new(plv05cl,50): na : na
fillColorP6 = plv06sw ? highSource > plv06Line ? color.new(plv06cl,40): na : na
fill(lowSourceP,lvlp01,fillColor01)
fill(lowSourceP,lvlp02,fillColor02)
fill(lowSourceP,lvlp03,fillColor03)
fill(lowSourceP,lvlp04,fillColor04)
fill(lowSourceP,lvlp05,fillColor05)
fill(lowSourceP,lvlp06,fillColor06)
fill(highSourceP,plvp01,fillColorP1)
fill(highSourceP,plvp02,fillColorP2)
fill(highSourceP,plvp03,fillColorP3)
fill(highSourceP,plvp04,fillColorP4)
fill(highSourceP,plvp05,fillColorP5)
fill(highSourceP,plvp06,fillColorP6)
// Labels
// Labels displays levels and price on each retracement / projection lines
strFormat = strFormatSw == 2 ? "{0,number,#.##}" :
strFormatSw == 3 ? "{0,number,#.###}" :
strFormatSw == 4 ? "{0,number,#.####}" :
strFormatSw == 5 ? "{0,number,#.#####}" :
strFormatSw == 6 ? "{0,number,#.######}" :
strFormatSw == 7 ? "{0,number,#.#######}" :
strFormatSw == 8 ? "{0,number,#.########}" : na
labelTopText = "High : " +str.format(strFormat,highestVal)
labelBotText = "Low : " +str.format(strFormat,lowestVal)
// Define Text for retracement levels
labelLVL01Text = str.tostring(lvl01*100)+"% : "+str.format(strFormat,lvl01Line)
labelLVL02Text = str.tostring(lvl02*100)+"% : "+str.format(strFormat,lvl02Line)
labelLVL03Text = str.tostring(lvl03*100)+"% : "+str.format(strFormat,lvl03Line)
labelLVL04Text = str.tostring(lvl04*100)+"% : "+str.format(strFormat,lvl04Line)
labelLVL05Text = str.tostring(lvl05*100)+"% : "+str.format(strFormat,lvl05Line)
labelLVL06Text = str.tostring(lvl06*100)+"% : "+str.format(strFormat,lvl06Line)
// Define text for projection levels
labelPLV01Text = "projection "+str.tostring(plv01*100)+"% : "+
str.format(strFormat,plv01Line)
labelPLV02Text = "projection "+str.tostring(plv02*100)+"% : "+
str.format(strFormat,plv02Line)
labelPLV03Text = "projection "+str.tostring(plv03*100)+"% : "+
str.format(strFormat,plv03Line)
labelPLV04Text = "projection "+str.tostring(plv04*100)+"% : "+
str.format(strFormat,plv04Line)
labelPLV05Text = "projection "+str.tostring(plv05*100)+"% : "+
str.format(strFormat,plv05Line)
labelPLV06Text = "projection "+str.tostring(plv06*100)+"% : "+
str.format(strFormat,plv06Line)
// Create Labels
x_time = openEnd ? time : endDate
labelTop = label.new(x = x_time, y = highestVal, text=labelTopText,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw ? labelTop[1] : labelTop)
labelLV1 = label.new(x = x_time, y = lvl01Line, text=labelLVL01Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl01sw ? labelLV1[1] : labelLV1)
labelLV2 = label.new(x = x_time, y = lvl02Line, text=labelLVL02Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl02sw ? labelLV2[1] : labelLV2)
labelLV3 = label.new(x = x_time, y = lvl03Line, text=labelLVL03Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl03sw ? labelLV3[1] : labelLV3)
labelLV4 = label.new(x = x_time, y = lvl04Line, text=labelLVL04Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl04sw ? labelLV4[1] : labelLV4)
labelLV5 = label.new(x = x_time, y = lvl05Line, text=labelLVL05Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl05sw ? labelLV5[1] : labelLV5)
labelLV6 = label.new(x = x_time, y = lvl06Line, text=labelLVL06Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and lvl06sw ? labelLV6[1] : labelLV6)
labelBot = label.new(x = x_time, y = lowestVal, text=labelBotText,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw ? labelBot[1] : labelBot)
labelPL1 = label.new(x = time, y = plv01Line, text=labelPLV01Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv01sw ? labelPL1[1] : labelPL1)
labelPL2 = label.new(x = time, y = plv02Line, text=labelPLV02Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv02sw ? labelPL2[1] : labelPL2)
labelPL3 = label.new(x = time, y = plv03Line, text=labelPLV03Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv03sw ? labelPL3[1] : labelPL3)
labelPL4 = label.new(x = time, y = plv04Line, text=labelPLV04Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv04sw ? labelPL4[1] : labelPL4)
labelPL5 = label.new(x = time, y = plv05Line, text=labelPLV05Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv05sw ? labelPL5[1] : labelPL5)
labelPL6 = label.new(x = time, y = plv06Line, text=labelPLV06Text,
xloc=xloc.bar_time, style = label.style_none)
label.delete(labelSw and not openEnd and plv06sw ? labelPL6[1] : labelPL6)
// END //
|
MTF EMA Ribbon & Bands + BB | https://www.tradingview.com/script/0AYkNiqr-MTF-EMA-Ribbon-Bands-BB/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("EMA โข Yata",
overlay = true)
// ------------------------------
groupMA = "Moving Average Ribbon"
// ------------------------------
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
"LSMA" => ta.linreg(source, length, offset=0)
// ------------------------------
maType = input.string("EMA", title="Moving Average Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA"], inline="MA01", group=groupMA)
trend_flip = input.int(defval=2, minval=0, title="Flip Trend Periods", inline="MA02", group=groupMA)
src = input(defval=close, title="Source", inline="MA02", group=groupMA)
visible1 = input.bool(true , title="MA 1:", inline="MA1", group=groupMA)
visible2 = input.bool(true , title="MA 2:", inline="MA2", group=groupMA)
visible3 = input.bool(true , title="MA 3:", inline="MA3", group=groupMA)
visible4 = input.bool(true , title="MA 4:", inline="MA4", group=groupMA)
visible5 = input.bool(true , title="MA 5:", inline="MA5", group=groupMA)
visible6 = input.bool(true , title="MA 6:", inline="MA6", group=groupMA)
visible7 = input.bool(false , title="MA 7:", inline="MA7", group=groupMA)
visible8 = input.bool(false , title="MA 8:", inline="MA8", group=groupMA)
visible9 = input.bool(false , title="MA 9:", inline="MA9", group=groupMA)
len1 = input.int(9 , minval=1, title="length", inline="MA1", group=groupMA)
len2 = input.int(21 , minval=1, title="length", inline="MA2", group=groupMA)
len3 = input.int(34 , minval=1, title="length", inline="MA3", group=groupMA)
len4 = input.int(55 , minval=1, title="length", inline="MA4", group=groupMA)
len5 = input.int(100 , minval=1, title="length", inline="MA5", group=groupMA)
len6 = input.int(200 , minval=1, title="length", inline="MA6", group=groupMA)
len7 = input.int(400 , minval=1, title="length", inline="MA7", group=groupMA)
len8 = input.int(800 , minval=1, title="length", inline="MA8", group=groupMA)
len9 = input.int(1600 , minval=1, title="length", inline="MA9", group=groupMA)
up_color1 = input.color(defval=color.new(#E12D7B, 25), title="up", inline="MA1", group=groupMA)
up_color2 = input.color(defval=color.new(#F67B52, 25), title="up", inline="MA2", group=groupMA)
up_color3 = input.color(defval=color.new(#EDCD3B, 25), title="up", inline="MA3", group=groupMA)
up_color4 = input.color(defval=color.new(#3BBC54, 25), title="up", inline="MA4", group=groupMA)
up_color5 = input.color(defval=color.new(#2665BD, 25), title="up", inline="MA5", group=groupMA)
up_color6 = input.color(defval=color.new(#481899, 25), title="up", inline="MA6", group=groupMA)
up_color7 = input.color(defval=color.new(#787b86, 75), title="up", inline="MA7", group=groupMA)
up_color8 = input.color(defval=color.new(#787b86, 75), title="up", inline="MA8", group=groupMA)
up_color9 = input.color(defval=color.new(#787b86, 75), title="up", inline="MA9", group=groupMA) // https://www.schemecolor.com/new-year-rainbow.php
down_color1 = input.color(defval=color.new(#F19A9C, 50), title="down", inline="MA1", group=groupMA)
down_color2 = input.color(defval=color.new(#FFC29F, 50), title="down", inline="MA2", group=groupMA)
down_color3 = input.color(defval=color.new(#FFFAAE, 50), title="down", inline="MA3", group=groupMA)
down_color4 = input.color(defval=color.new(#CDECAD, 50), title="down", inline="MA4", group=groupMA)
down_color5 = input.color(defval=color.new(#A0CDED, 50), title="down", inline="MA5", group=groupMA)
down_color6 = input.color(defval=color.new(#AF8FC1, 50), title="down", inline="MA6", group=groupMA)
down_color7 = input.color(defval=color.new(#787b86, 75), title="down", inline="MA7", group=groupMA)
down_color8 = input.color(defval=color.new(#787b86, 75), title="down", inline="MA8", group=groupMA)
down_color9 = input.color(defval=color.new(#787b86, 75), title="down", inline="MA9", group=groupMA) // https://www.schemecolor.com/thinnest-rainbow.php
// ------------------------------
ma1 = ma(src, len1, maType)
ma2 = ma(src, len2, maType)
ma3 = ma(src, len3, maType)
ma4 = ma(src, len4, maType)
ma5 = ma(src, len5, maType)
ma6 = ma(src, len6, maType)
ma7 = ma(src, len7, maType)
ma8 = ma(src, len8, maType)
ma9 = ma(src, len9, maType)
plot_color1 = visible1 ? ma1 >= ma1[trend_flip] ? up_color1 : down_color1 : na
plot_color2 = visible2 ? ma2 >= ma2[trend_flip] ? up_color2 : down_color2 : na
plot_color3 = visible3 ? ma3 >= ma3[trend_flip] ? up_color3 : down_color3 : na
plot_color4 = visible4 ? ma4 >= ma4[trend_flip] ? up_color4 : down_color4 : na
plot_color5 = visible5 ? ma5 >= ma5[trend_flip] ? up_color5 : down_color5 : na
plot_color6 = visible6 ? ma6 >= ma6[trend_flip] ? up_color6 : down_color6 : na
plot_color7 = visible7 ? ma7 >= ma7[trend_flip] ? up_color7 : down_color7 : na
plot_color8 = visible8 ? ma8 >= ma8[trend_flip] ? up_color8 : down_color8 : na
plot_color9 = visible9 ? ma9 >= ma9[trend_flip] ? up_color9 : down_color9 : na
map1 = plot(ma1, title="MA 1", style=plot.style_line, color=plot_color1, linewidth=1)
map2 = plot(ma2, title="MA 2", style=plot.style_line, color=plot_color2, linewidth=1)
map3 = plot(ma3, title="MA 3", style=plot.style_line, color=plot_color3, linewidth=1)
map4 = plot(ma4, title="MA 4", style=plot.style_line, color=plot_color4, linewidth=1)
map5 = plot(ma5, title="MA 5", style=plot.style_line, color=plot_color5, linewidth=1)
map6 = plot(ma6, title="MA 6", style=plot.style_line, color=plot_color6, linewidth=1)
map7 = plot(ma7, title="MA 7", style=plot.style_line, color=plot_color7, linewidth=1)
map8 = plot(ma8, title="MA 8", style=plot.style_line, color=plot_color8, linewidth=1)
map9 = plot(ma9, title="MA 9", style=plot.style_line, color=plot_color9, linewidth=1)
// ------------------------------
visiblefill = input.bool(false, title="Gradient Fill", inline="MA01", group=groupMA)
price = plot(close, title="Price Line", color=color.silver, display=display.none)
ma1color = (ma1 > ma1[1] ? color.new(#00FEEF, 95) : color.new(#E21B22, 95))
ma2color = (ma2 > ma2[1] ? color.new(#00FEEF, 95) : color.new(#E21B22, 95))
ma3color = (ma3 > ma3[1] ? color.new(#09EBEE, 95) : color.new(#F71746, 95))
ma4color = (ma4 > ma4[1] ? color.new(#09EBEE, 95) : color.new(#F71746, 95))
ma5color = (ma5 > ma5[1] ? color.new(#28ACEA, 95) : color.new(#F23D92, 95))
ma6color = (ma6 > ma6[1] ? color.new(#28ACEA, 95) : color.new(#F23D92, 95))
ma7color = (ma7 > ma7[1] ? color.new(#28ACEA, 95) : color.new(#CA3AB0, 95)) // https://www.schemecolor.com/light-green-to-blue-gradient.php
ma8color = (ma8 > ma8[1] ? color.new(#388EE9, 95) : color.new(#9138A7, 95)) // https://www.schemecolor.com/turquoise-to-blue-gradient.php
ma9color = (ma9 > ma9[1] ? color.new(#3D76E0, 95) : color.new(#69208E, 95)) // https://www.schemecolor.com/purple-red-gradient.php
fill(price, map1, visible1 and visiblefill ? ma1color : na, title="MA Fill 1")
fill(price, map2, visible2 and visiblefill ? ma2color : na, title="MA Fill 2")
fill(price, map3, visible3 and visiblefill ? ma3color : na, title="MA Fill 3")
fill(price, map4, visible4 and visiblefill ? ma4color : na, title="MA Fill 4")
fill(price, map5, visible5 and visiblefill ? ma5color : na, title="MA Fill 5")
fill(price, map6, visible6 and visiblefill ? ma6color : na, title="MA Fill 6")
fill(price, map7, visible7 and visiblefill ? ma7color : na, title="MA Fill 7")
fill(price, map8, visible8 and visiblefill ? ma8color : na, title="MA Fill 8")
fill(price, map9, visible9 and visiblefill ? ma9color : na, title="MA Fill 9")
// ----------------------------------------
groupMTF = "Moving Average Multi Timeframe"
// ----------------------------------------
maTypeMTF = input.string("EMA", title="Moving Average Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA"], inline="MTF0", group=groupMTF)
visibleMTF1 = input.bool(false, title="MA 1:", inline="MTF1", group=groupMTF)
visibleMTF2 = input.bool(false, title="MA 2:", inline="MTF2", group=groupMTF)
visibleMTF3 = input.bool(false, title="MA 3:", inline="MTF3", group=groupMTF)
visibleMTF4 = input.bool(false, title="MA 4:", inline="MTF4", group=groupMTF)
visibleMTF5 = input.bool(false, title="MA 5:", inline="MTF5", group=groupMTF)
visibleMTF6 = input.bool(false, title="MA 6:", inline="MTF6", group=groupMTF)
lenMTF1 = input.int(9 , title="length", inline="MTF1", group=groupMTF)
lenMTF2 = input.int(21 , title="length", inline="MTF2", group=groupMTF)
lenMTF3 = input.int(34 , title="length", inline="MTF3", group=groupMTF)
lenMTF4 = input.int(55 , title="length", inline="MTF4", group=groupMTF)
lenMTF5 = input.int(100 , title="length", inline="MTF5", group=groupMTF)
lenMTF6 = input.int(200 , title="length", inline="MTF6", group=groupMTF)
srcMTF = input(defval=close, title="Source", inline="MTF2", group=groupMTF)
// ----------------------------------------
maMTF1 = ma(srcMTF, lenMTF1, maTypeMTF)
maMTF2 = ma(srcMTF, lenMTF2, maTypeMTF)
maMTF3 = ma(srcMTF, lenMTF3, maTypeMTF)
maMTF4 = ma(srcMTF, lenMTF4, maTypeMTF)
maMTF5 = ma(srcMTF, lenMTF5, maTypeMTF)
maMTF6 = ma(srcMTF, lenMTF6, maTypeMTF)
res = input.timeframe(defval="D", title="Timef.", inline="MTF1", group=groupMTF)
MTF1 = request.security(syminfo.tickerid, res, maMTF1, gaps=barmerge.gaps_off)
MTF2 = request.security(syminfo.tickerid, res, maMTF2, gaps=barmerge.gaps_off)
MTF3 = request.security(syminfo.tickerid, res, maMTF3, gaps=barmerge.gaps_off)
MTF4 = request.security(syminfo.tickerid, res, maMTF4, gaps=barmerge.gaps_off)
MTF5 = request.security(syminfo.tickerid, res, maMTF5, gaps=barmerge.gaps_off)
MTF6 = request.security(syminfo.tickerid, res, maMTF6, gaps=barmerge.gaps_off)
plot(visibleMTF1 ? MTF1 : na, title="MA MTF 1", style=plot.style_stepline, color=color.new(#E12D7B, 50), linewidth=1)
plot(visibleMTF2 ? MTF2 : na, title="MA MTF 2", style=plot.style_stepline, color=color.new(#F67B52, 50), linewidth=1)
plot(visibleMTF3 ? MTF3 : na, title="MA MTF 3", style=plot.style_stepline, color=color.new(#EDCD3B, 50), linewidth=1)
plot(visibleMTF4 ? MTF4 : na, title="MA MTF 4", style=plot.style_stepline, color=color.new(#3BBC54, 50), linewidth=1)
plot(visibleMTF5 ? MTF5 : na, title="MA MTF 5", style=plot.style_stepline, color=color.new(#2665BD, 50), linewidth=1)
plot(visibleMTF6 ? MTF6 : na, title="MA MTF 6", style=plot.style_stepline, color=color.new(#481899, 50), linewidth=1)
// ----------------------------
groupB = "Moving Average Bands"
// ----------------------------
maTypeB = input.string("EMA", title="Moving Average Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA"], inline="MAB0", group=groupB)
visibleEB = input.bool(false, title="Bands:", inline="MAB1", group=groupB)
lengthEB = input.int(34, minval=1, title="length", inline="MAB1", group=groupB)
resEB = input.timeframe(defval="", title="Timef.", inline="MAB1", group=groupB)
highShortEMA = ma(high, lengthEB, maTypeB)
lowShortEMA = ma(low, lengthEB, maTypeB)
EMA = ma(close, lengthEB, maTypeB)
shortbandsHigh = ((highShortEMA - EMA) * math.phi) * math.pi + EMA
shortbandsLow = (-(EMA - lowShortEMA) * math.phi) * math.pi + EMA
shortbandsHighEMA = ta.wma(shortbandsHigh, 8)
shortbandsLowEMA = ta.wma(shortbandsLow, 8)
phiExtensionHigh = ((highShortEMA - EMA) * math.phi) * (math.phi + 4) + EMA
phiExtensionLow = (-(EMA - lowShortEMA) * math.phi) * (math.phi + 4) + EMA
phiExtensionHighEMA = ta.wma(phiExtensionHigh, 8)
phiExtensionLowEMA = ta.wma(phiExtensionLow, 8)
// ----------------------------
MTFhs = request.security(syminfo.tickerid, resEB, highShortEMA)
MTFls = request.security(syminfo.tickerid, resEB, lowShortEMA)
MTFsbh = request.security(syminfo.tickerid, resEB, shortbandsHighEMA)
MTFsbl = request.security(syminfo.tickerid, resEB, shortbandsLowEMA)
MTFhpeh = request.security(syminfo.tickerid, resEB, phiExtensionHighEMA)
MTFlpel = request.security(syminfo.tickerid, resEB, phiExtensionLowEMA)
highP1 = plot(visibleEB ? MTFhs : na , color=color.new(color.blue , 75), title = "B. Top Median Zone")
lowP1 = plot(visibleEB ? MTFls : na , color=color.new(color.blue , 75), title = "B. Bottom Median Zone")
highP3 = plot(visibleEB ? MTFsbh : na , color=color.new(color.orange , 75), title = "B. Lower Sell Zone")
lowP3 = plot(visibleEB ? MTFsbl : na , color=color.new(color.green , 75), title = "B. Higher Buy Zone")
phiPlotHigh = plot(visibleEB ? MTFhpeh : na , color=color.new(color.red , 75), title = "B. Top Sell Zone")
phiPlotLow = plot(visibleEB ? MTFlpel : na , color=color.new(color.teal , 75), title = "B. Bottom Buy Zone")
fill(phiPlotHigh, highP3, color.new(color.red , 97), title = "B. Sell Zone")
fill(lowP3, phiPlotLow , color.new(color.green , 97), title = "B. Buy Zone")
fill(highP1, lowP1 , color.new(color.silver, 97), title = "B. Median Zone")
// -----------------------------
groupHMA = "Hull Moving Average"
// -----------------------------
resHMA = input.timeframe(title="Time Frame", defval="", inline="HMA00", group=groupHMA)
trend_flipHMA = input.int(defval=2, minval=0, title="Flip Trend Periods:", inline="HMA0", group=groupHMA)
srcHMA = input(defval=close, title="Source", inline="HMA0", group=groupHMA)
visibleHMA1 = input.bool(false, title="HMA:", inline="HMA1", group=groupHMA)
lengthHMA1 = input.int(200, minval=1, title="length", inline="HMA1", group=groupHMA)
hullma1 = ta.wma(2*ta.wma(srcHMA, lengthHMA1/2)-ta.wma(srcHMA, lengthHMA1), math.floor(math.sqrt(lengthHMA1)))
hullmaS1 = request.security(syminfo.tickerid, resHMA, hullma1, gaps=barmerge.gaps_off)
up_colorHMA1 = input.color(defval=color.new(#00FEEF, 50), title="up", inline="HMA1", group=groupHMA)
down_colorHMA1 = input.color(defval=color.new(#E21B22, 50), title="down", inline="HMA1", group=groupHMA)
plot_colorHMA1 = visibleHMA1 ? hullmaS1 >= hullmaS1[trend_flipHMA] ? up_colorHMA1 : down_colorHMA1 : na
plot(visibleHMA1 ? hullmaS1 : na, title="HMA Line 1", style=plot.style_line, color=plot_colorHMA1, linewidth=2)
// ------------------------
groupBB = "Bollinger Bands"
// ------------------------
resBB = input.timeframe(defval="", title="Time Frame", inline="BB0", group=groupBB)
visibleBB = input.bool(false, title="BB:", inline="BB1", group=groupBB)
lengthBB = input.int(20, minval=1, title="length", inline="BB1", group=groupBB)
srcBB = input(defval=close, title="Source", inline="BB1", group=groupBB)
mult = input.float(2.0, minval=0.001, maxval=50, title="Standard Deviation", inline="BB2", group=groupBB)
basis = ta.sma(srcBB, lengthBB)
dev = mult * ta.stdev(srcBB, lengthBB)
offset = input.int(0, "Offset", minval=-500, maxval=500, inline="BB2", group=groupBB)
upper = basis + dev
lower = basis - dev
MTFbasis = request.security(syminfo.tickerid, resBB, basis)
MTFupper = request.security(syminfo.tickerid, resBB, upper)
MTFlower = request.security(syminfo.tickerid, resBB, lower)
plot(visibleBB ? MTFbasis : na, title="BB Basis", color=color.new(#787B86, 75), offset = offset)
p1 = plot(visibleBB ? MTFupper : na, title="BB Upper", color=color.new(#787B86, 75), offset = offset)
p2 = plot(visibleBB ? MTFlower : na, title="BB Lower", color=color.new(#787B86, 75), offset = offset)
fill(p1, p2, title = "BB Background", color=color.new(#787B86, 97))
// -------------------------
groupGC = "Gaussian Channel"
// -------------------------
f_filt9x(_a, _s, _i) =>
int _m2 = 0
int _m3 = 0
int _m4 = 0
int _m5 = 0
int _m6 = 0
int _m7 = 0
int _m8 = 0
int _m9 = 0
float _f = .0
_x = 1 - _a
// Weights.
// Initial weight _m1 is a pole number and equal to _i
_m2 := _i == 9 ? 36 : _i == 8 ? 28 : _i == 7 ? 21 : _i == 6 ? 15 : _i == 5 ? 10 : _i == 4 ? 6 : _i == 3 ? 3 : _i == 2 ? 1 : 0
_m3 := _i == 9 ? 84 : _i == 8 ? 56 : _i == 7 ? 35 : _i == 6 ? 20 : _i == 5 ? 10 : _i == 4 ? 4 : _i == 3 ? 1 : 0
_m4 := _i == 9 ? 126 : _i == 8 ? 70 : _i == 7 ? 35 : _i == 6 ? 15 : _i == 5 ? 5 : _i == 4 ? 1 : 0
_m5 := _i == 9 ? 126 : _i == 8 ? 56 : _i == 7 ? 21 : _i == 6 ? 6 : _i == 5 ? 1 : 0
_m6 := _i == 9 ? 84 : _i == 8 ? 28 : _i == 7 ? 7 : _i == 6 ? 1 : 0
_m7 := _i == 9 ? 36 : _i == 8 ? 8 : _i == 7 ? 1 : 0
_m8 := _i == 9 ? 9 : _i == 8 ? 1 : 0
_m9 := _i == 9 ? 1 : 0
// filter
_f := math.pow(_a, _i) * nz(_s) + _i * _x * nz(_f[1]) - (_i >= 2 ? _m2 * math.pow(_x, 2) * nz(_f[2]) : 0) + (_i >= 3 ? _m3 * math.pow(_x, 3) * nz(_f[3]) : 0) - (_i >= 4 ? _m4 * math.pow(_x, 4) * nz(_f[4]) : 0) + (_i >= 5 ? _m5 * math.pow(_x, 5) * nz(_f[5]) : 0) - (_i >= 6 ? _m6 * math.pow(_x, 6) * nz(_f[6]) : 0) + (_i >= 7 ? _m7 * math.pow(_x, 7) * nz(_f[7]) : 0) - (_i >= 8 ? _m8 * math.pow(_x, 8) * nz(_f[8]) : 0) + (_i == 9 ? _m9 * math.pow(_x, 9) * nz(_f[9]) : 0)
_f
f_pole(_a, _s, _i) =>
_f1 = f_filt9x(_a, _s, 1)
_f2 = _i >= 2 ? f_filt9x(_a, _s, 2) : 0
_f3 = _i >= 3 ? f_filt9x(_a, _s, 3) : 0
_f4 = _i >= 4 ? f_filt9x(_a, _s, 4) : 0
_f5 = _i >= 5 ? f_filt9x(_a, _s, 5) : 0
_f6 = _i >= 6 ? f_filt9x(_a, _s, 6) : 0
_f7 = _i >= 2 ? f_filt9x(_a, _s, 7) : 0
_f8 = _i >= 8 ? f_filt9x(_a, _s, 8) : 0
_f9 = _i == 9 ? f_filt9x(_a, _s, 9) : 0
_fn = _i == 1 ? _f1 : _i == 2 ? _f2 : _i == 3 ? _f3 : _i == 4 ? _f4 : _i == 5 ? _f5 : _i == 6 ? _f6 : _i == 7 ? _f7 : _i == 8 ? _f8 : _i == 9 ? _f9 : na
[_fn, _f1]
// -------------------------
visibleg = input(false, title="Show Gaussian Channel", inline="G1", group=groupGC)
int per = input.int(defval=144, minval=2, title="Samp. Period", inline="G2", group=groupGC)
int N = input.int(defval=4, minval=1, maxval=9, title="Poles", inline="G3", group=groupGC)
float multg = input.float(defval=1.414, minval=0, title="Filt. TR Mult.", inline="G3", group=groupGC)
srcg = input(defval=hlc3, title="Source", inline="G2", group=groupGC)
bool modeLag = input(defval=false, title="Reduced Lag Mode", inline="G4", group=groupGC)
bool modeFast = input(defval=false, title="Fast Response Mode", inline="G4", group=groupGC)
beta = (1 - math.cos(4 * math.asin(1) / per)) / (math.pow(1.414, 2 / N) - 1)
alpha = -beta + math.sqrt(math.pow(beta, 2) + 2 * beta)
lag = (per - 1) / (2 * N)
srcgdata = modeLag ? srcg + srcg - srcg[lag] : srcg
trdata = modeLag ? ta.tr(true) + ta.tr(true) - ta.tr(true)[lag] : ta.tr(true)
[filtn, filt1] = f_pole(alpha, srcgdata, N)
[filtntr, filt1tr] = f_pole(alpha, trdata, N)
filt = modeFast ? (filtn + filt1) / 2 : filtn
filttr = modeFast ? (filtntr + filt1tr) / 2 : filtntr
hband = filt + filttr * multg
lband = filt - filttr * multg
// -------------------------
resGC = input.timeframe(defval="", title="| Timef.", inline="G1", group=groupGC)
MTFfilt = request.security(syminfo.tickerid, resGC, filt, gaps=barmerge.gaps_off)
MTFhband = request.security(syminfo.tickerid, resGC, hband, gaps=barmerge.gaps_off)
MTFlband = request.security(syminfo.tickerid, resGC, lband, gaps=barmerge.gaps_off)
fcolor = MTFfilt > MTFfilt[1] ? #00FEEF : MTFfilt < MTFfilt[1] ? #E21B22 : color.silver
//barcolor = srcg > srcg[1] and srcg > filt and srcg < hband ? #0aff68 : srcg > srcg[1] and srcg >= hband ? #0aff1b : srcg <= srcg[1] and srcg > filt ? #00752d : srcg < srcg[1] and srcg < filt and srcg > lband ? #ff0a5a : srcg < srcg[1] and srcg <= lband ? #ff0a11 : srcg >= srcg[1] and srcg < filt ? #990032 : #cccccc
//barcolor(barcolor)
filtplot = plot(visibleg == true ? MTFfilt : na, title="GC Filter", color=fcolor, linewidth=2)
hbandplot = plot(visibleg == true ? MTFhband : na, title="GC Filtered True Range High Band", color=fcolor, transp=50, linewidth=2, display=display.none)
lbandplot = plot(visibleg == true ? MTFlband : na, title="GC Filtered True Range Low Band", color=fcolor, transp=50, linewidth=2, display=display.none)
fill(hbandplot, lbandplot, title="GC Channel Fill", color=fcolor, transp=95, display=display.all)
// ------------------
groupHT = "HalfTrend"
// ------------------
visibleh = input(false, title="Show HalfTrend", inline="H1", group=groupHT)
amplitude = input(defval=2, title="| Amplitude", inline="H1", group=groupHT)
var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)
var float up = 0.0
var float down = 0.0
atr2 = ta.atr(100) / 2
highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)
// ------------------
if nextTrend == 1
maxLowPrice := math.max(lowPrice, maxLowPrice)
if highma < maxLowPrice and close < nz(low[1], low)
trend := 1
nextTrend := 0
minHighPrice := highPrice
minHighPrice
else
minHighPrice := math.min(highPrice, minHighPrice)
if lowma > minHighPrice and close > nz(high[1], high)
trend := 0
nextTrend := 1
maxLowPrice := lowPrice
maxLowPrice
if trend == 0
if not na(trend[1]) and trend[1] != 0
up := na(down[1]) ? down : down[1]
else
up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])
up
else
if not na(trend[1]) and trend[1] != 1
down := na(up[1]) ? up : up[1]
else
down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])
down
ht = trend == 0 ? up : down
//htColor = trend == 0 ? color.new(#2196F3, 0) : color.new(#FF5252, 0)
htColor = ht >= ht[1] ? color.new(#2196F3, 0) : ht <= ht[1] ? color.new(#FF5252, 0) : color.new(#CCCCCC, 0)
htPlot = plot(visibleh == true ? ht : na, title="HalfTrend", linewidth=2, color=htColor)
// -------------------------------------
groupRV = "Rolling VWAP and StDev Bands"
// -------------------------------------
rVWAP(length) =>
float p = na
float vol = na
float sn = na
p_ = hlc3 * volume
p := nz(p[1]) + p_ - nz(p_[length])
vol := nz(vol[1]) + volume - nz(volume[length])
v = p / vol
sn_ = volume * (hlc3 - nz(v[1])) * (hlc3 - v)
sn := nz(sn[1]) + sn_ - nz(sn_[length])
std = math.sqrt(sn / vol)
[v, std]
// -------------------------------------
rolling_sv = input(false, title="Show Rolling VWAP", inline="RV1", group=groupRV)
rolling_dv = input(false, title="Show Rolling VWAP Bands |", inline="RV2", group=groupRV)
rolling_period = input(200, title="", inline="RV1", group=groupRV)
vR_color = input.color(color.new(color.silver, 50), title="", inline="RV1", group=groupRV)
showrL = input(false, "Lines", inline="RV2", group=groupRV)
showrLC = showrL ? display.all : display.none
[vwap_r, std_r] = rVWAP(rolling_period)
plot(rolling_sv == true ? vwap_r : na, title = "VWAP - Rolling", color=vR_color, linewidth = 1)
// -------------------------------------
fill_col_up3 = color.new(color.red , 85)
fill_col_up2 = color.new(color.red , 90)
fill_col_up = color.new(color.red , 95)
fill_col_mid = color.new(color.silver, 97)
fill_col_down = color.new(color.blue , 95)
fill_col_down2 = color.new(color.blue , 90)
fill_col_down3 = color.new(color.blue , 85)
b1_r_std_up_plot = plot(rolling_dv == true ? vwap_r + 0.618 * std_r : na, title="rVWAP - STDEV +1", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b1_r_std_dn_plot = plot(rolling_dv == true ? vwap_r - 0.618 * std_r : na, title="rVWAP - STDEV -1", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b2_r_std_up_plot = plot(rolling_dv == true ? vwap_r + 1 * std_r : na, title="rVWAP - STDEV +2", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b2_r_std_dn_plot = plot(rolling_dv == true ? vwap_r - 1 * std_r : na, title="rVWAP - STDEV -2", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b3_r_std_up_plot = plot(rolling_dv == true ? vwap_r + 1.618 * std_r : na, title="rVWAP - STDEV +3", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b3_r_std_dn_plot = plot(rolling_dv == true ? vwap_r - 1.618 * std_r : na, title="rVWAP - STDEV -3", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b4_r_std_up_plot = plot(rolling_dv == true ? vwap_r + 2 * std_r : na, title="rVWAP - STDEV +4", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
b4_r_std_dn_plot = plot(rolling_dv == true ? vwap_r - 2 * std_r : na, title="rVWAP - STDEV -4", color=color.new(color.silver, 75), style = plot.style_linebr, linewidth=1, display=showrLC)
fill(b1_r_std_up_plot, b1_r_std_dn_plot, title="rVWAP - STDEV +-1", color=fill_col_mid, display=display.none)
fill(b2_r_std_dn_plot, b1_r_std_dn_plot, title="rVWAP - STDEV -2", color=fill_col_down)
fill(b3_r_std_dn_plot, b2_r_std_dn_plot, title="rVWAP - STDEV -3", color=fill_col_down2)
fill(b4_r_std_dn_plot, b3_r_std_dn_plot, title="rVWAP - STDEV -4", color=fill_col_down3)
fill(b2_r_std_up_plot, b1_r_std_up_plot, title="rVWAP - STDEV +2", color=fill_col_up)
fill(b3_r_std_up_plot, b2_r_std_up_plot, title="rVWAP - STDEV +3", color=fill_col_up2)
fill(b4_r_std_up_plot, b3_r_std_up_plot, title="rVWAP - STDEV +4", color=fill_col_up3) |
EMA Cross (data chaining template) | https://www.tradingview.com/script/1OxN4rHC-EMA-Cross-data-chaining-template/ | Protervus | https://www.tradingview.com/u/Protervus/ | 23 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Protervus - https://protervus.trade
// [-------------- Start of your indicator's code --------------]
//@version=5
indicator("EMA Cross (data chaining)", overlay = true)
// Create inputs for our two EMAs
FastEmaLen = input.int(50, title = "Fast EMA Length")
SlowEmaLen = input.int(200, title = "Fast EMA Length")
// Calculate EMAs
FastEma = ta.ema(close, FastEmaLen)
SlowEma = ta.ema(close, SlowEmaLen)
// Create Entry conditions
BullishCross = ta.crossover(FastEma, SlowEma)
BearishCross = ta.crossunder(FastEma, SlowEma)
// Create Exit conditions
PriceAboveFastEma = ta.crossover(close, FastEma)
PriceBelowFastEma = ta.crossunder(close, FastEma)
// Create Filter conditions
FastAboveSlow = FastEma > SlowEma
SlowAboveFast = FastEma < SlowEma
// Show EMAs on chart
plot(FastEma, color = color.new(color.green, 0))
plot(SlowEma, color = color.new(color.red, 0))
// [-------------- End of your indicator's code ----------------]
//===================================================== START OF PROTERVUS TRADING TOOLKIT SNIPPET ========================================= Version 1.2 ===
// This snippet should be placed at the end of your code
//==========================================================================================================================================================
// CHAINED DATA INPUTS (do not edit)
//==========================================================================================================================================================
tooltip_source = 'Receive signals from an chained indicator'
tooltip_signal = 'Choose whether this indicator works as Signal or Filter for a chained indicator'
SourceGroup = '๐ Protervus Chaining'
ChainedIndicator = input.bool(false, title='Receive Data', group = SourceGroup, inline='input', tooltip = tooltip_source )
ExternalIndicator = input.source(close, title='', group = SourceGroup, inline='input' )
SignalMode = input.string(title='Output mode', defval='Signal', options=['Signal', 'Filter'], group = SourceGroup, tooltip = tooltip_signal )
ExtIndicatorData = nz(ExternalIndicator)
null = 0
//==========================================================================================================================================================
// CONDITIONS INPUTS (Your conditions go here) <-------------
//==========================================================================================================================================================
// You can null conditions you don't need, as well as adding new ones following the template below.
// Once the code has been compiled, you can enable the conditions by ticking the relevant box in the Settings panel.
EntryCondition_1 = input.bool(true, 'Ema Cross', group = 'Entry Conditions')
EntryCondition_2 = null //input.bool(false, 'Description of Entry condition', group = 'Entry Conditions')
EntryCondition_3 = null //input.bool(false, 'Description of Entry condition', group = 'Entry Conditions')
FilterCondition_1 = input.bool(false, 'Trend', group = 'Filters')
FilterCondition_2 = null //input.bool(false, 'Description of Filter condition', group = 'Filters')
ExitCondition_1 = input.bool(false, "Price crosses Fast Ema", group = "Exit Conditions")
ExitCondition_2 = null //input.bool(false, "Description of TakeProfit Condition", group = "Exit Conditions")
StopCondition_1 = null //input.bool(false, "Description of Stop Condition", group = "Stop Conditions")
StopCondition_2 = null //input.bool(false, "Description of Stop Condition", group = "Stop Conditions")
//==========================================================================================================================================================
// ENTRY \ FILTER CONDITIONS <-------------
//==========================================================================================================================================================
// You should now associate EntryCondition_X to Entry condition(s) scripted in your indicator - same for eventual Filters.
// By Default, EntryCondition_X can trigger both Long or Short signals, but you can also set conditions for Long Only or Short Only by separating inputs.
// (e.g. "LongEntryCondition_2 = null" and "ShortEntryCondition_2 = YOUR_CONDITION" will void Long Entry, keeping only the Short Entry as valid)
// Assign LONG ENTRY conditions --------------------------------------------------------------------------------------------------------------------------
LongEntryCondition_1 = BullishCross // Replace "null" with the condition of your Indicator or leave "null" to void this signal
LongEntryCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
LongFilterCondition_1 = FastAboveSlow // Replace "null" with the condition of your Indicator or leave "null" to void this signal
LongFilterCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare LONG ENTRY Conditions
LongCondition = SignalMode == 'Signal' ?
EntryCondition_1 and LongEntryCondition_1
or
EntryCondition_2 and LongEntryCondition_2
// If you don't use Filters, just leave "LongFilterCondition_X = null" and don't select "Filter" as Output mode
: SignalMode == "Filter" ?
FilterCondition_1 and LongFilterCondition_1
or
FilterCondition_2 and LongFilterCondition_2
: na // don't comment this
// Finalize LONG ENTRY signal (do not edit)
LongEntry = ChainedIndicator ? (ExtIndicatorData == 1 or ExtIndicatorData == 6) and LongCondition : LongCondition
// Assign SHORT ENTRY conditions ------------------------------------------------------------------------------------------------------------------------
ShortEntryCondition_1 = BearishCross // Replace "null" with the condition of your Indicator or leave "null" to void this signal
ShortEntryCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
ShortFilterCondition_1 = SlowAboveFast // Replace "null" with the condition of your Indicator or leave "null" to void this signal
ShortFilterCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare SHORT ENTRY Conditions
ShortCondition = SignalMode == 'Signal' ?
EntryCondition_1 and ShortEntryCondition_1
or
EntryCondition_2 and ShortEntryCondition_2
// If you don't use Filters, just leave "ShortFilterCondition_X = null" and don't select "Filter" as Output mode
: SignalMode == "Filter" ?
FilterCondition_1 and ShortFilterCondition_1
or
FilterCondition_2 and ShortFilterCondition_2
: na // don't comment this
// Finalize SHORT ENTRY signal (do not edit)
ShortEntry = ChainedIndicator ? (ExtIndicatorData == -1 or ExtIndicatorData == 6) and ShortCondition : ShortCondition
//==========================================================================================================================================================
// EXIT CONDITIONS (only in Signal mode) <-------------
//==========================================================================================================================================================
// Just like Entry conditions, you can add more Exit conditions by adding "or ExitCondition_X and LongExitCondition_X" in the Finalize section.
// Assign LONG EXIT conditions -----------------------------------------------------------------------------------------------------------------------------
LongExitCondition_1 = PriceBelowFastEma // Replace "null" with the condition of your Indicator or leave "null" to void this signal
LongExitCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare LONG EXIT conditions
LongExit =
ExitCondition_1 and LongExitCondition_1
or
ExitCondition_2 and LongExitCondition_2
// Assign SHORT EXIT conditions ----------------------------------------------------------------------------------------------------------------------------
ShortExitCondition_1 = PriceAboveFastEma // Replace "null" with the condition of your Indicator or leave "null" to void this signal
ShortExitCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare SHORT EXIT conditions
ShortExit =
ExitCondition_1 and ShortExitCondition_1
or
ExitCondition_2 and ShortExitCondition_2
//==========================================================================================================================================================
// STOP CONDITIONS (only in Signal mode) <-------------
//==========================================================================================================================================================
// Just like Entry and Exit conditions, you can add more Stop conditions by adding "or StopCondition_X and StopExitCondition_X" in the Finalize section.
// Also, If you want to use Exit Conditions as general closing signal, you can set the Stop = Exit, the rest of the code will handle that situation.
// Example: "LongStop = LongExit" and "ShortStop = ShortExit"
// Assigning LONG STOP conditions --------------------------------------------------------------------------------------------------------------------------
LongStopCondition_1 = PriceBelowFastEma // Replace "null" with the condition of your Indicator or leave "null" to void this signal
LongStopCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare LONG STOP conditions
LongStop =
StopCondition_1 and LongStopCondition_1
or
StopCondition_2 and LongStopCondition_2
// Assigning SHORT STOP conditions -------------------------------------------------------------------------------------------------------------------------
ShortStopCondition_1 = PriceAboveFastEma // Replace "null" with the condition of your Indicator or leave "null" to void this signal
ShortStopCondition_2 = null // Replace "null" with the condition of your Indicator or leave "null" to void this signal
// Prepare SHORT STOP conditions
ShortStop =
StopCondition_1 and ShortStopCondition_1
or
StopCondition_2 and ShortStopCondition_2
//==========================================================================================================================================================
// Signal Output (do not edit)
//==========================================================================================================================================================
// Prepare output signal and handle situations where more conditions are valid at the same time. Protervus Trading Toolkit will know what to do.
Signal
= LongEntry and not ShortEntry ? 1
: ShortEntry and not LongEntry ? -1
: LongExit ? 2
: ShortExit ? -2
: LongStop ? 3
: ShortStop ? -3
: 0
// This part must be separated from the initial Signal operation, otherwise the code will stop at the first condition when running.
if LongEntry and ShortEntry
Signal := 6
if (LongExit and ShortStop) or (ShortExit and LongStop) or (LongExit and LongStop) or (ShortExit and ShortStop)
Signal := 4
if LongEntry and (LongExit or LongStop or ShortExit and ShortStop)
Signal := 5
if ShortEntry and (ShortExit or ShortStop or LongExit and LongStop)
Signal := -5
// Send data via plot, ready to be received from a chained indicator or Protervus Trading Toolkit
plot(Signal, title='๐ Chained Data', display=display.none)
//==========================================================================================================================================================
// Preventing issues with Signal plot <-------------
//==========================================================================================================================================================
// Since we plot the Signal for Chained Data as "invisible", it cannot be the only plot in the code, otherwise it will lead to an error.
// So, if your indicator DOES NOT plot anything on the chart, please un-comment the line below:
// plot(close < 0 ? close : na, title='Dummy Plot')
//==========================================================================================================================================================
// SIGNALS LABEL (optional) <-------------
//==========================================================================================================================================================
// Optionally show labels for your signals. To add markers for Exits or Stops, just clone a label and replace variables (e.g. LongEntry --> LongExit),
// making sure to give labels unique names and text.
// LongLabel = LongEntry and SignalMode == 'Signal' ?
// label.new(bar_index,
// y=close,
// text='L',
// color=color.green,
// textcolor=color.white,
// style=label.style_label_upper_right,
// yloc=yloc.price,
// size=size.normal)
// : na
// label.delete(not LongEntry ? LongLabel : na)
// ShortLabel = ShortEntry and SignalMode == 'Signal' ?
// label.new(bar_index,
// y=close,
// text='S',
// color=color.red,
// textcolor=color.white,
// style=label.style_label_lower_right,
// yloc=yloc.price,
// size=size.normal)
// : na
// label.delete(not ShortEntry ? ShortLabel : na)
|
WAMASAMA/Intraday SL | https://www.tradingview.com/script/siQQ8M9p-WAMASAMA-Intraday-SL/ | avsr90 | https://www.tradingview.com/u/avsr90/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ avsr90
//@version=5
indicator(title="WAMASAMA",shorttitle="WASA",precision=2,overlay=false,max_bars_back=5000)
//Moving averages
Moving_Average1=ta.ema(close,9)
Moving_Average2=ta.ema(close,21)
Moving_Average3=ta.ema(close,50)
//Wama and Sama
wama1=Moving_Average1-Moving_Average2
sama1=Moving_Average2-Moving_Average1
wama11=wama1-sama1
wama2=Moving_Average2-Moving_Average3
sama2=Moving_Average3-Moving_Average2
wama22=wama2-sama2
WA_MA=(wama11+wama22)
SA_MA=(wama11-wama22)
//Upentry and Dnentry
Up_entry=ta.crossover(WA_MA,SA_MA)
Dn_entry=ta.crossunder(WA_MA,SA_MA)
plot(WA_MA,color=(WA_MA>WA_MA[1] ?color.green:color.red),style=plot.style_columns,title="WAMA")
plotshape(Up_entry,title="Upentry",color=color.green,text="U",textcolor=color.green,style=shape.arrowup,location=
location.bottom, size=size.normal)
plotshape(Dn_entry,title="Dnentry",color=color.red,text="D",textcolor=color.red,style=shape.arrowdown,location=
location.top, size=size.normal)
//intraday Stop Loss Calxulations
Res=input.timeframe(defval="D",title="resolution")
[Open_Price,Last_Price,OPCL_Dif]= request.security(syminfo.tickerid ,Res,[close[1],close,close-close[1]],barmerge.gaps_off, barmerge.lookahead_on)
Ch_Open= ta.change(Open_Price)
Length=int(math.max(1, nz(ta.barssince(Ch_Open)) + 1))
Op=math.round_to_mintick(Open_Price)
Cl=math.round_to_mintick(Last_Price)
Dif=math.round_to_mintick(Last_Price-Open_Price)
//Table
BT = 0
TW = 0
TH=0
TL = input.string("bottom_center", title='Select Table Position',options=["top_left","top_center","top_right",
"middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"] ,
tooltip="Default location is at bottom_center")
TS = input.string("Auto", title='Select Table Text Size',options=["Auto","Huge","Large","Normal","Small",
"Tiny"] , tooltip="Default Text Size is Auto")
assignedposition = switch TL
"top_left" => position.top_left
"top_center" => position.top_center
"top_right" => position.top_right
"middle_left" => position.middle_left
"middle_center" => position.middle_center
"middle_right" => position.middle_right
"bottom_left" => position.bottom_left
"bottom_center" => position.bottom_center
"bottom_right" => position.bottom_right
celltextsize = switch TS
"Auto" => size.auto
"Huge" => size.huge
"Large" => size.large
"Normal" => size.normal
"Small" => size.small
"Tiny" => size.tiny
var table i = table.new (TL,6, 6, color.yellow,border_width=BT)
if barstate.islast
table.cell(i, 1, 1, "Open ",text_size=celltextsize,width=TW,height=TH,bgcolor=color.green)
table.cell(i, 2, 1, "Close ",text_size=celltextsize,width=TW,height=TH,bgcolor=color.green)
table.cell(i, 3, 1, "Op-Cl ",text_size=celltextsize,width=TW,height=TH,bgcolor=color.green)
table.cell(i, 1, 2, str.tostring(Op) ,text_size=celltextsize, width=TW,height=TH)
table.cell(i, 2, 2, str.tostring(Cl) ,text_size=celltextsize, width=TW,height=TH,text_color=Last_Price>Last_Price[1] ?
color.green:color.red)
table.cell(i, 3, 2, str.tostring(Dif) ,text_size=celltextsize, width=TW,height=TH,text_color=OPCL_Dif>0?color.green:color.red)
|
Spot v Perp aggrRollingVWAP | https://www.tradingview.com/script/NZACNYxi-Spot-v-Perp-aggrRollingVWAP/ | TraderKalis | https://www.tradingview.com/u/TraderKalis/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// RVWAP code is from tradingview, I've just added EMAs to it
// @TRaderKalis
//@version=5
indicator("SPOTvPERP aggrRVWAP", "SPOTvPERP aggrRVWAP", true)
import PineCoders/ConditionalAverages/1 as pc
// โโโโโโโโโโโโโโโโโโโโ Constants and Inputs {
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int MS_IN_DAY = MS_IN_HOUR * 24
var string TT_WINDOW = "By default, the time period used to calculate the RVWAP automatically adjusts with the chart's timeframe.
Check this to use a fixed-size time period instead, which you define with the following three values."
var string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period.
This avoids situations where a large time gap between two bars would cause the time window to be empty."
var string TT_STDEV = "The multiplier for the standard deviation bands offset above and below the RVWAP. Example: 1.0 is 100% of the offset value.
\n\nNOTE: A value of 0.0 will hide the bands."
float srcInput = input.source(hlc3, "Source")
var string GRP2 = 'โโโโโโโโโโโ โโTime Periodโโ โโโโโโโโโโโ'
bool fixedTfInput = input.bool(false, "Use a fixed time period", group = GRP2)
int daysInput = input.int(1, "Days", minval = 0, group = GRP2) * MS_IN_DAY
int hoursInput = input.int(0, "Hours", minval = 0, group = GRP2) * MS_IN_HOUR
int minsInput = input.int(0, "Minutes", minval = 0, group = GRP2) * MS_IN_MIN
bool tableInput = input.bool(true, "Show time period", group = GRP2)
string textSizeInput = input.string("large", "Text size", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string tableYposInput = input.string("bottom", "Positionโโโโโ", inline = "21", group = GRP2, options = ["top", "middle", "bottom"])
string tableXposInput = input.string("right", "", inline = "21", group = GRP2, options = ["left", "center", "right"])
var string GRP3 = 'โโโโโโโโโ โDeviation Bandsโ โโโโโโโโโ'
stdevMult1 = input.float(defval = 1.9, title = "Inside Band")
stdevMult2 = input.float(defval = 3.1, title = "Outside Band")
// }
// โโโโโโโโโโโโโโโโโโโโ Functions {
timeStep() =>
// @function Determines a time period from the chart's timeframe.
// @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RVWAP calculation.
int tfInMs = timeframe.in_seconds() * 1000
float step =
switch
tfInMs <= MS_IN_MIN => MS_IN_HOUR
tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4
tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1
tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3
tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7
tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375
tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90
=> MS_IN_DAY * 365
int result = int(step)
tfString(int timeInMs) =>
// @function Produces a string corresponding to the input time in days, hours, and minutes.
// @param (series int) A time value in milliseconds to be converted to a string variable.
// @returns (string) A string variable reflecting the amount of time from the input time.
int s = timeInMs / 1000
int m = s / 60
int h = m / 60
int tm = math.floor(m % 60)
int th = math.floor(h % 24)
int d = math.floor(h / 24)
string result =
switch
d == 30 and th == 10 and tm == 30 => "1M"
d == 7 and th == 0 and tm == 0 => "1W"
=>
string dStr = d ? str.tostring(d) + "D " : ""
string hStr = th ? str.tostring(th) + "H " : ""
string mStr = tm ? str.tostring(tm) + "min" : ""
dStr + hStr + mStr
// }
// โโโโโโโโโโโโโโโโโโโโ SPOT Calculations and Plots {
// Stop the indicator on charts with no volume.
if barstate.islast and ta.cum(nz(volume)) == 0
runtime.error("No volume is provided by the data vendor.")
// RVWAP
var int timeInMs = fixedTfInput ? minsInput + hoursInput + daysInput : timeStep()
float spotCoinVol = request.security('COINBASE:BTCUSD', timeframe.period, volume)
float spotBinVol = request.security('BINANCE:BTCUSDT', timeframe.period, volume)
float spotFtxVol = request.security('FTX:BTCUSD', timeframe.period, volume)
float spotFinexVol = request.security('BITFINEX:BTCUSD', timeframe.period, volume)
float spotOkxVol = request.security('OKX:BTCUSDT', timeframe.period, volume)
float spotAggrVol = (spotCoinVol + spotBinVol + spotFtxVol + spotFinexVol + spotOkxVol)
float spotSumSrcVol = pc.totalForTimeWhen(srcInput * spotAggrVol, timeInMs, true, 10)
float spotSumVol = pc.totalForTimeWhen(spotAggrVol, timeInMs, true, 10)
float spotSumSrcSrcVol = pc.totalForTimeWhen(spotAggrVol * math.pow(srcInput, 2), timeInMs, true, 10)
float spotRollingVWAP = spotSumSrcVol / spotSumVol
float spotVariance = spotSumSrcSrcVol / spotSumVol - math.pow(spotRollingVWAP, 2)
spotVariance := spotVariance < 0 ? 0 : spotVariance
float stDev = math.sqrt(spotVariance)
plot(spotRollingVWAP, "Spot Rolling VWAP", color = color.new(#F2A900, 25))
// โโโโโโโโโโโโโโโโโโโโ PERP Calculations and Plots {
// Stop the indicator on charts with no volume.
if barstate.islast and ta.cum(nz(volume)) == 0
runtime.error("No volume is provided by the data vendor.")
//RVWAP
float perpBinVol = request.security('BINANCE:BTCUSDTPERP', timeframe.period, volume)
float perpMexVol = request.security('BITMEX:XBTUSD', timeframe.period, volume)
float perpFtxVol = request.security('FTX:BTCPERP', timeframe.period, volume)
float perpBybitVol = request.security('BYBIT:BTCUSDT', timeframe.period, volume)
float perpOkxVol = request.security('OKX:BTCUSDTPERP', timeframe.period, volume)
float perpAggrVol = (perpBinVol + perpMexVol + perpFtxVol + perpBybitVol + perpOkxVol)
float perpSumSrcVol = pc.totalForTimeWhen(srcInput * perpAggrVol, timeInMs, true, 10)
float perpSumVol = pc.totalForTimeWhen(perpAggrVol, timeInMs, true, 10)
float perpSumSrcSrcVol = pc.totalForTimeWhen(perpAggrVol * math.pow(srcInput, 2), timeInMs, true, 10)
float perpRollingVWAP = perpSumSrcVol / perpSumVol
float perpVariance = perpSumSrcSrcVol / perpSumVol - math.pow(perpRollingVWAP, 2)
perpVariance := perpVariance < 0 ? 0 : perpVariance
plot(perpRollingVWAP, "Perp Rolling VWAP", color = color.new(#00BCD4, 25))
//โโโโโโโโโโโโโโโโโโโโ aggr Calculations and Plots {
//stDev Bands
aggrVol = spotAggrVol + perpAggrVol
float sumSrcVol = pc.totalForTimeWhen(srcInput * aggrVol, timeInMs, true, 10)
float sumVol = pc.totalForTimeWhen(aggrVol, timeInMs, true, 10)
float sumSrcSrcVol = pc.totalForTimeWhen(aggrVol * math.pow(srcInput, 2), timeInMs, true, 10)
float aggrRollingVWAP = sumSrcVol / sumVol
float upperBand1 = aggrRollingVWAP + stDev * stdevMult1
float lowerBand1 = aggrRollingVWAP - stDev * stdevMult1
p1 = plot(stdevMult1 != 0 ? upperBand1 : na, "Inside Upper Band", color = color.new(#b9b8b8, 50), display = display.none)
p2 = plot(stdevMult1 != 0 ? lowerBand1 : na, "Inside Lower Band", color = color.new(#b9b8b8, 50), display = display.none)
float upperBand2 = aggrRollingVWAP + stDev * stdevMult2
float lowerBand2 = aggrRollingVWAP - stDev * stdevMult2
p3 = plot(stdevMult2 != 0 ? upperBand2 : na, "Outside Upper Band", color = color.new(#b9b8b8, 25))
p4 = plot(stdevMult2 != 0 ? lowerBand2 : na, "Outside Upper Band", color = color.new(#b9b8b8, 25))
fill(p1, p3, color = color.new(#b9b8b8, 95))
fill(p2, p4, color = color.new(#b9b8b8, 95))
// Display of time period.
var table tfDisplay = table.new(tableYposInput + "_" + tableXposInput, 1, 1)
if tableInput
table.cell(tfDisplay, 0, 0, tfString(timeInMs), bgcolor = na, text_color = color.new(#9a6c00, 0), text_size = textSizeInput)
// }
|
MTF VWAP & StDev Bands | https://www.tradingview.com/script/l4sEYRwV-MTF-VWAP-StDev-Bands/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 135 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("VWAP โข Yata",
overlay = true)
// ----------------------------------------
groupVWAP = "Volume Weighted Average Price"
// ----------------------------------------
computeVWAP(src, isNewPeriod) =>
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
_vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = math.sqrt(variance)
[_vwap, stDev]
// ----------------------------------------
compute_stDEV(_vwap, stDev, stDevMultiplier_1, stDevMultiplier_2, stDevMultiplier_3, stDevMultiplier_4, stDevMultiplier_5, stDevMultiplier_6) =>
upperBand_6 = _vwap + stDev * stDevMultiplier_6
upperBand_5 = _vwap + stDev * stDevMultiplier_5
upperBand_4 = _vwap + stDev * stDevMultiplier_4
upperBand_3 = _vwap + stDev * stDevMultiplier_3
upperBand_2 = _vwap + stDev * stDevMultiplier_2
upperBand_1 = _vwap + stDev * stDevMultiplier_1
lowerBand_1 = _vwap - stDev * stDevMultiplier_1
lowerBand_2 = _vwap - stDev * stDevMultiplier_2
lowerBand_3 = _vwap - stDev * stDevMultiplier_3
lowerBand_4 = _vwap - stDev * stDevMultiplier_4
lowerBand_5 = _vwap - stDev * stDevMultiplier_5
lowerBand_6 = _vwap - stDev * stDevMultiplier_6
[upperBand_6, upperBand_5, upperBand_4, upperBand_3, upperBand_2, upperBand_1, lowerBand_1, lowerBand_2, lowerBand_3, lowerBand_4, lowerBand_5, lowerBand_6]
// ----------------------------------------
f_drawLabel(_x, _y, _text, _textcolor, _style, _size) =>
var _label = label.new(
x = _x,
y = _y,
text = _text,
textcolor = _textcolor,
style = _style,
size = _size,
xloc = xloc.bar_time
)
label.set_xy(_label, _x, _y)
// ----------------------------------------
src = input(hlc3, title="VWAP Source", inline="V0", group=groupVWAP)
vD_color = input.color(color.new(#E12D7B, 50), title="" , inline="V1", group=groupVWAP)
vW_color = input.color(color.new(#F67B52, 50), title="" , inline="V2", group=groupVWAP)
vM_color = input.color(color.new(#EDCD3B, 50), title="" , inline="V3", group=groupVWAP)
vQ_color = input.color(color.new(#3BBC54, 50), title="" , inline="V4", group=groupVWAP)
vY_color = input.color(color.new(#2665BD, 50), title="" , inline="V5", group=groupVWAP)
plot_vD = input(true , title="Show Daily VWAP" , inline="V1", group=groupVWAP)
plot_vW = input(true , title="Show Weekly VWAP" , inline="V2", group=groupVWAP)
plot_vM = input(true , title="Show Monthly VWAP" , inline="V3", group=groupVWAP)
plot_vQ = input(false , title="Show Quarterly VWAP" , inline="V4", group=groupVWAP)
plot_vY = input(false , title="Show Yearly VWAP" , inline="V5", group=groupVWAP)
// ----------------------------------
groupSTD = "Standard Deviation Bands"
// ----------------------------------
Std_selection = input.string("Month", title="Timeframe", options = ["Day", "Week", "Month", "Quarter", "Year"], inline="STD0", group=groupSTD)
showStd = input(true, title="Show VWAP Bands |", inline="STD1", group=groupSTD)
showpStd = input(false, title="Show Prev. VWAP Bands |", inline="STD2", group=groupSTD)
showL = input(false, title="Lines", inline="STD1", group=groupSTD)
showpL = input(true, title="Lines", inline="STD2", group=groupSTD)
showLC = showL ? display.all : display.none
showpLC = showpL ? display.all : display.none
fill_bands = input(true, title="Fill", inline="STD1", group=groupSTD)
fill_pbands = input(false, title="Fill", inline="STD2", group=groupSTD)
stDevMultiplier_1 = input.float(0.618 , step=0.1, title="StDev 1:", inline="StDev1", group=groupSTD)
stDevMultiplier_2 = input.float(1.0 , step=0.1, title="StDev 2:", inline="StDev2", group=groupSTD)
stDevMultiplier_3 = input.float(1.618 , step=0.1, title="StDev 3:", inline="StDev3", group=groupSTD)
stDevMultiplier_4 = input.float(2.0 , step=0.1, title="StDev 4:", inline="StDev4", group=groupSTD)
stDevMultiplier_5 = input.float(2.618 , step=0.1, title="StDev 5:", inline="StDev5", group=groupSTD)
stDevMultiplier_6 = input.float(3.0 , step=0.1, title="StDev 6:", inline="StDev6", group=groupSTD)
plot_pL1 = input(true, title="Previous StDev 1", inline="StDev1", group=groupSTD)
plot_pL2 = input(true, title="Previous StDev 2", inline="StDev2", group=groupSTD)
plot_pL3 = input(true, title="Previous StDev 3", inline="StDev3", group=groupSTD)
plot_pL4 = input(true, title="Previous StDev 4", inline="StDev4", group=groupSTD)
plot_pL5 = input(true, title="Previous StDev 5", inline="StDev5", group=groupSTD)
plot_pL6 = input(true, title="Previous StDev 6", inline="StDev6", group=groupSTD)
up_color = input.color(color.red, title="|", inline="STD0", group=groupSTD)
lw_color = input.color(color.blue, title="", inline="STD0", group=groupSTD)
// --------------
groupL = "Labels"
// --------------
show_labels = input(true, title="Show Labels |", inline="L1", group=groupL)
show_VWAPlabels = input(true, title="VWAP", inline="L1", group=groupL)
show_STDlabels = input(true, title="StDev", inline="L1", group=groupL)
show_prevlabels = input(true, title="Show Previous Labels", inline="L2", group=groupL)
off_mult = input(15, title="| Offset", inline="L2", group=groupL)
var DEFAULT_LABEL_SIZE = size.normal
var DEFAULT_LABEL_STYLE = label.style_none
ll_offset = timenow + math.round(ta.change(time) * off_mult)
// --------------
timeChange(period) =>
ta.change(time(period))
newSessionD = timeChange("D")
newSessionW = timeChange("W")
newSessionM = timeChange("M")
newSessionQ = timeChange("3M")
newSessionY = timeChange("12M")
[vD, stdevD] = computeVWAP(src, newSessionD)
[vW, stdevW] = computeVWAP(src, newSessionW)
[vM, stdevM] = computeVWAP(src, newSessionM)
[vQ, stdevQ] = computeVWAP(src, newSessionQ)
[vY, stdevY] = computeVWAP(src, newSessionY)
// --------------
Vstyle = input(false, title="Circles Lines", inline="V0", group=groupVWAP)
VstyleC = Vstyle ? plot.style_circles : plot.style_line
vDplot = plot(plot_vD ? vD : na, title="VWAP - Daily", color=vD_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vD ? vD : na, "vD", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vWplot = plot(plot_vW ? vW : na, title="VWAP - Weekly", color=vW_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vW ? vW : na, "vW", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vMplot = plot(plot_vM ? vM : na, title="VWAP - Monthly", color=vM_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vM ? vM : na, "vM", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vQplot = plot(plot_vQ ? vQ : na, title="VWAP - Quarter", color=vQ_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vQ ? vQ : na, "vQ", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
vYplot = plot(plot_vY ? vY : na, title="VWAP - Year", color=vY_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and plot_vY ? vY : na, "vY", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
// --------------
stdev_sel = Std_selection == "Day" ? stdevD :
Std_selection == "Week" ? stdevW :
Std_selection == "Month" ? stdevM :
Std_selection == "Quarter" ? stdevQ :
Std_selection == "Year" ? stdevY : na
vwap_sel = Std_selection == "Day" ? vD :
Std_selection == "Week" ? vW :
Std_selection == "Month" ? vM :
Std_selection == "Quarter" ? vQ :
Std_selection == "Year" ? vY : na
prev_period = Std_selection == "Day" ? newSessionD :
Std_selection == "Week" ? newSessionW :
Std_selection == "Month" ? newSessionM :
Std_selection == "Quarter" ? newSessionQ :
Std_selection == "Year" ? newSessionY : na
[s6up, s5up, s4up, s3up, s2up, s1up, s1dn, s2dn, s3dn, s4dn, s5dn, s6dn] = compute_stDEV(vwap_sel, stdev_sel, stDevMultiplier_1, stDevMultiplier_2, stDevMultiplier_3, stDevMultiplier_4, stDevMultiplier_5, stDevMultiplier_6)
// --------------
A = plot(showStd ? s6up : na, title="VWAP - STDEV +6", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s6up : na , "SD+3", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
B = plot(showStd ? s5up : na, title="VWAP - STDEV +5", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s5up : na , "SD+2.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
C = plot(showStd ? s4up : na, title="VWAP - STDEV +4", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s4up : na , "SD+2", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
D = plot(showStd ? s3up : na, title="VWAP - STDEV +3", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s3up : na , "SD+1.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
E = plot(showStd ? s2up : na, title="VWAP - STDEV +2", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s2up : na , "SD+1", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
F = plot(showStd ? s1up : na, title="VWAP - STDEV +1", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s1up : na , "SD+0.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
G = plot(showStd ? s1dn : na, title="VWAP - STDEV -1", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s1dn : na , "SD-0.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
H = plot(showStd ? s2dn : na, title="VWAP - STDEV -2", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s2dn : na , "SD-1", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
I = plot(showStd ? s3dn : na, title="VWAP - STDEV -3", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s3dn : na , "SD-1.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
J = plot(showStd ? s4dn : na, title="VWAP - STDEV -4", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s4dn : na , "SD-2", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
K = plot(showStd ? s5dn : na, title="VWAP - STDEV -5", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s5dn : na , "SD-2.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
L = plot(showStd ? s6dn : na, title="VWAP - STDEV -6", color=color.new(color.silver, 75), style=plot.style_linebr, linewidth=1, display=showLC)
f_drawLabel(ll_offset, show_labels and show_STDlabels and showStd ? s6dn : na , "SD-3", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
// --------------
fb_transp = input.float(100, minval=0, maxval=100, title="Transp.", inline="STD3", group=groupSTD)
fb_step = input.float(5, minval=0, maxval=100, title="Step", inline="STD3", group=groupSTD)
fill_col_up5 = color.new(up_color, fb_transp - fb_step * 5)
fill_col_up4 = color.new(up_color, fb_transp - fb_step * 4)
fill_col_up3 = color.new(up_color, fb_transp - fb_step * 3)
fill_col_up2 = color.new(up_color, fb_transp - fb_step * 2)
fill_col_up = color.new(up_color, fb_transp - fb_step * 1)
//fill_col_mid = color.new(color.silver, fb_transp)
fill_col_down = color.new(lw_color, fb_transp - fb_step * 1)
fill_col_down2 = color.new(lw_color, fb_transp - fb_step * 2)
fill_col_down3 = color.new(lw_color, fb_transp - fb_step * 3)
fill_col_down4 = color.new(lw_color, fb_transp - fb_step * 4)
fill_col_down5 = color.new(lw_color, fb_transp - fb_step * 5)
fill(A, B, fill_bands ? fill_col_up5 : na)
fill(B, C, fill_bands ? fill_col_up4 : na)
fill(C, D, fill_bands ? fill_col_up3 : na)
fill(D, E, fill_bands ? fill_col_up2 : na)
fill(E, F, fill_bands ? fill_col_up : na)
//fill(F, G, fill_bands ? fill_col_mid : na)
fill(G, H, fill_bands ? fill_col_down : na)
fill(H, I, fill_bands ? fill_col_down2 : na)
fill(I, J, fill_bands ? fill_col_down3 : na)
fill(J, K, fill_bands ? fill_col_down4 : na)
fill(K, L, fill_bands ? fill_col_down5 : na)
// --------------
previouslevels(period, VWAP, s6up, s5up, s4up, s3up, s2up, s1up, s1dn, s2dn, s3dn, s4dn, s5dn, s6dn) =>
var float pV = na
var float ps6up = na
var float ps5up = na
var float ps4up = na
var float ps3up = na
var float ps2up = na
var float ps1up = na
var float ps1dn = na
var float ps2dn = na
var float ps3dn = na
var float ps4dn = na
var float ps5dn = na
var float ps6dn = na
pV := period ? VWAP[1] : pV
ps6up := period ? s6up[1] : ps6up
ps5up := period ? s5up[1] : ps5up
ps4up := period ? s4up[1] : ps4up
ps3up := period ? s3up[1] : ps3up
ps2up := period ? s2up[1] : ps2up
ps1up := period ? s1up[1] : ps1up
ps1dn := period ? s1dn[1] : ps1dn
ps2dn := period ? s2dn[1] : ps2dn
ps3dn := period ? s3dn[1] : ps3dn
ps4dn := period ? s4dn[1] : ps4dn
ps5dn := period ? s5dn[1] : ps5dn
ps6dn := period ? s6dn[1] : ps6dn
[ pV, ps6up, ps5up, ps4up, ps3up, ps2up, ps1up, ps1dn, ps2dn, ps3dn, ps4dn, ps5dn, ps6dn ]
[ pV, ps6up, ps5up, ps4up, ps3up, ps2up, ps1up, ps1dn, ps2dn, ps3dn, ps4dn, ps5dn, ps6dn ] = previouslevels(prev_period, vwap_sel, s6up, s5up, s4up, s3up, s2up, s1up, s1dn, s2dn, s3dn, s4dn, s5dn, s6dn)
// --------------
pVplot = plot(showpStd and plot_pL1 ? pV : na, title="Previous VWAP", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth = 3, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL1 and showpStd ? pV : na, "pVWAP", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pA = plot(showpStd and plot_pL6 ? ps6up : na, title="Previous VWAP - STDEV +6", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL6 and showpStd ? ps6up : na , "pSD+3", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pB = plot(showpStd and plot_pL5 ? ps5up : na, title="Previous VWAP - STDEV +5", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL5 and showpStd ? ps5up : na , "pSD+2.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pC = plot(showpStd and plot_pL4 ? ps4up : na, title="Previous VWAP - STDEV +4", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL4 and showpStd ? ps4up : na , "pSD+2", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pD = plot(showpStd and plot_pL3 ? ps3up : na, title="Previous VWAP - STDEV +3", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL3 and showpStd ? ps3up : na , "pSD+1.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pE = plot(showpStd and plot_pL2 ? ps2up : na, title="Previous VWAP - STDEV +2", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL2 and showpStd ? ps2up : na , "pSD+1", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pF = plot(showpStd and plot_pL1 ? ps1up : na, title="Previous VWAP - STDEV +1", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL1 and showpStd ? ps1up : na , "pSD+0.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pG = plot(showpStd and plot_pL1 ? ps1dn : na, title="Previous VWAP - STDEV -1", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL1 and showpStd ? ps1dn : na , "pSD-0.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pH = plot(showpStd and plot_pL2 ? ps2dn : na, title="Previous VWAP - STDEV -2", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL2 and showpStd ? ps2dn : na , "pSD-1", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pI = plot(showpStd and plot_pL3 ? ps3dn : na, title="Previous VWAP - STDEV -3", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL3 and showpStd ? ps3dn : na , "pSD-1.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pJ = plot(showpStd and plot_pL4 ? ps4dn : na, title="Previous VWAP - STDEV -4", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL4 and showpStd ? ps4dn : na , "pSD-2", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pK = plot(showpStd and plot_pL5 ? ps5dn : na, title="Previous VWAP - STDEV -5", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL5 and showpStd ? ps5dn : na , "pSD-2.5", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
pL = plot(showpStd and plot_pL6 ? ps6dn : na, title="Previous VWAP - STDEV -6", color=color.new(color.silver, 75), style=plot.style_stepline, linewidth=1, display=showpLC)
f_drawLabel(ll_offset, show_prevlabels and plot_pL6 and showpStd ? ps6dn : na , "pSD-3", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
// --------------
fill(pA, pB, fill_pbands ? fill_col_up5 : na)
fill(pB, pC, fill_pbands ? fill_col_up4 : na)
fill(pC, pD, fill_pbands ? fill_col_up3 : na)
fill(pD, pE, fill_pbands ? fill_col_up2 : na)
fill(pE, pF, fill_pbands ? fill_col_up : na)
//fill(pF, pG, fill_pbands ? fill_col_mid : na)
fill(pG, pH, fill_pbands ? fill_col_down : na)
fill(pH, pI, fill_pbands ? fill_col_down2 : na)
fill(pI, pJ, fill_pbands ? fill_col_down3 : na)
fill(pJ, pK, fill_pbands ? fill_col_down4 : na)
fill(pK, pL, fill_pbands ? fill_col_down5 : na)
// --------------
vR_color = input.color(color.new(#481899, 50), title="" , inline="V6", group=groupVWAP)
rolling_sv = input(false , title="Show Rolling VWAP" , inline="V6", group=groupVWAP)
rolling_period = input.int(200 , title="" , inline="V6", group=groupVWAP)
vwap_r = ta.vwma(src, rolling_period)
plot(rolling_sv == true ? vwap_r : na, title="VWAP - Rolling", color=vR_color, style=VstyleC, linewidth=1)
f_drawLabel(ll_offset, show_labels and show_VWAPlabels and rolling_sv ? vwap_r : na, "rV", color.silver, DEFAULT_LABEL_STYLE, DEFAULT_LABEL_SIZE)
// -----------------------------------
groupTD = "TD (Tom DeMark) Sequential"
// -----------------------------------
lastN = input.string("None", title="Show", options=["7, 8 and 9", "8 and 9", "Only 9", "None"], inline="TD1", group=groupTD)
LocBN = input.string("Below", title="Position: Buy", options=["Above", "Below"], inline="TD5", group=groupTD)
LocSN = input.string("Above", title="Sell", options=["Above", "Below"], inline="TD5", group=groupTD)
LocBNC = LocBN == "Above" ? location.abovebar : LocBN == "Below" ? location.belowbar : na
LocSNC = LocSN == "Above" ? location.abovebar : LocSN == "Below" ? location.belowbar : na
// -----------------------------------
i_style0 = "Label"
i_style1 = "Arrow"
i_style2 = "Triangle"
i_style3 = "Circle"
i_style4 = "Cross"
Bstyle = input.string(i_style3, title="Style: Buy" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="TD6", group=groupTD)
Sstyle = input.string(i_style3, title="Sell" , options=[i_style0, i_style1, i_style2, i_style3, i_style4], inline="TD6", group=groupTD)
f_getStyleB(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowup :
_inputStyle == i_style2 ? shape.triangleup :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.cross : shape.labelup
_return
f_getStyleS(_inputStyle) =>
_return = _inputStyle == i_style1 ? shape.arrowdown :
_inputStyle == i_style2 ? shape.triangledown :
_inputStyle == i_style3 ? shape.circle :
_inputStyle == i_style4 ? shape.xcross : shape.labeldown
_return
// -----------------------------------
sellSetup = 0
sellSetup := close > close[4] ? sellSetup[1] == 9 ? 1 : sellSetup[1] + 1 : 0
buySetup = 0
buySetup := close < close[4] ? buySetup[1] == 9 ? 1 : buySetup[1] + 1 : 0
// -----------------------------------
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" ?
buySetup == 7 : na, location=LocBNC, style=f_getStyleB(Bstyle), size=size.auto, color=color.new(color.lime, 0), text="", title="b7", textcolor=color.new(color.white, 15))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
buySetup == 8 : na, location=LocBNC, style=f_getStyleB(Bstyle), size=size.auto, color=color.new(color.green, 0), text="", title="b8", textcolor=color.new(color.white, 15))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
buySetup == 9 : na, location=LocBNC, style=f_getStyleB(Bstyle), size=size.auto, color=color.new(color.teal, 0), text="9", title="b9", textcolor=color.new(color.white, 15))
// -----------------------------------
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" ?
sellSetup == 7 : na, location=LocSNC, style=f_getStyleS(Sstyle), size=size.auto, color=color.new(color.orange, 0), text="", title="s7", textcolor=color.new(color.white, 15))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" ?
sellSetup == 8 : na, location=LocSNC, style=f_getStyleS(Sstyle), size=size.auto, color=color.new(color.red, 0), text="", title="s8", textcolor=color.new(color.white, 15))
plotshape(lastN == "1 to 9" or lastN == "6 to 9" or lastN == "7, 8 and 9" or lastN == "8 and 9" or lastN == "Only 9" ?
sellSetup == 9 : na, location=LocSNC, style=f_getStyleS(Sstyle), size=size.auto, color=color.new(color.maroon, 0), text="9", title="s9", textcolor=color.new(color.white, 15)) |
Levinson-Durbin Autocorrelation Extrapolation of Price [Loxx] | https://www.tradingview.com/script/mvUdLxSg-Levinson-Durbin-Autocorrelation-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 414 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Levinson-Durbin Autocorrelation Extrapolation of Price [Loxx]",
shorttitle = "LDAEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
//+-------------------------------------------------------------------------+
// Original Levinson-Durbin algorithm used to implement Levinson recursion
// where a[i=1..p] - coefficients of the model, p - order of the model.
// Here we need to find the autoregressive coefficients by solving directly
// our set of equations with n=2*p by the Levinson-Durbin method. Such method
// of prediction is called Prony Method; however, its disadvantage is the
// instability during the prediction of the future values of the series. That's
// why this method has not been included and instead we use a modified
// Levinson Recursion to calculate the prediction coefficients.
// I've included the origina method so one can compare the differences. You'll
// notice that both methods are very similar but the modified version gives the
// desired results. The difference is that the modified version calculates the
// coefficients a[] by decreasing the mean-root-square error on the training
// last n-p bars
//
//_LevinsonRecursion(float[] Rx, int p)=>
// float r = 0.
// float E = 1.
// kh = 0, ki = 0, err = 0.
// float[] result = array.new_float(p + 1, 0.)
// float[] Am = array.new_float(p + 1, 0.)
// E := 1
// r := 0.
// for k = 1 to p
// err := 0
// for i = 1 to k - 1
// err += array.get(Am, i) * array.get(Rx, k - i)
// r := (array.get(Rx, k) - err) / E
// array.set(result, k, r)
// for i = 1 to k - 1
// array.set(result, i, array.get(Am, i) - r * array.get(Am, k - i))
// E *= (1 - r * r)
// Am := array.copy(result)
// result
//+-------------------------------------------------------------------------+
_modLevinsonRecursion(float[] Rx, int p)=>
float r = 0.
float E = 1.
int kh = 0
int ki = 0
float[] result = array.new<float>(p + 1, 0.)
E := array.get(Rx, 0)
for k = 1 to p
//Calculate reflection coefficient
r := -array.get(Rx, k)
for i = 1 to k - 1
r -= array.get(result, i) * array.get(Rx, k - i)
r /= E
//Calculate prediction coefficients
array.set(result, k, r)
kh := k / 2
for i = 1 to kh
ki := k - i
tmp = array.get(result, i)
array.set(result, i, array.get(result, i) + r * array.get(result, ki))
if i != ki
array.set(result, ki, array.get(result, ki) + r * tmp)
//Calculate new residual energy
E *= (1 - r * r)
result
_ACF(float[] x, int p)=>
int n = array.size(x)
float[] Rx = array.new<float>(p + 1, 0.)
//Initialize
for j = 0 to p
array.set(Rx, j, 0.)
for i = j to n - 1
array.set(Rx, j, array.get(Rx, j) + array.get(x, i) * array.get(x, i - j))
out = _modLevinsonRecursion(Rx, p)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(300, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.6, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
FutBars = input.int(100, "Future Bars", group = "Basic Settings", maxval = 500)
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction ACF
float[] result = _ACF(x, no)
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1
|
ZigZag with Retracement Levels | https://www.tradingview.com/script/AubtKO9L-ZigZag-with-Retracement-Levels/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 386 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ PtGambler
// This source code is a modification to 'ZigZag with Fibonacci Levels' published by ยฉ LonesomeTheBlue
//@version=5
indicator('ZigZag with Retracement Levels', overlay=true, max_bars_back=500, max_lines_count=300)
prd = input.int(defval=10, title='ZigZag Period', minval=2, maxval=50)
showzigzag = input(defval=true, title='Show Zig Zag')
showfibo = input(defval=true, title='Show Retracement Ratios')
labelcol = input(defval=color.white, title='Text Color for Levels')
fibolinecol = input(defval=color.white, title='Line Color for Levels')
showcurrent = input(defval=true, title='Show Retracement Ratios based on latest pivot')
labelcol2 = input(defval=color.yellow, title='Text Color for Current Levels')
fibolinecol2 = input(defval=color.yellow, title='Line Color for Current Levels')
upcol = input.color(defval=color.lime, title='Zigzag Colors', inline='zzcol')
dncol = input.color(defval=color.red, title='', inline='zzcol')
labelloc = input.string(defval='Left', title='Label Location', options=['Left', 'Right'])
// Modified from ยฉ LonesomeTheBlue origial code, added options to enable/disable/customize levels ------------------------------------
enable1 = input(defval=true, title='Enable Level 1', inline ='level1')
level1 = input.float(defval=0.236, title='', inline='level1')
enable2 = input(defval=true, title='Enable Level 2', inline ='level2')
level2 = input.float(defval=0.382, title='', inline='level2')
enable3 = input(defval=true, title='Enable Level 3', inline ='level3')
level3 = input.float(defval=0.500, title='', inline='level3')
enable4 = input(defval=true, title='Enable Level 4', inline ='level4')
level4 = input.float(defval=0.618, title='', inline='level4')
enable5 = input(defval=true, title='Enable Level 5', inline ='level5')
level5 = input.float(defval=0.786, title='', inline='level5')
var fibo_ratios = array.new_float(0)
var shownlevels = 1
if barstate.isfirst
array.push(fibo_ratios, 0.0)
if enable1
array.push(fibo_ratios, level1)
shownlevels += 1
shownlevels
if enable2
array.push(fibo_ratios, level2)
shownlevels += 1
shownlevels
if enable3
array.push(fibo_ratios, level3)
shownlevels += 1
shownlevels
if enable4
array.push(fibo_ratios, level4)
shownlevels += 1
shownlevels
if enable5
array.push(fibo_ratios, level5)
shownlevels += 1
shownlevels
// for x = 1 to 5 by 1
// array.push(fibo_ratios, x)
// array.push(fibo_ratios, x + 0.272)
// array.push(fibo_ratios, x + 0.414)
// array.push(fibo_ratios, x + 0.618)
array.push(fibo_ratios, 1.0)
// -------------------------------------------------------------------------------
float ph = ta.highestbars(high, prd) == 0 ? high : na
float pl = ta.lowestbars(low, prd) == 0 ? low : na
var dir = 0
iff_1 = pl and na(ph) ? -1 : dir
dir := ph and na(pl) ? 1 : iff_1
var max_array_size = 10
var zigzag = array.new_float(0)
oldzigzag = array.copy(zigzag)
add_to_zigzag(value, bindex) =>
array.unshift(zigzag, bindex)
array.unshift(zigzag, value)
if array.size(zigzag) > max_array_size
array.pop(zigzag)
array.pop(zigzag)
update_zigzag(value, bindex) =>
if array.size(zigzag) == 0
add_to_zigzag(value, bindex)
else
if dir == 1 and value > array.get(zigzag, 0) or dir == -1 and value < array.get(zigzag, 0)
array.set(zigzag, 0, value)
array.set(zigzag, 1, bindex)
0.
bool dirchanged = dir != dir[1]
if ph or pl
if dirchanged
add_to_zigzag(dir == 1 ? ph : pl, bar_index)
else
update_zigzag(dir == 1 ? ph : pl, bar_index)
if showzigzag and array.size(zigzag) >= 4 and array.size(oldzigzag) >= 4
var line zzline = na
if array.get(zigzag, 0) != array.get(oldzigzag, 0) or array.get(zigzag, 1) != array.get(oldzigzag, 1)
if array.get(zigzag, 2) == array.get(oldzigzag, 2) and array.get(zigzag, 3) == math.round(array.get(oldzigzag, 3))
line.delete(zzline)
zzline := line.new(x1=math.round(array.get(zigzag, 1)), y1=array.get(zigzag, 0), x2=math.round(array.get(zigzag, 3)), y2=array.get(zigzag, 2), color=dir == 1 ? upcol : dncol, width=2)
zzline
var fibolines = array.new_line(0)
var fibolabels = array.new_label(0)
// Addition to ยฉ LonesomeTheBlue origial code ------------------------------------
var fibolines2 = array.new_line(0)
var fibolabels2 = array.new_label(0)
// -------------------------------------------------------------------------------
if showfibo and array.size(zigzag) >= 6 and barstate.islast
if array.size(fibolines) > 0
for x = 0 to array.size(fibolines) - 1 by 1
line.delete(array.get(fibolines, x))
label.delete(array.get(fibolabels, x))
if array.size(fibolines2) > 0
for x = 0 to array.size(fibolines2) - 1 by 1
line.delete(array.get(fibolines2, x))
label.delete(array.get(fibolabels2, x))
diff = array.get(zigzag, 4) - array.get(zigzag, 2)
stopit = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit and x > shownlevels
break
array.unshift(fibolines, line.new(x1=math.round(array.get(zigzag, 5)), y1=array.get(zigzag, 2) + diff * array.get(fibo_ratios, x), x2=bar_index, y2=array.get(zigzag, 2) + diff * array.get(fibo_ratios, x), color=fibolinecol, extend=extend.right, width=2))
label_x_loc = labelloc == 'Left' ? math.round(array.get(zigzag, 5)) - 1 : bar_index + 15
array.unshift(fibolabels, label.new(x=label_x_loc, y=array.get(zigzag, 2) + diff * array.get(fibo_ratios, x), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag, 2) + diff * array.get(fibo_ratios, x))) + ')', textcolor=labelcol, style=label.style_none))
if dir == 1 and array.get(zigzag, 2) + diff * array.get(fibo_ratios, x) > array.get(zigzag, 0) or dir == -1 and array.get(zigzag, 2) + diff * array.get(fibo_ratios, x) < array.get(zigzag, 0)
stopit := true
stopit
// Addition to ยฉ LonesomeTheBlue origial code ------------------------------------
if showcurrent and array.size(zigzag) >= 6 and barstate.islast
diff2 = array.get(zigzag, 0) - array.get(zigzag, 2)
stopit2 = false
for x = 0 to array.size(fibo_ratios) - 1 by 1
if stopit2 and x > shownlevels
break
array.unshift(fibolines2, line.new(x1=math.round(array.get(zigzag, 3)), y1=array.get(zigzag, 2) + diff2 * (1-array.get(fibo_ratios, x)), x2=bar_index, y2=array.get(zigzag, 2) + diff2 * (1-array.get(fibo_ratios, x)), color=fibolinecol2, extend=extend.right))
label_x_loc2 = labelloc == 'Left' ? math.round(array.get(zigzag, 3)) - 1 : bar_index + 15
array.unshift(fibolabels2, label.new(x=label_x_loc2, y=array.get(zigzag, 2) + diff2 * (1-array.get(fibo_ratios, x)), text=str.tostring(array.get(fibo_ratios, x), '#.###') + '(' + str.tostring(math.round_to_mintick(array.get(zigzag, 2) + diff2 * (1-array.get(fibo_ratios, x)))) + ')', textcolor=labelcol2, style=label.style_none))
if dir == 1 and array.get(zigzag, 2) + diff2 * array.get(fibo_ratios, x) > array.get(zigzag, 0) or dir == -1 and array.get(zigzag, 2) + diff2 * array.get(fibo_ratios, x) < array.get(zigzag, 0)
stopit2 := true
stopit2
// -------------------------------------------------------------------------------
|
SPY Volume Weighted Close | https://www.tradingview.com/script/UYDiPzhb-SPY-Volume-Weighted-Close/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 119 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Steversteves
//@version=5
indicator("SPY Volume Weighted Close", overlay=true)
// Grab data from previous daily candle
ticker = ticker.new(syminfo.prefix, syminfo.ticker, session.regular)
last_hvolume = request.security(ticker, "60", volume[1], lookahead=barmerge.lookahead_on)
today_hopen = request.security(ticker, "60", open, lookahead=barmerge.lookahead_on)
// Color code
purple_90 = color.new(color.purple, 90)
yellow_90 = color.new(color.yellow, 80)
blue_90 = color.new(color.blue, 80)
// Volume Weighted Close
o = today_hopen * 0.999
v = last_hvolume * 2.139E-9
close_analysis = (o + v) + 0.552
cl = plot(close_analysis, "Volume Weighted Close", color=color.blue, linewidth=2)
// bands
ucl = close_analysis + 1.45
lcl = close_analysis - 1.45
cl2 = plot(ucl, "Upper Confidence Level VWC", color=color.white)
cl1 = plot(lcl, "Lower Confidence Lvel VWC", color=color.purple)
// Averages
ucltocl = (ucl + close_analysis) / 2
lcltocl = (lcl + close_analysis) / 2
// Bools
bool highvol = close > ucltocl
bool lowvol = close < lcltocl
color highvolcolor = highvol ? yellow_90 : purple_90
color lowvolcolor = lowvol ? blue_90 : purple_90
// Fills
fill(cl1, cl, color=lowvolcolor, editable=true)
fill(cl2, cl, color=highvolcolor, editable=true)
|
Return Moving Average [SpiritualHealer117] | https://www.tradingview.com/script/FTh1jZzL-Return-Moving-Average-SpiritualHealer117/ | spiritualhealer117 | https://www.tradingview.com/u/spiritualhealer117/ | 21 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ spiritualhealer117
//@version=5
indicator("RMA")
src = input(close,"Source")
len = input(14, "Length")
off = input(1, "Offset")
smo = input(5, "Smoothing")
osmode = input(false, "Use Oscillator Mode")
ret = src/src[1]
avg = osmode ? ta.sma(ret,len) : ta.sma(ret,len)*src
max = osmode ? ta.highest(ret,len) : ta.highest(ret,len)*src
min = osmode ? ta.lowest(ret,len) : ta.lowest(ret,len)*src
smo_avg = ta.sma(avg, smo)
smo_max = ta.sma(max, smo)
smo_min = ta.sma(min, smo)
a = smo_max-smo_avg
b = smo_avg-smo_min
plot(smo_avg, offset=off, color=color.white, style=plot.style_line)
plot(osmode?(a > b?na:smo_max):smo_max, offset=off, color=color.red, style=plot.style_linebr)
plot(osmode?(b > a?na:smo_min):smo_min, offset=off, color=color.green, style=plot.style_linebr)
plot(osmode?ret:na, color=color.gray)
|
VWAP For NIFTY & BANKNIFTY [Zero54] | https://www.tradingview.com/script/kHpEnD57-VWAP-For-NIFTY-BANKNIFTY-Zero54/ | zero54 | https://www.tradingview.com/u/zero54/ | 140 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ zero54
//@version=5
indicator('Custom Vwap [Zero54]', overlay=true)
string i_maType = syminfo.tickerid
Symb = switch i_maType
"NSE:BANKNIFTY" => "NSE:BANKNIFTY1!"
"NSE:NIFTY" => "NSE:NIFTY1!"
// Default used when the cases first cases do not match.
=> syminfo.tickerid
vwapp2 = request.security(Symb, "", ta.vwap)
plot(vwapp2) |
Alternative MTF Table | https://www.tradingview.com/script/VeiLSmiW-Alternative-MTF-Table/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ RozaniGhani-RG
//@version=5
indicator('Alternative MTF Table', shorttitle = 'AMT', overlay = true)
// 1. Inputs
// 2. Variables
// 3. Arrays
// 4. Matrix
// 5. Construct
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 1. Inputs {
G2 = 'TABLE'
T0 = 'For Timeframe Table only'
T1 = 'For both table'
i_b_TF = input.bool( true, 'Timeframe Table', group = G2, inline = '6')
i_s_TF = input.string( 'Detail', '', group = G2, inline = '6', options = ['Simple', 'Detail'])
i_b_HP = input.bool( false, 'Helper Table', group = G2)
i_s_Y = input.string( 'bottom', 'Table Position', group = G2, inline = '7', options = ['top', 'middle', 'bottom'])
i_s_X = input.string( 'left', '', group = G2, inline = '7', options = ['left', 'center', 'right'], tooltip = T0)
i_s_font = input.string( 'normal', 'Font size', group = G2, options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T1)
// }
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 2. Variables {
PO = 'POSITION', SW = 'SWING', IN = 'INTRADAY'
var HPTable = table.new(position.middle_center, 4, 4, border_width = 1)
var TFtable = table.new( i_s_Y + '_' + i_s_X, 20, 10, border_width = 1)
// }
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 3. Arrays {
arr_time = array.new_bool(6)
arr_trader = array.from('POSITION', 'SWING', 'INTRADAY')
arr_res = array.from( 'HIGHER', 'PRIMARY', 'LOWER')
arr_res2 = array.from( 'DISTAL', 'CLEAR', 'PROXIMATE')
arr_tf0 = array.from( 'W', 'D', '60')
arr_tf1 = array.from( 'D', '60', '15')
arr_tf2 = array.from( '60', '15', '5')
for i = 0 to 5
arr_time.set(0, timeframe.period == 'W' and timeframe.change('W'))
arr_time.set(1, timeframe.period == 'D' and timeframe.change('D'))
arr_time.set(2, timeframe.period == '60' and timeframe.change('60'))
arr_time.set(3, timeframe.period == '15' and timeframe.change('15'))
arr_time.set(4, timeframe.period == '5' and timeframe.change('5'))
arr_time.set(5, timeframe.period == '1' and timeframe.change('1'))
index_TF = array.indexof(arr_time, true)
[TYPE, str_TF0, str_TF1, str_TF2, TF0, TF1, TF2] = switch index_TF
// [TYPE, str_TF0, str_TF1, str_TF2, TF0, TF1, TF2]
0 => [PO, 'HIGHER', 'PRIMARY', 'LOWER', 'W', 'D', '60']
1 => [PO, 'HIGHER', 'PRIMARY', 'LOWER', 'W', 'D', '60']
2 => [SW, 'HIGHER', 'PRIMARY', 'LOWER', 'D', '60', '15']
3 => [IN, 'HIGHER', 'PRIMARY', 'LOWER', '60', '15', '5']
4 => [IN, 'PRIMARY', 'LOWER', 'LOWEST', '15', '5', '1']
5 => [IN, 'PRIMARY', 'LOWER', 'LOWEST', '15', '5', '1']
[len_TF0, len_TF1, len_TF2] = switch index_TF
// [len_TF0, len_TF1, len_TF2]
0 => [ 100, 20, 4]
1 => [ 465, 100, 12]
2 => [ 700, 100, 28]
3 => [ 356, 100, 33]
4 => [ 300, 100, 22]
5 => [ 1461, 479, 100]
res_TF = array.from( TF0, TF1, TF2) // From index_TF
str_TF = array.from(str_TF0, str_TF1, str_TF2) // From index_TF
arr_len = array.from(len_TF0, len_TF1, len_TF2) // From index_TF
// }
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 4. Matrix {
m = matrix.new<string>(4, 4)
matrix.set(m, 0, 0, '')
for i = 0 to 2
matrix.set(m, i + 1, 0, arr_trader.get(i))
matrix.set(m, i + 1, 1, arr_tf0.get(i))
matrix.set(m, i + 1, 2, arr_tf1.get(i))
matrix.set(m, i + 1, 3, arr_tf2.get(i))
matrix.set(m, 0, i + 1, arr_res.get(i) + ' / ' + arr_res2.get(i))
// }
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 5. Construct {
if barstate.islast
if array.includes(arr_time, true) and i_b_TF
table.cell(TFtable, 0, 0, TYPE + ' TRADER', text_color = color.white, text_size = i_s_font, bgcolor = color.black)
if i_s_TF == 'Detail'
table.cell(TFtable, 0, 1, 'TIMEFRAME', text_color = color.white, text_size = i_s_font, bgcolor = color.black)
table.cell(TFtable, 2, 1, 'ITEM', text_color = color.white, text_size = i_s_font, bgcolor = color.black)
for i = 0 to 2
table.cell(TFtable, 0, i + 2, str_TF.get(i), text_color = color.white, text_size = i_s_font, bgcolor = color.black)
table.cell(TFtable, 1, i + 2, res_TF.get(i), text_color = color.white, text_size = i_s_font, bgcolor = color.black)
table.cell(TFtable, 2, i + 2, str.tostring(arr_len.get(i)) + ' BARS', text_color = color.white, text_size = i_s_font, bgcolor = color.black)
table.merge_cells(TFtable, 0, 0, 2, 0)
table.merge_cells(TFtable, 0, 1, 1, 1)
if TYPE == 'INTRADAY'
table.cell(TFtable, 0, 5, '* CHECK PRIMARY TF', text_color = color.blue, text_size = i_s_font, bgcolor = color.new(color.blue, 100))
table.merge_cells(TFtable, 0, 5, 2, 5)
if i_b_HP
for x = 0 to 3
for y = 0 to 3
table.cell(HPTable, y, x, matrix.get(m, y, x), text_color = color.white, text_size = i_s_font, bgcolor = color.black)
for y = 0 to 3
table.cell_set_bgcolor(HPTable, y, 1, color.gray)
table.cell_set_bgcolor(HPTable, y, 2, color.blue)
table.cell_set_bgcolor(HPTable, y, 3, color.purple)
table.cell_set_bgcolor(HPTable, 0, 0, color.new(color.blue, 100))
// }
// } |
Weighted Burg AR Spectral Estimate Extrapolation of Price [Loxx] | https://www.tradingview.com/script/G3VyvCoH-Weighted-Burg-AR-Spectral-Estimate-Extrapolation-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 199 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Weighted Burg AR Spectral Estimate Extrapolation of Price [Loxx]",
shorttitle = "WBAEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
_win(int i, int k, int n, string w)=>
out = 0.
if (w == "Rectangular")
out := 1
if (w == "Hamming")
out := (0.54 - 0.46 * math.cos(math.pi * (2.0 * (i - k) + 1.0) / (n - k)))
if (w == "Parabolic")
out := (6.0 * (i - k + 1.0) * (n - i) / (n - k) / (n - k + 1.0) / (n - k + 2.0))
out
_WBurg(float[] x, int p, string w)=>
int n = array.size(x)
float[] df = array.new<float>(n, 0.)
float[] db = array.new<float>(n, 0.)
float[] result = array.new<float>(n, 0.)
int kh = 0
int ki = 0
float tmp = 0.
float num = 0.
float den = 0.
float r = 0.
for i = 0 to n - 1
array.set(df, i, array.get(x, i))
array.set(db, i, array.get(x, i))
//Main loop
for k = 1 to p
//Calculate reflection coefficient
num := 0.
den := 0.
if (k == 1)
for i = 2 to n - 1
num += _win(i, 2, n, w) * array.get(x, i - 1) * (array.get(x, i) + array.get(x, i - 2))
den += _win(i, 2, n, w) * array.get(x, i - 1) * array.get(x, i - 1)
r := -num / den / 2.0
if (r > 1)
r := 1.0
if (r < -1.0)
r := -1.0
else
for i = k to n - 1
num += _win(i, k, n, w) * array.get(df, i) * array.get(db, i - 1)
den += _win(i, k, n, w) * (array.get(df, i) * array.get(df, i) + array.get(db, i - 1) * array.get(db, i - 1))
r := -2.0 * num / den
//Calculate prediction coefficients
array.set(result, k, r)
kh := k / 2
for i = 1 to kh
ki := k - i
tmp := array.get(result, i)
array.set(result, i, array.get(result, i) + r * array.get(result, ki))
if (i != ki)
array.set(result, ki, array.get(result, ki) + r * tmp)
if (k < p)
for i = n - 1 to k
tmp1 = array.get(df, i)
array.set(df, i, array.get(df, i) + r * array.get(db, i - 1))
array.set(db, i, array.get(db, i - 1) + r * tmp1)
result
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(300, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.6, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
FutBars = input.int(100, "Future Bars", group = "Basic Settings", maxval = 500)
BurgWin = input.string("Rectangular", "BurgWin", options = ["Rectangular", "Hamming", "Parabolic"], group = "Basic Settings")
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction ACF
//float[] result = _ACF(x, no)
float[] result = _WBurg(x, no, BurgWin)
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1
|
Helme-Nikias Weighted Burg AR-SE Extra. of Price [Loxx] | https://www.tradingview.com/script/8YbmmPCn-Helme-Nikias-Weighted-Burg-AR-SE-Extra-of-Price-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 263 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Helme-Nikias Weighted Burg AR-SE Extra. of Price [Loxx]",
shorttitle = "HNWBARSEEP [Loxx]",
overlay = true,
max_lines_count = 500)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
_HNBurg(float[] x, int p)=>
int n = array.size(x)
float[] df = array.new<float>(n, 0.)
float[] db = array.new<float>(n, 0.)
float[] result = array.new<float>(n, 0.)
int kh = 0
int ki = 0
float tmp = 0.
float num = 0.
float den = 0.
float r = 0.
for i = 0 to n - 1
array.set(df, i, array.get(x, i))
array.set(db, i, array.get(x, i))
//Main loop
for k = 1 to p
//Calculate reflection coefficient
num := 0.
den := 0.
if (k == 1)
for i = 2 to n - 1
w = math.pow(array.get(x, i - 1), 2)
num += w * array.get(x, i - 1) * (array.get(x, i) + array.get(x, i - 2))
den += w * array.get(x, i - 1) * array.get(x, i - 1)
r := -num / den / 2.0
if (r > 1)
r := 1.0
if (r < -1.0)
r := -1.0
else
w = 0.
for i = 1 to k - 1
w += math.pow(array.get(x, i), 2)
for i = k to n - 1
num += w * array.get(df, i) * array.get(db, i - 1)
den += w * (array.get(df, i) * array.get(df, i) + array.get(db, i - 1) * array.get(db, i - 1))
w := w + math.pow(array.get(x, i), 2) - math.pow(array.get(x, i - k + 1), 2)
r := -2.0 * num / den
//Calculate prediction coefficients
array.set(result, k, r)
kh := k / 2
for i = 1 to kh
ki := k - i
tmp := array.get(result, i)
array.set(result, i, array.get(result, i) + r * array.get(result, ki))
if (i != ki)
array.set(result, ki, array.get(result, ki) + r * tmp)
if (k < p)
for i = n - 1 to k
tmp1 = array.get(df, i)
array.set(df, i, array.get(df, i) + r * array.get(db, i - 1))
array.set(db, i, array.get(db, i - 1) + r * tmp1)
result
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Open", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
LastBar = input.int(30, "Last Bar", group = "Basic Settings", tooltip = "Bar from where to start prediction")
PastBars = input.int(300, "Past Bars", group = "Basic Settings", maxval = 2000)
LPOrder = input.float(0.6, "Order of Linear Prediction", group = "Basic Settings", minval = 0, maxval = 1, step = 0.01)
FutBars = input.int(100, "Future Bars", group = "Basic Settings", maxval = 500)
colorbars = input.bool(true, "Mute bar colors?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
barcolor(colorbars ? color.gray : na)
int lb = LastBar
int np = PastBars
int no = math.ceil(LPOrder * PastBars)
int nf = np - no - 1
float[] x = array.new<float>(np, 0.)
float[] pv = array.new<float>(np, 0.)
float[] fv = array.new<float>(nf + 1, 0.)
var pvlines = array.new_line(0)
var fvlines = array.new_line(0)
cnp = np >= 250 ? 250 : np
cnf = nf >= 250 ? 250 : nf
if barstate.isfirst
for i = 0 to 250 - 1
array.push(pvlines, line.new(na, na, na, na))
array.push(fvlines, line.new(na, na, na, na))
if barstate.islast
//Prepare data
float av = 0.
avar = array.new<float>(np, 0.)
for i = 0 to np - 1
array.set(avar, i, nz(src[i + lb]))
av := array.avg(avar)
for i = 0 to np - 1
array.set(x, np - 1 - i, nz(src[i + lb]) - av)
//Use linear prediction _HNBurg
float[] result = _HNBurg(x, no)
//Calculate linear predictions
for n = no to np + nf - 1
float sum = 0.
for i = 1 to no
if (n - i < np)
sum -= array.get(result, i) * array.get(x, n - i)
else
sum -= array.get(result, i) * array.get(fv, n - i - np + 1)
if (n < np)
array.set(pv, np - 1 - n, sum)
else
array.set(fv, n - np + 1, sum)
array.set(fv, 0, array.get(pv, 0))
for i = 0 to np - no - 1
array.set(pv, i, array.get(pv, i) + av)
array.set(fv, i, array.get(fv, i) + av)
//+------------------------------------------------------------------+
//| Draw lines w/ skipping to stay within 500 line limit
//+------------------------------------------------------------------+
skipperpv = array.size(pv) >= 2000 ? 8 : array.size(pv) >= 1000 ? 4 : array.size(pv) >= 500 ? 2 : 1
int i = 0
int j = 0
while i < np - no - 1 - skipperpv
if j > array.size(pvlines) - 1
break
pvline = array.get(pvlines, j)
line.set_xy1(pvline, bar_index - i - skipperpv - LastBar, array.get(pv, i + skipperpv))
line.set_xy2(pvline, bar_index - i - LastBar, array.get(pv, i))
line.set_color(pvline, greencolor)
line.set_style(pvline, line.style_solid)
line.set_width(pvline, 3)
i += skipperpv
j += 1
skipperfv = array.size(fv) >= 2000 ? 8 : array.size(fv) >= 1000 ? 4 : array.size(fv) >= 500 ? 2 : 1
i := 0
j := 0
outer = math.min(np - no - 1, FutBars)
while i < outer - skipperfv
if j > array.size(fvlines) - 1
break
fvline = array.get(fvlines, j)
line.set_xy1(fvline, bar_index + i + 1 - LastBar, array.get(fv, i + skipperfv))
line.set_xy2(fvline, bar_index + i + 1 - LastBar - skipperfv, array.get(fv, i))
line.set_color(fvline, color.blue)
line.set_style(fvline, line.style_solid)
line.set_width(fvline, 2)
i += skipperfv
j += 1 |
Polynomial-Regression-Fitted RSI [Loxx] | https://www.tradingview.com/script/gKdG39Do-Polynomial-Regression-Fitted-RSI-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Polynomial-Regression-Fitted RSI [Loxx]",
overlay = false,
shorttitle='PRFRSI [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
_specpolyfitMA(mode, float[] src, deg, len, bar)=>
sumout = 0.
AX = matrix.new<float>(12, 12, 0.)
BX = array.new<float>(12, 0.)
ZX = array.new<float>(12, 0.)
Pow = array.new<float>(12, 0.)
Row = array.new<int>(12, 0)
CX = array.new<float>(12, 0.)
if (len <= 1)
sumout := array.get(src, bar)
else
if mode == 1 or (mode == 0 and bar == -len + 1)
XK = 0.
Prod = 0.
for j = 1 to deg + 1
array.set(BX, j, 0)
for k = 1 to len
YK = array.get(src, len - k)
XK := k
Prod := 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
for j = 0 to 2 * deg
array.set(Pow, j, 0)
array.set(Pow, 0, len)
for k = 1 to len
XK := k
Prod := k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
if matrix.get(AX, array.get(Row, deg + 1), deg + 1) != 0.
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
sumout := array.get(CX, deg + 1)
for k = deg to 1
sumout := array.get(CX, k) + sumout * (len + bar)
sumout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(50, "RSI Period", maxval = 80, minval = 2, group = "Basic Settings")
dgr = input.int(1, "Degree of a Polynomial (no more 12)", minval = 1, maxval = 12, group = "Basic Settings")
sigper = input.int(9, "Signal Smoothing Period", minval = 1, group = "Signal Settings")
sigtype = input.string("Sine Weighted Moving Average", "Signal Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Signal Settings")
oblvl = input.int(70, "Overbought Level", maxval = 80, minval = 2, group = "Level Settings")
oslvl = input.int(30, "Oversold Level", maxval = 80, minval = 2, group = "Level Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
Bulls = array.new<float>(per, 0.)
Bears = array.new<float>(per, 0.)
for j = 0 to per - 1
Price1 = nz(src[j])
Price2 = nz(src[j + 1])
array.set(Bulls, j, (math.abs(Price1 - Price2) + (Price1 - Price2)) / syminfo.mintick)
array.set(Bears, j, (math.abs(Price1 - Price2) - (Price1 - Price2)) / syminfo.mintick)
PolyBulls = _specpolyfitMA(1, Bulls, dgr, per, 0)
PolyBears = _specpolyfitMA(1, Bears, dgr, per, 0)
if (PolyBulls <= 0.0)
PolyBulls := 0.001
if (PolyBears <= 0.0)
PolyBears := 0.001
prsi = 0.
if (math.abs(PolyBulls + PolyBears) != 0)
prsi := 100 * PolyBulls / math.abs(PolyBulls + PolyBears)
if (prsi > 100)
prsi := 100
if (prsi < 0)
prsi:= 0
prsi := variant(sigtype, prsi, sigper)
colorout = prsi < 50 ? redcolor : greencolor
plot(prsi, color = colorout, linewidth = 3)
mid = 0.
plot(mid, color = bar_index % 2 ? color.gray : na)
plot(oblvl, color = bar_index % 2 ? color.gray : na)
plot(oslvl, color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout: na)
goLong = ta.crossover(prsi, mid)
goShort = ta.crossunder(prsi, mid)
alertcondition(goLong, title="Long", message="Polynomial-Regression-Fitted RSI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Polynomial-Regression-Fitted RSI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
|
Simple Trading plan (by david zak) | https://www.tradingview.com/script/GcmdoMVs-Simple-Trading-plan-by-david-zak/ | Davidzak | https://www.tradingview.com/u/Davidzak/ | 119 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Swiss_Traders
//@version=5
indicator("Simple trading plan notes", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=1000)
//Visitiblity Section
visibility_group = "Visibility"
inside_bar_show = input.bool(true, "Show Inside Bar", group = visibility_group)
show_rules = input.bool(true, "Show Rules", group=visibility_group)
//Rules Section
table_color_groups = "Table Colors"
bg_table_color = input.color(#ffffff, "Table Color", group = table_color_groups, inline = "02")
bg_border_color = input.color(color.new(color.green, 70), "Table Border", group = table_color_groups, inline = "02")
title_text_color = input.color(color.blue, "Table Title", group = table_color_groups, inline = "02")
table_text_size = input.string("Normal", "Text Size", options = ["Small", "Normal", "Large"], group = "Table Text Size")
h1_size = size.huge //big title
h2_size = size.large //titles
h3_size = size.normal //text
h4_size = size.small //footer
switch table_text_size
"Large" =>
h1_size := size.huge
h2_size := size.large
h3_size := size.normal
h4_size := size.small
"Normal" =>
h1_size := size.large
h2_size := size.normal
h3_size := size.small
h4_size := size.tiny
"Small" =>
h1_size := size.normal
h2_size := size.small
h3_size := size.tiny
h4_size := size.tiny
trend_settings_group = "Trend Settings"
general_group = "General"
table_footers = "Footers"
table_title = "Notes"
headerColor = color.new(color.blue, 80)
infoColor = color.new(color.red, 80)
Trend_Title = input.string("Trend Settings", "General Title", group = trend_settings_group)
swing_structure_4h = input.string("Bearish", "4h Swing Structure", options = ["Bearish", "Bullish"], group = trend_settings_group)
swing_structure_15m = input.string("Bearish", "15m Swing Structure", options = ["Bearish", "Bullish"], group = trend_settings_group)
swing_structure_color_bull = input.color(#abe69b, "Bull", group = "Colors", inline = "01")
swing_structure_color_bear = input.color(#ffdbd2, "Bear", group = "Colors", inline = "01")
swing_structure_4h_color = color.green
swing_structure_15m_color = color.green
if swing_structure_4h == "Bearish"
swing_structure_4h_color := swing_structure_color_bear
else
swing_structure_4h_color := swing_structure_color_bull
if swing_structure_15m == "Bearish"
swing_structure_15m_color := swing_structure_color_bear
else
swing_structure_15m_color := swing_structure_color_bull
General_Title = input.string("General Infos", "General Title", group = general_group)
General_Infos = input.text_area("Type text...", "General Infos", group = general_group, tooltip = "use '\\n' for new line")
var maTable = table.new(
position=position.top_right, columns=2, rows=21, bgcolor=bg_table_color,
frame_color=color.gray, frame_width=1, border_width=3)
if barstate.islast and show_rules
Cell = 0
// Header
table.cell(maTable, 0, 0, text = table_title, text_size = h1_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
//Trend Settings
Cell += 1
table.cell(maTable, 0, Cell, text = Trend_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = "4h Swing Structure")
table.cell(maTable, 1, Cell, text = swing_structure_4h, bgcolor = swing_structure_4h_color, text_size = h2_size)
Cell += 1
table.cell(maTable, 0, Cell, text = "15m Swing Structure")
table.cell(maTable, 1, Cell, text = swing_structure_15m, bgcolor = swing_structure_15m_color, text_size = h2_size)
//table.merge_cells(maTable, 0, Cell, 1, Cell)
//General Infos
Cell += 1
table.cell(maTable, 0, Cell, text = General_Title, text_color = title_text_color, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
Cell += 1
table.cell(maTable, 0, Cell, text = General_Infos, text_size = h2_size)
table.merge_cells(maTable, 0, Cell, 1, Cell)
|
deseasonalized_mod | https://www.tradingview.com/script/Jv4AJcDh-deseasonalized-mod/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 178 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ palitoj_endthen
//@version=5
indicator(title = 'deseasonalized/centered_ma', shorttitle = 'deseasonalized_mod')
// Input
src = input.source(defval = ohlc4, title = 'Source', group = 'Source', tooltip = 'Choose the input data, default to OHLC4')
length = input.int(defval = 10, title = 'Length', group = 'Source', tooltip = 'Determines the length for deseasonalized, consider overfitting/bias-variance trade-off')
tf = input.timeframe('D', title = 'Time-Frame', group = 'Source', tooltip = 'Choose the input timeframe')
buy = input.bool(defval = true, title = 'Buy Signal', group = 'Options', tooltip = 'Determines whether to show the Buy signal')
sell = input.bool(defval = true, title = 'Sell Signal', group = 'Options', tooltip = 'Determines whether to show the Sell signal')
lag = input.bool(defval = true, title = 'Hysteresis', group = 'Options')
// Deseasonalized
deseasonalize(s, l)=>
wma = ta.wma(s, l)
seasonality_mod = s/ta.wma(wma, l)
deseasonalized_mod = s/seasonality_mod
src_adjusted = request.security(syminfo.tickerid, tf, src)
deseasonalized = deseasonalize(src_adjusted, length)
// Visualize
color_con = deseasonalized > deseasonalized[1] and deseasonalized[1] > deseasonalized[2] ? color.green : color.red
color_con_ = deseasonalized > deseasonalized[1] and deseasonalized[1] > deseasonalized[2]
plot(deseasonalized, color = color_con, linewidth = 3)
plot(lag ? deseasonalized*(1+(.5/100)) : na, color = color.new(color.yellow, 50))
plot(lag ? deseasonalized*(1-(.5/100)) : na, color = color.new(color.yellow, 50))
if (not color_con_[1] and color_con_)
b = label.new(bar_index[1], deseasonalized*(1-.01), text = buy ? 'B' : na, style = label.style_label_upper_right, color = buy ? color.gray : na, textcolor = color.white, size = size.normal)
label.set_tooltip(b, 'Expected to be uptrend.\nPosistion: Buy/Entry Long')
else
if (color_con_[1] and not color_con_)
s = label.new(bar_index[1], deseasonalized*(1+.01), text = sell ? 'S' : na, style = label.style_label_lower_right, color = sell ? color.blue : na, textcolor = color.white, size = size.normal)
label.set_tooltip(s, 'Expected to be downtrend.\nPosistion: Sell/Entry Short')
else
na
// Create Alert
alertcondition((not color_con_[1] and color_con_), title = 'Entry', message = 'Buy/Long entry point')
alertcondition((color_con_ and not color_con_), title = 'Close', message = 'Sell/Short entry point')
|
Simple Strat Numbers | https://www.tradingview.com/script/99HjpTrX-Simple-Strat-Numbers/ | TraderCreatorPro | https://www.tradingview.com/u/TraderCreatorPro/ | 54 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ TraderCreatorPro
//@version=5
indicator("Simple Strat Numbers", "Strat Numbers", true)
import ZenAndTheArtOfTrading/ZenLibrary/2 as zen
//Input Groups
var djs = "Strat Colors"
var stratnumbers = "Strat Numbers"
//User Imputs
Ones = input.bool(true, "1's marked", inline = stratnumbers, group = stratnumbers)
Twos = input.bool(true, "2's marked", inline = stratnumbers, group = stratnumbers)
Threes = input.bool(true, "3's marked", inline = stratnumbers, group = stratnumbers)
inside = input.color(color.white, "Ones Color (Inside Bars)", inline = djs)
outside = input.color(color.yellow, "Threes Color (Outside Bar)", inline = djs)
twoup = input.color(color.fuchsia, "Two up red candle", inline = djs)
twodown = input.color(color.maroon, "Two down Green candle", inline = djs)
up = input.color(color.green, "Two up and Green Candle", inline = djs)
down = input.color(color.red, "Two Down and Red Candle", inline = djs)
//Add Strat numbers to the chart
plotchar(Ones? high<high[1] and low > low[1]: na, "Inside Bars", char = '1',location = location.belowbar, color = inside)
plotchar(Threes? high>high[1] and low<low[1]:na, "Outside Bars", char = "3", location = location.belowbar, color = outside)
plotchar(Twos? high> high [1] and low >low[1] or low<low[1] and high<high[1] :na, "Up and Down Bars",
char = "2", location = location.belowbar, color = (high> high[1] and low>low[1] and close<open)? twoup: (high< high[1] and low<low[1] and close>open)? twodown: high> high[1] and low>low[1]? up : down)
|
Caleb's Supply and Demand Zones | https://www.tradingview.com/script/C5KvAonl-Caleb-s-Supply-and-Demand-Zones/ | tradercaleb | https://www.tradingview.com/u/tradercaleb/ | 838 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ CarreyTrades
//@version=5
indicator("Caleb Zones", overlay=true, max_bars_back=1000)
numbox = input.int(10, title="Number of Zones", minval=0, maxval=10)
efma = input.bool(false, title=" ", inline="fma", group="ma")
fma = input.int(9, title="Fast EMA", inline="fma", group="ma")
fmac = input.color(color.new(color.yellow, 50), title="Fast MA Color", inline="fma", group="ma")
esma = input.bool(false, title=" ", inline="sma", group="ma")
sma = input.int(21, title="Slow EMA", inline="sma", group="ma")
smac = input.color(color.new(color.orange, 50), title="Slow MA Color", inline="sma", group="ma")
vw = input.bool(false, title=" ", inline="vw", group="ma")
vwapc = input.color(color.new(color.aqua, 50), title="VWAP Color", inline="vw", group="ma")
src = input.source(ohlc4, title="EMA Source", group="ma")
ohour = input.int(9, title="Start Time", minval=0, maxval=23, step=1, tooltip="Hour values greater than 16 will push into the next day's session and will be off by one hour due to market settlement hour.", inline="a", group="Time")
ominute = input.int(30, title=" ", minval=0, maxval=59, step=1, inline="a", group="Time")
chour = input.int(16, title="End Time", minval=0, maxval=23, step=1, tooltip="Hour values greater than 16 will push into the next day's session and will be off by one hour due to market settlement hour.", inline="b", group="Time")
cminute = input.int(0, title=" ", minval=0, maxval=59, step=1, inline="b", group="Time")
ext = input.bool(false, title="Extend Zones Right?", inline="c")
extl = input.bool(false, title="Extend Zones Left?", inline="c")
extend = ext ? extend.right : extl ? extend.left : extend.none
//Logic
IsSPY = syminfo.root == "SPY"
IsQQQ = syminfo.root == "QQQ"
IsES = (syminfo.root == "ES" or syminfo.root == "MES" or syminfo.root == "US500" or syminfo.root == "SPX")
IsNQ = (syminfo.root == "NQ" or syminfo.root == "MNQ" or syminfo.root == "US100")
m = IsSPY ? 1 : IsQQQ ? 1 : IsES ? 10 : IsNQ ? 40 : na
// SPY Boxes
s1t = 447.08
s1b = 446.03
s2t = 444.16
s2b = 442.99
s3t = 440.50
s3b = 439.66
s4t = 437.27
s4b = 436.03
s5t = 434.35
s5b = 433.49
s6t = 431.49
s6b = 430.41
s7t = 428.83
s7b = 427.79
s8t = 425.90
s8b = 424.92
s9t = 422.32
s9b = 421.33
s10t = 420.17
s10b = 419.57
// QQQ Boxes
q1t = 341.85
q1b = 340.99
q2t = 338.13
q2b = 336.27
q3t = 334.22
q3b = 333.10
q4t = 331.15
q4b = 329.82
q5t = 327.52
q5b = 326.56
q6t = 323.33
q6b = 322.07
q7t = 320.15
q7b = 319.66
q8t = 318.10
q8b = 317.52
q9t = 316.21
q9b = 315.61
q10t = 314.45
q10b = 313.73
// Timeframe Logic
openTime = hour == ohour and minute == ominute
left = ta.barssince(openTime)
closeTime = hour == chour and minute == cminute
timerange = (chour - ohour - 1)*60 + math.abs(cminute - ominute)
tfcheck = timeframe.period
mult = timeframe.multiplier
right = timerange / mult
// Box 1
b1t = IsSPY or IsES ? s1t * m : IsQQQ or IsNQ ? q1t * m : na
b1b = IsSPY or IsES ? s1b * m : IsQQQ or IsNQ ? q1b * m : na
bc1 = close > b1t ? color.green : close < b1b ? color.red : color.white
bgc1 = close > b1t ? color.new(color.green, 99) : close < b1b ? color.new(color.red, 99) : color.new(color.white,99)
b1 = numbox >= 9 ? (box.new(bar_index[left], b1t, bar_index[left] + right, b1b, border_color = bc1, extend=extend, bgcolor=bgc1, text_color=color.white)) : na
// Box 2
b2t = IsSPY or IsES ? s2t * m : IsQQQ or IsNQ ? q2t * m : na
b2b = IsSPY or IsES ? s2b * m : IsQQQ or IsNQ ? q2b * m : na
bc2 = close > b2t ? color.green : close < b2b ? color.red : color.white
bgc2 = close > b2t ? color.new(color.green, 99) : close < b2b ? color.new(color.red, 99) : color.new(color.white,99)
b2 = numbox >= 7 ? (box.new(bar_index[left], b2t, bar_index[left] + right, b2b, border_color = bc2, extend=extend, bgcolor = bgc2, text_color=color.white)) : na
// Box 3
b3t = IsSPY or IsES ? s3t * m : IsQQQ or IsNQ ? q3t * m : na
b3b = IsSPY or IsES ? s3b * m : IsQQQ or IsNQ ? q3b * m : na
bc3 = close > b3t ? color.green : close < b3b ? color.red : color.white
bgc3 = close > b3t ? color.new(color.green, 99) : close < b3b ? color.new(color.red, 99) : color.new(color.white,99)
b3 = numbox >= 5 ? (box.new(bar_index[left], b3t, bar_index[left] + right, b3b, border_color = bc3, extend=extend, bgcolor = bgc3, text_color=color.white)) : na
// Box 4
b4t = IsSPY or IsES ? s4t * m : IsQQQ or IsNQ ? q4t * m : na
b4b = IsSPY or IsES ? s4b * m : IsQQQ or IsNQ ? q4b * m : na
bc4 = close > b4t ? color.green : close < b4b ? color.red : color.white
bgc4 = close > b4t ? color.new(color.green, 99) : close < b4b ? color.new(color.red, 99) : color.new(color.white,99)
b4 = numbox >= 3 ? (box.new(bar_index[left], b4t, bar_index[left] + right, b4b, border_color = bc4, extend=extend, bgcolor = bgc4, text_color=color.white)) : na
// Box 5
b5t = IsSPY or IsES ? s5t * m : IsQQQ or IsNQ ? q5t * m : na
b5b = IsSPY or IsES ? s5b * m : IsQQQ or IsNQ ? q5b * m : na
bc5 = close > b5t ? color.green : close < b5b ? color.red : color.white
bgc5 = close > b5t ? color.new(color.green, 99) : close < b5b ? color.new(color.red, 99) : color.new(color.white,99)
b5 = numbox >= 1 ? box.new(bar_index[left], b5t, bar_index[left] + right, b5b, border_color = bc5, extend=extend, bgcolor = bgc5, text_color=color.white) : na
// Box 6
b6t = IsSPY or IsES ? s6t * m : IsQQQ or IsNQ ? q6t * m : na
b6b = IsSPY or IsES ? s6b * m : IsQQQ or IsNQ ? q6b * m : na
bc6 = close > b6t ? color.green : close < b6b ? color.red : color.white
bgc6 = close > b6t ? color.new(color.green, 99) : close < b6b ? color.new(color.red, 99) : color.new(color.white,99)
b6 = numbox >= 2 ? box.new(bar_index[left], b6t, bar_index[left] + right, b6b, border_color = bc6, extend=extend, bgcolor = bgc6, text_color=color.white) : na
// Box 7
b7t = IsSPY or IsES ? s7t * m : IsQQQ or IsNQ ? q7t * m : na
b7b = IsSPY or IsES ? s7b * m : IsQQQ or IsNQ ? q7b * m : na
bc7 = close > b7t ? color.green : close < b7b ? color.red : color.white
bgc7 = close > b7t ? color.new(color.green, 99) : close < b7b ? color.new(color.red, 99) : color.new(color.white,99)
b7 = numbox >= 4 ? box.new(bar_index[left], b7t, bar_index[left] + right, b7b, border_color = bc7, extend=extend, bgcolor = bgc7, text_color=color.white) : na
// Box 8
b8t = IsSPY or IsES ? s8t * m : IsQQQ or IsNQ ? q8t * m : na
b8b = IsSPY or IsES ? s8b * m : IsQQQ or IsNQ ? q8b * m : na
bc8 = close > b8t ? color.green : close < b8b ? color.red : color.white
bgc8 = close > b8t ? color.new(color.green, 99) : close < b8b ? color.new(color.red, 99) : color.new(color.white,99)
b8 = numbox >= 6 ? box.new(bar_index[left], b8t, bar_index[left] + right, b8b, border_color = bc8, extend=extend, bgcolor = bgc8, text_color=color.white) : na
// Box 9
b9t = IsSPY or IsES ? s9t * m : IsQQQ or IsNQ ? q9t * m : na
b9b = IsSPY or IsES ? s9b * m : IsQQQ or IsNQ ? q9b * m : na
bc9 = close > b9t ? color.green : close < b9b ? color.red : color.white
bgc9 = close > b9t ? color.new(color.green, 99) : close < b9b ? color.new(color.red, 99) : color.new(color.white,99)
b9 = numbox >= 8 ? box.new(bar_index[left], b9t, bar_index[left] + right, b9b, border_color = bc9, extend=extend, bgcolor = bgc9, text_color=color.white) : na
// Box 10
b10t = IsSPY or IsES ? s10t * m : IsQQQ or IsNQ ? q10t * m : na
b10b = IsSPY or IsES ? s10b * m : IsQQQ or IsNQ ? q10b * m : na
bc10 = close > b10t ? color.green : close < b10b ? color.red : color.white
bgc10 = close > b10t ? color.new(color.green, 99) : close < b10b ? color.new(color.red, 99) : color.new(color.white,99)
b10 = numbox >= 10 ? box.new(bar_index[left], b10t, bar_index[left] + right, b10b, border_color = bc10, extend=extend, bgcolor = bgc10, text_color=color.white) : na
// EMA Plots
fmap = efma ? ta.ema(src, fma) : na
plot(fmap, title="Fast Moving Average", color=fmac)
smap = esma ? ta.ema(src, sma) : na
plot(smap, title="Slow Moving Average", color=smac)
vwap = vw ? ta.vwap(src) : na
plot(vwap, title="VWAP", color=vwapc)
|
50% Strat Retracement | https://www.tradingview.com/script/agxSKGci-50-Strat-Retracement/ | TraderCreatorPro | https://www.tradingview.com/u/TraderCreatorPro/ | 103 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ TraderCreatorPro
//@version=5
indicator("50% Retracement", "%", true)
import ZenAndTheArtOfTrading/ZenLibrary/2 as zen
//Input Groups
//User Imputs
percentage = input.float(50, "Percentage retracement")
arrowdown = input.bool(true, "Arrows Down")
arrowup = input.bool(true, "Arrows Up")
rline = input.bool(true, "A line at the Retracement level. (If you want the label to show on the side you will need to turn that on in your chart settings)")
alerts = input.bool(true, "Alerts you if there is a retracement happening")
//line calculation
twoupred = high > high[1] and open > close
twodowngreen = low < low[1] and open< close
Difference = high[1] - low[1]
multiplier = percentage/100
Calculation = Difference * multiplier + low[1]
fiftydown = twoupred and close < Calculation
fiftyup = twodowngreen and close > Calculation
//Add Arrow
plotshape(arrowdown? fiftydown:na , text = "% Rev down", style = shape.arrowdown, size = size.huge, color = color.red)
plotshape(arrowup? fiftyup:na , text = "% Rev Up", style = shape.arrowup, size = size.huge, color = color.green, location = location.belowbar)
plot (rline? Calculation:na, style = plot.style_linebr)
//Alerts
alertcondition (fiftydown and alerts, "Up {{ticker}}, {{close}}")
alertcondition (fiftyup and alerts, "down {{ticker}}, {{close}}")
|
Hodrick-Prescott Channel [Loxx] | https://www.tradingview.com/script/mSaeukoO-Hodrick-Prescott-Channel-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 176 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Hodrick-Prescott Channel [Loxx]",
shorttitle='HPC [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
_HPFilter(src, lamb, per)=>
H1 = 0., H2 = 0., H3 = 0., H4 = 0., H5 = 0.,
HH1 = 0., HH2 = 0., HH3 = 0., HH5 = 0.
HB= 0., HC= 0., Z= 0.
a = array.new<float>(per, 0.)
b = array.new<float>(per, 0.)
c = array.new<float>(per, 0.)
out = array.new<float>(per, 0.)
for i = 0 to per - 1
array.set(out, i, nz(src[i]))
array.set(a, 0, 1.0 + lamb)
array.set(b, 0, -2.0 * lamb)
array.set(c, 0, lamb)
for i = 1 to per - 3
array.set(a, i, 6.0 * lamb + 1.0)
array.set(b, i, -4.0 * lamb)
array.set(c, i, lamb)
array.set(a, 1, 5.0 * lamb + 1)
array.set(a, per - 1, 1.0 + lamb)
array.set(a, per - 2, 5.0 * lamb + 1.0)
array.set(b, per - 2, -2.0 * lamb)
array.set(b, per - 1, 0.)
array.set(c, per - 2, 0.)
array.set(c, per - 1, 0.)
for i = 0 to per - 1
Z := array.get(a, i) - H4 * H1 - HH5 * HH2
if (Z == 0)
break
HB := array.get(b, i)
HH1 := H1
H1 := (HB - H4 * H2) / Z
array.set(b, i, H1)
HC := array.get(c, i)
HH2 := H2
H2 := HC / Z
array.set(c, i, H2)
array.set(a, i, (array.get(out, i) - HH3 * HH5 - H3 * H4) / Z)
HH3 := H3
H3 := array.get(a, i)
H4 := HB - H5 * HH1
HH5 := H5
H5 := HC
H2 := 0
H1 := array.get(a, per - 1)
array.set(out, per - 1, H1)
for i = per - 2 to 0
array.set(out, i, array.get(a, i) - array.get(b, i) * H1 - array.get(c, i) * H2)
H2 := H1
H1 := array.get(out, i)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
fastper = input.int(21, 'Fast Period', minval=4, maxval = 32, group = "Basic Settings")
slowper = input.int(100, 'Slow Period', minval=48, maxval = 256, group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
lambfast = 0.0625 / math.pow(math.sin(math.pi / fastper), 4)
lambslow = 0.0625 / math.pow(math.sin(math.pi / slowper), 4)
fast = _HPFilter(src, lambfast, slowper)
slow = _HPFilter(array.get(fast, 0), lambslow, slowper)
disp = 0.
for i = 0 to slowper - 1
disp += (nz(array.get(fast, 0)[i]) - nz(array.get(slow, 0)[i])) * (nz(array.get(fast, 0)[i]) - nz(array.get(slow, 0)[i]))
disp := disp / (slowper - 1)
dev = math.sqrt(disp) * 2.0
slowout = array.get(slow, 0)
fastout = array.get(fast, 0)
Dev1 = slowout + dev
Dev2 = slowout - dev
colorout = fastout > slowout ? greencolor : fastout < slowout ? redcolor : color.gray
plot(slowout, color = colorout, linewidth = 3)
plot(Dev1, color = bar_index % 2 ? color.gray : na)
plot(Dev2, color = bar_index % 2 ? color.gray : na)
plot(fastout, color = color.white)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(fastout, slowout)
goShort = ta.crossunder(fastout, slowout)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx] | https://www.tradingview.com/script/QO1AFLrs-Cycle-Period-Adaptive-Linear-Regression-Slope-Oscillator-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]",
shorttitle='CPALRSO [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
SM02 = 'Slope'
SM03 = 'Zero Cross'
greencolor = #2DD204
redcolor = #D2042D
_median(x, y, z)=>
out = x + y + z - math.min(x, math.min(y, z)) - math.max(x, math.max(y, z))
out
_cycleper(src, alpha)=>
smooth = (src + 2 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 6.0
cycle = 0., instantper = 0., pout = 0., ac = 0.
cycle :=
bar_index < 7 ?
(src - 2 * src[1] + src[2]) / 4.0 :
(1 - 0.5 * alpha) * (1 - 0.5 * alpha) * (smooth - 2 * nz(smooth[1]) +nz(smooth[2])) + 2 * (1 - alpha) * nz(cycle[1]) - (1 - alpha) * (1 - alpha) * nz(cycle[2])
q1 = (.0962 * cycle + 0.5769 * nz(cycle[2]) - 0.5769 * nz(cycle[4]) - .0962 * nz(cycle[6])) * (0.5 + .08 * nz(instantper[1]))
I1 = cycle[3]
dp = q1 != 0 and nz(q1[1]) != 0 ? (I1 / q1 - nz(I1[1]) / nz(q1[1])) / (1 + I1 * nz(I1[1]) / (q1 * nz(q1[1]))) : 0
dp := dp > 1.1 ? 1.1 : dp
dp := dp < 0.1 ? 0.1 : dp
md = _median(dp, nz(dp[1]), _median(nz(dp[2]), nz(dp[3]), nz(dp[4])))
dc = md == 0 ? 15 : 6.28318 / md + 0.5
instantper := .33 * dc + .67 * nz(instantper[1])
pout := .15 * instantper + .85 * nz(pout[1])
pout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(14, "Period", group = "Basic Settings")
calpha = input.float(0.07, "Cycle Alpha", group = "Cycle Period Settings")
cmult = input.float(1, "Cycle Multiplier", group = "Cycle Period Settings")
smthper = input.int(9, "Smoothing Period", group = "Smoothing Settings")
type = input.string("Exponential Moving Average - EMA", "Fast MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Smoothing Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
tempper = _cycleper(src, calpha)
per := math.max(math.round(fixnan(tempper) * cmult), 3)
per := per < 1 ? 1 : per
sbars = per * (per - 1) * 0.5
sqbars = (per - 1.0) * per * (2.0 * per - 1.0) / 6.0
//because folks will ask why i'm looping this instead of using PS functions,
//this is to void problems with math.sum when using dynamic periods
Sum1 = 0.
for i = 0 to per - 1
Sum1 += i * nz(src[i])
sumy = 0.
for i = 0 to per - 1
sumy += nz(src[i])
sum2 = sbars * sumy
n1 = per * Sum1 - sum2
n2 = sbars * sbars - per * sqbars
rslp = 0.
rslp := n2 != 0 ? 100 * n1 / n2 : 0.
rslp := variant(type, rslp, smthper)
sig = rslp[1]
mid = 0.
state = 0.
if sigtype == SM02
if (rslp < sig)
state :=-1
if (rslp > sig)
state := 1
else if sigtype == SM03
if (rslp < mid)
state :=-1
if (rslp > mid)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(rslp, "Linear Regression Slope", color = colorout, linewidth = 3)
plot(mid, "Zero", color = bar_index % 2 ? color.white : na)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(rslp, sig) : ta.crossover(rslp, mid)
goShort = sigtype == SM02 ? ta.crossunder(rslp, sig) : ta.crossunder(rslp, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Cycle-Period Adaptive, Linear Regression Slope Oscillator [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Hodrick-Prescott MACD [Loxx] | https://www.tradingview.com/script/mutOT9kk-Hodrick-Prescott-MACD-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 96 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Hodrick-Prescott MACD [Loxx]",
shorttitle='HPMACD [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crosses'
SM04 = 'Signal Crosses'
_HPFilter(src, lamb, per)=>
H1 = 0., H2 = 0., H3 = 0., H4 = 0., H5 = 0.,
HH1 = 0., HH2 = 0., HH3 = 0., HH5 = 0.
HB= 0., HC= 0., Z= 0.
a = array.new<float>(per, 0.)
b = array.new<float>(per, 0.)
c = array.new<float>(per, 0.)
out = array.new<float>(per, 0.)
for i = 0 to per - 1
array.set(out, i, nz(src[i]))
array.set(a, 0, 1.0 + lamb)
array.set(b, 0, -2.0 * lamb)
array.set(c, 0, lamb)
for i = 1 to per - 3
array.set(a, i, 6.0 * lamb + 1.0)
array.set(b, i, -4.0 * lamb)
array.set(c, i, lamb)
array.set(a, 1, 5.0 * lamb + 1)
array.set(a, per - 1, 1.0 + lamb)
array.set(a, per - 2, 5.0 * lamb + 1.0)
array.set(b, per - 2, -2.0 * lamb)
array.set(b, per - 1, 0.)
array.set(c, per - 2, 0.)
array.set(c, per - 1, 0.)
for i = 0 to per - 1
Z := array.get(a, i) - H4 * H1 - HH5 * HH2
if (Z == 0)
break
HB := array.get(b, i)
HH1 := H1
H1 := (HB - H4 * H2) / Z
array.set(b, i, H1)
HC := array.get(c, i)
HH2 := H2
H2 := HC / Z
array.set(c, i, H2)
array.set(a, i, (array.get(out, i) - HH3 * HH5 - H3 * H4) / Z)
HH3 := H3
H3 := array.get(a, i)
H4 := HB - H5 * HH1
HH5 := H5
H5 := HC
H2 := 0
H1 := array.get(a, per - 1)
array.set(out, per - 1, H1)
for i = per - 2 to 0
array.set(out, i, array.get(a, i) - array.get(b, i) * H1 - array.get(c, i) * H2)
H2 := H1
H1 := array.get(out, i)
out
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
fastper = input.int(40, "Signal Period", group = "Basic Settings", minval = 3)
slowper = input.int(80, "Signal Period", group = "Basic Settings", minval = 3)
sigper = input.int(3, "Signal Period", group = "Basic Settings", minval = 3)
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03, SM04], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group= "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
lambfast = 0.0625 / math.pow(math.sin(math.pi / fastper), 4)
lambslow = 0.0625 / math.pow(math.sin(math.pi / slowper), 4)
lambsig = 0.0625 / math.pow(math.sin(math.pi / sigper), 4)
fast = _HPFilter(src, lambfast, fastper)
slow = _HPFilter(src, lambslow, slowper)
macd = array.get(fast, 0) - array.get(slow, 0)
macds = macd[1]
sig = _HPFilter(macd, lambsig, sigper)
sigout = array.get(sig, 0)
mid = 0
state = 0.
if sigtype == SM02
if (macd<macds)
state :=-1
if (macd>macds)
state := 1
else if sigtype == SM03
if (macd<mid)
state :=-1
if (macd>mid)
state := 1
else if sigtype == SM04
if (macd<sigout)
state :=-1
if (macd>sigout)
state := 1
colorout = state == -1 ? redcolor : state == 1 ? greencolor : color.gray
plot(sigout, "Signal", color = colorout, linewidth = 3)
plot(macd, "HP MACD", color = color.white)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
barcolor(colorbars ? colorout : na)
goLong = sigtype == SM02 ? ta.crossover(macd, macds) : sigtype == SM03 ? ta.crossover(macd, mid) : ta.crossover(macd, sigout)
goShort = sigtype == SM02 ? ta.crossunder(macd, macds) : sigtype == SM03 ? ta.crossunder(macd, mid) : ta.crossunder(macd, sigout)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Hodrick-Prescott MACD [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Hodrick-Prescott MACD [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Non-Lag Inverse Fisher Transform of RSX [Loxx] | https://www.tradingview.com/script/GqCxfTM2-Non-Lag-Inverse-Fisher-Transform-of-RSX-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 332 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Non-Lag Inverse Fisher Transform of RSX [Loxx]",
shorttitle='NLIFTRSX [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxmas/1
import loxx/loxxrsx/1
greencolor = #2DD204
redcolor = #D2042D
per = input.int(5, "Fisher Period")
src = input.source(close, "Fisher Source")
nlper = input.int(15, "Non-Lag MA Period")
Level1 = input.float(.9, "Upper Level")
Level2 = input.float(0, "Middle")
Level3 = input.float(-.9, "Lower Level")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
rsi = loxxrsx.rsx(src, per)
[avg, _, _] = loxxmas.nonlagma(0.1 * (rsi - 50), nlper)
fish = (math.exp(2 * avg) - 1) / (math.exp(2 * avg) + 1)
trend = 0
if (fish < Level1 and fish > Level3)
trend := 0
if (fish > Level1)
trend := 1
if (fish < Level3)
trend := -1
colorout = trend == 1 ? greencolor : trend == - 1 ? redcolor : color.gray
fishpl = plot(fish, color = colorout, linewidth = 2)
lvl1 = plot(Level1, color = bar_index % 2 ? greencolor : na)
plot(Level2, color = bar_index % 2 ? color.gray : na)
lvl3 = plot(Level3, color = bar_index % 2 ? redcolor : na)
fill(lvl1, fishpl, color = fish > Level1 ? greencolor : na)
fill(lvl3, fishpl, color = fish < Level3 ? redcolor : na)
barcolor(colorbars ? colorout: na)
goLong = ta.crossover(fish, Level1)
goShort = ta.crossunder(fish, Level3)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Non-Lag Inverse Fisher Transform of RSX [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Non-Lag Inverse Fisher Transform of RSX [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Days and Session | https://www.tradingview.com/script/U93Yy9hu-Days-and-Session/ | sosso_bott | https://www.tradingview.com/u/sosso_bott/ | 62 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ mbome237
//@version=5
indicator(title="Days and Session", overlay=true)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโ \\
// โผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผ \\
// โฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒ \\
// โโโโโโโโโโโโโโโโโโโโโโโโโโโ \\
separateDays = input.bool(true, title="Show New Session Candle")
colorDays = input.bool(true, title="Color Day's Background")
color lundi = input.color(color.yellow, "Monday")
color mardi = input.color(color.navy, "Tuesday")
color mercredi = input.color(color.olive, "Wednesday")
color jeudi = input.color(color.purple, "Thursday")
color vendredi = input.color(color.silver, "Friday")
color weekend = input.color(color.teal, "Weekend")
monday = color.new(lundi, 90)
tuesday = color.new(mardi, 90)
wednesday = color.new(mercredi, 90)
thursday = color.new(jeudi, 90)
friday = color.new(vendredi, 90)
sunday = color.new(weekend, 90)
lol2 = dayofweek(time) == dayofweek.monday ? monday : dayofweek(time) == dayofweek.tuesday ? tuesday : dayofweek(time) == dayofweek.wednesday ? wednesday : dayofweek(time) == dayofweek.thursday? thursday : dayofweek(time) == dayofweek.friday ? friday : sunday
bgcolor(color=colorDays? lol2:na)
is_newbar(res) =>
t = time(res)
not na(t) and (na(t[1]) or t > t[1])
xxx = is_newbar("D") ? 1 : 0
bgcolor(color= not separateDays? na : xxx==1 ?color.black:na, transp=50) |
HTF Candles | https://www.tradingview.com/script/rxWK99wo-HTF-Candles/ | sosso_bott | https://www.tradingview.com/u/sosso_bott/ | 23 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ sosso_bott
//@version=5
indicator("TF Overlay", overlay=true)
// Almost lol
no_rep(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1:0], barmerge.gaps_off, barmerge.lookahead_off)
//Heiken Ashi
isHA = input.bool(title="Heikin Ashi Ticker", defval=false)
tf = input.timeframe(title="Timeframe", defval="60")
bull_color = input.color(title="Bull Candle Color", defval=color.blue)
bear_color = input.color(title="Bear Candle Color", defval=color.orange)
show_Wick = input.bool(title="Show Wick", defval=false)
wick_color = input.color(title="Candle Wick Color", defval=color.black)
bull_transp = input.int(title="bull", defval=90, minval=0, maxval=100, step=5, group="Color Transparency")
bear_tranp = input.int(title="bear", defval=90, minval=0, maxval=100, step=5, group="Color Transparency")
wick_tranp = input.int(title="wick", defval=90, minval=0, maxval=100, step=5, group="Color Transparency")
int transp = show_Wick ? wick_tranp : 100
bull_candle = color.new(bull_color, bull_transp)
bear_candle = color.new(bear_color, 90)
wick = color.new(wick_color, transp)
ticker = isHA ? ticker.heikinashi(syminfo.ticker) : syminfo.ticker
o = no_rep(ticker, tf, open)
h = no_rep(ticker, tf, high)
l = no_rep(ticker, tf, low)
c = no_rep(ticker, tf, close)
candle_color = c > o ? bull_candle : bear_candle
plotcandle(o, h, l, c, "TF", candle_color, wick)
|
Position Size Calc. (Minimalist) | https://www.tradingview.com/script/CCYMWaBi-Position-Size-Calc-Minimalist/ | chartsniping | https://www.tradingview.com/u/chartsniping/ | 179 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("Position Size Calc.", overlay=true, max_labels_count=5)
var string curr = input.string('USD', title="Account Currency", options=['USD','EUR','CHF','CAD','GBP','JPY','AUD','HKD','NZD'])
var string unitcurr = syminfo.basecurrency
//var string tradepair = syminfo.ticker
//var float tickerexchange = request.security(tradepair, '3', open)
var string pair = unitcurr+curr
var string reversepair = curr+unitcurr
var float exchangerate = request.security(pair, '3', open, ignore_invalid_symbol=1)
var float reverserate = 1/request.security(reversepair, '3', open, ignore_invalid_symbol=1)
var float userate = 0
if (curr==unitcurr)
userate := 1
else if (na(exchangerate)==1)
userate := reverserate
else
userate := exchangerate
var float risk_amt = input.float(3, title="Risk Level in % (1%,2%,3%,etc.)")
var int deposit = input.int(1000, title="Account Size")
var float entry = input.float(1, title="Entry Price")
var float stop = input.float(1, title="Stop Price")
var float tprofit = input.float(1, title="Take Profit")
//non-forex calculations
var float doll_risk = (risk_amt/100)*deposit //this is printed as loss also
var float base_risk = math.abs(entry-stop) //just takes absolute value
var float pos_size = doll_risk/(base_risk/entry)
var float profit = (math.abs(entry-tprofit)/entry)*pos_size
//forex calculations
var float pos_size_base = pos_size/userate
var float lots = (pos_size_base) / 100000
var string GROUP_OTHERS = "Table"
var string tab_pos = input.string(position.bottom_right, options=[position.top_left,position.top_right,position.bottom_left,position.bottom_right], title="Position of table", group=GROUP_OTHERS)
var color DEFAULT_CELL_COLOR = #aaaaaa
var color DEFAULT_TXT_COLOR = color.white
var color DEFAULT_HEADER_COLOR = color.black
var tbl = table.new(tab_pos, 5, 5, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(DEFAULT_TXT_COLOR, 100))
var string text_size = size.small
ignored_list(sym) =>
bool ignore = switch sym
"VIX" => true
=> false
if barstate.islast and not ignored_list(syminfo.root)
table.cell(tbl, 0, 0, "Risk %", text_halign = text.align_left, bgcolor = DEFAULT_HEADER_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 1, 0, str.tostring(risk_amt, "#.##"), text_halign = text.align_right, bgcolor = DEFAULT_HEADER_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 0, 1, "Profit", text_halign = text.align_left, bgcolor = color.gray, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 1, 1, str.tostring(profit, "#.##"), text_halign = text.align_right, bgcolor = DEFAULT_CELL_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 0, 2, "Loss", text_halign = text.align_left, bgcolor = color.gray, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 1, 2, str.tostring(doll_risk, "#.##"), text_halign = text.align_right, bgcolor = DEFAULT_CELL_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 0, 3, "Pos. Size", text_halign = text.align_left, bgcolor = color.gray, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 1, 3, str.tostring(pos_size, "#.##"), text_halign = text.align_right, bgcolor = DEFAULT_CELL_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 0, 4, "Lots", text_halign = text.align_left, bgcolor = color.gray, text_color = DEFAULT_TXT_COLOR, text_size = text_size)
table.cell(tbl, 1, 4, str.tostring(lots, "#.######"), text_halign = text.align_right, bgcolor = DEFAULT_CELL_COLOR, text_color = DEFAULT_TXT_COLOR, text_size = text_size) |
Risk:Reward | https://www.tradingview.com/script/csluIyrj-Risk-Reward/ | sosso_bott | https://www.tradingview.com/u/sosso_bott/ | 154 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ sosso_bott
//@version=5
indicator("Risk:Reward", overlay=true)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโ \\
// โผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผโผ \\
// โฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒโฒ \\
// โโโโโโโโโโโโโโโโโโโโโโโโโโโ \\
tt_cstm_entry = "Disable this input to use selected entry source option and Make it Dynamic"
tt_cstm_exit = "Set BOTH Customs TP && custom SL BEFORE enabling this input"
// NOTE: ACTIVATE ONE MODE AT THE TIME
// 1. R:R MODE IS THE ONE BY DEFAULT
// 2. ALERT Mode is meant for SignalAutotraders who needs to figure out their exit strategy
// ------------------------ inputs \\
position = input.string(title="Position", options=["BUY", "SELL"], defval="BUY", group="===== SETTINGS =====")
entry_source = input.source(title="Entry source", defval=close, group="===== SETTINGS =====")
box_length = input.int(title="Left LookBack Length", defval=20, minval=1, group="===== SETTINGS =====")
box_length2 = input.int(title="Right LookBack Length", defval=20, minval=1, group="===== SETTINGS =====")
use_cstm_entry = input.bool(title="Use custom Entry ?", tooltip=tt_cstm_entry, defval=true, group="===== SETTINGS =====")
custom_entry = input.price(title="Entry Price: ", confirm=true, defval=0.0, group="===== SETTINGS =====")
full_custom = input.bool(title="Use custom TP && SL ?", tooltip=tt_cstm_exit, defval=false, group="===== SETTINGS =====")
custom_tp = input.float(title="Custom TP", defval=000.0, group="===== SETTINGS =====")
custom_sl = input.float(title="Custom SL", defval=000.0, group="===== SETTINGS =====")
use_RR = input.bool(title="Use Risk:Reward ?", defval=true, group="=== RISK:REWARD ===")
risk = input.float(title="Risk Value", defval=1, minval=0.5, step=0.5, group="=== RISK:REWARD ===")
reward = input.float(title="Reward Value", defval=1, minval=0.5, step=0.5, group="=== RISK:REWARD ===")
rr_tp = input.float(title='Percentage', defval=0.5, step=0.1, group="=== RISK:REWARD ===")
use_TPs = input.bool(title="Use Take profit levels ?", defval=false, group="=== TAKEPROFIT LEVELS ===")
useTp1 = input.bool(title="Use TP1 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp2 = input.bool(title="Use TP2 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp3 = input.bool(title="Use TP3 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp4 = input.bool(title="Use TP4 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp5 = input.bool(title="Use TP5 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
useTp6 = input.bool(title="Use TP6 ?", defval=true, group="=== TAKEPROFIT LEVELS ===")
slx = input.float(title="Percentage to SL", defval=1.0, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp1x = input.float(title="Percentage to TP1", defval=0.5, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp2x = input.float(title="Percentage to TP2", defval=1.0, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp3x = input.float(title="Percentage to TP3", defval=1.5, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp4x = input.float(title="Percentage to TP4", defval=2.0, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp5x = input.float(title="Percentage to TP5", defval=2.5, step=0.1, group="=== TAKEPROFIT LEVELS ===")
tp6x = input.float(title="Percentage to TP6", defval=3.0, step=0.1, group="=== TAKEPROFIT LEVELS ===")
long_alert = input.bool(title="Enable BUY Alerts", defval=false, group="====== ALERTS ======")
short_alert = input.bool(title="Enable SELL Alerts", defval=false, group="====== ALERTS ======")
order_type = input.string(title="Alert Order Type", options=["LIMIT", "MARKET"], defval="LIMIT", group="====== ALERTS ======")
resop = input.timeframe(title="timeFrame", defval="", group="====== ALERTS ======")
choice = input.bool(title="Heikin Choice", defval=false, group="====== ALERTS ======")
// โโโโโโโ LOGIC
round_price(x) =>
xx = int(x / syminfo.mintick)
xx * syminfo.mintick
Price_in = use_cstm_entry ? custom_entry : entry_source
var float tp1 = na
var float tp2 = na
var float tp3 = na
var float tp4 = na
var float tp5 = na
var float tp6 = na
var float sl = na
var float entry1 = na
var int et = 0
line l11 = na
line l2 = na
line l3 = na
line l4 = na
line l5 = na
line l6 = na
line l7 = na
line l8 = na
label lb11 = na
label lb2 = na
label lb3 = na
label lb4 = na
label lb5 = na
label lb6 = na
label lb7 = na
label lb8 = na
label lb_buyTP1 = na
label lb_buyTP2 = na
label lb_buyTP3 = na
label lb_buyTP4 = na
label lb_buyTP5 = na
label lb_buyTP6 = na
label lb_buySL = na
label lb_sellTP1 = na
label lb_sellTP2 = na
label lb_sellTP3 = na
label lb_sellTP4 = na
label lb_sellTP5 = na
label lb_sellTP6 = na
label lb_sellSL = na
dt = time - time[box_length]
if use_TPs
if position == "BUY"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(entry1 * (1 + (tp1x / 100)))
tp2 := round_price(entry1 * (1 + (tp2x / 100)))
tp3 := round_price(entry1 * (1 + (tp3x / 100)))
tp4 := round_price(entry1 * (1 + (tp4x / 100)))
tp5 := round_price(entry1 * (1 + (tp5x / 100)))
tp6 := round_price(entry1 * (1 + (tp6x / 100)))
sl := round_price(entry1 * (1 - (slx / 100)))
if position == "SELL"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(entry1 * (1 - (tp1x / 100)))
tp2 := round_price(entry1 * (1 - (tp2x / 100)))
tp3 := round_price(entry1 * (1 - (tp3x / 100)))
tp4 := round_price(entry1 * (1 - (tp4x / 100)))
tp5 := round_price(entry1 * (1 - (tp5x / 100)))
tp6 := round_price(entry1 * (1 - (tp6x / 100)))
sl := round_price(entry1 * (1 + (slx / 100)))
if use_RR
if position == "SELL"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(entry1 * ((1 - (rr_tp / 100)* reward)) )
sl := round_price(entry1 * ((1 + (rr_tp / 100)* risk)) )
if position == "BUY"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(entry1 * ((1 + (rr_tp / 100)* reward)) )
sl := round_price(entry1 * ((1 - (rr_tp / 100)* risk)) )
if full_custom
if position == "SELL"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(custom_tp)
sl := round_price(custom_sl)
if position == "BUY"
entry1 := round_price(Price_in)
et := time[box_length2]
tp1 := round_price(custom_tp)
sl := round_price(custom_sl)
if position == "BUY"
if barstate.islast
l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time)
l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time)
l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time)
lb11 := label.new(time + dt * 4, entry1, text="Entry:" + str.tostring(entry1), color=color.blue, textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb2 := label.new(time + dt * 4, sl, text="Stop:" + str.tostring(sl), color=color.red, textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb3 := label.new(time + dt * 4, tp1, text="TP1:" + str.tostring(tp1), color=color.green, textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
linefill3 = linefill.new(l11, l3, color = color.new(color.green, 85))
linefill4 = linefill.new(l2, l11, color = color.new(color.red, 85))
if not use_RR
l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text="TP2:" + str.tostring(tp2),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text="TP3:" + str.tostring(tp3),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text="TP4:" + str.tostring(tp4),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text="TP5:" + str.tostring(tp5),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text="TP6:" + str.tostring(tp6),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
linefill3 = linefill.new(l11, l8, color = color.new(color.green, 85))
linefill4 = linefill.new(l2, l11, color = color.new(color.red, 85))
if position == "SELL"
if barstate.islast
l11 := line.new(et, entry1, time + dt * 2, entry1, color=color.purple, style=line.style_solid,xloc = xloc.bar_time)
l2 := line.new(et, sl, time + dt * 2, sl, color=color.red, style=line.style_solid,xloc = xloc.bar_time)
l3 := line.new(et, tp1, time + dt * 2, tp1, color=color.green, style=line.style_solid,xloc = xloc.bar_time)
lb11 := label.new(time + dt * 4, entry1,text="Entry:" + str.tostring(entry1), color=color.blue, textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb2 := label.new(time + dt * 4, sl,text="Stop:" + str.tostring(sl), color=color.red, textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb3 := label.new(useTp1 ? time + dt * 4 : na, tp1,text="TP1:" + str.tostring(tp1),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
linefill3 = linefill.new(l11, l3, color = color.new(color.green, 85))
linefill4 = linefill.new(l2, l11, color = color.new(color.red, 85))
if not use_RR
l3 := line.new(useTp1 ? et : na, useTp1 ? tp1 : na,useTp1 ?time + dt * 2:na,useTp1 ? tp1 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l4 := line.new(useTp2 ? et : na, useTp2 ? tp2 : na,useTp2 ?time + dt * 2:na,useTp2 ? tp2 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l5 := line.new(useTp3 ? et : na, useTp3 ? tp3 : na,useTp3 ?time + dt * 2:na,useTp3 ? tp3 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l6 := line.new(useTp4 ? et : na, useTp4 ? tp4 : na,useTp4 ?time + dt * 2:na,useTp4 ? tp4 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l7 := line.new(useTp5 ? et : na, useTp5 ? tp5 : na,useTp5 ?time + dt * 2:na,useTp5 ? tp5 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
l8 := line.new(useTp6 ? et : na, useTp6 ? tp6 : na,useTp6 ?time + dt * 2:na,useTp6 ? tp6 : na,color=color.green,style=line.style_solid,xloc = xloc.bar_time)
lb4 := label.new(useTp2 ? time + dt * 4 : na, tp2,text="TP2:" + str.tostring(tp2),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb5 := label.new(useTp3 ? time + dt * 4 : na, tp3,text="TP3:" + str.tostring(tp3),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb6 := label.new(useTp4 ? time + dt * 4 : na, tp4,text="TP4:" + str.tostring(tp4),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb7 := label.new(useTp5 ? time + dt * 4 : na, tp5,text="TP5:" + str.tostring(tp5),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
lb8 := label.new(useTp6 ? time + dt * 4 : na, tp6,text="TP6:" + str.tostring(tp6),color=color.green,textcolor=color.white,style=label.style_label_left,xloc = xloc.bar_time,textalign=text.align_left,size=size.normal)
linefill3 = linefill.new(l11, l8, color = color.new(color.green, 85))
linefill4 = linefill.new(l2, l11, color = color.new(color.red, 85))
label.delete(lb11[1])
line.delete(l11[1])
line.delete(l2[1])
label.delete(lb2[1])
line.delete(l3[1])
label.delete(lb3[1])
line.delete(l4[1])
label.delete(lb4[1])
line.delete(l5[1])
label.delete(lb5[1])
line.delete(l6[1])
label.delete(lb6[1])
line.delete(l7[1])
label.delete(lb7[1])
line.delete(l8[1])
label.delete(lb8[1])
///////////// ******----- ALERTS ---------******** \\\\\\\\\\\\\\\\\\\\\
message = ""
message += syminfo.ticker
if position == "BUY"
message += "\nlong"
if position == "SELL"
message += "\nshort"
if order_type == "LIMIT"
message += "\nEntry: " + str.tostring(Price_in)
if use_TPs
if useTp1
message += "\nTP1: " + str.tostring(tp1)
if useTp2
message += "\nTP2: " + str.tostring(tp2)
if useTp3
message += "\nTP3: " + str.tostring(tp3)
if useTp4
message += "\nTP4: " + str.tostring(tp4)
if useTp5
message += "\nTP5: " + str.tostring(tp5)
if useTp6
message += "\nTP6: " + str.tostring(tp6)
else
message += "\nTP1: " + str.tostring(tp1)
message += "\nSL: " + str.tostring(sl)
no_rep(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1:0], barmerge.gaps_off, barmerge.lookahead_off)
ha_top = choice ? ticker.heikinashi(syminfo.tickerid) : syminfo.tickerid
ha_close= no_rep(ha_top, resop, close)
ha_open = no_rep(ha_top, resop, open)
longCondition = ha_close > ha_open and ha_open[1] > ha_close[1]
shortCondition = ha_close < ha_open and ha_open[1] < ha_close[1]
if long_alert and longCondition
alert(message, alert.freq_once_per_bar_close)
if short_alert and shortCondition
alert(message, alert.freq_once_per_bar_close)
plotshape(long_alert ? longCondition : na, title="Buy", location=location.belowbar, transp=0, color=color.blue, textcolor=color.blue, text="Buy", style=shape.triangleup, size=size.normal)
plotshape(short_alert ? shortCondition: na, title="Sell", location=location.abovebar, transp=0, color=color.orange, textcolor=color.orange, text="Sell", style=shape.triangledown, size=size.normal)
//////////////// ******----- ALERTS END ---------******** \\\\\\\\\\\\\\\\\\\\\
|
Plots CAGR lines for a given set of rates | https://www.tradingview.com/script/zET8OAWH-Plots-CAGR-lines-for-a-given-set-of-rates/ | iravan | https://www.tradingview.com/u/iravan/ | 58 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ iravan
//@version=5
indicator("Plots CAGR lines for a given set of rates", "CAGR Curves", overlay=true)
rate1 = input.float(10, "Growth Rate 1 (%)", minval=1, maxval=100)
rate2 = input.float(15, "Growth Rate 2 (%)", minval=1, maxval=100)
rate3 = input.float(20, "Growth Rate 3 (%)", minval=1, maxval=100)
custom_begin = input.bool(false, "", inline="begin")
begin = input.time(timestamp("01 Jan 2000"), "Begin At", confirm=false, inline="begin", tooltip="Enable and set this option to use a custom start date. If this option is unchecked earliest date available in TradingView for the security will be used as start date.")
var seed = 0.0
var set = false
var display = not timeframe.isintraday
var begin_time = begin
if (open > 0 and time >= begin and not set) or (not custom_begin and not set)
seed := open
set := true
begin_time := time
days = (time_close - begin_time) / (24 * 60 * 60 * 1000)
price1 = seed * math.pow(1 + rate1/100, days/365)
price2 = seed * math.pow(1 + rate2/100, days /365)
price3 = seed * math.pow(1 + rate3/100, days /365)
plot(set and display ? price1 : na, color=color.blue, title="Growth Rate 1")
plot(set and display ? price2 : na, color=color.green, title="Growth Rate 2")
plot(set and display ? price3 : na, color=color.red, title="Growth Rate 3")
if barstate.islast and display
rate = str.tostring(math.round((math.pow(close / seed, 365 / days) - 1) * 100, 2)) + "%"
label.new(bar_index + 1, close, rate, color=color.yellow, style=label.style_label_left) |
Intraday Buy/Sell using Gann Angles - RiTz | https://www.tradingview.com/script/YD4iLKQk-Intraday-Buy-Sell-using-Gann-Angles-RiTz/ | Keanu_ritz | https://www.tradingview.com/u/Keanu_ritz/ | 1,045 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Keanu_ritz
//@version=5
indicator("Intraday Buy/Sell using Gann Angles - RiTz", overlay=true)
Cal = input.string(title="Calculate Buy/Sell Levels based on :", defval='Todays Open', options=['Todays Open', 'Previous Days High','Previous Days Low','Previous Days Close'])
ShowTable = input(title="Show Buy/Sell Levels in a Table", defval=true , group="Table Settings")
ShowBlvl = input(title="Show Buy Levels on Chart", defval=true, group="Style Settings")
ShowSlvl = input(title="Show Sell Levels on Chart", defval=true, group="Style Settings")
ShowHBlvl = input(title="Show Historical Buy Levels on Chart", defval=true, group="Style Settings")
ShowHSlvl = input(title="Show Historical Sell Levels on Chart", defval=true, group="Style Settings")
BlvlColor = input.color(color.new(#78fa04,45),"Color for Buy Levels", group="Style Settings")
SlvlColor = input.color(color.new(#fa2f04,45),"Color for Sell Levels", group="Style Settings")
BTxtColor = input.color(color.new(#78fa04,35),"Color for Buy Levels Text", group="Style Settings")
STxtColor = input.color(color.new(#fa2f04,35),"Color for Sell Levels Text", group="Style Settings")
line_style = input.string("Dotted", options=["Dotted", "Dashed" , "Solid"], title="Line Style", group="Style Settings")
label_size = input.string("small", options=["auto", "tiny", "small", "normal", "large", "huge"], title="Label size", group="Style Settings")
l_size = label_size == "auto" ? size.auto : label_size == "tiny" ? size.tiny : label_size == "small" ? size.small : label_size == "normal" ? size.normal : label_size == "large" ? size.large : size.huge
position_labels = input.string("Left", "Labels Position", options=["Left", "Right"], group="Style Settings")
TDO = request.security(syminfo.tickerid, 'D', open, lookahead = barmerge.lookahead_on)
PDH = request.security(syminfo.tickerid, 'D', high[1], lookahead = barmerge.lookahead_on)
PDL = request.security(syminfo.tickerid, 'D', low[1], lookahead = barmerge.lookahead_on)
PDC = request.security(syminfo.tickerid, 'D', close[1], lookahead = barmerge.lookahead_on)
Do = request.security(syminfo.tickerid, "D", time, lookahead = barmerge.lookahead_on)
Dc = request.security(syminfo.tickerid, "D", time_close, lookahead = barmerge.lookahead_on)
var lstyle = ""
var l_pos = 0
if line_style == "Dotted"
lstyle := line.style_dotted
else if line_style == "Dashed"
lstyle := line.style_dashed
else if line_style == "Solid"
lstyle := line.style_solid
if position_labels == "Left"
l_pos := Do
else if position_labels == "Right"
l_pos := Dc
float sqCal = 0.00
if Cal == 'Todays Open'
sqCal := math.sqrt(TDO)
else if Cal == 'Previous Days High'
sqCal := math.sqrt(PDH)
else if Cal == 'Previous Days Low'
sqCal := math.sqrt(PDL)
else if Cal == 'Previous Days Close'
sqCal := math.sqrt(PDC)
Bsl=(sqCal-0.0625)*(sqCal-0.0625)
Bat=(sqCal+0.125)*(sqCal+0.125)
Bt1=(sqCal+0.25)*(sqCal+0.25)
Bt2=(sqCal+0.5)*(sqCal+0.5)
Bt3=(sqCal+0.75)*(sqCal+0.75)
Bt4=(sqCal+1)*(sqCal+1)
Bt5=(sqCal+1.25)*(sqCal+1.25)
Bt6=(sqCal+1.5)*(sqCal+1.5)
Bt7=(sqCal+1.75)*(sqCal+1.75)
Bt8=(sqCal+2)*(sqCal+2)
Ssl=(sqCal+0.0625)*(sqCal+0.0625)
Sat=(sqCal-0.125)*(sqCal-0.125)
St1=(sqCal-0.25)*(sqCal-0.25)
St2=(sqCal-0.5)*(sqCal-0.5)
St3=(sqCal-0.75)*(sqCal-0.75)
St4=(sqCal-1)*(sqCal-1)
St5=(sqCal-1.25)*(sqCal-1.25)
St6=(sqCal-1.5)*(sqCal-1.5)
St7=(sqCal-1.75)*(sqCal-1.75)
St8=(sqCal-2)*(sqCal-2)
if ShowBlvl and timeframe.isintraday
pBsl = line.new(Do, Bsl, Dc, Bsl, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pBsl[1])
lpBsl = label.new(l_pos, Bsl, text="SL for Buy Side : " + str.tostring(math.round(Bsl,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpBsl[1])
pBat = line.new(Do, Bat, Dc, Bat, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBat[1])
lpBat = label.new(l_pos, Bat, text="Buy At or Above : " + str.tostring(math.round(Bat,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBat[1])
pBt1 = line.new(Do, Bt1, Dc, Bt1, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt1[1])
lpBt1 = label.new(l_pos, Bt1, text="Target 1 : " + str.tostring(math.round(Bt1,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt1[1])
pBt2 = line.new(Do, Bt2, Dc, Bt2, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt2[1])
lpBt2 = label.new(l_pos, Bt2, text="Target 2 : " + str.tostring(math.round(Bt2,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt2[1])
pBt3 = line.new(Do, Bt3, Dc, Bt3, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt3[1])
lpBt3 = label.new(l_pos, Bt3, text="Target 3 : " + str.tostring(math.round(Bt3,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt3[1])
pBt4 = line.new(Do, Bt4, Dc, Bt4, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt4[1])
lpBt4 = label.new(l_pos, Bt4, text="Target 4 : " + str.tostring(math.round(Bt4,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt4[1])
pBt5 = line.new(Do, Bt5, Dc, Bt5, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt5[1])
lpBt5 = label.new(l_pos, Bt5, text="Target 5 : " + str.tostring(math.round(Bt5,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt5[1])
pBt6 = line.new(Do, Bt6, Dc, Bt6, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt6[1])
lpBt6 = label.new(l_pos, Bt6, text="Target 6 : " + str.tostring(math.round(Bt6,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt6[1])
pBt7 = line.new(Do, Bt7, Dc, Bt7, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt7[1])
lpBt7 = label.new(l_pos, Bt7, text="Target 7 : " + str.tostring(math.round(Bt7,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt7[1])
pBt8 = line.new(Do, Bt8, Dc, Bt8, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pBt8[1])
lpBt8 = label.new(l_pos, Bt8, text="Target 8 : " + str.tostring(math.round(Bt8,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpBt8[1])
if ShowSlvl and timeframe.isintraday
pSsl = line.new(Do, Ssl, Dc, Ssl, xloc.bar_time, color=BlvlColor, style=lstyle, width=2)
line.delete(pSsl[1])
lpSsl = label.new(l_pos, Ssl, text="SL for Sell Side : " + str.tostring(math.round(Ssl,2)), xloc=xloc.bar_time, textcolor=BTxtColor, style=label.style_none, size=l_size)
label.delete(lpSsl[1])
pSat = line.new(Do, Sat, Dc, Sat, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSat[1])
lpSat = label.new(l_pos, Sat, text="Sell At or Below : " + str.tostring(math.round(Sat,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSat[1])
pSt1 = line.new(Do, St1, Dc, St1, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt1[1])
lpSt1 = label.new(l_pos, St1, text="Target 1 : " + str.tostring(math.round(St1,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt1[1])
pSt2 = line.new(Do, St2, Dc, St2, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt2[1])
lpSt2 = label.new(l_pos, St2, text="Target 2 : " + str.tostring(math.round(St2,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt2[1])
pSt3 = line.new(Do, St3, Dc, St3, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt3[1])
lpSt3 = label.new(l_pos, St3, text="Target 3 : " + str.tostring(math.round(St3,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt3[1])
pSt4 = line.new(Do, St4, Dc, St4, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt4[1])
lpSt4 = label.new(l_pos, St4, text="Target 4 : " + str.tostring(math.round(St4,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt4[1])
pSt5 = line.new(Do, St5, Dc, St5, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt5[1])
lpSt5 = label.new(l_pos, St5, text="Target 5 : " + str.tostring(math.round(St5,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt5[1])
pSt6 = line.new(Do, St6, Dc, St6, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt6[1])
lpSt6 = label.new(l_pos, St6, text="Target 6 : " + str.tostring(math.round(St6,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt6[1])
pSt7 = line.new(Do, St7, Dc, St7, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt7[1])
lpSt7 = label.new(l_pos, St7, text="Target 7 : " + str.tostring(math.round(St7,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt7[1])
pSt8 = line.new(Do, St8, Dc, St8, xloc.bar_time, color=SlvlColor, style=lstyle, width=2)
line.delete(pSt8[1])
lpSt8 = label.new(l_pos, St8, text="Target 8 : " + str.tostring(math.round(St8,2)), xloc=xloc.bar_time, textcolor=STxtColor, style=label.style_none, size=l_size)
label.delete(lpSt8[1])
plot(timeframe.isintraday and ShowHBlvl ? Bsl : na, title="SL for Buy Side", color=color.new(color.gray,65), style=plot.style_cross, linewidth=2)
plot(timeframe.isintraday and ShowHBlvl ? Bat : na, title="Buy At or Above", color=color.new(color.green,60), style=plot.style_cross, linewidth=2)
plot(timeframe.isintraday and ShowHBlvl ? Bt1 : na, title="Buy Target 1", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt2 : na, title="Buy Target 2", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt3 : na, title="Buy Target 3", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt4 : na, title="Buy Target 4", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt5 : na, title="Buy Target 5", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt6 : na, title="Buy Target 6", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt7 : na, title="Buy Target 7", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHBlvl ? Bt8 : na, title="Buy Target 8", color=color.new(color.green,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? Ssl : na, title="SL for Sell Side", color=color.new(color.gray,65), style=plot.style_cross, linewidth=2)
plot(timeframe.isintraday and ShowHSlvl ? Sat : na, title="Sell At or Above", color=color.new(color.red,60), style=plot.style_cross, linewidth=2)
plot(timeframe.isintraday and ShowHSlvl ? St1 : na, title="Sell Target 1", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St2 : na, title="Sell Target 2", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St3 : na, title="Sell Target 3", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St4 : na, title="Sell Target 4", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St5 : na, title="Sell Target 5", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St6 : na, title="Sell Target 6", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St7 : na, title="Sell Target 7", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
plot(timeframe.isintraday and ShowHSlvl ? St8 : na, title="Sell Target 8", color=color.new(color.red,65), style=plot.style_circles, linewidth=1)
// ---- Table Settings Start {----//
max = 120 //Maximum Length
min = 10 //Minimum Length
dash_loc = input.session("Top Right","Table Location" ,options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"] ,group='Table Settings')
text_size = input.session('Normal',"Table Size" ,options=["Tiny","Small","Normal","Large"] ,group='Table Settings')
row_col = color.blue
col_col = color.blue
txt_col = color.white
// ---- Table Settings End ----}//
//-------------- Table code Start {-------------------//
//---- Table Position & Size code start {----//
var table_position = dash_loc == 'Top Left' ? position.top_left :
dash_loc == 'Bottom Left' ? position.bottom_left :
dash_loc == 'Middle Right' ? position.middle_right :
dash_loc == 'Bottom Center' ? position.bottom_center :
dash_loc == 'Top Right' ? position.top_right : position.bottom_right
var table_text_size = text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var t = table.new(table_position,14,math.abs(max-min)+2,
frame_color=color.new(#000000,0),
frame_width=1,
border_color=color.new(#000000,0),
border_width=1)
//---- Table Position & Size code end ----}//
//---- Table Column & Rows code start {----//
if ShowTable and (barstate.islast) and timeframe.isintraday
//---- Table Main Column Headers code start {----//
table.cell(t,1,0,'Intraday',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,2,0,'Buy/Sell',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,3,0,'Levels',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,4,0,'using',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,5,0,'Gann Angles',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,6,0,'based on',text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,7,0,str.tostring(Cal),text_color=color.new(#339cff,15),text_size=table_text_size,bgcolor=color.new(#339cff,80))
table.cell(t,1,1,ticker.standard(syminfo.ticker),text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,2,1,'Entry level',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,3,1,'Stop Loss',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,4,1,'Target 1',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,5,1,'Target 2',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,6,1,'Target 3',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,7,1,'Target 4',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,8,1,'Target 5',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,9,1,'Target 6',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,10,1,'Target 7',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,11,1,'Target 8',text_color=color.new(color.blue,40),text_size=table_text_size,bgcolor=color.new(color.blue,80))
//---- Table Main Column Headers code end ----}//
//---- Display Buying data code start {----//
table.cell(t,1,2, 'Buying',text_color=color.new(#78fa04,25),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,2,2, str.tostring(Bat, '#.##'),text_color=color.new(#78fa04,25),text_size=table_text_size, bgcolor=color.new(close >= Bat and close < Bt1 ? #000000 : #78fa04,85))
table.cell(t,3,2, str.tostring(Bsl, '#.##'),text_color=color.new(#fa2f04,35),text_size=table_text_size, bgcolor=color.new(close >= Bsl and close < Bat ? #000000 : #fa2f04,85))
table.cell(t,4,2, str.tostring(Bt1, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt1 and close < Bt2 ? #000000 : #78fa04,85))
table.cell(t,5,2, str.tostring(Bt2, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt2 and close < Bt3 ? #000000 : #78fa04,85))
table.cell(t,6,2, str.tostring(Bt3, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt3 and close < Bt4 ? #000000 : #78fa04,85))
table.cell(t,7,2, str.tostring(Bt4, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt4 and close < Bt5 ? #000000 : #78fa04,85))
table.cell(t,8,2, str.tostring(Bt5, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt5 and close < Bt6 ? #000000 : #78fa04,85))
table.cell(t,9,2, str.tostring(Bt6, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt6 and close < Bt7 ? #000000 : #78fa04,85))
table.cell(t,10,2, str.tostring(Bt7, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt7 and close < Bt8 ? #000000 : #78fa04,85))
table.cell(t,11,2, str.tostring(Bt8, '#.##'),text_color=color.new(#78fa04,45),text_size=table_text_size, bgcolor=color.new(close >= Bt8 ? #000000 : #78fa04,85))
//---- Display Buying data code end ----}//
//---- Display Selling data code start {----//
table.cell(t,1,3, 'Selling',text_color=color.new(#fa2f04,25),text_size=table_text_size,bgcolor=color.new(color.blue,80))
table.cell(t,2,3, str.tostring(Sat, '#.##'),text_color=color.new(#fa2f04,25),text_size=table_text_size, bgcolor=color.new(close <= Sat and close > St1 ? #000000 : #fa2f04,85))
table.cell(t,3,3, str.tostring(Ssl, '#.##'),text_color=color.new(#78fa04,35),text_size=table_text_size, bgcolor=color.new(close <= Ssl and close > Sat ? #000000 : #78fa04,85))
table.cell(t,4,3, str.tostring(St1, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St1 and close > St2 ? #000000 : #fa2f04,85))
table.cell(t,5,3, str.tostring(St2, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St2 and close > St3 ? #000000 : #fa2f04,85))
table.cell(t,6,3, str.tostring(St3, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St3 and close > St4 ? #000000 : #fa2f04,85))
table.cell(t,7,3, str.tostring(St4, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St4 and close > St5 ? #000000 : #fa2f04,85))
table.cell(t,8,3, str.tostring(St5, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St5 and close > St6 ? #000000: #fa2f04,85))
table.cell(t,9,3, str.tostring(St6, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St6 and close > St7 ? #000000 : #fa2f04,85))
table.cell(t,10,3, str.tostring(St7, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St7 and close > St8 ? #000000 : #fa2f04,85))
table.cell(t,11,3, str.tostring(St8, '#.##'),text_color=color.new(#fa2f04,45),text_size=table_text_size, bgcolor=color.new(close <= St8 ? #000000 : #fa2f04,85))
//---- Display Selling data code end ----}//
//---- Table Column & Rows code end ----}//
//-------------- Table code end -------------------}// |
TR High-Low | https://www.tradingview.com/script/B0MRscRO/ | Tommy_Rich | https://www.tradingview.com/u/Tommy_Rich/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Tommy_Rich
//@version=5
indicator("TR High-Low", overlay=true, max_labels_count=500, max_lines_count=500, max_bars_back=500)
import Tommy_Rich/TR_HighLow_Lib/7 as trHL
// ////// //
// //// input //// **********ใคใณใใใ**********
// // //////
// ZigZag
INP_HighLow_Length =input.int (defval =6, minval =2, step =1, title ="High-Low Length", group ="ZigZag", inline ='inline1-1')
INP_HighLow_Extension =input.int (defval =3, minval =0, step =1, title =" Extension", group ="ZigZag", inline ='inline1-1')
INP_HighLow_Difference =input.float (defval =0.3, minval =0, step =0.01, title ="Difference", group ="ZigZag", inline ='inline1-1')
INP_HighLow_Histories =input.int (defval =10, minval =4, step =2, title =" Histories", group ="ZigZag", inline ='inline1-1')
INP_HighLow_Color_1 =input (defval =color.blue, title ="Color1", group ="ZigZag", inline ='inline1-2')
INP_HighLow_Width_1 =input.int (defval =2, minval =1, step =1, title =" Width1", group ="ZigZag", inline ='inline1-2')
INP_HighLow_Color_2 =input (defval =color.red, title =" Color2", group ="ZigZag", inline ='inline1-2')
INP_HighLow_Width_2 =input.int (defval =2, minval =1, step =1, title =" Width2", group ="ZigZag", inline ='inline1-2')
INP_HighLow_ShowLabel =input.bool (defval =true, title ="Show Label", group ="ZigZag", inline ='inline1-3')
INP_HighLow_ShowZigZag =input.bool (defval =true, title ="Show ZigZag", group ="ZigZag", inline ='inline1-3')
INP_HighLow_ShowHiLoBar =input.bool (defval =true, title ="Show Hi-Lo Bar", group ="ZigZag", inline ='inline1-4')
INP_HighLow_BarWidth =input.int (defval =1, minval =1, step =1, title =" Bar Width", group ="ZigZag", inline ='inline1-4')
INP_HighLow_LabelSize =input.string(
defval =size.normal,
options =[size.auto,size.huge,size.large,size.normal,size.small,size.tiny],
title ="Label Size",
group ="ZigZag",
inline ="inline1-5")
// Trend Line
INP_Trend_ShowLine =input.bool (defval =true, title ="Show Trend Line", group ="Trend Line", inline ='inline2-1')
INP_Trend_MultiLine =input.bool (defval =false, title =" Multi Line", group ="Trend Line", inline ='inline2-1')
INP_Trend_ColorMode =input.int (
defval =1,
options =[0, 1],
title ="Color Mode 0:Nomal / 1:Gradiation",
group ="Trend Line",
inline ='inline2-2')
INP_Trend_Color1_1 =input (defval =color.rgb(252, 203, 205), title ="Trend Line Color1_1", group ="Trend Line Color", inline ='inline2-3')
INP_Trend_Color1_2 =input (defval =color.rgb(255, 0, 0), title =" Color1_2", group ="Trend Line Color", inline ='inline2-3')
INP_Trend_Color2_1 =input (defval =color.rgb(187, 217, 251), title =" Color2_1", group ="Trend Line Color", inline ='inline2-3')
INP_Trend_Color2_2 =input (defval =color.rgb( 0, 0, 255), title =" Color2_2", group ="Trend Line Color", inline ='inline2-3')
INP_Trend_StartWidth =input.float (defval =0.02, minval =0, step =0.01, title ="Start Width", group ="Trend Line Width", inline ='inline2-4')
INP_Trend_EndWidth =input.float (defval =0.02, minval =0, step =0.01, title =" End Width", group ="Trend Line Width", inline ='inline2-4')
INP_Trend_IncreWidth =input.float (defval =-0.02, step =0.01, title =" Increment Width", group ="Trend Line Width", inline ='inline2-4')
INP_Trend_StartTrans =input.int (defval =60, step =1, title ="Start Trans", group ="Trend Line Trans", inline ='inline2-5')
INP_Trend_EndTrans =input.int (defval =60, step =1, title =" End Trans", group ="Trend Line Trans", inline ='inline2-5')
INP_Trend_IncreTrans =input.int (defval =-2, step =1, title =" Increment Trans", group ="Trend Line Trans", inline ='inline2-5')
// Fibonacci
INP_Fib_Show =input.string(
defval="double",
options=["double", "single"],
title="Fibonacci type",
group="Fibonacci",
inline='inline3-1')
INP_Fib1_Index =input.int (defval =1, step =1, title ="Index", group ="Fibonacci 1", inline ='inline3-2')
INP_Fib1_FrontMargin =input.int (defval =0, step =1, title ="Margin Front", group ="Fibonacci 1", inline ='inline3-2')
INP_Fib1_BackMargin =input.int (defval =10, step =1, title ="Rear", group ="Fibonacci 1", inline ='inline3-2')
INP_Fib1_Transparent =input.int (defval =80, step =1, title ="Transparent", group ="Fibonacci 1", inline ='inline3-3')
INP_Fib1_TextColor =input (defval =color.black, title ="Color1", group ="Fibonacci 1", inline ='inline3-3')
INP_Fib1_TextMargin =input.int (defval =5, step =1, title ="Text Margin", group ="Fibonacci 1", inline ='inline3-3')
INP_Fib1_LabelSize =input.string(
defval =size.small,
options =[size.auto,size.huge,size.large,size.normal,size.small,size.tiny],
title ="Label Size",
group ="Fibonacci 1",
inline ="inline3-4")
INP_Fib1_Title =input.string(defval ="Fibonacci 1", title ="Title", group ="Fibonacci 1", inline ='inline3-4')
INP_Fib1_TitleMargin =input.float (defval =0.25, title ="Title Margin", group ="Fibonacci 1", inline ='inline3-4')
INP_Fib1_ChangeColor =input.bool (defval =true, title ="Change Trend Color1", group ="Fibonacci 1", inline ='inline3-5')
INP_Fib1_TrendColor =input (defval =color.purple, title ="Trend Color1", group ="Fibonacci 1", inline ='inline3-5')
INP_Fib1_TrendLineWidth =input.int (defval =4, step =1, title ="Trend Line Width1", group ="Fibonacci 1", inline ='inline3-5')
INP_Fib2_Index =input.int (defval =2, step =1, title ="Index", group ="Fibonacci 2", inline ='inline3-6')
INP_Fib2_FrontMargin =input.int (defval =15, step =1, title ="Margin Front", group ="Fibonacci 2", inline ='inline3-6')
INP_Fib2_BackMargin =input.int (defval =25, step =1, title ="Rear", group ="Fibonacci 2", inline ='inline3-6')
INP_Fib2_Transparent =input.int (defval =80, step =1, title ="Transparent", group ="Fibonacci 2", inline ='inline3-7')
INP_Fib2_TextColor =input (defval =color.black, title ="Color2", group ="Fibonacci 2", inline ='inline3-7')
INP_Fib2_TextMargin =input.int (defval =5, step =1, title ="Text Margin", group ="Fibonacci 2", inline ='inline3-7')
INP_Fib2_LabelSize =input.string(
defval =size.small,
options =[size.auto,size.huge,size.large,size.normal,size.small,size.tiny],
title ="Label Size",
group ="Fibonacci 2",
inline ="inline3-8")
INP_Fib2_Title =input.string(defval ="Fibonacci 2", title ="Title", group ="Fibonacci 2", inline ='inline3-8')
INP_Fib2_TitleMargin =input.float (defval =0.25, title ="Title Margin", group ="Fibonacci 2", inline ='inline3-4')
INP_Fib2_ChangeColor =input.bool (defval =true, title ="Change Trend Color2", group ="Fibonacci 2", inline ='inline3-9')
INP_Fib2_TrendColor =input (defval =color.orange, title ="Trend Color2", group ="Fibonacci 2", inline ='inline3-9')
INP_Fib2_TrendLineWidth =input.int (defval =4, step =1, title ="Trend Line Width2", group ="Fibonacci 2", inline ='inline3-9')
INP_Fib_m1000 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m1000_Value =input.float (defval =-1.000, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m0764 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m0764_Value =input.float (defval =-0.764, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m0618 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m0618_Value =input.float (defval =-0.618, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-1')
INP_Fib_m0500 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_m0500_Value =input.float (defval =-0.500, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_m0382 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_m0382_Value =input.float (defval =-0.382, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_m0236 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_m0236_Value =input.float (defval =-0.236, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-2')
INP_Fib_0000 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0000_Value =input.float (defval =0.000, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0236 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0236_Value =input.float (defval =0.236, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0382 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0382_Value =input.float (defval =0.382, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-3')
INP_Fib_0500 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_0500_Value =input.float (defval =0.500, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_0618 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_0618_Value =input.float (defval =0.618, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_0764 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_0764_Value =input.float (defval =0.764, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-4')
INP_Fib_1000 =input.bool (defval =true, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1000_Value =input.float (defval =1.000, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1236 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1236_Value =input.float (defval =1.236, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1382 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1382_Value =input.float (defval =1.382, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-5')
INP_Fib_1500 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_1500_Value =input.float (defval =1.500, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_1618 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_1618_Value =input.float (defval =1.618, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_1764 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_1764_Value =input.float (defval =1.764, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-6')
INP_Fib_2000 =input.bool (defval =false, title ="", group ="Fibonacci Level", inline ='inline4-7')
INP_Fib_2000_Value =input.float (defval =2.000, step =0.01, title ="", group ="Fibonacci Level", inline ='inline4-7')
// Table
INP_Tbl_show_1 =input.bool (defval =false, title="Show Table 1", group ="Table", inline ='inline5-1')
INP_Tbl_position_1 =input.string(
defval="bottom_left",
options=["top_left", "top_center", "top_right", "middle_left", "middle_center", "middle_right", "bottom_left", "bottom_center", "bottom_right"],
title="Display position",
group="Table",
inline='inline5-1')
INP_Tbl_show_2 =input.bool (defval=false, title="Show Table 2", group ="Table", inline ='inline5-2')
INP_Tbl_position_2 =input.string(
defval="top_right",
options=["top_left", "top_center", "top_right", "middle_left", "middle_center", "middle_right", "bottom_left", "bottom_center", "bottom_right"],
title="Display position",
group="Table",
inline='inline5-2')
////// //
//// global variable //// **********ใฐใญใผใใซๅคๆฐ**********
// //////
var float[] a_PHiLo =array.new_float (INP_HighLow_Histories, 0.0) // Array Price
var int[] a_IHiLo =array.new_int (INP_HighLow_Histories, bar_index) // Array Index
var int[] a_FHiLo =array.new_int (INP_HighLow_Histories, 0) // Array Flag 0:ๅๅใ1:Highใ2:Low
var float[] a_DHiLo =array.new_float (INP_HighLow_Histories, 0.0) // Array Difference
var float[] a_PHigh =array.new_float (INP_HighLow_Histories / 2, 0.) // Array High Price
var float[] a_PLow =array.new_float (INP_HighLow_Histories / 2, 0.) // Array Low Price
var int[] a_IHigh =array.new_int (INP_HighLow_Histories / 2, 0) // Array High Index
var int[] a_ILow =array.new_int (INP_HighLow_Histories / 2, 0) // Array Low Index
////// //
//// function //// **********้ขๆฐ**********
// //////
SetFibonacci() =>
float[] _Fibonacci =array.new_float()
if INP_Fib_0000
array.push(_Fibonacci, INP_Fib_0000_Value)
if INP_Fib_0236
array.push(_Fibonacci, INP_Fib_0236_Value)
if INP_Fib_0382
array.push(_Fibonacci, INP_Fib_0382_Value)
if INP_Fib_0500
array.push(_Fibonacci, INP_Fib_0500_Value)
if INP_Fib_0618
array.push(_Fibonacci, INP_Fib_0618_Value)
if INP_Fib_0764
array.push(_Fibonacci, INP_Fib_0764_Value)
if INP_Fib_1000
array.push(_Fibonacci, INP_Fib_1000_Value)
if INP_Fib_1236
array.push(_Fibonacci, INP_Fib_1236_Value)
if INP_Fib_1382
array.push(_Fibonacci, INP_Fib_1382_Value)
if INP_Fib_1500
array.push(_Fibonacci, INP_Fib_1500_Value)
if INP_Fib_1618
array.push(_Fibonacci, INP_Fib_1618_Value)
if INP_Fib_1764
array.push(_Fibonacci, INP_Fib_1764_Value)
if INP_Fib_2000
array.push(_Fibonacci, INP_Fib_2000_Value)
if INP_Fib_m0236
array.push(_Fibonacci, INP_Fib_m0236_Value)
if INP_Fib_m0382
array.push(_Fibonacci, INP_Fib_m0382_Value)
if INP_Fib_m0500
array.push(_Fibonacci, INP_Fib_m0500_Value)
if INP_Fib_m0618
array.push(_Fibonacci, INP_Fib_m0618_Value)
if INP_Fib_m0764
array.push(_Fibonacci, INP_Fib_m0764_Value)
if INP_Fib_m1000
array.push(_Fibonacci, INP_Fib_m1000_Value)
_Fibonacci
var float[] a_Fibonacci =SetFibonacci()
// Delete Object
trHL.DeleteLine()
trHL.DeleteLabel()
trHL.High_Low(
high, low,
a_PHiLo, a_IHiLo, a_FHiLo, a_DHiLo, a_PHigh, a_PLow, a_IHigh, a_ILow, a_Fibonacci,
INP_HighLow_Length, INP_HighLow_Extension, INP_HighLow_Difference, INP_HighLow_Histories,
INP_HighLow_ShowZigZag,
INP_HighLow_Color_1, INP_HighLow_Width_1,
INP_HighLow_Color_2, INP_HighLow_Width_2,
INP_HighLow_ShowLabel, INP_HighLow_LabelSize, INP_HighLow_ShowHiLoBar, INP_HighLow_BarWidth,
INP_Trend_ShowLine, INP_Trend_MultiLine,
INP_Trend_StartWidth, INP_Trend_EndWidth, INP_Trend_IncreWidth,
INP_Trend_StartTrans, INP_Trend_EndTrans, INP_Trend_IncreTrans, INP_Trend_ColorMode,
INP_Trend_Color1_1, INP_Trend_Color1_2, INP_Trend_Color2_1, INP_Trend_Color2_2,
INP_Fib_Show,
INP_Fib1_Index, INP_Fib1_FrontMargin, INP_Fib1_BackMargin, INP_Fib1_Transparent, INP_Fib1_TextColor, INP_Fib1_TextMargin, INP_Fib1_LabelSize,
INP_Fib1_Title, INP_Fib1_TitleMargin, INP_Fib1_ChangeColor, INP_Fib1_TrendColor, INP_Fib1_TrendLineWidth,
INP_Fib2_Index, INP_Fib2_FrontMargin, INP_Fib2_BackMargin, INP_Fib2_Transparent, INP_Fib2_TextColor, INP_Fib2_TextMargin, INP_Fib2_LabelSize,
INP_Fib2_Title, INP_Fib2_TitleMargin, INP_Fib2_ChangeColor, INP_Fib2_TrendColor, INP_Fib2_TrendLineWidth,
INP_Tbl_show_1, INP_Tbl_position_1, INP_Tbl_show_2, INP_Tbl_position_2) |
PharshK RSI and Zigzag with H/L | https://www.tradingview.com/script/rHx3fnYF-PharshK-RSI-and-Zigzag-with-H-L/ | pharshk | https://www.tradingview.com/u/pharshk/ | 156 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ ralagh
//@version=4
study("PharshK RSI and Zigzag with H/L", overlay=true)
lb = input(5, title="Left Bars", minval = 1)
rb = input(5, title="Right Bars", minval = 1)
showsupres = input(true, title="Support/Resistance", inline = "srcol")
supcol = input(color.lime, title ="", inline = "srcol")
rescol = input(color.red, title ="", inline = "srcol")
srlinestyle = input(line.style_dotted, title = "Line Style/Width", options = [line.style_solid, line.style_dashed, line.style_dotted], inline ="style")
srlinewidth = input(3, title = "", minval = 1, maxval = 5, inline ="style")
changebarcol = input(true, title="Change Bar Color", inline = "bcol")
bcolup = input(color.blue, title ="", inline = "bcol")
bcoldn = input(color.black, title ="", inline = "bcol")
ph = pivothigh(lb, rb)
pl = pivotlow(lb, rb)
hl = iff(ph, 1, iff(pl, -1, na)) // Trend direction
zz = iff(ph, ph, iff(pl, pl, na)) // similar to zigzag but may have multiple highs/lows
zz :=iff(pl and hl == -1 and valuewhen(hl, hl, 1) == -1 and pl > valuewhen(zz, zz, 1), na, zz)
zz :=iff(ph and hl == 1 and valuewhen(hl, hl, 1) == 1 and ph < valuewhen(zz, zz, 1), na, zz)
hl := iff(hl==-1 and valuewhen(hl, hl, 1)==1 and zz > valuewhen(zz, zz, 1), na, hl)
hl := iff(hl==1 and valuewhen(hl, hl, 1)==-1 and zz < valuewhen(zz, zz, 1), na, hl)
zz := iff(na(hl), na, zz)
findprevious()=> // finds previous three points (b, c, d, e)
ehl = iff(hl==1, -1, 1)
loc1 = 0.0, loc2 = 0.0, loc3 = 0.0, loc4 = 0.0
xx = 0
for x=1 to 1000
if hl[x]==ehl and not na(zz[x])
loc1 := zz[x]
xx := x + 1
break
ehl := hl
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc2 := zz[x]
xx := x + 1
break
ehl := iff(hl==1, -1, 1)
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc3 := zz[x]
xx := x + 1
break
ehl := hl
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc4 := zz[x]
break
[loc1, loc2, loc3, loc4]
float f = na, float g = na, float h = na, float j = na, float k = na
if not na(hl)
[loc1, loc2, loc3, loc4] = findprevious()
f := zz
g := loc1
h := loc2
j := loc3
k := loc4
_hh = zz and (f > g and f > h and h > g and h > j)
_ll = zz and (f < g and f < h and h < g and h < j)
_hl = zz and ((f >= h and (g > h and g > j and j > h and j > k)) or (f < g and f > h and g < j))
_lh = zz and ((f <= h and (g < h and g < j and j < h and j < k)) or (f > g and f < h and g > j))
plotshape(_hl, text="HL", title="Higher Low", style=shape.labelup, color=color.lime, textcolor=color.black, location=location.belowbar, offset = -rb)
plotshape(_hh, text="HH", title="Higher High", style=shape.labeldown, color=color.lime, textcolor=color.black, location=location.abovebar, offset = -rb)
plotshape(_ll, text="LL", title="Lower Low", style=shape.labelup, color=color.red, textcolor=color.white, location=location.belowbar, offset = -rb)
plotshape(_lh, text="LH", title="Lower High", style=shape.labeldown, color=color.red, textcolor=color.white, location=location.abovebar, offset = -rb)
float res = na, float sup = na
res := iff(_lh, zz, res[1])
sup := iff(_hl, zz, sup[1])
int trend = na
trend := iff(close > res, 1, iff(close < sup, -1, nz(trend[1])))
res := iff((trend == 1 and _hh) or (trend == -1 and _lh), zz, res)
sup := iff((trend == 1 and _hl) or (trend == -1 and _ll), zz, sup)
rechange = res != res[1]
suchange = sup != sup[1]
var line resline = na
var line supline = na
if showsupres
if rechange
line.set_x2(resline, bar_index)
line.set_extend(resline, extend = extend.none)
resline := line.new(x1 = bar_index - rb, y1 = res, x2 = bar_index, y2 = res, color = rescol, extend = extend.right, style = srlinestyle, width = srlinewidth)
if suchange
line.set_x2(supline, bar_index)
line.set_extend(supline, extend = extend.none)
supline := line.new(x1 = bar_index - rb, y1 = sup, x2 = bar_index, y2 = sup, color = supcol, extend = extend.right, style = srlinestyle, width = srlinewidth)
barcolor(color = iff(changebarcol, iff(trend == 1, bcolup, bcoldn), na))
alert_strings = array.new_string(4)
array.set(alert_strings, 0, "")
array.set(alert_strings, 1, "")
array.set(alert_strings, 2, "")
array.set(alert_strings, 3, "")
table_row_count = array.new_int(3)
array.set(table_row_count, 0, 1)
array.set(table_row_count, 1, 1)
array.set(table_row_count, 2, 1)
var UpTabl = table.new(position = position.top_center, columns = 3, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2)
var DnTabl = table.new(position = position.bottom_center, columns = 3, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2)
//table.cell(table_id = UpTabl, column = 1, row = 0, text = "Upper Channel Break")
//table.cell(table_id = DnTabl, column = 1, row = 0, text = "Lower Channel Break")
//table.cell(table_id = UpTabl, column = 2, row = 0, text = "โฒโฒ")
//table.cell(table_id = DnTabl, column = 2, row = 0, text = "โผโผ")
//table.cell(table_id = UpTabl, column = 0, row = 1, text = "Ticker")
//table.cell(table_id = UpTabl, column = 1, row = 1, text = "Close")
//table.cell(table_id = UpTabl, column = 2, row = 1, text = "High")
//table.cell(table_id = DnTabl, column = 0, row = 1, text = "Ticker")
//table.cell(table_id = DnTabl, column = 1, row = 1, text = "Close")
//table.cell(table_id = DnTabl, column = 2, row = 1, text = "Low")
devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
depthTooltip = "The minimum number of bars that will be taken into account when calculating the indicator."
// pivots threshold
threshold_multiplier = input(title="Deviation", type=input.float, defval=3, minval=0, tooltip=devTooltip)
dev_threshold = atr(10) / close * 100 * threshold_multiplier
depth = input(title="Depth", type=input.integer, defval=10, minval=1, tooltip=depthTooltip)
reverse = input(false, "Reverse")
// Zig Zag
ZigZag = input(true, "Zig Zagโโโ" , inline = "ZZ", group = "Zig Zag Settings")
zzColor = input(color.orange, "" , inline = "ZZ", group = "Zig Zag Settings")
zzWidth = input(1 , "", minval = 1 , inline = "ZZ", group = "Zig Zag Settings")
zzStyle = input("Dashed", "", options = ["Dashed", "Dotted", "Solid"] , inline = "ZZ", group = "Zig Zag Settings")
var extendLeft = input(false, "Extend Leftโโโโ|โโโโExtend Right", inline = "Extend Lines")
var extendRight = input(true, "", inline = "Extend Lines")
var extending = extend.none
if extendLeft and extendRight
extending := extend.both
if extendLeft and not extendRight
extending := extend.left
if not extendLeft and extendRight
extending := extend.right
prices = input(true, "Show Prices")
levels = input(true, "Show Levels", inline = "Levels")
levelsFormat = input("Values", "", options = ["Values", "Percent"], inline = "Levels")
labelsPosition = input("Left", "Labels Position", options = ["Left", "Right"])
// ---------------------------------------------------------------------------------------- //
// Fibonacci
var line lineLast = na
var int iLast = 0
var int iPrev = 0
var float pLast = 0
var isHighLast = false // otherwise the last pivot is a low pivot
var iPrevPivotRef = 0
var pPrevPivotRef = 0.
var iLastPivotRef = 0
var pLastPivotRef = 0.
pivots(src, length, isHigh) =>
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2
if isHigh and src[i] > c
ok := false
if not isHigh and src[i] < c
ok := false
if ok
[bar_index[length], c]
else
[int(na), float(na)]
[iH, pH] = pivots(high, depth / 2, true )
[iL, pL] = pivots(low , depth / 2, false)
calc_dev(base_price, price) =>
100 * (price - base_price) / price
pivotFound(dev, isHigh, index, price) =>
if isHighLast == isHigh and not na(lineLast)
// same direction
if isHighLast ? price > pLast : price < pLast
line.set_xy2(lineLast, index, price)
[lineLast, isHighLast]
else
[line(na), bool(na)]
else // reverse the direction (or create the very first line)
if abs(dev) > dev_threshold
// price move is significant
// ---------------------------------------------------------------------------------------- //
[zzCol, zzWid, zzSty] = if not ZigZag
[na, 1, line.style_dashed]
else
[zzColor, zzWidth, zzStyle == "Solid" ? line.style_solid : zzStyle == "Dotted" ? line.style_dotted : line.style_dashed]
// ---------------------------------------------------------------------------------------- //
id = line.new(iLast, pLast, index, price, color=zzCol, width=zzWid, style=zzSty)
[id, isHigh]
else
[line(na), bool(na)]
// Fibonacci, Zig Zag
if not na(iH)
dev = calc_dev(pLast, pH)
[id, isHigh] = pivotFound(dev, true, iH, pH)
if not na(id)
if id != lineLast
// ---------------------------------------------------------------------------------------- //
iPrevPivotRef := line.get_x1(lineLast)
pPrevPivotRef := line.get_y1(lineLast)
iLastPivotRef := line.get_x2(lineLast)
pLastPivotRef := line.get_y2(lineLast)
if not ZigZag
// ---------------------------------------------------------------------------------------- //
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iH
pLast := pH
else
if not na(iL)
dev = calc_dev(pLast, pL)
[id, isHigh] = pivotFound(dev, false, iL, pL)
if not na(id)
if id != lineLast
// ---------------------------------------------------------------------------------------- //
iPrevPivotRef := line.get_x1(lineLast)
pPrevPivotRef := line.get_y1(lineLast)
iLastPivotRef := line.get_x2(lineLast)
pLastPivotRef := line.get_y2(lineLast)
if not ZigZag
// ---------------------------------------------------------------------------------------- //
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iL
pLast := pL
// Zig Zag
_draw_line(price, col) =>
var id = line.new(iLast, price, bar_index, price, color=col, width=1, extend=extending)
if not na(lineLast)
line.set_xy1(id, line.get_x1(lineLast), price)
line.set_xy2(id, line.get_x2(lineLast), price)
_draw_label(price, txt, txtColor) =>
x = labelsPosition == "Left" ? line.get_x1(lineLast) : not extendRight ? line.get_x2(lineLast) : bar_index
labelStyle = labelsPosition == "Left" ? label.style_label_right : label.style_label_left
align = labelsPosition == "Left" ? text.align_right : text.align_left
labelsAlignStrLeft = txt + '\n โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \n'
labelsAlignStrRight = ' ' + txt + '\n โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \n'
labelsAlignStr = labelsPosition == "Left" ? labelsAlignStrLeft : labelsAlignStrRight
var id = label.new(x=x, y=price, text=labelsAlignStr, textcolor=txtColor, style=labelStyle, textalign=align, color=#00000000)
label.set_xy(id, x, price)
label.set_text(id, labelsAlignStr)
label.set_textcolor(id, txtColor)
_wrap(txt) =>
"(" + tostring(txt, "#.##") + ")"
_label_txt(level, price) =>
l = levelsFormat == "Values" ? tostring(level) : tostring(level * 100) + "%"
(levels ? l : "") + (prices ? _wrap(price) : "")
_crossing_level(sr, r) =>
(r > sr and r < sr[1]) or (r < sr and r > sr[1])
startPrice = reverse ? line.get_y1(lineLast) : pLast
endPrice = reverse ? pLast : line.get_y1(lineLast)
iHL = startPrice > endPrice
diff = (iHL ? -1 : 1) * abs(startPrice - endPrice)
processLevel(show, value, colorL) =>
float m = value
r = startPrice + diff * m
if show
_draw_line(r, colorL)
_draw_label(r, _label_txt(m, r), colorL)
//if _crossing_level(close, r)
//alert("Autofib: " + syminfo.ticker + " crossing level " + tostring(value))
show_0 = input(true, "", inline = "Level0")
value_0 = input(0, "", inline = "Level0")
color_0 = input(#787b86, "", inline = "Level0")
processLevel(show_0, value_0, color_0)
show_0_5 = input(true, "", inline = "Level1")
value_0_5 = input(0.5, "", inline = "Level1")
color_0_5 = input(#4caf50, "", inline = "Level1")
processLevel(show_0_5, value_0_5, color_0_5)
show_0_618 = input(true, "", inline = "Level2")
value_0_618 = input(0.618, "", inline = "Level2")
color_0_618 = input(#009688, "", inline = "Level2")
processLevel(show_0_618, value_0_618, color_0_618)
show_1 = input(true, "", inline = "Level3")
value_1 = input(1, "", inline = "Level3")
color_1 = input(#787b86, "", inline = "Level3")
processLevel(show_1, value_1, color_1)
show_1_618 = input(true, "", inline = "Level5")
value_1_618 = input(1.618, "", inline = "Level5")
color_1_618 = input(#2196f3, "", inline = "Level5")
processLevel(show_1_618, value_1_618, color_1_618)
upperMult = input(2, "Linear Regression : Upper Deviation")
lowerMult = input(-2, "Linear Regression : Lower Deviation")
useUpperDev = input(true, "Linear Regression : Use Upper Deviation")
useLowerDev = input(true, "Linear Regression : Use Lower Deviation")
showPearson = input(true, "Linear Regression : Show Pearson`s R")
extendLines = input(false, "Linear Regression : Extend Lines")
len = input(100, "Linear Regression : Count")
src = input(close, "Linear Regression : Source")
// Linear Regression - build-in
extend = extendLines ? extend.right : extend.none
calcSlope(src, len) =>
max_bars_back(src, 300)
if not barstate.islast or len <= 1
[float(na), float(na), float(na)]
else
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for i = 0 to len - 1
val = src[i]
per = i + 1.0
sumX := sumX + per
sumY := sumY + val
sumXSqr := sumXSqr + per * per
sumXY := sumXY + val * per
slope = (len * sumXY - sumX * sumY) / (len * sumXSqr - sumX * sumX)
average = sumY / len
intercept = average - slope * sumX / len + slope
[slope, average, intercept]
[slp, a, i] = calcSlope(src, len)
startPriceL = i + slp * (len - 1)
endPriceL = i
var line baseLine = na
if na(baseLine) and not na(startPriceL)
baseLine := line.new(bar_index - len + 1, startPriceL, bar_index, endPriceL, width=1, extend=extend, color=color.red)
else
line.set_xy1(baseLine, bar_index - len + 1, startPriceL)
line.set_xy2(baseLine, bar_index, endPriceL)
na
calcDev(src, len, slope, average, intercept) =>
upDev = 0.0
dnDev = 0.0
stdDevAcc = 0.0
dsxx = 0.0
dsyy = 0.0
dsxy = 0.0
periods = len - 1
daY = intercept + (slope * periods) / 2
val = intercept
for i = 0 to periods
price = high[i] - val
if (price > upDev)
upDev := price
price := val - low[i]
if (price > dnDev)
dnDev := price
price := src[i]
dxt = price - average
dyt = val - daY
price := price - val
stdDevAcc := stdDevAcc + price * price
dsxx := dsxx + dxt * dxt
dsyy := dsyy + dyt * dyt
dsxy := dsxy + dxt * dyt
val := val + slope
stdDev = sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / sqrt(dsxx * dsyy)
[stdDev, pearsonR, upDev, dnDev]
[stdDev, pearsonR, upDev, dnDev] = calcDev(src, len, slp, a, i)
upperStartPrice = startPriceL + (useUpperDev ? upperMult * stdDev : upDev)
upperEndPrice = endPriceL + (useUpperDev ? upperMult * stdDev : upDev)
var line upper = na
lowerStartPrice = startPriceL + (useLowerDev ? lowerMult * stdDev : -dnDev)
lowerEndPrice = endPriceL + (useLowerDev ? lowerMult * stdDev : -dnDev)
var line lower = na
if na(upper) and not na(upperStartPrice)
upper := line.new(bar_index - len + 1, upperStartPrice, bar_index, upperEndPrice, width=1, extend=extend, color=#0000ff)
else
line.set_xy1(upper, bar_index - len + 1, upperStartPrice)
line.set_xy2(upper, bar_index, upperEndPrice)
na
if na(lower) and not na(lowerStartPrice)
lower := line.new(bar_index - len + 1, lowerStartPrice, bar_index, lowerEndPrice, width=1, extend=extend, color=#0000ff)
else
line.set_xy1(lower, bar_index - len + 1, lowerStartPrice)
line.set_xy2(lower, bar_index, lowerEndPrice)
na
// Pearson`s R
var label r = na
transparent = color.new(color.white, 100)
label.delete(r[1])
if showPearson and not na(pearsonR)
r := label.new(bar_index - len + 1, lowerStartPrice, tostring(pearsonR, "#.########"), color=transparent, textcolor=#0000ff, size=size.normal, style=label.style_labelup)
plot(round(pearsonR*1000)/1000, display=display.none)
//(cl_p > (ep_mp + st_dv * 2))//
//(cl_p < (ep_mp - st_dv * 2)//
f_LregBrk(_ticker)=>
[cl_p, ep_mp, st_dv, sp_mp, val_hi, val_lo, sr_01] = security(_ticker, timeframe.period, [close, endPriceL, stdDev, startPriceL, high, low, rsi(close, 14)], lookahead = barmerge.lookahead_on)
_msg = _ticker + "~CLS-" + tostring(round(cl_p * 100) / 100)
if (sp_mp - ep_mp) > 0 and crossover(cl_p, (ep_mp + st_dv * 2))
_msg := _msg + "~>" + " Uppper Channel Break โฒโฒ"
array.set(alert_strings, 0, array.get(alert_strings, 0) + "\n" + _msg)
array.set(table_row_count, 0, array.get(table_row_count, 0) + 1)
if barstate.islast
table.cell(table_id = UpTabl, column = 0, row = array.get(table_row_count, 0), text = _ticker)
table.cell(table_id = UpTabl, column = 1, row = array.get(table_row_count, 0), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(0, 200, 100))
table.cell(table_id = UpTabl, column = 2, row = array.get(table_row_count, 0), text = tostring(round(val_hi * 100) / 100), bgcolor=color.rgb(0, 200, 100))
else if (sp_mp - ep_mp) < 0 and crossunder(cl_p, (ep_mp - st_dv * 2))
_msg := _msg + "~>" + " Lower Channel Break โผโผ"
array.set(alert_strings, 1, array.get(alert_strings, 1) + "\n" + _msg)
array.set(table_row_count, 1, array.get(table_row_count, 1) + 1)
if barstate.islast
table.cell(table_id = DnTabl, column = 0, row = array.get(table_row_count, 1), text = _ticker)
table.cell(table_id = DnTabl, column = 1, row = array.get(table_row_count, 1), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(255, 0, 0))
table.cell(table_id = DnTabl, column = 2, row = array.get(table_row_count, 1), text = tostring(round(val_lo * 100) / 100), bgcolor=color.rgb(255, 0, 0))
var RsStoTabl = table.new(position = position.bottom_left, columns = 3, rows = 20, bgcolor = color.rgb(200, 230, 255), border_width = 2, frame_color= color.black, frame_width = 2)
if barstate.islast
table.cell(table_id = RsStoTabl, column = 0, row = 0, text = "Ticker")
table.cell(table_id = RsStoTabl, column = 1, row = 0, text = "RSI ~")
if sr_01 > 65
_msg := _msg + "~>" + "RSI - OB โฒ " + tostring(round(sr_01 * 10) / 10)
array.set(alert_strings, 2, array.get(alert_strings, 2) + "\n" + _msg)
array.set(table_row_count, 2, array.get(table_row_count, 2) + 1)
table.cell(table_id = RsStoTabl, column = 0, row = array.get(table_row_count, 2), text = _ticker)
table.cell(table_id = RsStoTabl, column = 1, row = array.get(table_row_count, 2), text = tostring(int(sr_01)), bgcolor=color.from_gradient(sr_01, 40, 60, color.rgb(255, 70, 70), color.rgb(0, 200, 100)))
else if sr_01 < 35
_msg := _msg + "~>" + "RSI - OS โผ " + tostring(round(sr_01 * 10) / 10)
array.set(alert_strings, 3, array.get(alert_strings, 3) + "\n" + _msg)
array.set(table_row_count, 2, array.get(table_row_count, 2) + 1)
table.cell(table_id = RsStoTabl, column = 0, row = array.get(table_row_count, 2), text = _ticker)
table.cell(table_id = RsStoTabl, column = 1, row = array.get(table_row_count, 2), text = tostring(int(sr_01)), bgcolor=color.from_gradient(sr_01, 40, 60, color.rgb(255, 70, 70), color.rgb(0, 200, 100)))
f_LregBrk(syminfo.tickerid)
f_LregBrk(input('DJI', title=input.symbol))
f_LregBrk(input('IXIC', title=input.symbol))
f_LregBrk(input('SPX', title=input.symbol))
f_LregBrk(input('RUT', title=input.symbol))
f_LregBrk(input('AAPL', title=input.symbol))
f_LregBrk(input('AMZN', title=input.symbol))
f_LregBrk(input('FB', title=input.symbol))
f_LregBrk(input('GOOG', title=input.symbol))
f_LregBrk(input('NFLX', title=input.symbol))
f_LregBrk(input('MSFT', title=input.symbol))
f_LregBrk(input('NVDA', title=input.symbol))
f_LregBrk(input('FDX', title=input.symbol))
f_LregBrk(input('GLD', title=input.symbol))
if array.get(alert_strings, 0) != ""
alert(array.get(alert_strings, 0), alert.freq_once_per_bar)
if array.get(alert_strings, 1) != ""
alert(array.get(alert_strings, 1), alert.freq_once_per_bar)
//if array.get(alert_strings, 2) != ""
//alert(array.get(alert_strings, 2), alert.freq_once_per_bar)
//if array.get(alert_strings, 3) != ""
//alert(array.get(alert_strings, 3), alert.freq_once_per_bar)
|
PharshK RSI and Zigzag with H/L | https://www.tradingview.com/script/4VTP6qVh-PharshK-RSI-and-Zigzag-with-H-L/ | pharshk | https://www.tradingview.com/u/pharshk/ | 75 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ ralagh
//@version=4
study("PharshK RSI and Zigzag with H/L", overlay=true)
lb = input(5, title="Left Bars", minval = 1)
rb = input(5, title="Right Bars", minval = 1)
showsupres = input(true, title="Support/Resistance", inline = "srcol")
supcol = input(color.lime, title ="", inline = "srcol")
rescol = input(color.red, title ="", inline = "srcol")
srlinestyle = input(line.style_dotted, title = "Line Style/Width", options = [line.style_solid, line.style_dashed, line.style_dotted], inline ="style")
srlinewidth = input(3, title = "", minval = 1, maxval = 5, inline ="style")
changebarcol = input(true, title="Change Bar Color", inline = "bcol")
bcolup = input(color.blue, title ="", inline = "bcol")
bcoldn = input(color.black, title ="", inline = "bcol")
ph = pivothigh(lb, rb)
pl = pivotlow(lb, rb)
hl = iff(ph, 1, iff(pl, -1, na)) // Trend direction
zz = iff(ph, ph, iff(pl, pl, na)) // similar to zigzag but may have multiple highs/lows
zz :=iff(pl and hl == -1 and valuewhen(hl, hl, 1) == -1 and pl > valuewhen(zz, zz, 1), na, zz)
zz :=iff(ph and hl == 1 and valuewhen(hl, hl, 1) == 1 and ph < valuewhen(zz, zz, 1), na, zz)
hl := iff(hl==-1 and valuewhen(hl, hl, 1)==1 and zz > valuewhen(zz, zz, 1), na, hl)
hl := iff(hl==1 and valuewhen(hl, hl, 1)==-1 and zz < valuewhen(zz, zz, 1), na, hl)
zz := iff(na(hl), na, zz)
findprevious()=> // finds previous three points (b, c, d, e)
ehl = iff(hl==1, -1, 1)
loc1 = 0.0, loc2 = 0.0, loc3 = 0.0, loc4 = 0.0
xx = 0
for x=1 to 1000
if hl[x]==ehl and not na(zz[x])
loc1 := zz[x]
xx := x + 1
break
ehl := hl
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc2 := zz[x]
xx := x + 1
break
ehl := iff(hl==1, -1, 1)
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc3 := zz[x]
xx := x + 1
break
ehl := hl
for x=xx to 1000
if hl[x]==ehl and not na(zz[x])
loc4 := zz[x]
break
[loc1, loc2, loc3, loc4]
float f = na, float g = na, float h = na, float j = na, float k = na
if not na(hl)
[loc1, loc2, loc3, loc4] = findprevious()
f := zz
g := loc1
h := loc2
j := loc3
k := loc4
_hh = zz and (f > g and f > h and h > g and h > j)
_ll = zz and (f < g and f < h and h < g and h < j)
_hl = zz and ((f >= h and (g > h and g > j and j > h and j > k)) or (f < g and f > h and g < j))
_lh = zz and ((f <= h and (g < h and g < j and j < h and j < k)) or (f > g and f < h and g > j))
plotshape(_hl, text="HL", title="Higher Low", style=shape.labelup, color=color.lime, textcolor=color.black, location=location.belowbar, offset = -rb)
plotshape(_hh, text="HH", title="Higher High", style=shape.labeldown, color=color.lime, textcolor=color.black, location=location.abovebar, offset = -rb)
plotshape(_ll, text="LL", title="Lower Low", style=shape.labelup, color=color.red, textcolor=color.white, location=location.belowbar, offset = -rb)
plotshape(_lh, text="LH", title="Lower High", style=shape.labeldown, color=color.red, textcolor=color.white, location=location.abovebar, offset = -rb)
float res = na, float sup = na
res := iff(_lh, zz, res[1])
sup := iff(_hl, zz, sup[1])
int trend = na
trend := iff(close > res, 1, iff(close < sup, -1, nz(trend[1])))
res := iff((trend == 1 and _hh) or (trend == -1 and _lh), zz, res)
sup := iff((trend == 1 and _hl) or (trend == -1 and _ll), zz, sup)
rechange = res != res[1]
suchange = sup != sup[1]
var line resline = na
var line supline = na
if showsupres
if rechange
line.set_x2(resline, bar_index)
line.set_extend(resline, extend = extend.none)
resline := line.new(x1 = bar_index - rb, y1 = res, x2 = bar_index, y2 = res, color = rescol, extend = extend.right, style = srlinestyle, width = srlinewidth)
if suchange
line.set_x2(supline, bar_index)
line.set_extend(supline, extend = extend.none)
supline := line.new(x1 = bar_index - rb, y1 = sup, x2 = bar_index, y2 = sup, color = supcol, extend = extend.right, style = srlinestyle, width = srlinewidth)
barcolor(color = iff(changebarcol, iff(trend == 1, bcolup, bcoldn), na))
alert_strings = array.new_string(4)
array.set(alert_strings, 0, "")
array.set(alert_strings, 1, "")
array.set(alert_strings, 2, "")
array.set(alert_strings, 3, "")
table_row_count = array.new_int(3)
array.set(table_row_count, 0, 1)
array.set(table_row_count, 1, 1)
array.set(table_row_count, 2, 1)
var UpTabl = table.new(position = position.top_center, columns = 3, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2)
var DnTabl = table.new(position = position.bottom_center, columns = 3, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2)
//table.cell(table_id = UpTabl, column = 1, row = 0, text = "Upper Channel Break")
//table.cell(table_id = DnTabl, column = 1, row = 0, text = "Lower Channel Break")
//table.cell(table_id = UpTabl, column = 2, row = 0, text = "โฒโฒ")
//table.cell(table_id = DnTabl, column = 2, row = 0, text = "โผโผ")
//table.cell(table_id = UpTabl, column = 0, row = 1, text = "Ticker")
//table.cell(table_id = UpTabl, column = 1, row = 1, text = "Close")
//table.cell(table_id = UpTabl, column = 2, row = 1, text = "High")
//table.cell(table_id = DnTabl, column = 0, row = 1, text = "Ticker")
//table.cell(table_id = DnTabl, column = 1, row = 1, text = "Close")
//table.cell(table_id = DnTabl, column = 2, row = 1, text = "Low")
devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot."
depthTooltip = "The minimum number of bars that will be taken into account when calculating the indicator."
// pivots threshold
threshold_multiplier = input(title="Deviation", type=input.float, defval=3, minval=0, tooltip=devTooltip)
dev_threshold = atr(10) / close * 100 * threshold_multiplier
depth = input(title="Depth", type=input.integer, defval=10, minval=1, tooltip=depthTooltip)
reverse = input(false, "Reverse")
// Zig Zag
ZigZag = input(true, "Zig Zagโโโ" , inline = "ZZ", group = "Zig Zag Settings")
zzColor = input(color.orange, "" , inline = "ZZ", group = "Zig Zag Settings")
zzWidth = input(1 , "", minval = 1 , inline = "ZZ", group = "Zig Zag Settings")
zzStyle = input("Dashed", "", options = ["Dashed", "Dotted", "Solid"] , inline = "ZZ", group = "Zig Zag Settings")
var extendLeft = input(false, "Extend Leftโโโโ|โโโโExtend Right", inline = "Extend Lines")
var extendRight = input(true, "", inline = "Extend Lines")
var extending = extend.none
if extendLeft and extendRight
extending := extend.both
if extendLeft and not extendRight
extending := extend.left
if not extendLeft and extendRight
extending := extend.right
prices = input(true, "Show Prices")
levels = input(true, "Show Levels", inline = "Levels")
levelsFormat = input("Values", "", options = ["Values", "Percent"], inline = "Levels")
labelsPosition = input("Left", "Labels Position", options = ["Left", "Right"])
// ---------------------------------------------------------------------------------------- //
// Fibonacci
var line lineLast = na
var int iLast = 0
var int iPrev = 0
var float pLast = 0
var isHighLast = false // otherwise the last pivot is a low pivot
var iPrevPivotRef = 0
var pPrevPivotRef = 0.
var iLastPivotRef = 0
var pLastPivotRef = 0.
pivots(src, length, isHigh) =>
l2 = length * 2
c = nz(src[length])
ok = true
for i = 0 to l2
if isHigh and src[i] > c
ok := false
if not isHigh and src[i] < c
ok := false
if ok
[bar_index[length], c]
else
[int(na), float(na)]
[iH, pH] = pivots(high, depth / 2, true )
[iL, pL] = pivots(low , depth / 2, false)
calc_dev(base_price, price) =>
100 * (price - base_price) / price
pivotFound(dev, isHigh, index, price) =>
if isHighLast == isHigh and not na(lineLast)
// same direction
if isHighLast ? price > pLast : price < pLast
line.set_xy2(lineLast, index, price)
[lineLast, isHighLast]
else
[line(na), bool(na)]
else // reverse the direction (or create the very first line)
if abs(dev) > dev_threshold
// price move is significant
// ---------------------------------------------------------------------------------------- //
[zzCol, zzWid, zzSty] = if not ZigZag
[na, 1, line.style_dashed]
else
[zzColor, zzWidth, zzStyle == "Solid" ? line.style_solid : zzStyle == "Dotted" ? line.style_dotted : line.style_dashed]
// ---------------------------------------------------------------------------------------- //
id = line.new(iLast, pLast, index, price, color=zzCol, width=zzWid, style=zzSty)
[id, isHigh]
else
[line(na), bool(na)]
// Fibonacci, Zig Zag
if not na(iH)
dev = calc_dev(pLast, pH)
[id, isHigh] = pivotFound(dev, true, iH, pH)
if not na(id)
if id != lineLast
// ---------------------------------------------------------------------------------------- //
iPrevPivotRef := line.get_x1(lineLast)
pPrevPivotRef := line.get_y1(lineLast)
iLastPivotRef := line.get_x2(lineLast)
pLastPivotRef := line.get_y2(lineLast)
if not ZigZag
// ---------------------------------------------------------------------------------------- //
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iH
pLast := pH
else
if not na(iL)
dev = calc_dev(pLast, pL)
[id, isHigh] = pivotFound(dev, false, iL, pL)
if not na(id)
if id != lineLast
// ---------------------------------------------------------------------------------------- //
iPrevPivotRef := line.get_x1(lineLast)
pPrevPivotRef := line.get_y1(lineLast)
iLastPivotRef := line.get_x2(lineLast)
pLastPivotRef := line.get_y2(lineLast)
if not ZigZag
// ---------------------------------------------------------------------------------------- //
line.delete(lineLast)
lineLast := id
isHighLast := isHigh
iPrev := iLast
iLast := iL
pLast := pL
// Zig Zag
_draw_line(price, col) =>
var id = line.new(iLast, price, bar_index, price, color=col, width=1, extend=extending)
if not na(lineLast)
line.set_xy1(id, line.get_x1(lineLast), price)
line.set_xy2(id, line.get_x2(lineLast), price)
_draw_label(price, txt, txtColor) =>
x = labelsPosition == "Left" ? line.get_x1(lineLast) : not extendRight ? line.get_x2(lineLast) : bar_index
labelStyle = labelsPosition == "Left" ? label.style_label_right : label.style_label_left
align = labelsPosition == "Left" ? text.align_right : text.align_left
labelsAlignStrLeft = txt + '\n โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \n'
labelsAlignStrRight = ' ' + txt + '\n โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \n'
labelsAlignStr = labelsPosition == "Left" ? labelsAlignStrLeft : labelsAlignStrRight
var id = label.new(x=x, y=price, text=labelsAlignStr, textcolor=txtColor, style=labelStyle, textalign=align, color=#00000000)
label.set_xy(id, x, price)
label.set_text(id, labelsAlignStr)
label.set_textcolor(id, txtColor)
_wrap(txt) =>
"(" + tostring(txt, "#.##") + ")"
_label_txt(level, price) =>
l = levelsFormat == "Values" ? tostring(level) : tostring(level * 100) + "%"
(levels ? l : "") + (prices ? _wrap(price) : "")
_crossing_level(sr, r) =>
(r > sr and r < sr[1]) or (r < sr and r > sr[1])
startPrice = reverse ? line.get_y1(lineLast) : pLast
endPrice = reverse ? pLast : line.get_y1(lineLast)
iHL = startPrice > endPrice
diff = (iHL ? -1 : 1) * abs(startPrice - endPrice)
processLevel(show, value, colorL) =>
float m = value
r = startPrice + diff * m
if show
_draw_line(r, colorL)
_draw_label(r, _label_txt(m, r), colorL)
//if _crossing_level(close, r)
//alert("Autofib: " + syminfo.ticker + " crossing level " + tostring(value))
show_0 = input(true, "", inline = "Level0")
value_0 = input(0, "", inline = "Level0")
color_0 = input(#787b86, "", inline = "Level0")
processLevel(show_0, value_0, color_0)
show_0_5 = input(true, "", inline = "Level1")
value_0_5 = input(0.5, "", inline = "Level1")
color_0_5 = input(#4caf50, "", inline = "Level1")
processLevel(show_0_5, value_0_5, color_0_5)
show_0_618 = input(true, "", inline = "Level2")
value_0_618 = input(0.618, "", inline = "Level2")
color_0_618 = input(#009688, "", inline = "Level2")
processLevel(show_0_618, value_0_618, color_0_618)
show_1 = input(true, "", inline = "Level3")
value_1 = input(1, "", inline = "Level3")
color_1 = input(#787b86, "", inline = "Level3")
processLevel(show_1, value_1, color_1)
show_1_618 = input(true, "", inline = "Level5")
value_1_618 = input(1.618, "", inline = "Level5")
color_1_618 = input(#2196f3, "", inline = "Level5")
processLevel(show_1_618, value_1_618, color_1_618)
upperMult = input(2, "Linear Regression : Upper Deviation")
lowerMult = input(-2, "Linear Regression : Lower Deviation")
useUpperDev = input(true, "Linear Regression : Use Upper Deviation")
useLowerDev = input(true, "Linear Regression : Use Lower Deviation")
showPearson = input(true, "Linear Regression : Show Pearson`s R")
extendLines = input(false, "Linear Regression : Extend Lines")
len = input(100, "Linear Regression : Count")
src = input(close, "Linear Regression : Source")
// Linear Regression - build-in
extend = extendLines ? extend.right : extend.none
calcSlope(src, len) =>
max_bars_back(src, 300)
if not barstate.islast or len <= 1
[float(na), float(na), float(na)]
else
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for i = 0 to len - 1
val = src[i]
per = i + 1.0
sumX := sumX + per
sumY := sumY + val
sumXSqr := sumXSqr + per * per
sumXY := sumXY + val * per
slope = (len * sumXY - sumX * sumY) / (len * sumXSqr - sumX * sumX)
average = sumY / len
intercept = average - slope * sumX / len + slope
[slope, average, intercept]
[slp, a, i] = calcSlope(src, len)
startPriceL = i + slp * (len - 1)
endPriceL = i
var line baseLine = na
if na(baseLine) and not na(startPriceL)
baseLine := line.new(bar_index - len + 1, startPriceL, bar_index, endPriceL, width=1, extend=extend, color=color.red)
else
line.set_xy1(baseLine, bar_index - len + 1, startPriceL)
line.set_xy2(baseLine, bar_index, endPriceL)
na
calcDev(src, len, slope, average, intercept) =>
upDev = 0.0
dnDev = 0.0
stdDevAcc = 0.0
dsxx = 0.0
dsyy = 0.0
dsxy = 0.0
periods = len - 1
daY = intercept + (slope * periods) / 2
val = intercept
for i = 0 to periods
price = high[i] - val
if (price > upDev)
upDev := price
price := val - low[i]
if (price > dnDev)
dnDev := price
price := src[i]
dxt = price - average
dyt = val - daY
price := price - val
stdDevAcc := stdDevAcc + price * price
dsxx := dsxx + dxt * dxt
dsyy := dsyy + dyt * dyt
dsxy := dsxy + dxt * dyt
val := val + slope
stdDev = sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / sqrt(dsxx * dsyy)
[stdDev, pearsonR, upDev, dnDev]
[stdDev, pearsonR, upDev, dnDev] = calcDev(src, len, slp, a, i)
upperStartPrice = startPriceL + (useUpperDev ? upperMult * stdDev : upDev)
upperEndPrice = endPriceL + (useUpperDev ? upperMult * stdDev : upDev)
var line upper = na
lowerStartPrice = startPriceL + (useLowerDev ? lowerMult * stdDev : -dnDev)
lowerEndPrice = endPriceL + (useLowerDev ? lowerMult * stdDev : -dnDev)
var line lower = na
if na(upper) and not na(upperStartPrice)
upper := line.new(bar_index - len + 1, upperStartPrice, bar_index, upperEndPrice, width=1, extend=extend, color=#0000ff)
else
line.set_xy1(upper, bar_index - len + 1, upperStartPrice)
line.set_xy2(upper, bar_index, upperEndPrice)
na
if na(lower) and not na(lowerStartPrice)
lower := line.new(bar_index - len + 1, lowerStartPrice, bar_index, lowerEndPrice, width=1, extend=extend, color=#0000ff)
else
line.set_xy1(lower, bar_index - len + 1, lowerStartPrice)
line.set_xy2(lower, bar_index, lowerEndPrice)
na
// Pearson`s R
var label r = na
transparent = color.new(color.white, 100)
label.delete(r[1])
if showPearson and not na(pearsonR)
r := label.new(bar_index - len + 1, lowerStartPrice, tostring(pearsonR, "#.########"), color=transparent, textcolor=#0000ff, size=size.normal, style=label.style_labelup)
plot(round(pearsonR*1000)/1000, display=display.none)
//(cl_p > (ep_mp + st_dv * 2))//
//(cl_p < (ep_mp - st_dv * 2)//
f_LregBrk(_ticker)=>
[cl_p, ep_mp, st_dv, sp_mp, val_hi, val_lo, sr_01] = security(_ticker, timeframe.period, [close, endPriceL, stdDev, startPriceL, high, low, rsi(close, 14)], lookahead = barmerge.lookahead_on)
_msg = _ticker + "~CLS-" + tostring(round(cl_p * 100) / 100)
if (sp_mp - ep_mp) > 0 and crossover(cl_p, (ep_mp + st_dv * 2))
_msg := _msg + "~>" + " Uppper Channel Break โฒโฒ"
array.set(alert_strings, 0, array.get(alert_strings, 0) + "\n" + _msg)
array.set(table_row_count, 0, array.get(table_row_count, 0) + 1)
if barstate.islast
table.cell(table_id = UpTabl, column = 0, row = array.get(table_row_count, 0), text = _ticker)
table.cell(table_id = UpTabl, column = 1, row = array.get(table_row_count, 0), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(0, 200, 100))
table.cell(table_id = UpTabl, column = 2, row = array.get(table_row_count, 0), text = tostring(round(val_hi * 100) / 100), bgcolor=color.rgb(0, 200, 100))
else if (sp_mp - ep_mp) < 0 and crossunder(cl_p, (ep_mp - st_dv * 2))
_msg := _msg + "~>" + " Lower Channel Break โผโผ"
array.set(alert_strings, 1, array.get(alert_strings, 1) + "\n" + _msg)
array.set(table_row_count, 1, array.get(table_row_count, 1) + 1)
if barstate.islast
table.cell(table_id = DnTabl, column = 0, row = array.get(table_row_count, 1), text = _ticker)
table.cell(table_id = DnTabl, column = 1, row = array.get(table_row_count, 1), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(255, 0, 0))
table.cell(table_id = DnTabl, column = 2, row = array.get(table_row_count, 1), text = tostring(round(val_lo * 100) / 100), bgcolor=color.rgb(255, 0, 0))
var RsStoTabl = table.new(position = position.bottom_left, columns = 3, rows = 20, bgcolor = color.rgb(200, 230, 255), border_width = 2, frame_color= color.black, frame_width = 2)
if barstate.islast
table.cell(table_id = RsStoTabl, column = 0, row = 0, text = "Ticker")
table.cell(table_id = RsStoTabl, column = 1, row = 0, text = "RSI ~")
if sr_01 > 65
_msg := _msg + "~>" + "RSI - OB โฒ " + tostring(round(sr_01 * 10) / 10)
array.set(alert_strings, 2, array.get(alert_strings, 2) + "\n" + _msg)
array.set(table_row_count, 2, array.get(table_row_count, 2) + 1)
table.cell(table_id = RsStoTabl, column = 0, row = array.get(table_row_count, 2), text = _ticker)
table.cell(table_id = RsStoTabl, column = 1, row = array.get(table_row_count, 2), text = tostring(int(sr_01)), bgcolor=color.from_gradient(sr_01, 40, 60, color.rgb(255, 70, 70), color.rgb(0, 200, 100)))
else if sr_01 < 35
_msg := _msg + "~>" + "RSI - OS โผ " + tostring(round(sr_01 * 10) / 10)
array.set(alert_strings, 3, array.get(alert_strings, 3) + "\n" + _msg)
array.set(table_row_count, 2, array.get(table_row_count, 2) + 1)
table.cell(table_id = RsStoTabl, column = 0, row = array.get(table_row_count, 2), text = _ticker)
table.cell(table_id = RsStoTabl, column = 1, row = array.get(table_row_count, 2), text = tostring(int(sr_01)), bgcolor=color.from_gradient(sr_01, 40, 60, color.rgb(255, 70, 70), color.rgb(0, 200, 100)))
f_LregBrk(syminfo.tickerid)
f_LregBrk(input('DJI', title=input.symbol))
f_LregBrk(input('IXIC', title=input.symbol))
f_LregBrk(input('SPX', title=input.symbol))
f_LregBrk(input('RUT', title=input.symbol))
f_LregBrk(input('AAPL', title=input.symbol))
f_LregBrk(input('AMZN', title=input.symbol))
f_LregBrk(input('FB', title=input.symbol))
f_LregBrk(input('GOOG', title=input.symbol))
f_LregBrk(input('NFLX', title=input.symbol))
f_LregBrk(input('MSFT', title=input.symbol))
f_LregBrk(input('NVDA', title=input.symbol))
f_LregBrk(input('FDX', title=input.symbol))
f_LregBrk(input('GLD', title=input.symbol))
if array.get(alert_strings, 0) != ""
alert(array.get(alert_strings, 0), alert.freq_once_per_bar)
if array.get(alert_strings, 1) != ""
alert(array.get(alert_strings, 1), alert.freq_once_per_bar)
//if array.get(alert_strings, 2) != ""
//alert(array.get(alert_strings, 2), alert.freq_once_per_bar)
//if array.get(alert_strings, 3) != ""
//alert(array.get(alert_strings, 3), alert.freq_once_per_bar)
|
Nifty - Gap up Screener | https://www.tradingview.com/script/pfUoQGjP-Nifty-Gap-up-Screener/ | gadicherlaavinash | https://www.tradingview.com/u/gadicherlaavinash/ | 27 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0
// ยฉ achalmeena
// Reference E-Book - Teach Yourself Coding Indicators PineScript
// Udemy course on Creating trade strategies backtesting using pinescript
//Inspired from achalmeena
//@version=4
study("Nifty - Gap up Screener", overlay = true)
condition() => open > high[1]
ACC_result = security('ACC', 'D', condition())
ADANIPORTS_result = security('ADANIPORTS', 'D', condition())
AMBUJACEM_result = security('AMBUJACEM', 'D', condition())
ASIANPAINT_result = security('ASIANPAINT', 'D', condition())
AXISBANK_result = security('AXISBANK', 'D', condition())
BAJAJ_AUTO_result = security('BAJAJ_AUTO', 'D', condition())
BANKBARODA_result = security('BANKBARODA', 'D', condition())
BHEL_result = security('BHEL', 'D', condition())
BPCL_result = security('BPCL', 'D', condition())
BHARTIARTL_result = security('BHARTIARTL', 'D', condition())
BOSCHLTD_result = security('BOSCHLTD', 'D', condition())
CIPLA_result = security('CIPLA', 'D', condition())
COALINDIA_result = security('COALINDIA', 'D', condition())
DRREDDY_result = security('DRREDDY', 'D', condition())
GAIL_result = security('GAIL', 'D', condition())
GRASIM_result = security('GRASIM', 'D', condition())
HCLTECH_result = security('HCLTECH', 'D', condition())
HDFCBANK_result = security('HDFCBANK', 'D', condition())
HEROMOTOCO_result = security('HEROMOTOCO', 'D', condition())
HINDALCO_result = security('HINDALCO', 'D', condition())
HINDUNILVR_result = security('HINDUNILVR', 'D', condition())
HDFC_result = security('HDFC', 'D', condition())
ITC_result = security('ITC', 'D', condition())
ICICIBANK_result = security('ICICIBANK', 'D', condition())
IDEA_result = security('IDEA', 'D', condition())
INDUSINDBK_result = security('INDUSINDBK', 'D', condition())
INFY_result = security('INFY', 'D', condition())
KOTAKBANK_result = security('KOTAKBANK', 'D', condition())
LT_result = security('LT', 'D', condition())
LUPIN_result = security('LUPIN', 'D', condition())
M_M_result = security('M_M', 'D', condition())
MARUTI_result = security('MARUTI', 'D', condition())
NTPC_result = security('NTPC', 'D', condition())
ONGC_result = security('ONGC', 'D', condition())
POWERGRID_result = security('POWERGRID', 'D', condition())
PNB_result = security('PNB', 'D', condition())
RELIANCE_result = security('RELIANCE', 'D', condition())
SBIN_result = security('SBIN', 'D', condition())
SUNPHARMA_result = security('SUNPHARMA', 'D', condition())
label1 = '------Nifty40 GapUps -------\n'
label1 := ACC_result ? label1+'ACC\n' : label1
label1 := ADANIPORTS_result ? label1+'ADANIPORTS\n' : label1
label1 := AMBUJACEM_result ? label1+'AMBUJACEM\n' : label1
label1 := ASIANPAINT_result ? label1+'ASIANPAINT\n' : label1
label1 := AXISBANK_result ? label1+'AXISBANK\n' : label1
label1 := BAJAJ_AUTO_result ? label1+'BAJAJ_AUTO\n' : label1
label1 := BANKBARODA_result ? label1+'BANKBARODA\n' : label1
label1 := BHEL_result ? label1+'BHEL\n' : label1
label1 := BPCL_result ? label1+'BPCL\n' : label1
label1 := BHARTIARTL_result ? label1+'BHARTIARTL\n' : label1
label1 := BOSCHLTD_result ? label1+'BOSCHLTD\n' : label1
label1 := CIPLA_result ? label1+'CIPLA\n' : label1
label1 := COALINDIA_result ? label1+'COALINDIA\n' : label1
label1 := DRREDDY_result ? label1+'DRREDDY\n' : label1
label1 := GAIL_result ? label1+'GAIL\n' : label1
label1 := GRASIM_result ? label1+'GRASIM\n' : label1
label1 := HCLTECH_result ? label1+'HCLTECH\n' : label1
label1 := HDFCBANK_result ? label1+'HDFCBANK\n' : label1
label1 := HEROMOTOCO_result ? label1+'HEROMOTOCO\n' : label1
label1 := HINDALCO_result ? label1+'HINDALCO\n' : label1
label1 := HINDUNILVR_result ? label1+'HINDUNILVR\n' : label1
label1 := HDFC_result ? label1+'HDFC\n' : label1
label1 := ITC_result ? label1+'ITC\n' : label1
label1 := ICICIBANK_result ? label1+'ICICIBANK\n' : label1
label1 := IDEA_result ? label1+'IDEA\n' : label1
label1 := INDUSINDBK_result ? label1+'INDUSINDBK\n' : label1
label1 := INFY_result ? label1+'INFY\n' : label1
label1 := KOTAKBANK_result ? label1+'KOTAKBANK\n' : label1
label1 := LT_result ? label1+'LT\n' : label1
label1 := LUPIN_result ? label1+'LUPIN\n' : label1
label1 := M_M_result ? label1+'M-n-M\n' : label1
label1 := MARUTI_result ? label1+'MARUTI\n' : label1
label1 := NTPC_result ? label1+'NTPC\n' : label1
label1 := ONGC_result ? label1+'ONGC\n' : label1
label1 := POWERGRID_result ? label1+'POWERGRID\n' : label1
label1 := PNB_result ? label1+'PNB\n' : label1
label1 := RELIANCE_result ? label1+'RELIANCE\n' : label1
label1 := SBIN_result ? label1+'SBIN\n' : label1
label1 := SUNPHARMA_result ? label1+'SUNPHARMA\n' : label1
caption = label.new(bar_index, close, label1,color=color.blue,textcolor=color.black,style=label.style_labeldown,yloc = yloc.price)
label.delete(caption[1]) |
Averager | https://www.tradingview.com/script/pdUGLvq0-averager/ | gnutovv | https://www.tradingview.com/u/gnutovv/ | 26 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ gnutovv
//@version=5
indicator("Averager", overlay = true, max_lines_count = 3, max_labels_count = 2)
//m_price = input.int(10000, minval = 10, title = "Balance")
period = input.int(45, minval=10, title="Period")
ma_fast = input.int(3, minval=1, title = "MA fast")
ma_slow = input.int(8, minval=3, title = "MA slow")
high_line = ta.highest(period)
low_line = ta.lowest(period)
divider = (high_line - low_line) / 6
in_divider = divider / 5
line_2 = low_line + divider
line_3 = low_line + divider * 2
line_4 = low_line + divider * 3
line_5 = low_line + divider * 4
line_6 = low_line + divider * 5
first_index = last_bar_index - period
first_analize_index = first_index + 1
last_index = last_bar_index + 3
// start_analyze_box
line.new(first_analize_index, high_line, first_analize_index, low_line, color = color.gray)
line.new(first_analize_index, high_line, last_index, high_line, color = color.gray)
line.new(first_analize_index, low_line, last_index, low_line, color = color.gray)
// MA
fast_ma_ind = ta.sma(close, ma_fast)
slow_ma_ind = ta.sma(close, ma_slow)
// Channel lines
line.new(first_analize_index, line_2, last_index, line_2, color=color.blue)
line.new(first_analize_index, line_3, last_index, line_3, color=color.green)
line.new(first_analize_index, line_4, last_index, line_4, color=color.yellow)
line.new(first_analize_index, line_5, last_index, line_5, color=color.orange)
line.new(first_analize_index, line_6, last_index, line_6, color=color.red)
// lables
label.new(last_index, low_line, '5; '+str.tostring(math.round(low_line, 4)), color=color.purple)
label.new(last_index, line_2, '4; '+str.tostring(math.round(line_2, 4)), color=color.blue)
label.new(last_index, line_3, '3; '+str.tostring(math.round(line_3, 4)), color=color.green)
label.new(last_index, line_4, '2; '+str.tostring(math.round(line_4, 4)), color=color.yellow)
label.new(last_index, line_5, '1; '+str.tostring(math.round(line_5, 4)), color=color.orange)
label.new(last_index, line_6, '0; '+str.tostring(math.round(line_6, 4)), color=color.red)
// icons
plotchar(fast_ma_ind > slow_ma_ind, 'plotchar', '๐ข', location.belowbar, color.green, size = size.tiny, show_last = period)
plotchar(fast_ma_ind < slow_ma_ind, 'plotchar', 'โ', location.belowbar, color.red, size = size.tiny, show_last = period) |
Polynomial-Regression-Fitted Oscillator [Loxx] | https://www.tradingview.com/script/ZKdY5nCV-Polynomial-Regression-Fitted-Oscillator-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 139 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Polynomial-Regression-Fitted Oscillator [Loxx]",
overlay = false,
shorttitle='PRFOSC [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
lightgreencolor = #96E881
lightredcolor = #DF4F6C
_iLWMA(src, per)=>
lwma = src, workLwma = src
sumw = per, sum = per * src
for k = 1 to per - 1
weight = per - k
sumw += weight
sum += weight * nz(workLwma[k])
lwma := (sum/sumw)
lwma
_iRMA(src, per) =>
rma = src
rma := na(rma[1]) ? src : (src - nz(rma[1])) * (1/per) + nz(rma[1])
rma
_iEMA(src, per) =>
ema = src
ema := na(ema[1]) ? src : (src - nz(ema[1])) * (2 / (per + 1)) + nz(ema[1])
ema
_iSMA(src, per)=>
avg = src, k = 1, workSma = src
while k < per
avg += nz(workSma[k])
k += 1
out = avg/k
out
_specpolyfitMA(mode, ord, float[] src, deg, len, bar)=>
sumout = 0.
AX = matrix.new<float>(12, 12, 0.)
BX = array.new<float>(12, 0.)
ZX = array.new<float>(12, 0.)
Pow = array.new<float>(12, 0.)
Row = array.new<int>(12, 0)
CX = array.new<float>(12, 0.)
if (len <= 1)
sumout := array.get(src, bar)
else
if mode == 1 or (mode == 0 and bar == -len + 1)
XK = 0.
Prod = 0.
for j = 1 to deg + 1
array.set(BX, j, 0)
for k = 1 to len
YK = array.get(src, len - k)
XK := k
Prod := 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
for j = 0 to 2 * deg
array.set(Pow, j, 0)
array.set(Pow, 0, len)
for k = 1 to len
XK := k
Prod := k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
if matrix.get(AX, array.get(Row, deg + 1), deg + 1) != 0.
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
int mult = 1
if (ord >= 1)
for k = 1 to ord
mult *= (deg - k + 1)
sumout := mult * array.get(CX, deg + 1)
if (deg > ord)
for k = deg to ord + 1
int mult1 = 1
if (ord > 0)
for i = 1 to ord
mult1 *= (k - i)
sumout := mult1 * array.get(CX, k) + sumout * (len + bar)
sumout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
smthper = input.int(9, "Preliminary Source Smoothing Period", minval = 1, group = "Source Settings")
type = input.string("Exponential Moving Average - EMA", "Preliminary Source Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Source Settings")
per = input.int(30, "Period", maxval = 80, minval = 2, group = "Basic Settings")
dgr = input.int(1, "Degree of a Polynomial (no more 12)", minval = 1, maxval = 12, group = "Basic Settings")
slplen = input.int(20, "Slope Length", minval = 2, maxval = 80, group = "Basic Settings")
slpdeg = input.int(2, "Slope Degree (no more 12)", minval = 1, maxval = 12, group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
sum = 0.
srcarray = array.new<float>(per, 0.)
for j = 0 to per - 1
temp = nz(variant(type, src, smthper)[j])
array.set(srcarray, j, temp)
poly = 0.
for j = per - 1 to 0
poly := _specpolyfitMA(1, 0., srcarray, dgr, per, -j)
del1 = array.get(srcarray, j) - poly
sum += del1 * del1
sdev = 0.
if (per - 1 > 0 and sum > 0)
if (per < 32)
sdev := math.sqrt(sum / (per - 1))
else
sdev := math.sqrt(sum / per)
osc = 0.
osc := (src - poly) / sdev
slope = _specpolyfitMA(1, 1, srcarray, slpdeg, slplen, 0)
uptrnd = 0., updive = 0., dntrnd = 0., dndive = 0.
var color colorout = na
if (slope > 0)
if (slope > nz(slope[1]))
uptrnd := osc
updive := na
colorout := greencolor
if (slope <= nz(slope[1]))
updive := osc
uptrnd := na
colorout := lightgreencolor
if (slope < 0)
if (slope < nz(slope[1]))
dntrnd := osc
dndive := na
colorout := redcolor
if (slope >= nz(slope[1]))
dndive := osc
dntrnd := na
colorout := lightredcolor
plot(osc, color = colorout, style = plot.style_histogram)
plot(osc, color = colorout, linewidth = 1)
conts = 0.
conts := nz(conts[1])
conts := uptrnd ? 1 : updive ? 2 : dntrnd ? -1 : dndive ? -2 : conts
goLong = ta.change(conts) and uptrnd
goShort = ta.change(conts) and dntrnd
barcolor(colorbars ? colorout: na)
alertcondition(goLong, title="Long", message="Polynomial-Regression-Fitted Oscillator [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Polynomial-Regression-Fitted Oscillator [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
|
Digital Kahler Stochastic [Loxx] | https://www.tradingview.com/script/q2lNtMex-Digital-Kahler-Stochastic-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Digital Kahler Stochastic [Loxx]",
shorttitle='DKSTOCH [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Zero Cross'
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
rperiod = input.int(5, "Calculation Period", group = "Basic Settings")
type = input.string("Exponential Moving Average - EMA", "Fast MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Digital Kahler Signal Settings")
mtperiod = input.int(3, "Signal Period", group = "Digital Kahler Signal Settings")
fastr = input.int(8, "Fast Ratio", group = "Digital Kahler Signal Settings")
slowr = input.int(22, "Slow Ratio", group = "Digital Kahler Signal Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
fast_k = variant(type, ta.stoch(src, high, low, rperiod), mtperiod)
slow_k = variant(type, fast_k, mtperiod)
temp = 0
if ((slowr * slow_k + fastr * fast_k) / (fastr + slowr) > 50.0)
temp := 1
if ((slowr * slow_k + fastr * fast_k) / (fastr + slowr) < 50.0)
temp := -1
kstoch = ta.ema(temp, rperiod)
sig = kstoch[1]
mid = 0.
state = 0.
if sigtype == SM02
if (kstoch < sig)
state :=-1
if (kstoch > sig)
state := 1
else if sigtype == SM03
if (kstoch < mid)
state :=-1
if (kstoch > mid)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(mid, "Zero", color = bar_index % 2 ? color.gray : na)
plot(kstoch, "Kahler stoch", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(kstoch, sig) : ta.crossover(kstoch, mid)
goShort = sigtype == SM02 ? ta.crossunder(kstoch, sig) : ta.crossunder(kstoch, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Digital Kahler Stochastic [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Digital Kahler Stochastic [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Chiko-Span Momentum_PineScript_Version5 | https://www.tradingview.com/script/R5QUNYWY/ | KobySK | https://www.tradingview.com/u/KobySK/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ KobySK
//@version=5
indicator("Chiko-Span Momentum_PineScript_Version5", "CSM_P5", false)
// input
src = input.source(close, "Chiko-span source")
chart = input.source(open, "Chart to compare with Chiko-span")
len = input.int(26, "Chiko-span length")
type = input.string("Rate of Momentum", "Type of Momentum", options=["Divergence of Momentum", "Rate of Momentum"])
loc = input.int(-26, "Location of Momentum")
// momentum
mom = switch type
"Rate of Momentum" => src / chart[len-1] * 100
"Divergence of Momentum" => src - chart[len-1]
// plot
plot(mom, "Chiko-Span Momemtum", color.lime, 2, style=plot.style_line, offset=loc<0 ? loc+1 : loc>0 ? loc-1 : 0)
// h-line
level = type == "Rate of Momentum" ? 100 : 0
hline(level) |
Digital Kahler CCI [Loxx] | https://www.tradingview.com/script/c635BOmS-Digital-Kahler-CCI-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 56 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Digital Kahler CCI [Loxx]",
shorttitle='DKCCI [Loxx]',
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Zero Cross'
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
rperiod = input.int(14, "Calculation Period", group = "Basic Settings")
type = input.string("Simple Moving Average - SMA", "Fast MA Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Digital Kahler Signal Settings")
mtperiod = input.int(14, "Signal Period", group = "Digital Kahler Signal Settings")
fastr = input.int(8, "Fast Ratio", group = "Digital Kahler Signal Settings")
slowr = input.int(22, "Slow Ratio", group = "Digital Kahler Signal Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
cci = ta.cci(src, rperiod)
fast_k = cci
slow_k = variant(type, cci, mtperiod)
temp = 0
if ((slowr * slow_k + fastr * fast_k) / (fastr + slowr) > 0.0)
temp := 1
if ((slowr * slow_k + fastr * fast_k) / (fastr + slowr) < 0.0)
temp := -1
kcci = ta.ema(temp, rperiod)
sig = kcci[1]
mid = 0.
state = 0.
if sigtype == SM02
if (kcci < sig)
state :=-1
if (kcci > sig)
state := 1
else if sigtype == SM03
if (kcci < mid)
state :=-1
if (kcci > mid)
state := 1
colorout = state == 1 ? greencolor : state == -1 ? redcolor : color.gray
plot(mid, "Zero", color = bar_index % 2 ? color.gray : na)
plot(kcci, "Kahler CCI", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout: na)
goLong = sigtype == SM02 ? ta.crossover(kcci, sig) : ta.crossover(kcci, mid)
goShort = sigtype == SM02 ? ta.crossunder(kcci, sig) : ta.crossunder(kcci, mid)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Digital Kahler CCI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Digital Kahler CCI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Buy_Sell_Vol_with_50EMA | https://www.tradingview.com/script/lkZA06Vy-Buy-Sell-Vol-with-50EMA/ | astralytics | https://www.tradingview.com/u/astralytics/ | 178 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ astralytics
//@version=4
// Sets the variable for the default integer to 50 for the EMA (The lower the
// input integer, the tighter the ema() band becomes in relation to volume).
volPeriod = input(50, "Period")
// Variable to pass the volume and volPeriod into the ema() function params.
vEma = ema(volume, volPeriod)
study("BS",format=format.volume, precision=0)
// Buy volume bar formula.
bV = iff((high==low), 0, volume*(close-low)/(high-low))
// Sell volume bar formula.
sV = iff((high==low), 0, volume*(high-close)/(high-low))
// Plots the seller's volume.
plot(volume, style=plot.style_columns, color=color.red, title="SellVol")
// Plots the buyer's volume.
plot(bV, style=plot.style_columns, color=color.teal, title="BuyVol")
// Plots the moving average.
plot(vEma,style=plot.style_line, color=color.white, title="VolPeriod") |
Average Daily Range (ADR) (Multi Timeframe, Multi Period) | https://www.tradingview.com/script/6JsHCBzf-Average-Daily-Range-ADR-Multi-Timeframe-Multi-Period/ | Arun_K_Bhaskar | https://www.tradingview.com/u/Arun_K_Bhaskar/ | 1,102 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Arun_K_Bhaskar
//@version=5
indicator(title="Average Day Range (ADR) (Multi Timeframe, Multi Period)", shorttitle="ADR", overlay=true)
//__________________________ Menu General Inputs Start
g_adr_s = 'General Inputs'
tt_l2 = 'default 14' + '\n' + 'input same lengths to appear the levels as a line '
int i_adr_length_2 = input.int(defval=7, minval=0, title='Length', inline='1', group=g_adr_s)
int i_adr_length_1 = input.int(defval=14, minval=0, title='', tooltip=tt_l2, inline='1', group=g_adr_s)
//__________________________ Menu General Inputs End
//__________________________ Menu ADR 1 Start
g_adr_1 = 'Average Day Range 1'
string i_adr_1_tf = input.timeframe(defval='D', title='Timeframe', inline='1', group=g_adr_1)
int i_adr_1_showlast = input.int(defval=1, minval=0, title='Show Last', inline='1', group=g_adr_1) + 1
bool i_adr_1_multi_show_1 = input.bool(defval=true, title='M1โโ', inline='2', group=g_adr_1)
float i_adr_1_multi_1 = input.float(defval=0.33, title='', minval=0, inline='2', group=g_adr_1)
bool i_adr_1_multi_show_2 = input.bool(defval=false, title='M2โโ', inline='2', group=g_adr_1)
float i_adr_1_multi_2 = input.float(defval=2.64, title='', minval=0, inline='2', group=g_adr_1) // 1.75, 2 for Index
bool i_adr_1_multi_show_3 = input.bool(defval=false, title='M3โโ', inline='3', group=g_adr_1)
float i_adr_1_multi_3 = input.float(defval=4.62, title='', minval=0, inline='3', group=g_adr_1)
bool i_adr_1_multi_show_4 = input.bool(defval=false, title='M4โโ', inline='3', group=g_adr_1)
float i_adr_1_multi_4 = input.float(defval=7.59, title='', minval=0, inline='3', group=g_adr_1)
color i_adr_1_r_bx_color = input.color(defval=#F7525F40, title='Box', inline='4', group=g_adr_1)
color i_adr_1_s_bx_color = input.color(defval=#22AB9440, title='', inline='4', group=g_adr_1)
string i_adr_1_bx_style = input.string(defval=line.style_solid, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='4', group=g_adr_1)
color i_adr_1_multi_color = input.color(defval=#2A2E39, title='Multiplierโโ', inline='5', group=g_adr_1)
string i_adr_1_ln_style = input.string(defval=line.style_solid, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='5', group=g_adr_1)
int i_adr_1_ln_width = input.int(defval=1, title='', inline='5', group=g_adr_1)
color i_adr_1_r_txt_color = input.color(defval=#F7525F, title='Text', inline='6', group=g_adr_1)
color i_adr_1_s_txt_color = input.color(defval=#22AB94, title='', inline='6', group=g_adr_1)
string i_adr_1_bx_size = input.string(defval=size.auto, title='', options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline='6', group=g_adr_1)
string i_adr_1_bx_text_align = input.string(text.align_left,'', options = [text.align_right, text.align_center, text.align_left], inline='6', group=g_adr_1)
//__________________________ Menu ADR 1 End
//__________________________ Menu ADR 2 Start
g_adr_2 = 'Average Day Range 2'
string i_adr_2_tf = input.timeframe(defval='W', title='Timeframe', inline='1', group=g_adr_2)
int i_adr_2_showlast = input.int(defval=0, minval=0, title='Show Last', inline='1', group=g_adr_2) + 1
bool i_adr_2_multi_show_1 = input.bool(defval=true, title='M1โโ', inline='2', group=g_adr_2)
float i_adr_2_multi_1 = input.float(defval=0.33, title='', minval=0, inline='2', group=g_adr_2)
color i_adr_2_r_bx_color = input.color(defval=#F7525F40, title='Box', inline='3', group=g_adr_2)
color i_adr_2_s_bx_color = input.color(defval=#22AB9440, title='', inline='3', group=g_adr_2)
string i_adr_2_bx_style = input.string(defval=line.style_dashed, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='3', group=g_adr_2)
color i_adr_2_multi_color = input.color(defval=#2A2E39, title='Multiplierโโ', inline='4', group=g_adr_2)
string i_adr_2_ln_style = input.string(defval=line.style_dashed, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='4', group=g_adr_2)
int i_adr_2_ln_width = input.int(defval=1, title='', inline='4', group=g_adr_2)
color i_adr_2_r_txt_color = input.color(defval=#F7525F, title='Text', inline='5', group=g_adr_2)
color i_adr_2_s_txt_color = input.color(defval=#22AB94, title='', inline='5', group=g_adr_2)
string i_adr_2_bx_size = input.string(defval=size.auto, title='', options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline='5', group=g_adr_2)
string i_adr_2_bx_text_align = input.string(text.align_left,'', options = [text.align_right, text.align_center, text.align_left], inline='5', group=g_adr_2)
//__________________________ Menu ADR 2 End
//__________________________ Menu ADR 3 Start
g_adr_3 = 'Average Day Range 3'
string i_adr_3_tf = input.timeframe(defval='M', title='Timeframe', inline='1', group=g_adr_3)
int i_adr_3_showlast = input.int(defval=0, minval=0, title='Show Last', inline='1', group=g_adr_3) + 1
bool i_adr_3_multi_show_1 = input.bool(defval=true, title='M1โโ', inline='2', group=g_adr_3)
float i_adr_3_multi_1 = input.float(defval=0.33, title='', minval=0, inline='2', group=g_adr_3)
color i_adr_3_r_bx_color = input.color(defval=#F7525F40, title='Box', inline='3', group=g_adr_3)
color i_adr_3_s_bx_color = input.color(defval=#22AB9440, title='', inline='3', group=g_adr_3)
string i_adr_3_bx_style = input.string(defval=line.style_dotted, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='3', group=g_adr_3)
color i_adr_3_multi_color = input.color(defval=#2A2E39, title='Multiplierโโ', inline='4', group=g_adr_3)
string i_adr_3_ln_style = input.string(defval=line.style_dotted, title='', options=[line.style_solid, line.style_dashed, line.style_dotted], inline='4', group=g_adr_3)
int i_adr_3_ln_width = input.int(defval=1, title='', inline='4', group=g_adr_3)
color i_adr_3_r_txt_color = input.color(defval=#F7525F, title='Text', inline='5', group=g_adr_3)
color i_adr_3_s_txt_color = input.color(defval=#22AB94, title='', inline='5', group=g_adr_3)
string i_adr_3_bx_size = input.string(defval=size.auto, title='', options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline='5', group=g_adr_3)
string i_adr_3_bx_text_align = input.string(text.align_left,'', options = [text.align_right, text.align_center, text.align_left], inline='5', group=g_adr_3)
//__________________________ Menu ADR 3 End
//__________________________ Menu Table Start
g_tb = 'Table'
bool i_table_show = input.bool(defval=true, title='Table', inline='tb_1', group=g_tb)
color i_tbl_text_color = input.color(defval=#B2B5BE, title='', inline='tb_1', group=g_tb)
string i_tbl_position = input.string(defval=position.top_right, title='', options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], inline='tb_1', group=g_tb)
string i_tbl_text_size = input.string(defval=size.auto, title='', options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline='tb_1', group=g_tb)
//__________________________ Menu Table End
//__________________________ Get Data Start
get_ohlcv(timeframe, source) =>
request.security(symbol=syminfo.tickerid, timeframe=timeframe, expression=source, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
// Get Time
adr_1_time = get_ohlcv(i_adr_1_tf, time)
adr_1_time_close = get_ohlcv(i_adr_1_tf, time_close)
adr_2_time = get_ohlcv(i_adr_2_tf, time)
adr_2_time_close = get_ohlcv(i_adr_2_tf, time_close)
adr_3_time = get_ohlcv(i_adr_3_tf, time)
adr_3_time_close = get_ohlcv(i_adr_3_tf, time_close)
//__________________________ Get Data End
//__________________________ ADR Calculations Start
// ADR Function
adr(timeframe, length, multiplier) =>
day_open = get_ohlcv(timeframe, open)
prev_high_sma = get_ohlcv(timeframe, ta.sma(high[1], length))
prev_low_sma = get_ohlcv(timeframe, ta.sma(low[1], length))
// ADR Formula
adr_value = prev_high_sma - prev_low_sma
adr_r = day_open + (adr_value / 2) * multiplier
adr_s = day_open - (adr_value / 2) * multiplier
[adr_r, adr_s]
// ADR 1
[adr_1_len_1_r, adr_1_len_1_s] = adr(i_adr_1_tf, i_adr_length_1, 1)
[adr_1_len_2_r, adr_1_len_2_s] = adr(i_adr_1_tf, i_adr_length_2, 1)
[adr_1_len_1_r_m_1, adr_1_len_1_s_m_1] = adr(i_adr_1_tf, i_adr_length_1, i_adr_1_multi_1)
[adr_1_len_1_r_m_2, adr_1_len_1_s_m_2] = adr(i_adr_1_tf, i_adr_length_1, i_adr_1_multi_2)
[adr_1_len_1_r_m_3, adr_1_len_1_s_m_3] = adr(i_adr_1_tf, i_adr_length_1, i_adr_1_multi_3)
[adr_1_len_1_r_m_4, adr_1_len_1_s_m_4] = adr(i_adr_1_tf, i_adr_length_1, i_adr_1_multi_4)
// ADR 2
[adr_2_len_1_r, adr_2_len_1_s] = adr(i_adr_2_tf, i_adr_length_1, 1)
[adr_2_len_2_r, adr_2_len_2_s] = adr(i_adr_2_tf, i_adr_length_2, 1)
[adr_2_len_1_r_m_1, adr_2_len_1_s_m_1] = adr(i_adr_2_tf, i_adr_length_1, i_adr_2_multi_1)
// ADR 3
[adr_3_len_1_r, adr_3_len_1_s] = adr(i_adr_3_tf, i_adr_length_1, 1)
[adr_3_len_2_r, adr_3_len_2_s] = adr(i_adr_3_tf, i_adr_length_2, 1)
[adr_3_len_1_r_m_1, adr_3_len_1_s_m_1] = adr(i_adr_3_tf, i_adr_length_1, i_adr_3_multi_1)
//__________________________ ADR Calculations End
//__________________________ Draw Functions Start
draw_line(left_time, right_time, float price, color _color, string _style, int _width) =>
_line = line.new(x1=left_time, y1=price, x2=right_time, y2=price, xloc=xloc.bar_time, color=_color, style=_style, width=_width)
draw_box(left_time, right_time, float top_price, float bottom_price, color _color, int _border_width, string _border_style, string _text, string _text_size, color _text_color, string _text_halign) =>
//_text = str.tostring(math.round_to_mintick(top_price))
_box = box.new(left=left_time, top=top_price, right=right_time, bottom=bottom_price, border_color=_color, border_width=_border_width, border_style=_border_style, xloc=xloc.bar_time, bgcolor=_color, text=_text, text_size=_text_size, text_color=_text_color, text_halign=_text_halign, text_valign=text.align_center)//, text_wrap=text.wrap_auto)
//draw_label(float price, color _color, string _size) =>
// _text = str.tostring(math.round_to_mintick(price))
// label.new(point=adr_1_time, text=_text, xloc=xloc.bar_time, color=#00000000, style=label.style_label_right, textcolor=_color, size=_size, textalign=text.align_right)
//__________________________ Draw Functions End
//__________________________ Draw ADR 1 Levels Start
var adr_1_r = array.new_box(), var adr_1_s = array.new_box()
var adr_1_r_m_1 = array.new_line(), var adr_1_s_m_1 = array.new_line()
var adr_1_r_m_2 = array.new_line(), var adr_1_s_m_2 = array.new_line()
var adr_1_r_m_3 = array.new_line(), var adr_1_s_m_3 = array.new_line()
var adr_1_r_m_4 = array.new_line(), var adr_1_s_m_4 = array.new_line()
if(timeframe.change(i_adr_1_tf))
adr_1_r_bx = draw_box(adr_1_time, adr_1_time_close, adr_1_len_1_r, adr_1_len_2_r, i_adr_1_r_bx_color, 1, i_adr_1_bx_style, str.tostring(i_adr_1_tf) + ': ' + str.tostring(math.round_to_mintick(adr_1_len_1_r)), i_adr_1_bx_size, i_adr_1_r_txt_color, i_adr_1_bx_text_align)
array.push(adr_1_r, adr_1_r_bx)
adr_1_s_bx = draw_box(adr_1_time, adr_1_time_close, adr_1_len_1_s, adr_1_len_2_s, i_adr_1_s_bx_color, 1, i_adr_1_bx_style, str.tostring(i_adr_1_tf) + ': ' + str.tostring(math.round_to_mintick(adr_1_len_1_s)), i_adr_1_bx_size, i_adr_1_s_txt_color, i_adr_1_bx_text_align)
array.push(adr_1_s, adr_1_s_bx)
if i_adr_1_multi_show_1
adr_1_r_m_1_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_r_m_1, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_r_m_1, adr_1_r_m_1_ln)
adr_1_s_m_1_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_s_m_1, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_s_m_1, adr_1_s_m_1_ln)
if i_adr_1_multi_show_2
adr_1_r_m_2_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_r_m_2, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_r_m_2, adr_1_r_m_2_ln)
adr_1_s_m_2_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_s_m_2, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_s_m_2, adr_1_s_m_2_ln)
if i_adr_1_multi_show_3
adr_1_r_m_3_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_r_m_3, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_r_m_3, adr_1_r_m_3_ln)
adr_1_s_m_3_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_s_m_3, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_s_m_3, adr_1_s_m_3_ln)
if i_adr_1_multi_show_4
adr_1_r_m_4_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_r_m_4, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_r_m_4, adr_1_r_m_4_ln)
adr_1_s_m_4_ln = draw_line(adr_1_time, adr_1_time_close, adr_1_len_1_s_m_4, i_adr_1_multi_color, i_adr_1_ln_style, i_adr_1_ln_width)
array.push(adr_1_s_m_4, adr_1_s_m_4_ln)
// Function to delete past lines & boxes
show_last_boxes(arr, showlast) =>
if array.size(arr) >= showlast
box = array.get(arr, 0)
box.delete(box)
array.remove(arr, 0)
show_last_lines(arr, showlast) =>
if array.size(arr) >= showlast
line = array.get(arr, 0)
line.delete(line)
array.remove(arr, 0)
show_last_boxes(adr_1_r, i_adr_1_showlast)
show_last_boxes(adr_1_s, i_adr_1_showlast)
show_last_lines(adr_1_r_m_1, i_adr_1_showlast)
show_last_lines(adr_1_s_m_1, i_adr_1_showlast)
show_last_lines(adr_1_r_m_2, i_adr_1_showlast)
show_last_lines(adr_1_s_m_2, i_adr_1_showlast)
show_last_lines(adr_1_r_m_3, i_adr_1_showlast)
show_last_lines(adr_1_s_m_3, i_adr_1_showlast)
show_last_lines(adr_1_r_m_4, i_adr_1_showlast)
show_last_lines(adr_1_s_m_4, i_adr_1_showlast)
//__________________________ Draw ADR 1 Levels End
//__________________________ Draw ADR 2 Levels Start
var adr_2_r = array.new_box(), var adr_2_s = array.new_box()
var adr_2_r_m_1 = array.new_line(), var adr_2_s_m_1 = array.new_line()
if(timeframe.change(i_adr_2_tf))
adr_2_r_bx = draw_box(adr_2_time, adr_2_time_close, adr_2_len_1_r, adr_2_len_2_r, i_adr_2_r_bx_color, 1, i_adr_2_bx_style, str.tostring(i_adr_2_tf) + ': ' + str.tostring(math.round_to_mintick(adr_2_len_1_r)), i_adr_2_bx_size, i_adr_2_r_txt_color, i_adr_2_bx_text_align)
array.push(adr_2_r, adr_2_r_bx)
adr_2_s_bx = draw_box(adr_2_time, adr_2_time_close, adr_2_len_1_s, adr_2_len_2_s, i_adr_2_s_bx_color, 1, i_adr_2_bx_style, str.tostring(i_adr_2_tf) + ': ' + str.tostring(math.round_to_mintick(adr_2_len_1_s)), i_adr_2_bx_size, i_adr_2_s_txt_color, i_adr_2_bx_text_align)
array.push(adr_2_s, adr_2_s_bx)
if i_adr_2_multi_show_1
adr_2_r_m_1_ln = draw_line(adr_2_time, adr_2_time_close, adr_2_len_1_r_m_1, i_adr_2_multi_color, i_adr_2_ln_style, i_adr_2_ln_width)
array.push(adr_2_r_m_1, adr_2_r_m_1_ln)
adr_2_s_m_1_ln = draw_line(adr_2_time, adr_2_time_close, adr_2_len_1_s_m_1, i_adr_2_multi_color, i_adr_2_ln_style, i_adr_2_ln_width)
array.push(adr_2_s_m_1, adr_2_s_m_1_ln)
show_last_boxes(adr_2_r, i_adr_2_showlast)
show_last_boxes(adr_2_s, i_adr_2_showlast)
show_last_lines(adr_2_r_m_1, i_adr_2_showlast)
show_last_lines(adr_2_s_m_1, i_adr_2_showlast)
//__________________________ Draw ADR 2 Levels End
//__________________________ Draw ADR 3 Levels Start
var adr_3_r = array.new_box(), var adr_3_s = array.new_box()
var adr_3_r_m_1 = array.new_line(), var adr_3_s_m_1 = array.new_line()
if(timeframe.change(i_adr_3_tf))
adr_3_r_bx = draw_box(adr_3_time, adr_3_time_close, adr_3_len_1_r, adr_3_len_2_r, i_adr_3_r_bx_color, 1, i_adr_3_bx_style, str.tostring(i_adr_3_tf) + ': ' + str.tostring(math.round_to_mintick(adr_3_len_1_r)), i_adr_3_bx_size, i_adr_3_r_txt_color, i_adr_3_bx_text_align)
array.push(adr_3_r, adr_3_r_bx)
adr_3_s_bx = draw_box(adr_3_time, adr_3_time_close, adr_3_len_1_s, adr_3_len_2_s, i_adr_3_s_bx_color, 1, i_adr_3_bx_style, str.tostring(i_adr_3_tf) + ': ' + str.tostring(math.round_to_mintick(adr_3_len_1_s)), i_adr_3_bx_size, i_adr_3_s_txt_color, i_adr_3_bx_text_align)
array.push(adr_3_s, adr_3_s_bx)
if i_adr_3_multi_show_1
adr_3_r_m_1_ln = draw_line(adr_3_time, adr_3_time_close, adr_3_len_1_r_m_1, i_adr_3_multi_color, i_adr_3_ln_style, i_adr_3_ln_width)
array.push(adr_3_r_m_1, adr_3_r_m_1_ln)
adr_3_s_m_1_ln = draw_line(adr_3_time, adr_3_time_close, adr_3_len_1_s_m_1, i_adr_3_multi_color, i_adr_3_ln_style, i_adr_3_ln_width)
array.push(adr_3_s_m_1, adr_3_s_m_1_ln)
show_last_boxes(adr_3_r, i_adr_3_showlast)
show_last_boxes(adr_3_s, i_adr_3_showlast)
show_last_lines(adr_3_r_m_1, i_adr_3_showlast)
show_last_lines(adr_3_s_m_1, i_adr_3_showlast)
//__________________________ Draw ADR 3 Levels End
//__________________________ Table Start
// Current Timeframe ADR
[adr_1_len_1_r_ctf, adr_1_len_1_s_ctf] = adr('', i_adr_length_1, 1)
// Caculate ADR Range
pchg_chg(prev_value, current_value) =>
pchg = (prev_value / current_value - 1) * 100
chg = prev_value - current_value
[pchg, chg]
[adr_1_pchg, adr_1_chg] = pchg_chg(adr_1_len_1_r_ctf, adr_1_len_1_s_ctf)
[adr_2_pchg, adr_2_chg] = pchg_chg(adr_1_len_1_r, adr_1_len_1_s)
// Bg Color
bgcolor_1 = color.new(i_tbl_text_color, 80)
bgcolor_2 = color.new(i_tbl_text_color, 90)
// Plot Table
var table plot_table = table.new(position=i_tbl_position, columns=3, rows=2, border_width=2)
if barstate.islast and i_table_show
table.cell(plot_table, column=0, row=0, text='Chart', text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_1, text_size=i_tbl_text_size)
table.cell(plot_table, column=1, row=0, text=str.tostring(adr_1_chg, '#.##') + ' โน', text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_1, text_size=i_tbl_text_size)
table.cell(plot_table, column=2, row=0, text=str.tostring(adr_1_pchg, '#.##') + ' %', text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_1, text_size=i_tbl_text_size)
table.cell(plot_table, column=0, row=1, text=str.tostring(i_adr_1_tf), text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_2, text_size=i_tbl_text_size)
table.cell(plot_table, column=1, row=1, text=str.tostring(adr_2_chg, '#.##') + ' โน', text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_2, text_size=i_tbl_text_size)
table.cell(plot_table, column=2, row=1, text=str.tostring(adr_2_pchg, '#.##') + ' %', text_color=i_tbl_text_color, text_halign=text.align_right, bgcolor=bgcolor_2, text_size=i_tbl_text_size)
//__________________________ Table End
//__________________________ CODE END |
07srsi | https://www.tradingview.com/script/AeYk1S7K-07srsi/ | therockmangotem | https://www.tradingview.com/u/therockmangotem/ | 8 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ therockmangotem
//@version=5
indicator(title = "07srsi", timeframe="7", timeframe_gaps=true, precision=0)
smoothK = 3
smoothD = 3
lengthRSI = 14
lengthStoch = 14
src1 = close
src2 = close[1]
rsi1 = ta.rsi(src1, lengthRSI)
rsi2 = ta.rsi(src2, lengthRSI)
k1 = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d1 = ta.sma(k1, smoothD)
k2 = ta.sma(ta.stoch(rsi2, rsi2, rsi2, lengthStoch), smoothK)
d2 = ta.sma(k2, smoothD)
hi = 90
lo = 10
i07srsi = 0
if k1 >= hi
if d1 >= hi
i07srsi := 1
// if k2 >= hi
// if d2 >= hi
// i07srsi := 1
else if k1 <= lo
if d1 <= lo
i07srsi := -1
// if k2 <= lo
// if d2 <= lo
// i07srsi := -1
else
i07srsi := 0
plot(i07srsi, "07srsi", color=#DA70D6)
|
15srsi | https://www.tradingview.com/script/lQIt2ypl-15srsi/ | therockmangotem | https://www.tradingview.com/u/therockmangotem/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ therockmangotem
//@version=5
indicator(title = "15srsi", timeframe="15", timeframe_gaps=true, precision=0)
smoothK = 3
smoothD = 3
lengthRSI = 14
lengthStoch = 14
src1 = close
src2 = close[1]
rsi1 = ta.rsi(src1, lengthRSI)
rsi2 = ta.rsi(src2, lengthRSI)
k1 = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d1 = ta.sma(k1, smoothD)
k2 = ta.sma(ta.stoch(rsi2, rsi2, rsi2, lengthStoch), smoothK)
d2 = ta.sma(k2, smoothD)
hi = 90
lo = 10
i15srsi = 0
if k1 >= hi
if d1 >= hi
if k2 >= hi
if d2 >= hi
i15srsi := 1
else if k1 <= lo
if d1 <= lo
if k2 <= lo
if d2 <= lo
i15srsi := -1
else
i15srsi := 0
plot(i15srsi, "15srsi", color=#FF8000)
|
Masculine Relative Strength | https://www.tradingview.com/script/SjiCMHAe-Masculine-Relative-Strength/ | Ikaikai | https://www.tradingview.com/u/Ikaikai/ | 53 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ ikaikai
//@version=5
indicator("Masculine Relative Strength", overlay = true)
timeframe_input = input.timeframe("", title = 'Timeframe')
ma_length = input.int(200, title = 'MA Length')
var int EUR_count = 0
var int GBP_count = 0
var int AUD_count = 0
var int NZD_count = 0
var int USD_count = 0
var int CAD_count = 0
var int CHF_count = 0
var int JPY_count = 0
//
//EUR
//
symbol_1 = "OANDA:EURUSD"
symbol_2 = "OANDA:EURJPY"
symbol_3 = "OANDA:EURCHF"
symbol_4 = "OANDA:EURAUD"
symbol_5 = "OANDA:EURGBP"
symbol_6 = "OANDA:EURCAD"
symbol_7 = "OANDA:EURNZD"
symbol1_return = request.security(symbol_1, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol2_return = request.security(symbol_2, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol3_return = request.security(symbol_3, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol4_return = request.security(symbol_4, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol5_return = request.security(symbol_5, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol6_return = request.security(symbol_6, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol7_return = request.security(symbol_7, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
EUR_count := (symbol1_return) + (symbol2_return) + (symbol3_return) + (symbol4_return) + (symbol5_return) + (symbol6_return) + (symbol7_return)
//
//GBP
//
symbol_8 = "OANDA:GBPUSD"
symbol_9 = "OANDA:GBPJPY"
symbol_10 = "OANDA:GBPAUD"
symbol_11 = "OANDA:GBPNZD"
symbol_12 = "OANDA:GBPCHF"
symbol_13 = "OANDA:GBPCAD"
symbol8_return = request.security(symbol_8, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol9_return = request.security(symbol_9, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol10_return = request.security(symbol_10, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol11_return = request.security(symbol_11, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol12_return = request.security(symbol_12, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol13_return = request.security(symbol_13, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
GBP_count := (-symbol5_return) + (symbol8_return) + (symbol9_return) + (symbol10_return) + (symbol11_return) + (symbol12_return) + (symbol13_return)
//
//AUD
//
symbol_14 = "OANDA:AUDUSD"
symbol_15 = "OANDA:AUDNZD"
symbol_16 = "OANDA:AUDJPY"
symbol_17 = "OANDA:AUDCHF"
symbol_18 = "OANDA:AUDCAD"
symbol14_return = request.security(symbol_14, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol15_return = request.security(symbol_15, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol16_return = request.security(symbol_16, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol17_return = request.security(symbol_17, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol18_return = request.security(symbol_18, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
AUD_count := (-symbol4_return) + (-symbol10_return) + (symbol14_return) + (symbol15_return) + (symbol16_return) + (symbol17_return) + (symbol18_return)
//
//NZD
//
symbol_19 = "OANDA:NZDUSD"
symbol_20 = "OANDA:NZDJPY"
symbol_21 = "OANDA:NZDCHF"
symbol_22 = "OANDA:NZDCAD"
symbol19_return = request.security(symbol_19, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol20_return = request.security(symbol_20, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol21_return = request.security(symbol_21, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol22_return = request.security(symbol_22, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
NZD_count := (-symbol7_return) + (-symbol11_return) + (-symbol15_return) + (symbol19_return) + (symbol20_return) + (symbol21_return) + (symbol22_return)
//
//USD
//
symbol_23 = "OANDA:USDJPY"
symbol_24 = "OANDA:USDCAD"
symbol_25 = "OANDA:USDCHF"
symbol23_return = request.security(symbol_23, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol24_return = request.security(symbol_24, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol25_return = request.security(symbol_25, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
USD_count := (-symbol1_return) + (-symbol8_return) + (-symbol14_return) + (-symbol19_return) + (symbol23_return) + (symbol24_return) + (symbol25_return)
//
//CAD
//
symbol_26 = "OANDA:CADJPY"
symbol_27 = "OANDA:CADCHF"
symbol26_return = request.security(symbol_26, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
symbol27_return = request.security(symbol_27, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
CAD_count := (-symbol6_return) + (-symbol13_return) + (-symbol18_return) + (-symbol22_return) + (-symbol24_return) + (symbol26_return) + (symbol27_return)
//
//CHF
//
symbol_28 = "OANDA:CHFJPY"
symbol28_return = request.security(symbol_28, timeframe_input, (close >= ta.ema(close, ma_length) ? 1 : -1)[1], lookahead = barmerge.lookahead_on)
CHF_count := (-symbol3_return) + (-symbol12_return) + (-symbol17_return) + (-symbol21_return) + (-symbol25_return) + (-symbol27_return) + (symbol28_return)
//
//JPY
//
JPY_count := (-symbol2_return) + (-symbol9_return) + (-symbol16_return) + (-symbol20_return) + (-symbol23_return) + (-symbol26_return) + (-symbol28_return)
//create arrays
symbol_array = array.new_string(8)
symbol_value_array = array.new_int(8)
bull_color = input.color(color.green, title = 'Bull Color', group = 'Visual Settings', inline = '1')
bear_color = input.color(color.red, title = 'Bear Color', group = 'Visual Settings', inline = '1')
neutral_color = input.color(color.white, title = 'Neutral Color', group = 'Visual Settings', inline = '1')
text_color = input.color(color.new(#000000,0), title = 'Text Color', group = 'Visual Settings', inline = '2')
show_tf_label = input.bool(false, title = 'Show Timeframe Label', group = 'Visual Settings', inline = '3')
LabelSize = input.string(defval="Small", options=["Small", "Medium", "Large"], group = "Visual Settings", title = "Dashboard Size", inline = '2')
label_size = LabelSize == "Small" ? size.small : LabelSize == "Medium" ? size.normal : LabelSize == "Large" ? size.large : size.small
var table = table.new(position = position.top_right, columns = 9, rows = 2, bgcolor = color.black,
frame_color = text_color, frame_width = 2, border_color = text_color, border_width = 1)
if barstate.islast
//set the value of array
array.set(symbol_value_array, 0, EUR_count)
array.set(symbol_value_array, 1, GBP_count)
array.set(symbol_value_array, 2, AUD_count)
array.set(symbol_value_array, 3, NZD_count)
array.set(symbol_value_array, 4, USD_count)
array.set(symbol_value_array, 5, CAD_count)
array.set(symbol_value_array, 6, CHF_count)
array.set(symbol_value_array, 7, JPY_count)
//sort the array
array.sort(symbol_value_array, order.descending)
//get the new index of each
eur_index = array.indexof(symbol_value_array, EUR_count)
gbp_index = array.indexof(symbol_value_array, GBP_count)
aud_index = array.indexof(symbol_value_array, AUD_count)
nzd_index = array.indexof(symbol_value_array, NZD_count)
usd_index = array.indexof(symbol_value_array, USD_count)
cad_index = array.indexof(symbol_value_array, CAD_count)
chf_index = array.indexof(symbol_value_array, CHF_count)
jpy_index = array.indexof(symbol_value_array, JPY_count)
// set a name with the same index above
array.set(symbol_array, eur_index, "EUR")
array.set(symbol_array, gbp_index, "GBP")
array.set(symbol_array, aud_index, "AUD")
array.set(symbol_array, nzd_index, "NZD")
array.set(symbol_array, usd_index, "USD")
array.set(symbol_array, cad_index, "CAD")
array.set(symbol_array, chf_index, "CHF")
array.set(symbol_array, jpy_index, "JPY")
if show_tf_label
table.cell(table_id = table, column = 0, row = 0, text = str.tostring(timeframe_input) == "" ? "Chart" : "TF: " + str.tostring(timeframe_input) , bgcolor = neutral_color, text_color = text_color, text_size = label_size)
table.merge_cells(table_id = table, start_column = 0, start_row = 0, end_column = 0, end_row = 1)
table.cell(table_id = table, column = 1, row = 0, text = '7', bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 2, row = 0, text = '6', bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 3, row = 0, text = '5', bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 4, row = 0, text = '4', bgcolor = neutral_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 5, row = 0, text = '3', bgcolor = neutral_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 6, row = 0, text = '2', bgcolor = bear_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 7, row = 0, text = '1', bgcolor = bear_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 8, row = 0, text = '0', bgcolor = bear_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 1, row = 1, text = str.tostring(array.get(symbol_array,0)), bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 2, row = 1, text = str.tostring(array.get(symbol_array,1)), bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 3, row = 1, text = str.tostring(array.get(symbol_array,2)), bgcolor = bull_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 4, row = 1, text = str.tostring(array.get(symbol_array,3)), bgcolor = neutral_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 5, row = 1, text = str.tostring(array.get(symbol_array,4)), bgcolor = neutral_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 6, row = 1, text = str.tostring(array.get(symbol_array,5)), bgcolor = bear_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 7, row = 1, text = str.tostring(array.get(symbol_array,6)), bgcolor = bear_color, text_color = text_color, text_size = label_size)
table.cell(table_id = table, column = 8, row = 1, text = str.tostring(array.get(symbol_array,7)), bgcolor = bear_color, text_color = text_color, text_size = label_size)
|
PA-Adaptive Polynomial Regression Fitted Moving Average [Loxx] | https://www.tradingview.com/script/xj9dbGma-PA-Adaptive-Polynomial-Regression-Fitted-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("PA-Adaptive Polynomial Regression Fitted Moving Average [Loxx]",
overlay = true,
shorttitle='PAAPRFMA [Loxx]',
timeframe="",
timeframe_gaps=true)
import loxx/loxxexpandedsourcetypes/4
import loxx/loxxpaaspecial/1
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
_specpolyfitMA(src, deg, len)=>
sumout = src
AX = matrix.new<float>(12, 12, 0.)
BX = array.new<float>(12, 0.)
ZX = array.new<float>(12, 0.)
Pow = array.new<float>(12, 0.)
Row = array.new<int>(12, 0)
CX = array.new<float>(12, 0.)
for k = 1 to len
YK = nz(src[len - k])
XK = k
Prod = 1
for j = 1 to deg + 1
array.set(BX, j, array.get(BX, j) + YK * Prod)
Prod *= XK
array.set(Pow, 0, len)
for k = 1 to len
XK = k
Prod = k
for j = 1 to 2 * deg
array.set(Pow, j, array.get(Pow, j) + Prod)
Prod *= XK
for j = 1 to deg + 1
for l = 1 to deg + 1
matrix.set(AX, j, l, array.get(Pow, j + l - 2))
for j = 1 to deg + 1
array.set(Row, j, j)
for i = 1 to deg
for k = i + 1 to deg + 1
if math.abs(matrix.get(AX, array.get(Row, k), i)) >
math.abs(matrix.get(AX, array.get(Row, i), i))
temp = array.get(Row, i)
array.set(Row, i, array.get(Row, k))
array.set(Row, k, temp)
for k = i + 1 to deg + 1
if matrix.get(AX, array.get(Row, i), i) != 0
matrix.set(AX, array.get(Row, k), i,
matrix.get(AX, array.get(Row, k), i) /
matrix.get(AX, array.get(Row, i), i))
for l = i + 1 to deg + 1
matrix.set(AX, array.get(Row, k), l,
matrix.get(AX, array.get(Row, k), l) -
matrix.get(AX, array.get(Row, k), i) *
matrix.get(AX, array.get(Row, i), l))
array.set(ZX, 1, array.get(BX, array.get(Row, 1)))
for k = 2 to deg + 1
sum = 0.
for l = 1 to k - 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(ZX, l)
array.set(ZX, k, array.get(BX, array.get(Row, k)) - sum)
if matrix.get(AX, array.get(Row, deg + 1), deg + 1) != 0.
array.set(CX, deg + 1, array.get(ZX, deg + 1) / matrix.get(AX, array.get(Row, deg + 1), deg + 1))
for k = deg to 1
sum = 0.
for l = k + 1 to deg + 1
sum += matrix.get(AX, array.get(Row, k), l) * array.get(CX, l)
array.set(CX, k, (array.get(ZX, k) - sum) / matrix.get(AX, array.get(Row, k), k))
sumout := array.get(CX, deg + 1)
for k = deg to 1
sumout := array.get(CX, k) + sumout * len
sumout
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
dgr = input.int(1, "Degree of a Polynomial (no more 12)", minval = 1, maxval = 12, group = "Basic Settings")
smthper = input.int(9, "Preliminary Source Smoothing Period", minval = 1, group = "Basic Settings")
type = input.string("Exponential Moving Average - EMA", "Preliminary Source Smoothing Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Basic Settings")
sigper = input.int(9, "Signal Smoothing Period", minval = 1, group = "Signal Settings")
sigtype = input.string("Exponential Moving Average - EMA", "Signal Type", options = ["ADXvma - Average Directional Volatility Moving Average", "Ahrens Moving Average"
, "Alexander Moving Average - ALXMA", "Double Exponential Moving Average - DEMA", "Double Smoothed Exponential Moving Average - DSEMA"
, "Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA", "Fractal Adaptive Moving Average - FRAMA"
, "Hull Moving Average - HMA", "IE/2 - Early T3 by Tim Tilson", "Integral of Linear Regression Slope - ILRS"
, "Instantaneous Trendline", "Laguerre Filter", "Leader Exponential Moving Average", "Linear Regression Value - LSMA (Least Squares Moving Average)"
, "Linear Weighted Moving Average - LWMA", "McGinley Dynamic", "McNicholl EMA", "Non-Lag Moving Average", "Parabolic Weighted Moving Average"
, "Recursive Moving Trendline", "Simple Moving Average - SMA", "Sine Weighted Moving Average", "Smoothed Moving Average - SMMA"
, "Smoother", "Super Smoother", "Three-pole Ehlers Butterworth", "Three-pole Ehlers Smoother"
, "Triangular Moving Average - TMA", "Triple Exponential Moving Average - TEMA", "Two-pole Ehlers Butterworth", "Two-pole Ehlers smoother"
, "Volume Weighted EMA - VEMA", "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average", "Zero-Lag Moving Average"
, "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"],
group = "Signal Settings")
fregcycles = input.float(1.5, title = "PA Cycles", group= "Phase Accumulation Cycle Settings")
fregfilter = input.float(1., title = "PA Filter", group= "Phase Accumulation Cycle Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showSigs = input.bool(true, "Show signals?", group = "UI Options")
frama_FC = input.int(defval=1, title="* Fractal Adjusted (FRAMA) Only - FC", group = "Moving Average Inputs")
frama_SC = input.int(defval=200, title="* Fractal Adjusted (FRAMA) Only - SC", group = "Moving Average Inputs")
instantaneous_alpha = input.float(defval=0.07, minval = 0, title="* Instantaneous Trendline (INSTANT) Only - Alpha", group = "Moving Average Inputs")
_laguerre_alpha = input.float(title="* Laguerre Filter (LF) Only - Alpha", minval=0, maxval=1, step=0.1, defval=0.7, group = "Moving Average Inputs")
lsma_offset = input.int(defval=0, title="* Least Squares Moving Average (LSMA) Only - Offset", group = "Moving Average Inputs")
_pwma_pwr = input.int(2, "* Parabolic Weighted Moving Average (PWMA) Only - Power", minval=0, group = "Moving Average Inputs")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
variant(type, src, len) =>
sig = 0.0
trig = 0.0
special = false
if type == "ADXvma - Average Directional Volatility Moving Average"
[t, s, b] = loxxmas.adxvma(src, len)
sig := s
trig := t
special := b
else if type == "Ahrens Moving Average"
[t, s, b] = loxxmas.ahrma(src, len)
sig := s
trig := t
special := b
else if type == "Alexander Moving Average - ALXMA"
[t, s, b] = loxxmas.alxma(src, len)
sig := s
trig := t
special := b
else if type == "Double Exponential Moving Average - DEMA"
[t, s, b] = loxxmas.dema(src, len)
sig := s
trig := t
special := b
else if type == "Double Smoothed Exponential Moving Average - DSEMA"
[t, s, b] = loxxmas.dsema(src, len)
sig := s
trig := t
special := b
else if type == "Exponential Moving Average - EMA"
[t, s, b] = loxxmas.ema(src, len)
sig := s
trig := t
special := b
else if type == "Fast Exponential Moving Average - FEMA"
[t, s, b] = loxxmas.fema(src, len)
sig := s
trig := t
special := b
else if type == "Fractal Adaptive Moving Average - FRAMA"
[t, s, b] = loxxmas.frama(src, len, frama_FC, frama_SC)
sig := s
trig := t
special := b
else if type == "Hull Moving Average - HMA"
[t, s, b] = loxxmas.hma(src, len)
sig := s
trig := t
special := b
else if type == "IE/2 - Early T3 by Tim Tilson"
[t, s, b] = loxxmas.ie2(src, len)
sig := s
trig := t
special := b
else if type == "Integral of Linear Regression Slope - ILRS"
[t, s, b] = loxxmas.ilrs(src, len)
sig := s
trig := t
special := b
else if type == "Instantaneous Trendline"
[t, s, b] = loxxmas.instant(src, instantaneous_alpha)
sig := s
trig := t
special := b
else if type == "Laguerre Filter"
[t, s, b] = loxxmas.laguerre(src, _laguerre_alpha)
sig := s
trig := t
special := b
else if type == "Leader Exponential Moving Average"
[t, s, b] = loxxmas.leader(src, len)
sig := s
trig := t
special := b
else if type == "Linear Regression Value - LSMA (Least Squares Moving Average)"
[t, s, b] = loxxmas.lsma(src, len, lsma_offset)
sig := s
trig := t
special := b
else if type == "Linear Weighted Moving Average - LWMA"
[t, s, b] = loxxmas.lwma(src, len)
sig := s
trig := t
special := b
else if type == "McGinley Dynamic"
[t, s, b] = loxxmas.mcginley(src, len)
sig := s
trig := t
special := b
else if type == "McNicholl EMA"
[t, s, b] = loxxmas.mcNicholl(src, len)
sig := s
trig := t
special := b
else if type == "Non-Lag Moving Average"
[t, s, b] = loxxmas.nonlagma(src, len)
sig := s
trig := t
special := b
else if type == "Parabolic Weighted Moving Average"
[t, s, b] = loxxmas.pwma(src, len, _pwma_pwr)
sig := s
trig := t
special := b
else if type == "Recursive Moving Trendline"
[t, s, b] = loxxmas.rmta(src, len)
sig := s
trig := t
special := b
else if type == "Simple Moving Average - SMA"
[t, s, b] = loxxmas.sma(src, len)
sig := s
trig := t
special := b
else if type == "Sine Weighted Moving Average"
[t, s, b] = loxxmas.swma(src, len)
sig := s
trig := t
special := b
else if type == "Smoothed Moving Average - SMMA"
[t, s, b] = loxxmas.smma(src, len)
sig := s
trig := t
special := b
else if type == "Smoother"
[t, s, b] = loxxmas.smoother(src, len)
sig := s
trig := t
special := b
else if type == "Super Smoother"
[t, s, b] = loxxmas.super(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Butterworth"
[t, s, b] = loxxmas.threepolebuttfilt(src, len)
sig := s
trig := t
special := b
else if type == "Three-pole Ehlers Smoother"
[t, s, b] = loxxmas.threepolesss(src, len)
sig := s
trig := t
special := b
else if type == "Triangular Moving Average - TMA"
[t, s, b] = loxxmas.tma(src, len)
sig := s
trig := t
special := b
else if type == "Triple Exponential Moving Average - TEMA"
[t, s, b] = loxxmas.tema(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers Butterworth"
[t, s, b] = loxxmas.twopolebutter(src, len)
sig := s
trig := t
special := b
else if type == "Two-pole Ehlers smoother"
[t, s, b] = loxxmas.twopoless(src, len)
sig := s
trig := t
special := b
else if type == "Volume Weighted EMA - VEMA"
[t, s, b] = loxxmas.vwema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag DEMA - Zero Lag Double Exponential Moving Average"
[t, s, b] = loxxmas.zlagdema(src, len)
sig := s
trig := t
special := b
else if type == "Zero-Lag Moving Average"
[t, s, b] = loxxmas.zlagma(src, len)
sig := s
trig := t
special := b
else if type == "Zero Lag TEMA - Zero Lag Triple Exponential Moving Average"
[t, s, b] = loxxmas.zlagtema(src, len)
sig := s
trig := t
special := b
trig
src := variant(type, src, smthper)
int flen = math.floor(loxxpaaspecial.paa(src, fregcycles, fregfilter))
flen := flen < 1 ? 1 : flen
polyout = _specpolyfitMA(src, dgr, flen)
sig = variant(sigtype, polyout, sigper)
colorout = polyout > sig ? greencolor : redcolor
plot(polyout, "Polyfit MA", color = colorout, linewidth = 4)
barcolor(colorbars ? colorout: na)
goLong = ta.crossover(polyout, sig)
goShort = ta.crossunder(polyout, sig)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="PA-Adaptive Polynomial Regression Fitted Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="PA-Adaptive Polynomial Regression Fitted Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
EMA-Deviation-Corrected Super Smoother [Loxx] | https://www.tradingview.com/script/W8TehfRB-EMA-Deviation-Corrected-Super-Smoother-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 640 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("EMA-Deviation-Corrected Super Smoother [Loxx]",
shorttitle='EDCCSS [Loxx]',
overlay = true,
timeframe="",
timeframe_gaps = true)
import loxx/loxxmas/1
greencolor = #2DD204
redcolor = #D2042D
_corMa(src, work, per)=>
out = 0.
v1 = math.pow(ta.stdev(src, per), 2)
v2 = math.pow(nz(out[1]) - work, 2)
c = (v2 < v1 or v2 == 0) ? 0 : 1 - v1 / v2
out := nz(out[1]) + c * (work - nz(out[1]))
out
src = input.source(close, "Source", group = "Basic Settings")
per = input.int(20, "Period", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
[work, _, _] = loxxmas.super(src, per)
out = _corMa(src, work, per)
goLong = ta.crossover(work, out)
goShort = ta.crossunder(work, out)
colorout = work > out ? greencolor : redcolor
colorout2 = work > out ? color.yellow : color.fuchsia
plot(out, "Corrected Super Smoother", color = colorout, linewidth = 3)
plot(work, "Super Smoother", color = colorout2, linewidth = 1)
barcolor(colorbars ? colorout : na)
plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)
plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)
alertcondition(goLong, title="Long", message="Corrected Super Smoother [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Corrected Super Smoother [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
VWAP Delayed | https://www.tradingview.com/script/OVdtABvK-VWAP-Delayed/ | raymah48 | https://www.tradingview.com/u/raymah48/ | 50 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ raymah48
//@version=5
indicator("VWAP Delayed", "", true)
src = input.source(hlc3, "Source")
overrideTimeZone = input(false, "Override Time Zone", inline = "tz", tooltip = "Time input values use this IANA time zone instead of the symbol's native timezone.")
timezoneOverride = input.string("America/New_York", " ", inline = "tz")
validTimeRange = input.session("1000-2000", "VWAP Visible Between", tooltip="VWAP is calculated for the entire day but only displayed during this time period")
startCalcInPremarket = input(true, "Include Premarket", tooltip="Start calculating VWAP for the day on the first bar of the premarket session. Chart must be showing extended session for this to take effect")
showSdInfo = input(true, "Show Standard Deviation Value", inline="info")
position = input.string("Top Right", " ", options=["Bottom Left", "Top Left", "Bottom Center", "Top Center", "Bottom Right", "Top Right"], inline="info")
showVWAP = input(true, "Show VWAP", inline="vwap")
alwaysShowVWAP = input(false, "Always", inline="vwap", tooltip="Always show VWAP regardless of Session defined above. Show VWAP must also be checked for VWAP to always be displayed.")
showStdDevMultiple1 = input(true, "", inline="band_1")
stdDevMultiplier1 = input(1.0, "Std. Dev Multiplier 1", inline="band_1")
showStdDevMultiple2 = input(true, "", inline="band_2")
stdDevMultiplier2 = input(2.0, "Std. Dev Multiplier 2", inline="band_2")
showStdDevMultiple3 = input(false, "", inline="band_3")
stdDevMultiplier3 = input(3.0, "Std. Dev Multiplier 3", inline="band_3")
var resetGroup = "Reset Times"
reset1 = input(false, "Reset 1", group=resetGroup, inline="Reset1")
reset1Hour = input(8, " ", group=resetGroup, inline="Reset1")
reset1Minute = input(30, " ", group=resetGroup, inline="Reset1")
reset2 = input(false, "Reset 2", group=resetGroup, inline="Reset2")
reset2Hour = input(15, " ", group=resetGroup, inline="Reset2")
reset2Minute = input(00, " ", group=resetGroup, inline="Reset2")
var alertsGroup = "Alerts"
alertTooltip = "Changing this option does NOT affect existing alerts. If you want to change when alerts are triggered, you will need to update existing alerts."
alertSession = input.session("1000-1530", "Alert Between", group = alertsGroup, tooltip = alertTooltip)
alertPlus3 = input(false, "+3 SD", group=alertsGroup, tooltip = alertTooltip)
alertPlus2 = input(false, "+2 SD", group=alertsGroup, tooltip = alertTooltip)
alertPlus1 = input(false, "+1 SD", group=alertsGroup, tooltip = alertTooltip)
alertPlus0 = input(false, "VWAP", group=alertsGroup, tooltip = alertTooltip)
alertNeg1 = input(false, "-1 SD", group=alertsGroup, tooltip = alertTooltip)
alertNeg2 = input(false, "-2 SD", group=alertsGroup, tooltip = alertTooltip)
alertNeg3 = input(false, "-3 SD", group=alertsGroup, tooltip = alertTooltip)
showAlerts = input(true, "Show Alerts on Chart", group=alertsGroup)
realtimeAlerts = input(false, "Realtime Alerts", group = alertsGroup,
tooltip = "Alert as soon as the conditions are met. When set to false, detects cross events only after the current bar closes. NOTE: Setting this to true may create false alarms.")
//
// VWAP
//
timezoneVal = overrideTimeZone ? timezoneOverride : syminfo.timezone
var float reset1Time = na
var float reset2Time = na
if dayofmonth(time) != dayofmonth(time[1])
reset1Time := timestamp(timezoneVal, year(time), month(time), dayofmonth(time), reset1Hour, reset1Minute)
reset2Time := timestamp(timezoneVal, year(time), month(time), dayofmonth(time), reset2Hour, reset2Minute)
inReset1Time = time >= reset1Time
inReset2Time = time >= reset2Time
resetCalc = if reset1 or reset2
(reset1 and inReset1Time and not inReset1Time[1]) or (reset2 and inReset2Time and not inReset2Time[1])
else
(startCalcInPremarket and session.isfirstbar) or (startCalcInPremarket == false and session.isfirstbar_regular)
[vwap, vwapSdHigh, vwapSdLow] = ta.vwap(src, resetCalc, 1.0)
vwapSd = (vwapSdHigh - vwap)
vwapStdDev1AbsVal = vwapSd * stdDevMultiplier1
vwapPlus1 = vwap + vwapStdDev1AbsVal
vwapNeg1 = vwap - vwapStdDev1AbsVal
vwapStdDev2AbsVal = vwapSd * stdDevMultiplier2
vwapPlus2 = vwap + vwapStdDev2AbsVal
vwapNeg2 = vwap - vwapStdDev2AbsVal
vwapStdDev3AbsVal = vwapSd * stdDevMultiplier3
vwapPlus3 = vwap + vwapStdDev3AbsVal
vwapNeg3 = vwap - vwapStdDev3AbsVal
// Show plots if current candle is in the specified display time range
isInRange = not na(time(timeframe.period, validTimeRange, timezoneVal))
firstVisibleCandle = isInRange and not isInRange[1]
vwapVal = showVWAP and isInRange or (alwaysShowVWAP and session.isfirstbar == false) ? vwap : na
vwapPlus1Val = isInRange and showStdDevMultiple1 ? vwapPlus1 : na
vwapPlus2Val = isInRange and showStdDevMultiple2 ? vwapPlus2 : na
vwapPlus3Val = isInRange and showStdDevMultiple3 ? vwapPlus3 : na
vwapNeg1Val = isInRange and showStdDevMultiple1 ? vwapNeg1 : na
vwapNeg2Val = isInRange and showStdDevMultiple2 ? vwapNeg2 : na
vwapNeg3Val = isInRange and showStdDevMultiple3 ? vwapNeg3 : na
var plus1Color = color.new(#ffe600, 20)
var plus2Color = color.new(color.orange, 60)
var plus3Color = color.new(color.yellow, 80)
plot(vwapPlus3Val, "SD +3", color = plus3Color, linewidth = 1, style=plot.style_linebr, display = showStdDevMultiple3 ? display.all : display.none)
plot(vwapPlus2Val, "SD +2", color = plus2Color, linewidth=2, style=plot.style_linebr, display = showStdDevMultiple2 ? display.all : display.none)
plot(vwapPlus1Val, "SD +1", color = plus1Color, style=plot.style_cross, display = showStdDevMultiple1 ? display.all : display.none)
vwapColor = color.new(color.white, 40)
plot(vwapVal, "VWAP", color = vwapColor, style=plot.style_linebr, display = showVWAP ? display.all : display.none)
var neg1Color = color.new(#6ef372, 20)
var neg2Color = color.new(color.green, 60)
var neg3Color = color.new(color.lime, 80)
plot(vwapNeg1Val, "SD -1", color = neg1Color, style=plot.style_cross, display = showStdDevMultiple1 ? display.all : display.none)
plot(vwapNeg2Val, "SD -2", color = neg2Color, linewidth=2, style=plot.style_linebr, display = showStdDevMultiple2 ? display.all : display.none)
plot(vwapNeg3Val, "SD -3", color = neg3Color, linewidth = 1, style=plot.style_linebr, display = showStdDevMultiple3 ? display.all : display.none)
//
// Alerts
//
inBarAlertTime = realtimeAlerts or barstate.isconfirmed
inAlertTime = not na(time("", alertSession, timezoneVal)) and inBarAlertTime
firstAlertCandle = inAlertTime and not inAlertTime[1]
barCross(val) => ta.crossunder(low, val) or ta.crossover(high, val)
plus1Hit = barCross(vwapPlus1) or (firstVisibleCandle and high > vwapPlus1)
plus2Hit = barCross(vwapPlus2) or (firstVisibleCandle and high > vwapPlus2)
plus3Hit = barCross(vwapPlus3) or (firstVisibleCandle and high > vwapPlus3)
neg1Hit = barCross(vwapNeg1) or (firstVisibleCandle and low < vwapNeg1)
neg2Hit = barCross(vwapNeg2) or (firstVisibleCandle and low < vwapNeg2)
neg3Hit = barCross(vwapNeg3) or (firstVisibleCandle and low < vwapNeg3)
vwapHit = barCross(vwap)
triggerPlus1HitAlert = alertPlus1 and ((inAlertTime and plus1Hit) or (firstAlertCandle and high > vwapPlus1))
triggerPlus2HitAlert = alertPlus2 and ((inAlertTime and plus2Hit) or (firstAlertCandle and high > vwapPlus2))
triggerPlus3HitAlert = alertPlus3 and ((inAlertTime and plus3Hit) or (firstAlertCandle and high > vwapPlus3))
triggerNeg1HitAlert = alertNeg1 and ((inAlertTime and neg1Hit) or (firstAlertCandle and low < vwapNeg1))
triggerNeg2HitAlert = alertNeg2 and ((inAlertTime and neg2Hit) or (firstAlertCandle and low < vwapNeg2))
triggerNeg3HitAlert = alertNeg3 and ((inAlertTime and neg3Hit) or (firstAlertCandle and low < vwapNeg3))
triggerVWAPHitAlert = alertPlus0 and ((inAlertTime and vwapHit))
plus1Marker = false
plus2Marker = false
plus3Marker = false
vwapMarker = false
neg1Marker = false
neg2Marker = false
neg3Marker = false
alertInfo = " " + syminfo.ticker + ". " + timeframe.period + (timeframe.isminutes ? "m" : "") + " chart."
if triggerPlus1HitAlert
alert("+" + str.tostring(stdDevMultiplier1) + " hit." + alertInfo)
plus1Marker := true
if triggerPlus2HitAlert
alert("+" + str.tostring(stdDevMultiplier2) + " hit." + alertInfo)
plus2Marker := true
if triggerPlus3HitAlert
alert("+" + str.tostring(stdDevMultiplier3) + " hit." + alertInfo)
plus3Marker := true
if triggerVWAPHitAlert
alert("VWAP hit." + alertInfo)
vwapMarker := true
if triggerNeg1HitAlert
alert("-" + str.tostring(stdDevMultiplier1) + " hit." + alertInfo)
neg1Marker := true
if triggerNeg2HitAlert
alert("-" + str.tostring(stdDevMultiplier2) + " hit." + alertInfo)
neg2Marker := true
if triggerNeg3HitAlert
alert("-" + str.tostring(stdDevMultiplier3) + " hit." + alertInfo)
neg3Marker := true
plotshape(showAlerts ? plus3Marker : na, "+3 Alert", shape.labeldown, location.abovebar, color.red, text="+3", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? plus2Marker : na, "+2 Alert", shape.labeldown, location.abovebar, color.red, text="+2", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? plus1Marker : na, "+1 Alert", shape.labeldown, location.abovebar, color.red, text="+1", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? vwapMarker : na, "VWAP Alert", shape.labeldown, location.abovebar, color.rgb(171, 156, 20), text="V", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? neg3Marker : na, "-3 Alert", shape.labelup, location.belowbar, color.green, text="-3", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? neg2Marker : na, "-2 Alert", shape.labelup, location.belowbar, color.green, text="-2", textcolor = color.white, display = display.pane)
plotshape(showAlerts ? neg1Marker : na, "-1 Alert", shape.labelup, location.belowbar, color.green, text="-1", textcolor = color.white, display = display.pane)
alertcondition(plus3Hit and inBarAlertTime, "+3 Hit", "+3 hit. {{ticker}}")
alertcondition(plus2Hit and inBarAlertTime, "+2 Hit", "+2 hit. {{ticker}}")
alertcondition(plus1Hit and inBarAlertTime, "+1 Hit", "+1 hit. {{ticker}}")
alertcondition(vwapHit and inBarAlertTime, "VWAP Hit", "VWAP Hit. {{ticker}}")
alertcondition(neg3Hit and inBarAlertTime, "-3 Hit", "-3 hit. {{ticker}}")
alertcondition(neg2Hit and inBarAlertTime, "-2 Hit", "-2 hit. {{ticker}}")
alertcondition(neg1Hit and inBarAlertTime, "-1 Hit", "-1 hit. {{ticker}}")
//
// Info Card
//
cardPostion = switch position
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
var table reportCard = table.new(cardPostion, 2, 1, color.gray, color.black, 1, color.black, 1)
if barstate.islast and showSdInfo and isInRange
table.cell(reportCard, 0, 0, "VWAP SD", text_color=color.black, bgcolor=color.white)
table.cell(reportCard, 1, 0, str.tostring(vwapSd, "0.00"), text_color=color.black, bgcolor=color.white)
plot(isInRange ? vwapSd : na, "SD Value", color.gray, display = display.status_line) |
EMAs Distances | https://www.tradingview.com/script/nG5MpHyz-EMAs-Distances/ | seba34e | https://www.tradingview.com/u/seba34e/ | 67 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Create by seba34e
//@version=5
indicator('EMAs Distances', overlay=true)
// Inputs and variables
ema1 = input.int ( 8, title = 'EMA 1', minval=1, tooltip='EMA #1')
ema2 = input.int ( 20, title = 'EMA 2', minval=1, tooltip='EMA #2')
ema3 = input.int ( 50, title = 'EMA 3', minval=1, tooltip='EMA #3')
ema4 = input.int ( 200, title = 'EMA 4', minval=1, tooltip='EMA #4')
src = input (close, title = 'Source', tooltip='Source')
tablePosition = input.string(title = 'Table Position', defval="Top right", options = ["Top right", "Top left", "Bottom right", "Bottom left"], tooltip='Position of the table')
// Get EMAs
xEMA1 = ta.ema (src, ema1)
xEMA2 = ta.ema (src, ema2)
xEMA3 = ta.ema (src, ema3)
xEMA4 = ta.ema (src, ema4)
// Ploting EMAs
plot(xEMA1, color=color.new(color.blue, 0), linewidth=2, title='EMA 1')
plot(xEMA2, color=color.new(color.orange, 0), linewidth=2, title='EMA 2')
plot(xEMA3, color=color.new(color.gray, 0), linewidth=2, title='EMA 3')
plot(xEMA4, color=color.new(color.purple, 0), linewidth=2, title='EMA 4')
// Prepare table
var bgcolor = color.new(color.black, 50)
var table emaTable = table.new(tablePosition == "Top right" ? position.top_right : tablePosition == "Top left" ? position.top_left : tablePosition == "Bottom right" ? position.bottom_right : position.bottom_left, 5, 6, border_width=4)
fill_Cell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + '\n' + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_halign=text.align_right)
// Prepare cells
if barstate.islast
fill_Cell(emaTable, 0, 0, 'Distance EMA ' + str.tostring (ema1) , str.tostring(close - xEMA1, "0.00") + '\n ' + str.tostring(1-xEMA1/close, "0.00%") , bgcolor, color.blue)
fill_Cell(emaTable, 1, 0, 'Distance EMA ' + str.tostring (ema2) , str.tostring(close - xEMA2, "0.00") + '\n ' + str.tostring(1-xEMA2/close, "0.00%") , bgcolor, color.orange)
fill_Cell(emaTable, 0, 1, 'Distance EMA ' + str.tostring (ema3) , str.tostring(close - xEMA3, "0.00") + '\n ' + str.tostring(1-xEMA3/close, "0.00%") , bgcolor, color.gray)
fill_Cell(emaTable, 1, 1, 'Distance EMA ' + str.tostring (ema4) , str.tostring(close - xEMA4, "0.00") + '\n ' + str.tostring(1-xEMA4/close, "0.00%") , bgcolor, color.purple)
|
DEMA Supertrend Bands [Misu] | https://www.tradingview.com/script/bJ3fyrKm-DEMA-Supertrend-Bands-Misu/ | Fontiramisu | https://www.tradingview.com/u/Fontiramisu/ | 140 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=5
indicator(title="DEMA Supertrend Bands [Misu]", shorttitle="DEMA Supertrend [Misu]", overlay=true, timeframe="", timeframe_gaps=true)
lenMas = input.int(10, minval=1, title="Length DEMA")
lenAtr = input.int(14, minval=1, title="Length Atr")
mult = input.float(1.5, step=0.1, minval=0.001, maxval=50, title="Band Mult")
// @function to get dema.
getDema(float src, simple int length) =>
ema1= ta.ema(src, length)
ema2 = ta.ema(ema1,length)
differenceFast = ema1 - ema2
zerolagEMA = ema1 + differenceFast
dema = (2 * ema1) - ema2
dema
atr = ta.atr(lenAtr)
bandOffset = mult * atr
upperBand = getDema(high + bandOffset, lenMas)
lowerBand = getDema(low - bandOffset, lenMas)
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
avPlot = plot((lowerBand + upperBand)/2, title='Mid Band', linewidth=1, color=color.orange)
upPlot = plot(upperBand, title='Up Band', linewidth=1, color=color.green)
lowPlot = plot(lowerBand, title='Low Band', linewidth=1, color=color.red)
fill(upPlot, avPlot, color.new(color.green, 90), 'Upper Area')
fill(avPlot,lowPlot, color.new(color.red, 90), 'Lower Area')
|
Poly Cycle [Loxx] | https://www.tradingview.com/script/ywjaMkyI-Poly-Cycle-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 122 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Poly Cycle [Loxx]",
shorttitle="PC [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
greencolor = #2DD204
redcolor = #D2042D
sm1 = "Data and Fit"
sm2 = "Analytic Signal"
sm3 = "Phase Shift"
sm4 = "Periods"
sm5 = "RSI"
type = input.string(sm1, "Tool Type", options = [sm1, sm2, sm3, sm4, sm5], group = "Basic Settings")
src = input.source(hl2, "Source", group = "Basic Settings")
per = input.int(17, "Period", group = "Basic Settings")
dgr = input.int(4, "Degree", group = "Basic Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
HilbertWidth = 7
Width = math.floor((per - 1.0) / 2.0)
DataSize = 2 * Width + 1
Polynomial = array.new<float>(DataSize * (dgr + 1) + 1, 0.)
Coefficient = array.new<float>(dgr + 1, 0.)
Cycle = array.new<float>(DataSize, 0.)
Signal = array.new<float>(DataSize, 0.)
Hilbert = array.new<float>(DataSize, 0.)
HilbertTransform = array.new<float>(2 * HilbertWidth + 1, 0.)
SignalTransform = array.new<float>(2 * HilbertWidth + 1, 0.)
for k = -HilbertWidth to HilbertWidth
if (k % 2.0 == 0)
array.set(HilbertTransform, HilbertWidth + k, 0.)
else
array.set(HilbertTransform, HilbertWidth + k, 2.0 / (math.pi * k))
if (k == 0)
array.set(SignalTransform, HilbertWidth + k, 1.)
else
array.set(SignalTransform, HilbertWidth + k, 0.)
for k = -Width to Width
array.set(Polynomial, 0 * DataSize + Width + k, 1.)
if (dgr >= 1)
for k = -Width to Width
array.set(Polynomial, 1 * DataSize + Width + k, k)
if (dgr > 1)
for p = 1 to dgr - 1
for k = -Width to Width
temp1 = k * (2.0 * p + 1.0) / (p + 1.0)
temp2 = -(p / (p + 1.0)) * (2.0 * Width + 1 + p) * (2.0 * Width + 1 - p) / 4.0
array.set(Polynomial, (p + 1) * DataSize + Width + k, temp1 * array.get(Polynomial, p * DataSize + Width + k) + temp2 * array.get(Polynomial, (p - 1) * DataSize + Width + k))
for p = 0 to dgr
temp = math.pow(2, -2 * p) / (2.0 * p + 1.0)
for k = -p to p
temp *= (2.0 * Width + 1.0 + k)
if (temp > 0)
temp := 1 / math.sqrt(temp)
for k = -Width to Width
array.set(Polynomial, p * DataSize + Width + k, temp * array.get(Polynomial, p * DataSize + Width + k))
PhaseShift = 0.
_price = 1
radToDegrees = 180.0 / math.pi
EarliestWidth = Width - 2.0 * HilbertWidth - 1.0
for p = 0 to dgr
array.set(Coefficient, p, 0.)
for j = -Width to Width
temp = array.get(Coefficient, p)
array.set(Coefficient, p, temp + array.get(Polynomial, p * DataSize + int(Width + j)) * nz(src[int(Width + j)]))
DC = array.get(Coefficient, 0) * array.get(Polynomial, Width + Width)
for j = EarliestWidth to Width
array.set(Cycle, int(Width + j), 0.)
for p = 1 to dgr
tmp = array.get(Cycle, int(Width + j))
array.set(Cycle, int(Width + j), tmp + array.get(Coefficient, p) * array.get(Polynomial, p * DataSize + int(Width + j)))
for j = EarliestWidth + HilbertWidth to Width - HilbertWidth
array.set(Signal, int(Width + j), 0.)
array.set(Hilbert, int(Width + j), 0.)
for k = -HilbertWidth to HilbertWidth
tmphil = array.get(Hilbert,int(Width + j))
tmpsig = array.get(Signal, int(Width + j))
array.set(Hilbert, int(Width + j), tmphil + array.get(HilbertTransform, HilbertWidth + k) * array.get(Cycle, int(Width + j) + k))
array.set(Signal, int(Width + j), tmpsig + array.get(SignalTransform, HilbertWidth + k) * array.get(Cycle, int(Width + j) + k))
temp = math.pow(array.get(Signal, int(Width + j)), 2) + math.pow(array.get(Hilbert, int(Width + j)), 2)
if (temp > 0)
temp := math.pow(temp, -0.5)
tmpsig = array.get(Signal, int(Width + j))
tmphil = array.get(Hilbert, int(Width + j))
array.set(Signal, int(Width + j), temp * tmpsig)
array.set(Hilbert, int(Width + j), temp * tmphil)
T1 = array.get(Signal, 2 * Width - HilbertWidth) *
array.get(Signal, 2 * Width - HilbertWidth - 1) +
array.get(Hilbert, 2 * Width - HilbertWidth) *
array.get(Hilbert, 2 * Width - HilbertWidth - 1)
T2 = -array.get(Hilbert, 2 * Width - HilbertWidth) *
array.get(Signal, 2 * Width - HilbertWidth - 1) +
array.get(Signal, 2 * Width - HilbertWidth) *
array.get(Hilbert, 2 * Width - HilbertWidth - 1)
PhaseShift := 0.
if (T1 != 0)
PhaseShift := math.atan(T2 / T1) * radToDegrees
else
PhaseShift := nz(PhaseShift[1])
temp = 0.
j = 0., k = 0.
while math.abs(temp) < 360 and j < bar_index
temp += nz(PhaseShift[j])
j += 1
period = j
temp := 0
while math.abs(temp) < 180 and k < bar_index
temp += nz(PhaseShift[k])
k += 1
halfPeriod = k
LeadingSignalEdge = array.get(Signal, Width + Width - HilbertWidth)
LeadingHilbertEdge = array.get(Hilbert, Width + Width - HilbertWidth)
LeadingCycleEdge = array.get(Cycle, Width + Width)
value1 = 0.
value2 = 0.
switch type
sm1 =>
value1 := src - DC
value2 := LeadingCycleEdge
sm2 =>
value1 := LeadingSignalEdge
value2 := LeadingHilbertEdge
sm3 =>
if (T2 > 0)
value1 := PhaseShift
if (T2 < 0)
value2 := PhaseShift
sm4 =>
value1 := period
value2 := halfPeriod
sm5 =>
int count = math.floor(period + HilbertWidth + 1)
smax = src
smin = src
smax := ta.highest(src, count)
smin := ta.lowest(src, count)
if (smax != smin)
value1 := -1 + 2 * (src - smin) / (smax - smin)
=>
value1 := 0.
value2 := 0.
plot(type != sm3 ? value1 : na, color = type == sm5 ? (value1 > 0 ? greencolor : redcolor) : greencolor, linewidth = 2)
plot(type != sm5 and type != sm3 ? value2 : na, color = redcolor, linewidth = 2)
plot(type != sm4 and type != sm3 ? 0. : na, color = bar_index % 2 ? color.gray : na)
plotshape(type == sm3 and value1 != 0. ? value1 : na, color = greencolor, location = location.absolute)
plotshape(type == sm3 and value2 != 0. ? value2 : na, color = redcolor, location = location.absolute)
colorout = type == sm5 ? (value1 > 0 ? greencolor : redcolor) : value1 > value2 ? greencolor : redcolor
barcolor(colorbars ? type != sm3 and type != sm4 ? colorout : na : na)
|
Halfback + One-Time-Framing Bars | https://www.tradingview.com/script/0CrrAN2T-Halfback-One-Time-Framing-Bars/ | OasisTrading | https://www.tradingview.com/u/OasisTrading/ | 141 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ OasisTrading
//@version=4
study(title="Halfback + One-Time-Framing Bars", shorttitle="HB + OTF Bars", overlay=true)
halfbackplot = input(true, title="Enable Halfback")
otfplot = input(true, title="Enable One-Time-Framing")
res = input(title="Resolution", type=input.resolution, defval="30")
highprice = security(syminfo.tickerid, res, high)
lowprice = security(syminfo.tickerid, res, low)
Halfback = avg(highprice,lowprice)
Halfbackline = valuewhen(halfbackplot==true and Halfback, avg(highprice,lowprice), 0)
colorrgb = color.rgb(236,64,122)
plot(halfbackplot ? Halfbackline : na, title="Halfback", color=colorrgb, style=plot.style_stepline, linewidth=2, transp=0, offset=1)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//one-time-framing
onetimeframeup= (highprice > highprice[1]) and (lowprice > lowprice[1])
onetimeframedown= (highprice < highprice[1]) and (lowprice < lowprice[1])
plotshape(otfplot ? onetimeframeup : na,title= "OTF Bullish", style=shape.triangleup,location=location.abovebar,color=color.blue,size=size.tiny)
plotshape(otfplot ? onetimeframedown : na,title= "OTF Bearish", style=shape.triangledown,location=location.belowbar,color=color.orange,size=size.tiny)
|
True Adaptive-Lookback Phase Change Index [Loxx] | https://www.tradingview.com/script/Xmr3pHTa-True-Adaptive-Lookback-Phase-Change-Index-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 64 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("True Adaptive-Lookback Phase Change Index [Loxx]",
shorttitle="TALBPCI [Loxx]",
overlay = false,
timeframe="",
timeframe_gaps = true)
import loxx/loxxjuriktools/1
import loxx/loxxexpandedsourcetypes/4
greencolor = #2DD204
redcolor = #D2042D
SM02 = 'Slope'
SM03 = 'Middle Crosses'
_albper(swingCount, speed, mmin, mmax)=>
swing = 0.
if bar_index > 3
if (high > nz(high[1]) and
nz(high[1]) > nz(high[2]) and
nz(low[2]) < nz(low[3]) and
nz(low[3]) < nz(low[4]))
swing := -1
if (low < nz(low[1]) and
nz(low[1]) < nz(low[2]) and
nz(high[2]) > nz(high[3]) and
nz(high[3]) > nz(high[4]))
swing := 1
swingBuffer = swing
k = 0, n = 0
while (k < bar_index) and (n < swingCount)
if(swingBuffer[k] != 0)
n += 1
k += 1
albPeriod = math.min(mmin - swingCount + math.max(math.round(k/swingCount/speed), 1), mmax)
albPeriod
src = input.source(close, "Source", group = "Basic Settings")
MinimalLength = input.int(25, "Minimum ALB Period", group = "Basic Settings")
MaximalLength = input.int(45, "Maximum ALB Period", group = "Basic Settings")
swingCount = input.int(5, "ALB Swing Count", group = "Adaptive Lookback Settings")
speed = input.float(1, "ALB Speed", minval = 0., step = 0.01, group = "Adaptive Lookback Settings")
smthper = input.int(5, "Jurik Smoothing Period", group = "Jurik Settings")
smthphs = input.float(0., "Jurik Smoothing Phase", group = "Jurik Settings")
LevelHigh = input.int(80, "Oversold Leve", group = "Levels Settings")
LevelLow = input.int(20, "Overbought Level", group = "Levels Settings")
sigtype = input.string(SM03, "Signal type", options = [SM02, SM03], group = "Signal Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
showsignals = input.bool(true, "Show signals?", group = "UI Options")
MinimalLength := math.max(MinimalLength, swingCount)
alb = _albper(swingCount, speed, MinimalLength, MaximalLength)
momentum = src - nz(src[alb])
sumUpDi = 0.
sumDnDi = 0.
for j = 1 to alb
gradient = nz(src[alb]) + momentum * (alb - j) / alb
deviation = nz(src[j]) - gradient
if (deviation > 0)
sumUpDi += deviation
else
sumDnDi -= deviation
pci = 0.
if ((sumUpDi+sumDnDi) !=0)
pci := loxxjuriktools.jurik_filt(loxxjuriktools.jurik_filt((100.0*sumUpDi)/(sumUpDi+sumDnDi), smthper, smthphs), smthper, smthphs)
else
pci := loxxjuriktools.jurik_filt(0, smthper, smthphs)
sig = pci[1]
mid = 50
state = 0.
if sigtype == SM02
if (pci<sig)
state := 1
if (pci>sig)
state :=-1
else if sigtype == SM03
if (pci<mid)
state :=1
if (pci>mid)
state := -1
colorout = state == -1 ? redcolor : state == 1 ? greencolor : color.gray
plot(LevelHigh, "Oversold", color = bar_index % 2 ? color.gray : na)
plot(LevelLow, "Overbought", color = bar_index % 2 ? color.gray : na)
plot(mid, "Middle", color = bar_index % 2 ? color.gray : na)
plot(pci, "PCI", color = colorout, linewidth = 3)
barcolor(colorbars ? colorout : na)
goLong = sigtype == SM02 ? ta.crossunder(pci, sig) : ta.crossunder(pci, mid)
goShort = sigtype == SM02 ? ta.crossover(pci, sig) : ta.crossover(pci, mid)
plotshape(goLong and showsignals, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="True Adaptive-Lookback Phase Change Index [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="True Adaptive-Lookback Phase Change Index [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")
|
Crypto Terminal [Kioseff Trading] | https://www.tradingview.com/script/3PlLOQCF-Crypto-Terminal-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 391 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ KioseffTrading
//@version=5
// ________________________________________________
// | |
// | --------------------------------- |
// | | Kฬฒ iฬฒ oฬฒ sฬฒ eฬฒ fฬฒ fฬฒ Tฬฒ rฬฒ aฬฒ dฬฒ iฬฒ nฬฒ g | |
// | | | |
// | | ฦ u แด p ษ ษน ๊ โ
โ
ว s o แด ๊ | |
// | -------------------------------- |
// | |
// |_______________________________________________|
indicator("Crypto Terminal [Kioseff Trading]", overlay = false, max_lines_count = 500)
import TradingView/ta/2 as ta
tab = input.string(defval = "Coin Data #1", title = "Chart Data", options = ["Coin Data #1", "Coin Data #2", "Custom Index", "None"])
plo = input.string(defval = "Twitter", title = "Plot Data?", options =
[
"Twitter",
"Telegram",
"Whale %",
"$100,000+ Tx",
"Bulls/Bears",
"Current Position PnL",
"Avg. Balance",
"Holders/Traders Percentage",
"Correlation",
"Futures OI",
"Perpetual OI",
"Zero Balance Addresses",
"Flow",
"Active Addresses",
"Avg. Tx. Time",
"Realized PnL",
"Cruisers",
"None"
])
allIn = input.string(defval = "No", title = "Convert All Data to Line Graph?", options = ["No", "Yes"])
hea = input.string(defval = "Fixed", title = "Table Header Color Change", options = ["Dynamic", "Fixed"])
txtS = input.string(defval = "Normal", title = "Table Text Size", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], inline = "1")
background = input.bool(true, title = "Black Background?", inline = "1")
sym1 = input.symbol(defval = "BTCUSD" , title = "Symbol 1 ", group = "Custom Crypto Index")
sym2 = input.symbol(defval = "ETHUSD" , title = "Symbol 2 ", group = "Custom Crypto Index")
sym3 = input.symbol(defval = "BNBUSD" , title = "Symbol 3 ", group = "Custom Crypto Index")
sym4 = input.symbol(defval = "XRPUSD" , title = "Symbol 4 ", group = "Custom Crypto Index")
sym5 = input.symbol(defval = "BUSDUSD" , title = "Symbol 5 ", group = "Custom Crypto Index")
sym6 = input.symbol(defval = "ADAUSD" , title = "Symbol 6 ", group = "Custom Crypto Index")
sym7 = input.symbol(defval = "SOLUSD" , title = "Symbol 7 ", group = "Custom Crypto Index")
sym8 = input.symbol(defval = "DOGEUSD" , title = "Symbol 8 ", group = "Custom Crypto Index")
sym9 = input.symbol(defval = "DOTUSD" , title = "Symbol 9 ", group = "Custom Crypto Index")
sym10 = input.symbol(defval = "DAIUSD" , title = "Symbol 10", group = "Custom Crypto Index")
sZ = switch txtS
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
coinCount = matrix.new<float>(40, 5)
coinPos = array.new_float(40)
coinNeg = array.new_float(40)
coinHi = array.new_float(40)
coinLo = array.new_float(40)
date(val, Y, M, D) =>
yeaR = ta.valuewhen(ta.change(val), Y, 0)
montH = ta.valuewhen(ta.change(val), M, 0)
daY = ta.valuewhen(ta.change(val), D, 0)
[yeaR, montH, daY]
[hiTweetY, hiTweetM, hiTweetD] = date(ta.allTimeHigh(close), year, month, dayofmonth)
[loWhaleY, loWhaleM, loWhaleD] = date(ta.allTimeLow (close), year, month, dayofmonth)
[hiVolY , hiVolM , hiVolD ] = date(ta.allTimeHigh(close), year, month, dayofmonth)
strReq() =>
position = str.pos(syminfo.tickerid, ":")
position1 = str.contains(syminfo.ticker, "USDT") == true ? str.pos(syminfo.tickerid, "USDT") : str.pos(syminfo.tickerid, "USD")
finReq1 = str.substring(syminfo.tickerid, position + 1, position1)
finReq1
tuple() =>
[
close,
close > close[1] ? 1 : -1,
close > ta.highest(close, 365)[365] ? 1 : 0,
close < ta.highest(close, 365)[365] ? 1 : 0,
((close / close[1] - 1) * 100),
year >= 2020 ? ((close / ta.allTimeHigh(high) - 1) * 100) : na
]
req(ticker) =>
[R, R1, R2, R3, R4, R5] = request.security(ticker, "D", tuple())
[R, R1, R2, R3, R4, R5]
[BTC, BTC1, BTCH, BTCL, BTCR, BTCF ] = req(sym1 ), matrix.set(coinCount, 0 , 0, BTC1), matrix.set(coinCount, 0 , 1, BTCH), matrix.set(coinCount, 0 , 2, BTCL), matrix.set(coinCount, 0 , 3, BTCR), matrix.set(coinCount, 0 , 4, BTCF )
[ETH, ETH1, ETHH, ETHL, ETHR, ETHF ] = req(sym2 ), matrix.set(coinCount, 1 , 0, ETH1), matrix.set(coinCount, 1 , 1, ETHH), matrix.set(coinCount, 1 , 2, ETHL), matrix.set(coinCount, 1 , 3, ETHR), matrix.set(coinCount, 1 , 4, ETHF )
[BNB, BNB1, BNBH, BNBL, BNBR, BNBF ] = req(sym3 ), matrix.set(coinCount, 2 , 0, BNB1), matrix.set(coinCount, 2 , 1, BNBH), matrix.set(coinCount, 2 , 2, BNBL), matrix.set(coinCount, 2 , 3, BNBR), matrix.set(coinCount, 2 , 4, BNBF )
[XRP, XRP1, XRPH, XRPL, XRPR, XRPF ] = req(sym4 ), matrix.set(coinCount, 3 , 0, XRP1), matrix.set(coinCount, 3 , 1, XRPH), matrix.set(coinCount, 3 , 2, XRPL), matrix.set(coinCount, 3 , 3, XRPR), matrix.set(coinCount, 3 , 4, XRPF )
[BIN, BIN1, BINH, BINL, BINR, BINF ] = req(sym5 ), matrix.set(coinCount, 4 , 0, BIN1), matrix.set(coinCount, 4 , 1, BINH), matrix.set(coinCount, 4 , 2, BINL), matrix.set(coinCount, 4 , 3, BINR), matrix.set(coinCount, 4 , 4, BINF )
[ADA, ADA1, ADAH, ADAL, ADAR, ADAF ] = req(sym6 ), matrix.set(coinCount, 5 , 0, ADA1), matrix.set(coinCount, 5 , 1, ADAH), matrix.set(coinCount, 5 , 2, ADAL), matrix.set(coinCount, 5 , 3, ADAR), matrix.set(coinCount, 5 , 4, ADAF )
[SOL, SOL1, SOLH, SOLL, SOLR, SOLF ] = req(sym7 ), matrix.set(coinCount, 6 , 0, SOL1), matrix.set(coinCount, 6 , 1, SOLH), matrix.set(coinCount, 6 , 2, SOLL), matrix.set(coinCount, 6 , 3, SOLR), matrix.set(coinCount, 6 , 4, SOLF )
[DOG, DOG1, DOGH, DOGL, DOGR, DOGF ] = req(sym8 ), matrix.set(coinCount, 7 , 0, DOG1), matrix.set(coinCount, 7 , 1, DOGH), matrix.set(coinCount, 7 , 2, DOGL), matrix.set(coinCount, 7 , 3, DOGR), matrix.set(coinCount, 7 , 4, DOGF )
[DOT, DOT1, DOTH, DOTL, DOTR, DOTF ] = req(sym9 ), matrix.set(coinCount, 8 , 0, DOT1), matrix.set(coinCount, 8 , 1, DOTH), matrix.set(coinCount, 8 , 2, DOTL), matrix.set(coinCount, 8 , 3, DOTR), matrix.set(coinCount, 8 , 4, DOTF )
[DAI, DAI1, DAIH, DAIL, DAIR, DAIF ] = req(sym10), matrix.set(coinCount, 9 , 0, DAI1), matrix.set(coinCount, 9 , 1, DAIH), matrix.set(coinCount, 9 , 2, DAIL), matrix.set(coinCount, 9 , 3, DAIR), matrix.set(coinCount, 9 , 4, DAIF )
[twit, twitB, twitB1, twitB2, twitH ] = request.security("INTOTHEBLOCK:" + strReq() + "_TWITTERPOSITIVE", "D", [close , hiTweetY, hiTweetM, hiTweetD, ta.allTimeHigh(close) ], ignore_invalid_symbol = true)
[whale, whaleB, whaleB1, whaleB2, whaleL] = request.security("INTOTHEBLOCK:" + strReq() + "_WHALESPERCENTAGE", "D", [close , loWhaleY, loWhaleM, loWhaleD, ta.allTimeLow(close) ], ignore_invalid_symbol = true)
[vol, volB, volB1, volB2, volH, volSma] = request.security("INTOTHEBLOCK:" + strReq() + "_LARGETXVOLUMEUSD", "D", [close , hiVolY, hiVolM, hiVolD, ta.allTimeHigh(close), ta.sma(close, 50)], ignore_invalid_symbol = true)
[twitL , twitLsma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TWITTERNEGATIVE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[twitN , twitNsma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TWITTERNEUTRAL", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[bulls , bullSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_BULLSVOLUME", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[bears , bearSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_BEARSVOLUME", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[loss , lossSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_INOUTMONEYOUT", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[prof , profSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_INOUTMONEYIN", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[even , evenSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_INOUTMONEYBETWEEN", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[avgB , avgBsma ] = request.security("INTOTHEBLOCK:" + strReq() + "_AVGBALANCE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[hodl , hodlSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_HOLDERSBALANCEPERCENTAGE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[trad , tradSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TRADERSBALANCEPERCENTAGE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[corr , corrSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_BTCCORRELATION30", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[oi , oiSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_FUTURESOPENINTEREST", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[perp , perpSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_PERPETUALOPENINTEREST", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[zero , zeroSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_ZEROBALANCEADDRESSES", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[telePos , tpSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TELEGRAMPOSITIVE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[teleNeg , tnSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TELEGRAMNEGATIVE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[teleMem , tmSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_TELEGRAMMEMBERS", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[out , outSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_OUTFLOWTXVOLUMEUSD", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[iN , iNsma ] = request.security("INTOTHEBLOCK:" + strReq() + "_INFLOWTXVOLUMEUSD", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[act , actSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_ACTIVEADDRESSES", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[tim , timSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_AVGTIMEBETWEENTX", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[hOut , hOutSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_BREAKEVENPICEOUT", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[hIn , hInSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_BREAKEVENPICEIN", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[hBetween, hBetweenSma] = request.security("INTOTHEBLOCK:" + strReq() + "_BREAKEVENPICEBETWEEN", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[cru , cruSma ] = request.security("INTOTHEBLOCK:" + strReq() + "_CRUISESRSBALANCEPERCENTAGE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
[cr1 , cr1Sma ] = request.security("INTOTHEBLOCK:" + strReq() + "_CRUISESRSPERCENTAGE", "D", [close , ta.sma(close, 50)], ignore_invalid_symbol = true)
// sec = request.security(syminfo.tickerid, "D", ta.correlation(syminfo.ticker, "BTCUSD", 30))
var float [] avgTwi = array.new_float()
var float [] avgTwil = array.new_float()
var float [] avgTwin = array.new_float()
var float [] avgWha = array.new_float()
var float [] ATHL = array.new_float()
var float [] volA = array.new_float()
calculation() =>
for i = 0 to 39
if matrix.get(coinCount, i, 0) == 1
array.set(coinPos, i, 1)
if matrix.get(coinCount, i, 0) == -1
array.set(coinNeg, i, 1)
if matrix.get(coinCount, i, 1) == 1
array.set(coinHi, i, 1)
if matrix.get(coinCount, i, 2) == 1
array.set(coinLo, i, 1)
array.push(volA, vol)
if array.size(volA) > 50
array.shift(volA)
returN = matrix.submatrix(coinCount, 0, 39, 3, 4)
belATH = matrix.submatrix(coinCount, 0, 39, 4, 5)
calc = array.sum(coinPos) / array.sum(coinNeg)
sma1 = ta.sma(array.sum(coinPos), 200)
sma2 = ta.sma(array.sum(coinNeg), 200)
calcH = array.sum(coinHi)
calcL = array.sum(coinLo)
sma1HL = ta.sma(array.sum(coinHi), 200)
sma2HL = ta.sma(array.sum(coinLo), 200)
meanMult = ta.sma(matrix.avg(returN), 50)
finVol = array.avg(volA)
[calc, sma1, sma2, calcH, calcL, sma1HL, sma2HL, meanMult, returN, belATH, finVol]
[calc, sma1, sma2, calcH, calcL, sma1HL, sma2HL, meanMult, returN, belATH, volFin] = calculation()
var float [] corrLowHigh = array.new_float()
array.push(avgTwi, twit )
array.push(avgTwil, twitL )
array.push(avgTwin, twitN )
array.push(ATHL, matrix.avg(belATH) )
array.push(avgWha, whale )
array.push(corrLowHigh, corr )
volCol = vol > volSma ? color.lime : #9dfff5
plot(plo == "Whale %" ? whale : na, color = color.yellow , style = plot.style_line, title = "Whale %" )
plot(plo == "$100,000+ Tx" ? volSma : na, color = color.white , style = plot.style_line, title = "100,000$+ Transactions Avg." )
plot(plo == "Current Position PnL" ? loss : na, color = color.purple , style = plot.style_line, title = "Current Positions at Loss" )
plot(plo == "Current Position PnL" ? prof : na, color = color.teal , style = plot.style_line, title = "Current Positions at Profit" )
plot(plo == "Current Position PnL" ? even : na, color = color.white , style = plot.style_line, title = "Current Positions at B/E" )
plot(plo == "Avg. Balance" ? avgB : na, color = color.red , style = plot.style_line, title = "Avg. Balance" )
plot(plo == "Holders/Traders Percentage" ? hodl : na, color = color.olive , style = plot.style_cross, title = "Holders Balance Percentage" )
plot(plo == "Holders/Traders Percentage" ? trad : na, color = color.maroon , style = plot.style_cross, title = "Traders Balance Percentage" )
plot(plo == "Correlation" ? corr : na, color = #ff6700 , style = plot.style_line, title = "Correlation to BTC" )
plot(plo == "Futures OI" ? oi : na, color = color.aqua , style = plot.style_line, title = "Futures OI" )
plot(plo == "Perpetual OI" ? perp : na, color = color.gray , style = plot.style_line, title = "Perpetual OI" )
plot(plo == "Zero Balance Addresses" ? zero : na, color = color.lime , style = plot.style_line, title = "Zero Balance Adresses" )
plot(plo == "Active Addresses" ? act : na, color = #81c784 , style = plot.style_line, title = "Active Addresses" )
plot(plo == "Avg. Tx. Time" ? tim : na, color = #5b9cf6 , style = plot.style_line, title = "Average Transaction Time Between Blocks" )
plot(plo == "Realized PnL" ? hOut : na, color = #fccbcd , style = plot.style_line, title = "Addresses at Realized Loss" )
plot(plo == "Realized PnL" ? hIn : na, color = #c8e6c9 , style = plot.style_line, title = "Addresses at Realized Profit" )
plot(plo == "Realized PnL" ? hBetween : na, color = #fff9c4 , style = plot.style_line, title = "Addresses at B/E" )
plot(plo == "Bulls/Bears" ? bullSma : na, color = color.lime , style = plot.style_line, title = "Bulls Buying Average" )
plot(plo == "Bulls/Bears" ? bearSma * -1 : na, color = color.red , style = plot.style_line, title = "Bears Selling Average" )
plot(plo == "Flow" ? outSma * -1 : na, color = color.red , style = plot.style_line, title = "Inflow Tx. Volume USD Average" )
plot(plo == "Flow" ? iNsma : na, color = color.green , style = plot.style_line, title = "Outflow Tx. Volume USD Average" )
plot(plo == "Twitter" ? twitN : na, color = color.blue , style = plot.style_stepline, title = "Twitter Neutral" )
plot(plo == "Cruisers" ? cru * 100 : na, color = #e1bee7 , style = plot.style_stepline_diamond, title = "% of Assets Belonging to Cruisers" )
plot(plo == "Cruisers" ? cr1 * 100 : na, color = #fc3278 , style = plot.style_stepline_diamond, title = "% of Cruiser Addresses" )
plot(plo == "$100,000+ Tx" ? vol : na, color = volCol , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "100,000$+ Transactions" )
plot(plo == "Twitter" ? twitL * -1 : na, color = color.red , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Twitter Negative" )
plot(plo == "Twitter" ? twit : na, color = color.lime , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Twitter Positive" )
plot(plo == "Telegram" ? telePos : na, color = #ffe500 , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Telegram Positive" )
plot(plo == "Telegram" ? teleNeg * -1 : na, color = #ff00e8 , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Telegram Negative" )
plot(plo == "Flow" ? out * -1 : na, color = #f77c80 , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Inflow Tx. Volume USD" )
plot(plo == "Flow" ? iN : na, color = #4dd0e1 , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Outflow Tx. Volume USD" )
plot(plo == "Bulls/Bears" ? bulls : na, color = color.orange , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Bulls Buying" )
plot(plo == "Bulls/Bears" ? bears * -1 : na, color = color.fuchsia , style = allIn == "No" ? plot.style_columns : plot.style_line, title = "Bears Selling" )
varip float [] timeColor = array.new_float()
timeSize = array.size(timeColor)
if ta.change(timenow % 16)
if array.size(timeColor) > 16
array.clear(timeColor)
array.push(timeColor, 1)
color col = na
if hea == "Dynamic"
col :=
timeSize == 0 ? color.lime :
timeSize == 1 ? color.aqua :
timeSize == 2 ? color.black :
timeSize == 3 ? color.blue :
timeSize == 4 ? color.fuchsia:
timeSize == 5 ? color.gray :
timeSize == 6 ? color.green :
timeSize == 7 ? color.lime :
timeSize == 8 ? color.maroon :
timeSize == 9 ? color.navy :
timeSize == 10 ? color.olive :
timeSize == 11 ? color.orange :
timeSize == 12 ? color.purple :
timeSize == 13 ? color.red :
timeSize == 14 ? color.silver :
timeSize == 15 ? color.teal :
color.yellow
else
col := color.blue
if barstate.islast
var table tablePerformance = table.new(position.bottom_right, 20, 20, border_color = color.white, frame_color = color.white, border_width = 1, frame_width = 1)
if tab == "Custom Index"
table.cell(
tablePerformance,
0,
0,
text = "Custom Index: Tabular Data ",
bgcolor = color.new(col, 50),
text_color = color.white,
text_size = sZ
)
table.merge_cells(tablePerformance, 0, 0, 1, 0)
table.cell(
tablePerformance,
0,
1,
text = "ADV-DEC Data",
bgcolor = color.new(color.white, 50),
text_color = #000000,
text_size = sZ
)
table.merge_cells(tablePerformance, 0, 1, 1, 1)
table.cell(
tablePerformance,
0,
2,
text = "ADV-DEC Ratio: " + str.tostring(calc, "###.###")
+ " \n(" + str.tostring(array.sum(coinPos), "###")
+ " Gainers; "
+ str.tostring(array.sum(coinNeg), "###")
+ " Losers)",
bgcolor = array.sum(coinPos) > array.sum(coinNeg) ? color.new(color.green, 90) : color.new(color.red, 90),
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
2,
text = "Avg. ADV-DEC Ratio: " + str.tostring(math.round(sma1) / math.round(sma2), "###.###")
+ " \n(" + str.tostring(math.round(sma1), "###.##")
+ " Avg. Gainers; "
+ str.tostring(math.round(sma2), "###.##")
+ " Avg. Losers)",
bgcolor = math.round(sma1) / math.round(sma2) > 1 ? color.new(color.green, 90) : color.new(color.red, 90),
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
3,
text = "Last Year Price",
bgcolor = color.new(color.white, 50),
text_color = #000000,
text_size = sZ
)
table.merge_cells(tablePerformance, 0, 3, 1, 3)
table.cell(
tablePerformance,
0,
4,
text = "Coins Trading Above Last Year High: " + str.tostring(calcH, "###.###")
+ "\n" + str.tostring("Average: " + str.tostring(math.round(sma1HL), "###.###")),
bgcolor = calcH > calcL ? color.new(color.green, 90) : color.new(color.red, 90),
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
4,
text = "Coins Trading Below Last Year High: " + str.tostring(calcL, "###.###")
+ "\n" + str.tostring("Average: " + str.tostring(math.round(sma2HL), "###.###")),
bgcolor = calcH > calcL ? color.new(color.green, 90) : color.new(color.red, 90),
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
5,
text = "Mean Index Return",
bgcolor = color.new(color.white, 50),
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
6,
text = "Mean Daily Return: " + str.tostring(matrix.avg(returN), format.percent)
+ "\n50-Session Mean Return: " + str.tostring(meanMult, format.percent),
bgcolor = matrix.avg(returN) >= 0.0 ? color.new(color.green, 90) : color.new(color.red, 90),
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
5,
text = "Mean % Below ATH",
bgcolor = color.new(color.white, 50),
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
6,
text = "Mean % Coins Are Trading Below ATH: "+ str.tostring(matrix.avg(belATH), format.percent)
+ "\nLowest (Since 2020): " + str.tostring(array.min(ATHL), format.percent),
bgcolor = color.new(color.yellow, 90) ,
text_color = color.white,
text_size = sZ
)
if tab == "Coin Data #1"
table.cell(
tablePerformance,
0,
4,
text = syminfo.description + " Min.Tick Value: " + str.tostring(syminfo.mintick) + " Volume Type: " + syminfo.volumetype,
bgcolor = color.new(col, 50) ,
text_color = color.white,
text_size = sZ
)
table.merge_cells(tablePerformance, 0, 4, 1, 4)
table.cell(
tablePerformance,
0,
5,
text =
"Twitter Sentiment",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
6,
text =
"โPositiveโ Tweets: "+ str.tostring(twit, "###,###")
+ " (Avg: " + str.tostring(array.avg(avgTwi), "###,###") + ")"
+ "\n โNeutralโ Tweets : " + str.tostring(twitN, "###,###")
+ " (Avg: " + str.tostring(array.avg(avgTwin), "###,###") + ")"
+ "\nโNegativeโ Tweets : " + str.tostring(twitL, "###,###")
+ " (Avg :" + str.tostring(array.avg(avgTwil), "###,###") + ")",
bgcolor = color.new(#00ffdd, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
5,
text = "Whales",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
6,
text = "Asset % Belonging to Whales : "+ str.tostring(whale * 100, format.percent)
+ "\nLowest: " + str.tostring(whaleL * 100, format.percent) + " (" + str.tostring(whaleB) + "/" + str.tostring(whaleB1) + "/" + str.tostring(whaleB2) + ")" +
"\nTTM Value: " + str.tostring(whale[365] * 100, format.percent),
bgcolor = color.new(#fff900, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
7,
text = "Tx. Stats",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
8,
text = "# of $100,000+ Transactions : "+ str.tostring(vol, format.volume)
+ "\n50-Session Average: " + str.tostring(volFin, format.volume)
+ "\nHighest: " + str.tostring(volH, format.volume) + " (" + str.tostring(volB) + "/" + str.tostring(volB1) + "/" + str.tostring(volB2) + ")",
bgcolor = color.new(#00ff20, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
7,
text = "Bulls | Bears",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
8,
text = "# of Tokens Bought by Bulls: "+ str.tostring(bulls, format.volume)
+ "\n# of Tokens Sold by Bears: " + str.tostring(bears, format.volume),
bgcolor = color.new(#0006ff, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
9,
text = "Open Position Stats",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
10,
text = "Currently Profitable Addresses: "+ str.tostring(prof, format.volume)
+ "\nCurrently Breakeven Addresses: " + str.tostring(even, format.volume)
+ "\nCurrently Losing Addresses: " + str.tostring(loss, format.volume),
bgcolor = color.new(#ff0000, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
9,
text = "Holders | Traders",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
10,
text = "Market Cap Divided by # of Addresses: " + str.tostring(avgB, format.volume)
+ "\n% of Assets Belonging to Holders: " + str.tostring(hodl * 100, format.percent)
+"\n% of Assets Belonging to Traders: " + str.tostring(trad * 100, format.percent),
bgcolor = color.new(#ff8100, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
11,
text = "OI | Correlation | Zero",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
12,
text = "30-Session Correlation to BTC: " + str.tostring(corr * 100, format.percent)
+ "\nFutures OI: " + str.tostring(oi, "###,###.00")
+ "\nPerpetual OI: " + str.tostring(perp, "###,###.00")
+ "\nZero Balance Adresses: " + str.tostring(zero, "###,###"),
bgcolor = color.new(color.purple, 90) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
11,
text = "Telegram",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
12,
text = '"Positive" Telegrams: ' + str.tostring(telePos, "###,###,###")
+ '\n"Negative" Telegrams: ' + str.tostring(teleNeg, "###,###,###")
+ "\nIf Project Has a TG Channel, \n# Of Members: " + str.tostring(teleMem, "###,###,###") ,
bgcolor = color.new(#000000, 90) ,
text_color = color.white,
text_size = sZ
)
if tab == "Coin Data #2"
table.cell(
tablePerformance,
0,
4,
text = syminfo.description + " Min.Tick Value: " + str.tostring(syminfo.mintick) + " Volume Type: " + syminfo.volumetype,
bgcolor = color.new(col, 50) ,
text_color = color.white,
text_size = sZ
)
table.merge_cells(tablePerformance, 0, 4, 1, 4)
table.cell(
tablePerformance,
0,
5,
text = "Flow",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
0,
6,
text = "$USD Flowing Out of Withdrawal Addresses: $" + str.tostring(out, format.volume)
+ "\n$USD Into Exchanges: $" + str.tostring(iN, format.volume),
bgcolor = color.new(color.lime, 50) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
5,
text = "Activity",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
6,
text = "Active Addresses: " + str.tostring(act, format.volume)
+ "\nAvg. Time Between Transactions: " + str.tostring(tim, "###,###.00") + " Seconds",
bgcolor = color.new(color.orange, 50) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
0,
7,
text = "Realized PnL",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
//
table.cell(
tablePerformance,
0,
8,
text = "# of Addresses With Realized Profits: " + str.tostring(hIn, format.volume)
+ "\n# of Addresses With Realized Losses: " + str.tostring(hOut, format.volume)
+ "\n# of Addresses at B/E: " + str.tostring(hBetween, format.volume) ,
bgcolor = color.new(color.yellow, 50) ,
text_color = color.white,
text_size = sZ
)
table.cell(
tablePerformance,
1,
7,
text = "Cruiser Data",
bgcolor = color.new(color.white, 50) ,
text_color = #000000,
text_size = sZ
)
table.cell(
tablePerformance,
1,
8,
text = "% of Cruiser Addresses: " + str.tostring(cr1 * 100, format.percent)
+ "\nTotal % of Assets Belonging to Cruisers: " + str.tostring(cru * 100, format.percent),
bgcolor = color.new(color.purple, 50) ,
text_color = color.white,
text_size = sZ
)
var label [] twtL = array.new_label()
var line [] twtLi = array.new_line()
if plo == "Twitter"
array.push(twtL, label.new(bar_index + 7, twit, style= label.style_label_left,
color = color.new(color.lime, 50),
text = '"Positive" Tweets\n(' + str.tostring(twit, "###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, twitL * -1, style = label.style_label_left,
color = color.new(color.red, 50),
text = '"Negative" Tweets\n(' + str.tostring(twitL, "###,###") + ")",
textcolor = color.white,
size = size.small
))
array.push(twtL, label.new(bar_index + 7, twitN, style = label.style_label_left,
color = color.new(color.blue, 50),
text = '"Neutral" Tweets\n(' + str.tostring(twitN, "###,###") + ")",
textcolor = color.white,
size = size.small
))
array.push(twtLi, line.new(bar_index, twit, bar_index + 7, twit, color = color.lime))
array.push(twtLi, line.new(bar_index, twitL * -1, bar_index + 7, twitL * -1, color = color.red))
array.push(twtLi, line.new(bar_index, twitN, bar_index + 7, twitN, color = color.blue))
if array.size(twtL) > 3
label.delete(array.shift(twtL))
if array.size(twtLi) > 3
line.delete(array.shift(twtLi))
if plo == "Whale %"
array.push(twtL, label.new(bar_index + 7, whale, style= label.style_label_left,
color = color.new(color.yellow, 50),
text = '% Belonging to Whales\n(' + str.tostring(whale * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, whale, bar_index + 7, whale, color = color.yellow, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "$100,000+ Tx"
var label [] txLa = array.new_label()
var line [] ext = array.new_line()
array.push(ext, line.new(bar_index, volSma[1], bar_index + 7, volSma, color = color.white, style = line.style_dotted))
array.push(txLa, label.new(bar_index + 7, volSma, color = color.white, textcolor = #000000,
text = "50-Session Average\n" + str.tostring(math.round(volSma),"###,###"),
size = size.small,
style = vol > volSma ?
label.style_label_up :
label.style_label_down
))
array.push(twtL, label.new(bar_index + 7, vol, style= label.style_label_left, color = color.new(color.green, 50),
text = '$100,000+ Txs.\n(' + str.tostring(vol, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, vol, bar_index + 7, vol, color = color.green, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if array.size(txLa) > 1
label.delete(array.shift(txLa))
if array.size(ext) > 1
line.delete(array.shift(ext))
if plo == "Bulls/Bears"
array.push(twtL, label.new(bar_index + 7, bulls, style= label.style_label_down, color = color.new(color.orange, 50),
text = 'Bulls Buying\n(' + str.tostring(bulls, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, bears * -1, style= label.style_label_up, color = color.new(color.fuchsia, 50),
text = 'Bears Selling\n(' + str.tostring(bears, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, bulls, bar_index + 7, bulls, color = color.orange, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, bears * -1, bar_index + 7, bears * -1, color = color.fuchsia, style = line.style_dotted))
if array.size(twtL) > 2
label.delete(array.shift(twtL))
if array.size(twtLi) > 2
line.delete(array.shift(twtLi))
if plo == "Current Position PnL"
array.push(twtL, label.new(bar_index + 7, prof, style= prof > loss ? label.style_label_down : label.style_label_up, color = color.new(color.teal, 50),
text = 'Current Positions at Profit\n(' + str.tostring(prof, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, loss, style= prof > loss ? label.style_label_up : label.style_label_down, color = color.new(color.purple, 50),
text = 'Current Positions at Loss\n(' + str.tostring(loss, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, even, style= label.style_label_left, color = color.new(color.white, 50),
text = 'Current Positions at B/E\n(' + str.tostring(even, format.volume) + ")",
textcolor = #000000,
size =size.small
))
array.push(twtLi, line.new(bar_index, prof, bar_index + 7, prof, color = color.teal, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, loss, bar_index + 7, loss, color = color.purple, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, even, bar_index + 7, even, color = color.white, style = line.style_dotted))
if array.size(twtL) > 3
label.delete(array.shift(twtL))
if array.size(twtLi) > 3
line.delete(array.shift(twtLi))
if plo == "Avg. Balance"
array.push(twtL, label.new(bar_index + 7, avgB, style= label.style_label_left, color = color.new(color.red, 50),
text = 'Average Balance\n(' + str.tostring(avgB, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, avgB, bar_index + 7, avgB, color = color.red, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Holders/Traders Percentage"
array.push(twtL, label.new(bar_index + 7, trad, style= label.style_label_left, color = color.new(color.maroon, 50),
text = '% Belonging to Traders\n(' + str.tostring(trad * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, hodl, style= label.style_label_left, color = color.new(color.olive, 50),
text = '% Belonging to Holders\n(' + str.tostring(hodl * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, trad, bar_index + 7, trad, color = color.maroon, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, hodl, bar_index + 7, hodl, color = color.olive, style = line.style_dotted))
if array.size(twtL) > 2
label.delete(array.shift(twtL))
if array.size(twtLi) > 2
line.delete(array.shift(twtLi))
if plo == "Correlation"
array.push(twtL, label.new(bar_index + 7, corr, style= label.style_label_left, color = color.new(#ff6700, 50),
text = 'Correlation to BTC\n(' + str.tostring(corr * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, array.min(corrLowHigh), style= label.style_label_up, color = color.new(color.red, 50),
text = 'Lowest Correlation\n(' + str.tostring(array.min(corrLowHigh) * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, array.max(corrLowHigh), style= label.style_label_down, color = color.new(color.lime, 50),
text = 'Highest Correlation\n(' + str.tostring(array.max(corrLowHigh) * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, corr, bar_index + 7, corr, color = #ff6700, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, array.min(corrLowHigh), bar_index + 7, array.min(corrLowHigh), extend = extend.left, color = color.red, style = line.style_solid))
array.push(twtLi, line.new(bar_index, array.max(corrLowHigh), bar_index + 7, array.max(corrLowHigh), extend = extend.left, color = color.lime, style = line.style_solid))
if array.size(twtL) > 3
label.delete(array.shift(twtL))
if array.size(twtLi) > 3
line.delete(array.shift(twtLi))
if plo == "Futures OI"
array.push(twtL, label.new(bar_index + 7, oi, style= label.style_label_left, color = color.new(color.aqua, 50),
text = 'Futuires OI\n(' + str.tostring(oi, "###,###,###.00") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, oi, bar_index + 7, oi, color = color.aqua, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Perpetual OI"
array.push(twtL, label.new(bar_index + 7, perp, style= label.style_label_left, color = color.new(color.gray, 50),
text = 'Perpetual OI\n(' + str.tostring(perp, "###,###,###.00") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, perp, bar_index + 7, perp, color = color.gray, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Zero Balance Addresses"
array.push(twtL, label.new(bar_index + 7, zero, style= label.style_label_left, color = color.new(color.lime, 50),
text = 'Zero-Bal Addresses\n(' + str.tostring(zero, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, zero, bar_index + 7, zero, color = color.lime, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Telegram"
array.push(twtL, label.new(bar_index + 7, telePos, style= label.style_label_down, color = color.new(#ffe500, 50),
text = '"Positive" Telegrams\n(' + str.tostring(telePos, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, teleNeg * -1, style= label.style_label_up, color = color.new(#ff00e8, 50),
text = '"Negative" Telegrams\n(' + str.tostring(teleNeg, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, telePos, bar_index + 7, telePos, color = #ffe500, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, teleNeg * -1, bar_index + 7, teleNeg * -1, color = #ff00e8, style = line.style_dotted))
if not na(teleMem)
array.push(twtL, label.new(bar_index + 50, math.avg(telePos, teleNeg * -1), style= label.style_label_center, color = color.new(#00ffdd, 50),
text = "If Project Has a TG Channel, \n# Of Members: " + str.tostring(teleMem, "###,###,###"),
textcolor = color.white,
size =size.small
))
if not na(teleMem)
if array.size(twtL) > 3
label.delete(array.shift(twtL))
else
if array.size(twtL) > 2
label.delete(array.shift(twtL))
if array.size(twtLi) > 2
line.delete(array.shift(twtLi))
if plo == "Flow"
array.push(twtL, label.new(bar_index + 7, iN, style= label.style_label_down, color = color.new(#4dd0e1, 50),
text = '$USD Flowing Into Exchanges\n($' + str.tostring(iN, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, iN, bar_index + 7, iN, color = color.new(#4dd0e1, 50), style = line.style_dotted))
array.push(twtL, label.new(bar_index + 7, out * -1, style= label.style_label_up, color = color.new(#f77c80, 50),
text = '$USD Flowing Out of Exchanges\n($' + str.tostring(out, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, out * -1, bar_index + 7, out * -1, color = color.new(#f77c80, 50), style = line.style_dotted))
if array.size(twtL) > 2
label.delete(array.shift(twtL))
if array.size(twtLi) > 2
line.delete(array.shift(twtLi))
if plo == "Active Addresses"
array.push(twtL, label.new(bar_index + 7, act, style= label.style_label_left, color = color.new(#81c784, 50),
text = 'Active Addresses\n(' + str.tostring(act, format.volume) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, act, bar_index + 7, act, color = #81c784, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Avg. Tx. Time"
array.push(twtL, label.new(bar_index + 7, tim, style= label.style_label_left, color = color.new(#5b9cf6, 50),
text = 'Average Transaction Time\n(' + str.tostring(tim, "###,###.####") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, tim, bar_index + 7, tim, color = #5b9cf6, style = line.style_dotted))
if array.size(twtL) > 1
label.delete(array.shift(twtL))
if array.size(twtLi) > 1
line.delete(array.shift(twtLi))
if plo == "Realized PnL"
array.push(twtL, label.new(bar_index + 7, hIn, style= label.style_label_left, color = color.new(#c8e6c9, 50),
text = 'Addresses at Realized Profit\n(' + str.tostring(hIn, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, hOut, style= label.style_label_left, color = color.new(#fccbcd, 50),
text = 'Addresses at Realized Loss\n(' + str.tostring(hOut, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtL, label.new(bar_index + 7, hBetween, style= label.style_label_left, color = color.new(#fff9c4, 50),
text = 'Addresses at B/E\n(' + str.tostring(hBetween, "###,###,###") + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, hIn, bar_index + 7, hIn, color = #c8e6c9, style = line.style_dotted))
array.push(twtLi, line.new(bar_index, hOut, bar_index + 7, hOut, color = #fccbcd, style = line.style_solid))
array.push(twtLi, line.new(bar_index, hBetween, bar_index + 7, hBetween, color = #fff9c4, style = line.style_solid))
if array.size(twtL) > 3
label.delete(array.shift(twtL))
if array.size(twtLi) > 3
line.delete(array.shift(twtLi))
if plo == "Cruisers"
array.push(twtL, label.new(bar_index + 7, cr1 * 100, style= label.style_label_left, color = color.new(#fc3278, 50),
text = '% of Cruiser Addresses\n(' + str.tostring(cr1 * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, cr1 * 100, bar_index + 7, cr1 * 100, color = color.new(#fc3278, 50), style = line.style_dotted))
array.push(twtL, label.new(bar_index + 7, cru * 100, style= label.style_label_left, color = color.new(#e1bee7, 50),
text = 'Total % of Assets Belonging to Cruisers\n(' + str.tostring(cru * 100, format.percent) + ")",
textcolor = color.white,
size =size.small
))
array.push(twtLi, line.new(bar_index, cru * 100, bar_index + 7, cru * 100, color = color.new(#e1bee7, 50), style = line.style_dotted))
if array.size(twtL) > 2
label.delete(array.shift(twtL))
if array.size(twtLi) > 2
line.delete(array.shift(twtLi))
bgcolor(background == true and plo != "None" ? #000000 : na)
if syminfo.type != "crypto"
runtime.error("Incalculable Asset. Please Try This Script On a Cryptocurrency.")
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.