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
|
---|---|---|---|---|---|---|---|---|
Support Resistance Classification (VR) [LuxAlgo] | https://www.tradingview.com/script/hQc9VrGn-Support-Resistance-Classification-VR-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,035 | 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(title='Support Resistance Classification (VR) [LuxAlgo]', shorttitle='LuxAlgo - Support Resistance Classification (VR)', max_lines_count=500, overlay=true, max_bars_back=3000)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
set = 'SET (Nยฐย โย Typeย โย Lengthย โย Multย โย HTF)'
fade = input.int ( 5 , 'fade' , tooltip='After x breaks\nthe line is invisible')
opt = input.string ('line', 'value' , options= ['value', 'line'] )
colU = input.color (color.lime, 'ย ย ย ย ย ย ย ย ย ย ย ย ย ย ' , inline='c')
colD = input.color (color.red , '' , inline='c')
left = input.int ( 10, 'left' , minval=1, maxval=20 , group='Swings settings' )
right = input.int ( 1, 'right', minval=1, maxval=10 , group='Swings settings' )
showPP = input.bool (false, 'show' , group='Swings settings' )
chc1 = input.string ( 'SMA' , '1'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='1')
len1 = input.int ( 50 , '' , group=set , inline='1')
mlt1 = input.float ( 2 , '' , group=set , inline='1')
res1 = input.timeframe( 'D' , '' , group=set , inline='1')
chc2 = input.string ( 'SMA' , '2'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='2')
len2 = input.int ( 100 , '' , group=set , inline='2')
mlt2 = input.float ( 2 , '' , group=set , inline='2')
res2 = input.timeframe( 'D' , '' , group=set , inline='2')
chc3 = input.string ( 'SMA' , '3'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='3')
len3 = input.int ( 20 , '' , group=set , inline='3')
mlt3 = input.float ( 2 , '' , group=set , inline='3')
res3 = input.timeframe( 'W', '' , group=set , inline='3')
chc4 = input.string ('Previous High' , '4'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='4')
len4 = input.int ( 20 , '' , group=set , inline='4')
mlt4 = input.float ( 2 , '' , group=set , inline='4')
res4 = input.timeframe( 'W' , '' , group=set , inline='4')
chc5 = input.string ( 'Previous Low' , '5'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='5')
len5 = input.int ( 20 , '' , group=set , inline='5')
mlt5 = input.float ( 2 , '' , group=set , inline='5')
res5 = input.timeframe( 'W' , '' , group=set , inline='5')
chc6 = input.string ('Upper' , '6'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='6')
len6 = input.int ( 20 , '' , group=set , inline='6')
mlt6 = input.float ( 2 , '' , group=set , inline='6')
res6 = input.timeframe( 'D' , '' , group=set , inline='6')
chc7 = input.string ('Lower' , '7'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='7')
len7 = input.int ( 20 , '' , group=set , inline='7')
mlt7 = input.float ( 2 , '' , group=set , inline='7')
res7 = input.timeframe( 'D' , '' , group=set , inline='7')
chc8 = input.string ('Swings' , '8'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='8')
len8 = input.int ( 20 , '' , group=set , inline='8')
mlt8 = input.float ( 2 , '' , group=set , inline='8')
res8 = input.timeframe( 'D' , '' , group=set , inline='8')
chc9 = input.string ('Fibonacci' , '9'
, options = ['NONE','SMA','Upper','Lower','Previous High','Previous Low','Swings','Fibonacci'] , group=set , inline='9')
len9 = input.int ( 20 , '' , group=set , inline='9')
mlt9 = input.float ( 2 , '' , group=set , inline='9')
res9 = input.timeframe( 'W' , '' , group=set , inline='9')
pick1 = input.bool (false , 'A' , group='show values', inline='1')
choice1 = input.int ( 1 , '' , minval=1, maxval=9, group='show values', inline='1')
pick2 = input.bool (false , 'B' , group='show values', inline='2')
choice2 = input.int ( 3 , '' , minval=1, maxval=9, group='show values', inline='2')
pick3 = input.bool (false , 'C' , group='show values', inline='3')
choice3 = input.int ( 5 , '' , minval=1, maxval=9, group='show values', inline='3')
pick4 = input.bool (false , 'D' , group='show values', inline='4')
choice4 = input.int ( 7 , '' , minval=1, maxval=9, group='show values', inline='4')
pick5 = input.bool (false , 'E' , group='show values', inline='5')
choice5 = input.int ( 9 , '' , minval=1, maxval=9, group='show values', inline='5')
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
type piv
int b
float p
type lab
label lb
float gr
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
n = bar_index
max = array.from(0.)
lab[] lab = array.new<lab>()
float[] aGrade = array.new<float>()
arrChoices = array.from(chc1, chc2, chc3, chc4, chc5, chc6, chc7, chc8, chc9)
var box top = box.new(na, na, na, na, bgcolor=color.new(color.red , 90), border_color=color(na), extend=extend.left)
var box btm = box.new(na, na, na, na, bgcolor=color.new(color.lime, 90), border_color=color(na), extend=extend.left)
var piv[] pivH = array.new<piv>()
var piv[] pivL = array.new<piv>()
var float highest = na
var float lowest = na
var int sBix = na
var float mxPiv = na
var float mnPiv = na
//-----------------------------------------------------------------------------}
//General Calculations
//-----------------------------------------------------------------------------{
fromR = opt == 'value'
ph = ta.pivothigh(left, right)
pl = ta.pivotlow (left, right)
if time == chart.left_visible_bar_time
highest := high
lowest := high
sBix := n
pivH.unshift(piv.new(n, high))
pivL.unshift(piv.new(n, high))
mxPiv := high
mnPiv := high
if time > chart.left_visible_bar_time
if high > highest
highest := high
if low < lowest
lowest := low
if time <= chart.right_visible_bar_time
if ph
if ph > mxPiv
mxPiv := ph
for i = pivH.size() -1 to 0
get = pivH.get(i)
if ph >= get.p
pivH.remove(i)
pivH.unshift(piv.new(n -right, ph))
if pl
if pl < mnPiv
mnPiv := pl
for i = pivL.size() -1 to 0
get = pivL.get(i)
if pl <= get.p
pivL.remove(i)
pivL.unshift(piv.new(n -right, pl))
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
isPP(get) => pp = get == 'Traditional' or get == 'Fibonacci' or get == 'Classic'
choiceIsPP(i) => get = arrChoices.get(i), isPP(get)
f(choice) =>
c = choice == 1 ? chc1 : choice == 2 ? chc2 : choice == 3 ? chc3 : choice == 4 ? chc4
: choice == 5 ? chc5 : choice == 6 ? chc6 : choice == 7 ? chc7 : choice == 8 ? chc8 : chc9
notPP = c != 'Fibonacci'
setLine(e, sBs, chc, len, res) =>
var float val = na
val := sBs
hl = chc == 'Previous High'
or chc == 'Previous Low'
htf = timeframe.in_seconds(res)
>= timeframe.in_seconds(timeframe.period)
tfChange = timeframe.change (res)
bsChange = ta.barssince (tfChange)
bars = hl and fromR ? math.min(last_bar_index - sBix, bsChange)
: last_bar_index - sBix
if time == chart.right_visible_bar_time and val <= highest and val >= lowest and htf
firstPos = sBs > close ? 'r' : 's' // 's/r' support or resistance at chart.right_visible_bar_time
pos = 1 // 1/0 -> 1 = same position as firstPos , 0 = diff pos
breaks = 0
switch firstPos
'r' =>
for i = 0 to bars // last_bar_index - sBix
v = hl ? val : fromR ? val[i] : val
if pos == 1 and close[i] > v
breaks += 1
pos := 0
if pos == 0 and close[i] < v
pos := 1
's' =>
for i = 0 to bars // last_bar_index - sBix
v = hl ? val : fromR ? val[i] : val
if pos == 1 and close[i] < v
breaks += 1
pos := 0
if pos == 0 and close[i] > v
pos := 1
isAbove = close > val
grade = math.min(100, math.round((100 / fade) * breaks))
max.set(0, math.max(max.get(0), grade))
col = color.new(
isAbove ?
colU
: colD
, grade)
chart = res == ''
s = chart ? 'chart' : res
line.new (n -1, val, n +8, val, color=col, extend=extend.left)
lab.unshift(lab.new(
label.new(n +8 + (e * 5), val, style=label.style_label_left, color=color(na)
, textcolor=col
, tooltip=str.format("Nยฐ{0} โ HTF: {1} \n{2}", e, s, chc) + (hl ? '' : ', len ' + str.tostring(len))
, size=size.small
, text= (chart ? '' : '(') + res + (chart ? '' : ')')
)
, grade
)
)
aGrade.unshift(grade)
calc(e, chc, len, mlt, res) =>
var arrPP = array.from( 0., 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. )
act = chc != 'NONE'
htf = timeframe.in_seconds(res) >= timeframe.in_seconds(timeframe.period)
var float bs = na, var float up = na, var float lo = na
ema1 = ta.ema(close, len)
ema2 = ta.ema(ema1 , len)
ema3 = ta.ema(ema2 , len)
if htf
bs := switch chc
'SMA' => ta.sma(close, len)
"Swings" => na
"Previous High" => high
"Previous Low" => low
=>
[b, u, l] = ta.bb(close, len, mlt)
switch chc
'Upper' => u
'Lower' => l
=> na
sBs = htf ? request.security(syminfo.tickerid, res, act ? bs[1] : na, lookahead=barmerge.lookahead_on) : na
if act
pp = isPP(chc)
st = chc == 'Fibonacci' ? 'Fib.' : chc
switch
pp and htf =>
var arStr = array.from('P', 'R1', 'S1', 'R2', 'S2', 'R3', 'S3', 'R4', 'S4', 'R5', 'S5')
tfChange = timeframe.change(res)
bsChange = ta.barssince(tfChange)
pivotPointsArray = ta.pivot_point_levels(chc, timeframe.change(res))
if tfChange
for i = 0 to pivotPointsArray.size() -1
arrPP.set(i, pivotPointsArray.get(i))
if time == chart.right_visible_bar_time
for i = 0 to arrPP.size() -1
p = arrPP.get(i)
if p <= highest and p >= lowest
firstPos = p > close ? 'r' : 's' // 's/r' support or resistance at chart.left_visible_bar_time
pos = 1 // 1/0 -> 1 = same position as firstPos , 0 = diff pos
breaks = 0
bars = fromR ? math.min(last_bar_index - sBix, bsChange)
: last_bar_index - sBix
switch firstPos
'r' =>
for d = 0 to bars
if pos == 1 and close[d] > p
breaks += 1
pos := 0
if pos == 0 and close[d] < p
pos := 1
's' =>
for d = 0 to bars
if pos == 1 and close[d] < p
breaks += 1
pos := 0
if pos == 0 and close[d] > p
pos := 1
isAbove = close > p
chart = res == ''
s = chart ? 'chart' : res
grade = math.min(100, math.round((100 / fade) * breaks))
max.set(0, math.max(max.get(0), grade))
col =
color.new(
isAbove ?
colU
: colD
, grade)
line.new(n -1, p, n +8, p
, color=col, extend=extend.left)
lab.unshift(lab.new(
label.new(n +8 + (e * 5), p, color=color(na)
, tooltip=str.format("Nยฐ{0} โ HTF: {1} \n{2} ({3})"
, e , s , arStr.get(i) , st )
, style=label.style_label_left
, size=size.small
, textcolor=col
, text= (chart ? '' : '(') + res + (chart ? '' : ')')
)
, grade
)
)
aGrade.unshift(grade)
chc != 'Swings' and htf => setLine(e, sBs, chc, len, res)
chc == 'Swings' => // Swings
if time == chart.right_visible_bar_time
for i = 0 to pivH.size() -1
p = pivH.get(i)
if p.p <= highest and p.p >= lowest
pos = 1
breaks = 0
//only 'line', otherwise 0 breaks (if breaks, Swings would not be included)
for d = 0 to last_bar_index - sBix
if pos == 1 and close[d] > p.p
breaks += 1
pos := 0
if pos == 0 and close[d] < p.p
pos := 1
grade = math.min(100, math.round((100 / fade) * breaks))
max.set(0, math.max(max.get(0) , grade))
line.new(n -1, p.p, n +8, p.p
, color=color.new(colD, grade), extend=extend.left)
lab.unshift(lab.new(
label.new(n +8 + (e * 5), p.p, color=color(na)
, tooltip= 'Nยฐ' + str.tostring(e) + ' Swings'
, style=label.style_label_left
, size=size.small
, textcolor=color.new(colD, grade)
, text= ''
)
, grade
)
)
aGrade.unshift(grade)
for i = 0 to pivL.size() -1
p = pivL.get(i)
if p.p <= highest and p.p >= lowest
pos = 1
breaks = 0
//only 'line', otherwise 0 breaks (if breaks, Swings would not be included)
for d = 0 to last_bar_index - sBix
if pos == 1 and close[d] < p.p
breaks += 1
pos := 0
if pos == 0 and close[d] > p.p
pos := 1
grade = math.min(100, math.round((100 / fade) * breaks))
max.set(0, math.max(max.get(0) , grade))
line.new(n -1, p.p, n +8, p.p
, color=color.new(colU, grade), extend=extend.left)
lab.unshift(lab.new(
label.new(n +8 + (e * 5), p.p, color=color(na)
, tooltip= 'Nยฐ' + str.tostring(e) + ' Swings'
, style=label.style_label_left
, size=size.small
, textcolor=color.new(colU, grade)
, text= ''
)
, grade
)
)
aGrade.unshift(grade)
[sBs, arrPP]
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
e = 1
[sBs1, arrPP1] = calc(e, chc1 , len1 , mlt1 , res1 ), e +=1
[sBs2, arrPP2] = calc(e, chc2 , len2 , mlt2 , res2 ), e +=1
[sBs3, arrPP3] = calc(e, chc3 , len3 , mlt3 , res3 ), e +=1
[sBs4, arrPP4] = calc(e, chc4 , len4 , mlt4 , res4 ), e +=1
[sBs5, arrPP5] = calc(e, chc5 , len5 , mlt5 , res5 ), e +=1
[sBs6, arrPP6] = calc(e, chc6 , len6 , mlt6 , res6 ), e +=1
[sBs7, arrPP7] = calc(e, chc7 , len7 , mlt7 , res7 ), e +=1
[sBs8, arrPP8] = calc(e, chc8 , len8 , mlt8 , res8 ), e +=1
[sBs9, arrPP9] = calc(e, chc9 , len9 , mlt9 , res9 ), e +=1
arrVal = array.from(
sBs1, sBs2, sBs3, sBs4, sBs5, sBs6, sBs7, sBs8, sBs9
)
if time == chart.right_visible_bar_time
top.set_lefttop (n -1, highest)
top.set_rightbottom(n +8, highest - ((highest - lowest) / 20))
btm.set_lefttop (n -1, lowest + ((highest - lowest) / 20))
btm.set_rightbottom(n +8, lowest )
sz = lab.size(), arr = aGrade.copy(), arr.sort(), aSz = arr.size()
// sort + rank ~ grade
if aSz > 1
lastValue = arr.get(aSz -1)
for j = arr.size() -2 to 0
if arr.get(j) == lastValue
arr.remove(j)
lastValue := arr.get(j)
// set label (grade)
if sz > 1
for i = 0 to sz -1
get = lab.get(i)
get.lb.set_text(str.tostring(arr.indexof(get.gr) + 1) + ' ' + get.lb.get_text())
// Make Swings visible
if showPP
for i = 0 to pivH.size() -1
label.new(pivH.get(i).b, pivH.get(i).p, style=label.style_label_right, size=size.tiny)
l = line.new(pivH.get(i).b, pivH.get(i).p, n +8, pivH.get(i).p)
for i = 0 to pivL.size() -1
label.new(pivL.get(i).b, pivL.get(i).p, style=label.style_label_right, size=size.tiny)
l = line.new(pivL.get(i).b, pivL.get(i).p, n +8, pivL.get(i).p)
//-----------------------------------------------------------------------------}
//Plot Functions
//-----------------------------------------------------------------------------{
pickArrPP(i, f) =>
out =
i == 1 ? arrPP1.get(f) :
i == 2 ? arrPP2.get(f) :
i == 3 ? arrPP3.get(f) :
i == 4 ? arrPP4.get(f) :
i == 5 ? arrPP5.get(f) :
i == 6 ? arrPP6.get(f) :
i == 7 ? arrPP7.get(f) :
i == 8 ? arrPP8.get(f) :
arrPP9.get(f)
plots(pick, choice) =>
p1 = pick ? not choiceIsPP(choice -1) ? arrVal.get(choice -1) : pickArrPP(choice, 0 ) : na
p2 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 1 ) : na
p3 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 2 ) : na
p4 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 3 ) : na
p5 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 4 ) : na
p6 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 5 ) : na
p7 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 6 ) : na
p8 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 7 ) : na
p9 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 8 ) : na
p10 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 9 ) : na
p11 = pick ? not choiceIsPP(choice -1) ? na : pickArrPP(choice, 10) : na
[p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11]
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
[plotA1, plotA2, plotA3, plotA4, plotA5, plotA6, plotA7, plotA8, plotA9, plotA10, plotA11] = plots(pick1, choice1)
[plotB1, plotB2, plotB3, plotB4, plotB5, plotB6, plotB7, plotB8, plotB9, plotB10, plotB11] = plots(pick2, choice2)
[plotC1, plotC2, plotC3, plotC4, plotC5, plotC6, plotC7, plotC8, plotC9, plotC10, plotC11] = plots(pick3, choice3)
[plotD1, plotD2, plotD3, plotD4, plotD5, plotD6, plotD7, plotD8, plotD9, plotD10, plotD11] = plots(pick4, choice4)
[plotE1, plotE2, plotE3, plotE4, plotE5, plotE6, plotE7, plotE8, plotE9, plotE10, plotE11] = plots(pick5, choice5)
plot(plotA1 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , display=display.pane)
plot(plotA2 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA3 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA4 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA5 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA6 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA7 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA8 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA9 , 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA10, 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotA11, 'A', style= f(choice1) ? plot.style_line : plot.style_circles, color=color.blue , editable=false, display=display.pane)
plot(plotB1 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, display=display.pane)
plot(plotB2 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB3 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB4 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB5 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB6 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB7 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB8 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB9 , 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB10, 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotB11, 'B', style= f(choice2) ? plot.style_line : plot.style_circles, color=color.yellow, editable=false, display=display.pane)
plot(plotC1 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, display=display.pane)
plot(plotC2 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC3 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC4 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC5 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC6 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC7 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC8 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC9 , 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC10, 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotC11, 'C', style= f(choice3) ? plot.style_line : plot.style_circles, color=color.purple, editable=false, display=display.pane)
plot(plotD1 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, display=display.pane)
plot(plotD2 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD3 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD4 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD5 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD6 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD7 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD8 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD9 , 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD10, 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotD11, 'D', style= f(choice4) ? plot.style_line : plot.style_circles, color=color.orange, editable=false, display=display.pane)
plot(plotE1 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , display=display.pane)
plot(plotE2 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE3 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE4 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE5 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE6 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE7 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE8 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE9 , 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE10, 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
plot(plotE11, 'E', style= f(choice5) ? plot.style_line : plot.style_circles, color=color.white , editable=false, display=display.pane)
//-----------------------------------------------------------------------------} |
T3 JMA KAMA VWMA | https://www.tradingview.com/script/pycr0zpy-T3-JMA-KAMA-VWMA/ | simwai | https://www.tradingview.com/u/simwai/ | 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/
// ยฉ simwai
//@version=5
indicator('T3 JMA KAMA VWMA', shorttitle='C_VWMA', overlay=true)
// C_ -> Custom
// -- Inputs --
string indicatorMaType = input.string(defval='T3', title='Choose MA', options=['KAMA', 'T3', 'JMA'], group='General', inline='1')
string resolution = input.timeframe('', 'Choose Resolution', group='General', inline='2')
int length = input.int(3, 'Length', group='General', inline='2')
float t3Hot = input.float(title='T3 โ Smoothing Factor (hot)', defval=0.5, step=0.1, minval=0.00001, group='General', inline='2')
string t3Type = input.string(title='T3 โ Type', defval='T3 New', options=['T3 Normal', 'T3 New'], group='General', inline='2')
int jmaPhase = input.int(title='JMA โ Phase', defval=50, minval=-100, maxval=100, tooltip='The phase is used to shift the input data before applying the smoothing algorithm. The phase shift can help to identify the turning points of the data.', group='General', inline='3')
int jmaPower = input.int(title='JMA โ Power', defval=2, minval=2, tooltip='The power is used to adjust the sensitivity of the JMA to changes in the input data. Higher values of the power will make the JMA more sensitive to changes in the data.', group='General', inline='3')
// -- Colors --
color myGreen = color.rgb(0, 183, 165)
color myPurple = color.rgb(172, 78, 255)
// -- Global State --
[_close, _volume, _high, _low] = request.security(syminfo.tickerid, resolution, expression=[close[1], volume[1], high[1], low[1]], lookahead=barmerge.lookahead_on, gaps=barmerge.gaps_off)
// -- Functions --
tr() =>
math.max(math.max(_high - _low, math.abs(_high - _close[1])), math.abs(_low - _close[1]))
// Jurik Moving Average (JMA) - Credits to @everget
jma(float _src, int _length, int _phase=50, int _power=2) =>
phaseRatio = _phase < -100 ? 0.5 : _phase > 100 ? 2.5 : _phase / 100 + 1.5
beta = 0.45 * (_length - 1) / (0.45 * (_length - 1) + 2)
alpha = math.pow(beta, _power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * _src + alpha * nz(e0[1])
e1 = 0.0
e1 := (_src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
// Kaufman's Adaptive Moving Average (KAMA)
kama(float _src, int _period) =>
if (bar_index > _period)
tmpVal = 0.0
tmpVal := nz(tmpVal[1]) + math.pow(((math.sum(math.abs(_src - _src[1]), _period) != 0) ? (math.abs(_src - _src[_period]) / math.sum(math.abs(_src - _src[1]), _period)) : 0) * (0.666 - 0.0645) + 0.0645, 2) * (_src - nz(tmpVal[1]))
tmpVal
// T3 - Credits to @loxx
t3(float _src, float _length, float hot=1, string clean='T3')=>
a = hot
_c1 = -a * a * a
_c2 = 3 * a * a + 3 * a * a * a
_c3 = -6 * a * a - 3 * a - 3 * a * a * a
_c4 = 1 + 3 * a + a * a * a + 3 * a * a
alpha = 0.
if (clean == 'T3 New')
alpha := 2.0 / (2.0 + (_length - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + _length)
_t30 = _src, _t31 = _src
_t32 = _src, _t33 = _src
_t34 = _src, _t35 = _src
_t30 := nz(_t30[1]) + alpha * (_src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
// Volume Weighted Custom Moving Averages
t3Vwma(float _src, float _volume, int _period, float _t3Hot=0.5, _t3Type='T3 Normal') =>
t3(_src * _volume, _period, _t3Hot, _t3Type) / t3(_volume, _period, _t3Hot, _t3Type)
jmaVwma(float _src, float _volume, int _period, int _phase=50, int _power=2) =>
jma(_src * _volume, _period, _phase, _power) / jma(_volume, _period, _phase, _power)
kamaVwma(float _src, float _volume, int _period) =>
kama(_src * _volume, _period) / kama(_volume, _period)
// Hann Window Smoothing โ Credits to @cheatcountry
doHannWindow(float _series, float _hannWindowLength) =>
sum = 0.0, coef = 0.0
for i = 1 to _hannWindowLength
cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1))
sum := sum + (cosine * nz(_series[i - 1]))
coef := coef + cosine
h = coef != 0 ? sum / coef : 0
atr(atrLength) =>
float tr = tr()
// jma(tr, atrLength)
doHannWindow(tr, atrLength)
normalize(float _src, int _min, int _max) =>
var float _historicMin = 1.0
var float _historicMax = -1.0
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1)
angle(_src) =>
rad2degree=180/3.14159265359 //pi
ang=rad2degree*math.atan((_src[0] - _src[1])/atr(14))
nAngle = normalize(ang, 0, 1)
nAngle
// -- Calculation --
t3Vwma = t3Vwma(_close, _volume, length, t3Hot, t3Type)
jmaVwma = jmaVwma(_close, _volume, length)
kamaVwma = kamaVwma(_close, _volume, length)
float myVwma = switch indicatorMaType
'T3' => t3Vwma
'JMA' => jmaVwma
'KAMA' => kamaVwma
maAngle = angle(myVwma)
angleGradient = color.from_gradient(maAngle, 0.1, 0.9, myPurple, myGreen)
plot(myVwma, 'C_VWMA', linewidth=2, color=angleGradient)
barcolor(maAngle > 0.7 ? myGreen : maAngle < 0.3 ? myPurple : color.new(color.silver, 25)) |
Machine Learning : Cosine Similarity & Euclidean Distance | https://www.tradingview.com/script/uD5oLgFB-Machine-Learning-Cosine-Similarity-Euclidean-Distance/ | chhagansinghmeena | https://www.tradingview.com/u/chhagansinghmeena/ | 981 | 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/
// ยฉ chhagansinghmeena
//@version=5
indicator("Machine Learning : Cosine Similarity & Euclidean + Lorentzian Distance", overlay=true)
import chhagansinghmeena/BankNifty_CSM/16 as CSM
//====================================== Thanks to JDEHORTY For coding structure ==========//
//========== Here i am using similar coding structure that JDEHORTY used in his script =========//
//=============== There are some piece of code is similar to JDEHORTY script, Gratitude to him =============//
//===============================================================================================//
//============== For Customization Thanks to LUX ALGO idea taken from one of his script ===========
//This function appears to calculate the weighted average of a series (_src) using a rational quadratic weighting scheme.
//It iterates over the elements of _src, assigning a weight (w) to each element based on its index and the provided parameters (_lookback and _relativeWeight).
// The weighted average is then calculated and returned as rationalQuad.
// Function to calculate the rational quadratic value based on input parameters
// Parameters:
// - _src: Input series
// - _lookback: Lookback period for calculating weights
// - _relativeWeight: Relative weight factor
// - startAtBar: Starting index for the loop (default: 0)
// Returns:
// - Rational quadratic value based on the calculations
rationalQuadratic(_src, _lookback, _relativeWeight, startAtBar) =>
_currentWeight = 0.0 // Initialize the current weight variable
_cumulativeWeight = 0.0 // Initialize the cumulative weight variable
_size = array.size(array.from(_src)) // Get the size of the input series
for i = 0 to _size + startAtBar // Iterate over the input series
y = _src[i] // Get the value at index i
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight) // Calculate the weight using the rational quadratic formula
_currentWeight += y * w // Add the weighted value to the current weight
_cumulativeWeight += w // Add the weight to the cumulative weight
rationalQuad = _currentWeight / _cumulativeWeight // Calculate the rational quadratic value
rationalQuad
//Linear interpolation involves finding a proportional value within a range based on the relative position of the original value.
// Function to perform linear interpolation on a series
// Parameters:
// - src: Input series for interpolation
// - oldMax: Maximum value of the original range
// - lookback: Number of bars to look back for calculating the minimum value (default: 100)
// Returns:
// - Interpolated values based on the relative position in the range
get_Linear_interpolation(series float src, float oldMax , simple int lookback=100) =>
minVal = ta.lowest(src,lookback)
(src - minVal) / (oldMax - minVal)
// Function to calculate get_linear_transformationd RSI using linear interpolation
// Parameters:
// - src: Input series for RSI calculation
// - n1: Lookback period for RSI calculation
// - n2: Lookback period for EMA smoothing of RSI
// Returns:
// - get_linear_transformationd RSI value using linear interpolation
n_rsi(series float src, simple int n1, simple int n2) =>
get_Linear_interpolation(ta.ema(ta.rsi(src, n1), n2),100)
// The purpose of this code is to provide a function that calculates the KST line, which is a technical indicator used in financial analysis to identify potential trend reversals and generate trading signals.
// Function to calculate the KST (Know Sure Thing) line based on the input series
// Parameters:
// - src: Input series
// Returns:
// - KST line calculated using the input series
calc_kst(series float src) =>
// Define the lengths for rate of change (ROC) calculations
lengthROC1 = 10, lengthROC2 = 15, lengthROC3 = 20, lengthROC4 = 30
// Calculate the rate of change (ROC) for each length
roc1 = ta.change(src, lengthROC1), roc2 = ta.change(src, lengthROC2), roc3 = ta.change(src, lengthROC3), roc4 = ta.change(src, lengthROC4)
// Apply smoothing to the ROC values
smoothed1 = ta.sma(roc1, 3), smoothed2 = ta.sma(roc2, 3), smoothed3 = ta.sma(roc3, 3), smoothed4 = ta.sma(roc4, 3)
// Calculate the KST line
kstLine = smoothed1 + 2 * smoothed2 + 3 * smoothed3 + 4 * smoothed4
// Calculate the RSI (Relative Strength Index) of the KST line with a length of 14
rsiKST = ta.rsi(kstLine, 14)
rsiKST
// Function to perform a linear transformation on a series based on historical minimum and maximum values
// Purpose: The purpose of this code is to perform a linear transformation on a given series (src) based on the historical minimum and maximum values within a specified lookback period.
// Parameters:
// - src: Input series to be transformed (default: close)
// - min: Minimum value of the new range
// - max: Maximum value of the new range
// - lookback: Number of bars to consider for calculating historical minimum and maximum (default: 200)
// Returns:
// - Transformed series based on the linear transformation
get_linear_transformation(series float src = close, float min, float max, int lookback = 200) =>
// Calculate the historical minimum and maximum values within the lookback period
_historicMin = ta.highest(nz(src), lookback)
_historicMax = ta.lowest(nz(src), lookback)
// Perform the linear transformation calculation using the formula
linearValue = min + (max - min) * (src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
// Return the transformed series
linearValue
// new approach to calculate more realistic and accurate quarditic calculation
// Purpose: Perform a sigmoidal transformation on a series based on the provided parameters
// Parameters:
// - src: The input series to be transformed
// - lookback: The number of bars to consider for the sigmoid calculation (default: 20)
// - relativeWeight: The relative weight factor for the sigmoid calculation (default: 8)
// - startAtBar: The starting bar index for the calculation (default: 25)
// Returns: The transformed value after applying the sigmoidal transformation
sigmoid(series float src, int lookback = 20, float relativeWeight = 8, int startAtBar = 25) =>
_currentWeight = 0.0
_cumulativeWeight = 0.0
_size = ta.barssince(startAtBar) + 1
for i = _size to math.max(startAtBar, lookback + startAtBar) - 1
y = src[i]
w = math.pow(1 + (math.pow(i - startAtBar, 2) / (math.pow(lookback, 2) * 2 * relativeWeight)), -relativeWeight)
_currentWeight += y * w
_cumulativeWeight += w
sigmoidValue = _currentWeight / _cumulativeWeight
sigmoidValue
// Calculate MACD
// Purpose: Calculate the MACD (Moving Average Convergence Divergence) value based on the input series
// Parameters:
// src: The input series for which to calculate the MACD (default: close)
// Returns: The MACD value
macd(series float src = close) =>
[macdLine, signalLine, _] = ta.macd(src, 12, 26, 9)
// Calculate the linear transformation of the MACD line
ma = get_linear_transformation(macdLine, 14, 1)
// Calculate the linear transformation of the signal line
sa = get_linear_transformation(signalLine, 14, 1)
// Average the transformed MACD and signal lines
macd_val = math.avg(ma, sa)
macd_val
// Define input parameters
historyLookBack = input.int(title='History Lookback', defval=2000, group='General Settings', tooltip='Number of historical periods to consider for analysis.')
nearest_Probable_Distance = input.int(title='Nearest Probable Distance', defval=8, group='General Settings', tooltip='The closest distance to consider when determining probable values.')
dash_loc = input.session("Top Right", "Stats Location", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right", "Bottom Center"], group='General Settings', inline="Stats Location", tooltip='The position of the statistics display on the chart.')
text_size = input.session('Small', "Stats Size", options=["Tiny", "Small", "Normal", "Large"], group='General Settings', inline="Stats Location", tooltip='The size of the text used for the statistics display.')
trenSelection = input.string(title='Moving Average Selection', options=['CPMA', 'FRMA', 'RationalQuad'], defval='RationalQuad', group='Moving Averages', tooltip='The type of moving average to use for trend analysis.')
cpmaLength = input.int(title="CPMA Length", defval=9, group='Moving Averages', tooltip='The length of the Centered Price Moving Average (CPMA) used for trend analysis.')
frmaLength = input.int(title="FRMA Length", defval=14, group='Moving Averages', tooltip='The length of the Fractal Adaptive Moving Average (FRMA) used for trend analysis.')
enableFilter = input.bool(title="Enable Trend Filter", defval=true, group='Filter', tooltip='Enable or disable the trend filter for signal processing, which provides greater accuracy.')
isRational = input.bool(title="Use Rational smoothing", defval=true, group='Filter', tooltip='Enable or disable the rational smoothing function for the selected moving average, used as a trend filter.')
isRationalSigma = input.bool(title="Use Sigmoid smoothing ", defval=true, group='Filter', tooltip='Enable or disable the sigmoid smoothing function, which works in conjunction with the rational smoothing function.')
methodSelection = input.string(title='Distance Calculation', options=['Lorentzian', 'Euclidean', 'Cosine similarity'], defval='Cosine similarity', group='Machine Learning : Methods', tooltip='The method used for calculating the distance similarity or dissimilarity when processing signals using machine learning techniques.')
start = input.time(title='Start Date', defval=timestamp('01 Jan 2023 03:30 +0000'), group='Backtesting', tooltip='The date and time to begin trading from during the backtesting period.')
finish = input.time(title='End Date', defval=timestamp('1 Jan 2099 15:30 +0000'), group='Backtesting', tooltip='The date and time to stop trading during the backtesting period.')
// Define variables for the position of the table and the text size
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
// Get CPMA(Conceptive Price Moving Average) and FRMA(Fractional Moving Average)
CPMA = CSM.CSM_CPMA(length = cpmaLength)
FRMA = CSM.frama_Calculation(close,length = frmaLength)
type FeatureArrays
array<float> f1
array<float> f2
array<float> f3
array<float> f4
array<float> f5
array<float> f6
type FeatureSeries
float f1
float f2
float f3
float f4
float f5
float f6
series_from(feature_string, _close, _high, _low, _hlc3, f_paramA, f_paramB) =>
switch feature_string
"RSI" => n_rsi(_close, f_paramA, f_paramB)
"KST" => get_Linear_interpolation(calc_kst(src = _close),100)
"CPMA"=> get_linear_transformation(CPMA,14,1)
"VWAP"=> get_linear_transformation(ta.vwap(_close),14,1)
"FRAMA"=> get_linear_transformation(FRMA,14,1)
"MACD"=> macd(_close)
featureSeries =
FeatureSeries.new(
series_from("CPMA", close, high, low, hlc3, 0, 0), // f1
series_from("RSI", close, high, low, hlc3, 14, 1), // f2
series_from("VWAP", close, high, low, hlc3, 0, 0), // f3
series_from("KST", close, high, low, hlc3, 0, 0), // f4
series_from("FRAMA", close, high, low, hlc3, 0, 0), // f5
series_from("MACD", close, high, low, hlc3, 0, 0) // f6
)
var f1Array = array.new_float()
var f2Array = array.new_float()
var f3Array = array.new_float()
var f4Array = array.new_float()
var f5Array = array.new_float()
var f6Array = array.new_float()
array.push(f1Array, featureSeries.f1)
array.push(f2Array, featureSeries.f2)
array.push(f3Array, featureSeries.f3)
array.push(f4Array, featureSeries.f4)
array.push(f5Array, featureSeries.f5)
array.push(f6Array, featureSeries.f6)
featureArrays =
FeatureArrays.new(
f1Array, // f1
f2Array, // f2
f3Array, // f3
f4Array, // f4
f5Array, // f5
f6Array // f6
)
// Calculate RQK value for historical data
rqkValue = isRationalSigma ? sigmoid(close) : rationalQuadratic(close, 8, 0.5, 25)
// Purpose: Calculate the Euclidean distance between a given feature series and the corresponding feature arrays at index 'i'.
// Parameters:
// i: The index at which to calculate the distance.
// featureSeries: An instance of the FeatureSeries structure containing feature values.
// featureArrays: An instance of the FeatureArrays structure containing arrays of feature values.
// Returns: The Euclidean distance between the feature series and feature arrays.
get_euclidean_distance(int i, FeatureSeries featureSeries, FeatureArrays featureArrays) =>
distance = 0.0
distance += math.pow(featureSeries.f1 - array.get(featureArrays.f1, i), 2)
distance += math.pow(featureSeries.f2 - array.get(featureArrays.f2, i), 2)
distance += math.pow(featureSeries.f4 - array.get(featureArrays.f4, i), 2)
distance += math.pow(featureSeries.f5 - array.get(featureArrays.f5, i), 2)
distance += math.pow(featureSeries.f6 - array.get(featureArrays.f6, i), 2)
if str.tonumber(timeframe.period) <= 20
distance += math.pow(featureSeries.f3 - array.get(featureArrays.f3, i), 2)
math.sqrt(distance)
// Purpose: Calculate the Lorentzian distance between a given feature series and the corresponding feature arrays at index 'i'.
// Lorentzian distance is a measure of dissimilarity between two vectors, considering the absolute difference between their corresponding elements.
// It is calculated as the sum of the logarithm of one plus the absolute difference for each feature.
// Use For: Comparing the dissimilarity between feature series and feature arrays in the context of trading signals or other applications.
// Parameters:
// i: The index at which to calculate the distance.
// featureSeries: An instance of the FeatureSeries structure containing feature values.
// featureArrays: An instance of the FeatureArrays structure containing arrays of feature values.
// Returns: The Lorentzian distance between the feature series and feature arrays.
// A higher value indicates higher dissimilarity, while a lower value indicates higher similarity.
get_lorentzian_distance(int i, FeatureSeries featureSeries, FeatureArrays featureArrays) =>
distance = 0.0
distance += math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i)))
distance += math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i)))
distance += math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i)))
distance += math.log(1+math.abs(featureSeries.f5 - array.get(featureArrays.f5, i)))
distance += math.log(1+math.abs(featureSeries.f6 - array.get(featureArrays.f6, i)))
if str.tonumber(timeframe.period) <= 20
distance += math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i)))
math.sqrt(distance)
// Purpose: Calculate the cosine similarity between a given feature series and the corresponding feature arrays at index 'i'.
// Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space.
// It measures the cosine of the angle between the vectors, indicating their directional similarity.
// The closer the cosine similarity value is to 1, the more similar the vectors are.
// Use For: Comparing the similarity between feature series and feature arrays in the context of trading signals or other applications.
// Parameters:
// i: The index at which to calculate the similarity.
// featureSeries: An instance of the FeatureSeries structure containing feature values.
// featureArrays: An instance of the FeatureArrays structure containing arrays of feature values.
// Returns: The cosine similarity between the feature series and feature arrays.
// A value close to 1 indicates high similarity, while a value close to 0 indicates low similarity or dissimilarity.
get_cosine_similarity(i, featureSeries, featureArrays) =>
dotProduct = 0.0
magnitudeSeries = 0.0
magnitudeArray = 0.0
dotProduct += featureSeries.f1 * array.get(featureArrays.f1, i)
dotProduct += featureSeries.f2 * array.get(featureArrays.f2, i)
dotProduct += featureSeries.f4 * array.get(featureArrays.f4, i)
dotProduct += featureSeries.f5 * array.get(featureArrays.f5, i)
dotProduct += featureSeries.f6 * array.get(featureArrays.f6, i)
magnitudeSeries += math.pow(featureSeries.f1, 2)
magnitudeSeries += math.pow(featureSeries.f2, 2)
magnitudeSeries += math.pow(featureSeries.f4, 2)
magnitudeSeries += math.pow(featureSeries.f5, 2)
magnitudeSeries += math.pow(featureSeries.f6, 2)
magnitudeArray += math.pow(array.get(featureArrays.f1, i), 2)
magnitudeArray += math.pow(array.get(featureArrays.f2, i), 2)
magnitudeArray += math.pow(array.get(featureArrays.f4, i), 2)
magnitudeArray += math.pow(array.get(featureArrays.f5, i), 2)
magnitudeArray += math.pow(array.get(featureArrays.f6, i), 2)
if str.tonumber(timeframe.period) <= 20
dotProduct += featureSeries.f3 * array.get(featureArrays.f3, i)
magnitudeSeries += math.pow(featureSeries.f3, 2)
magnitudeArray += math.pow(array.get(featureArrays.f3, i), 2)
magnitudeSeries := math.sqrt(magnitudeSeries)
magnitudeArray := math.sqrt(magnitudeArray)
if magnitudeSeries == 0.0 or magnitudeArray == 0.0
0.0
else
dotProduct / (magnitudeSeries * magnitudeArray)
// Purpose: Perform machine learning logic to calculate distances and predictions based on the selected method.
// Use For: Analyzing and predicting signals in trading or other applications using machine learning techniques.
maxBarsBackIndex = last_bar_index >= historyLookBack ? last_bar_index - historyLookBack : 0
src = close
y_train_series = src[4] < src[0] ? -1 : src[4] > src[0] ? 1 : 0
var y_train_array = array.new_int(0)
// Variables used for ML Logic
var predictions = array.new_float(0)
var prediction = 0.
var signal = 0
var distances = array.new_float(0)
array.push(y_train_array, y_train_series)
lastDistance = -1.0
size = math.min(historyLookBack-1, array.size(y_train_array)-1)
sizeLoop = math.min(historyLookBack-1, size)
// Purpose: Get the machine learning distance based on the selected method.
// Parameters:
// i: The index at which to calculate the distance.
// Returns: The distance value based on the selected method (Lorentzian, Euclidean, or Cosine).
get_ML_Distance(i) =>
switch
methodSelection == 'Lorentzian' => get_lorentzian_distance(i, featureSeries, featureArrays)
methodSelection == 'Euclidean' => get_euclidean_distance(i, featureSeries, featureArrays)
methodSelection == 'Cosine similarity' => get_cosine_similarity(i, featureSeries, featureArrays)
// Purpose: Perform machine learning logic to calculate distances and predictions based on the selected method.
// Use For: Analyzing and predicting signals in trading or other applications using machine learning techniques.
// Parameters: None
// Returns: None
if bar_index >= maxBarsBackIndex
for i = 0 to sizeLoop
d = get_ML_Distance(i)
// Compare the distance with the last recorded distance and check if the index is divisible by 4.
if d >= lastDistance and i % 4
lastDistance := d
// Store the distance and corresponding prediction in arrays.
array.push(distances, d)
array.push(predictions, math.round(array.get(y_train_array, i)))
// Check if the number of predictions exceeds the desired count.
if array.size(predictions) > nearest_Probable_Distance
// Update the last recorded distance to account for the shifting of arrays.
lastDistance := array.get(distances, math.round(nearest_Probable_Distance * 3 / 4))
// Remove the oldest distance and prediction from the arrays.
array.shift(distances)
array.shift(predictions)
// Calculate the final prediction by summing up the predictions.
prediction := array.sum(predictions)
// Purpose: Get the trend value based on the selected trend selection method.
// Returns: The calculated trend value.
getTrend() =>
switch
trenSelection == 'CPMA' => isRational ? isRationalSigma ? sigmoid(CPMA) : rationalQuadratic(CPMA, 8, 0.5, 25) : CPMA
trenSelection == 'FRMA' => isRational ? isRationalSigma ? sigmoid(FRMA) : rationalQuadratic(FRMA, 8, 0.5, 25) : FRMA
trenSelection == 'RationalQuad' => rqkValue
trend = getTrend()
// Determine if the current price is bullish or bearish relative to the trend.
bool isBullishSmooth = close >= trend
bool isBearishSmooth = close <= trend
// Get the gradient color and plot the trend line.
[avgrationalQuad, plotColor] = CSM.getGradientColor(isFirstbar = barstate.isfirst, src = trend, length = trenSelection == 'CPMA' ? cpmaLength : trenSelection == 'FRMA' ? frmaLength : 14, isSmoothed = false)
plot(avgrationalQuad, color=plotColor, linewidth=2, title="Trend")
// Filtered Signal: The model's prediction of future price movement direction with user-defined filters applied
signal := prediction > 0 and (enableFilter ? isBullishSmooth : true) ? 1 : prediction < 0 and (enableFilter ? isBearishSmooth : true) ? -1 : nz(signal[1])
// Check if the signal type has changed
isDifferentSignalType = ta.change(signal)
// Check if there is an early signal flip
isEarlySignalFlip = ta.change(signal) and (ta.change(signal[1]) or ta.change(signal[2]) or ta.change(signal[3]))
// Check if the signal indicates a buy
isBuySignal = signal == 1
// Check if the signal indicates a sell
isSellSignal = signal == -1
// Check if a new buy signal has occurred with a different signal type
isNewBuySignal = isBuySignal and isDifferentSignalType
// Check if a new sell signal has occurred with a different signal type
isNewSellSignal = isSellSignal and isDifferentSignalType
// Purpose: Get the color associated with a prediction value.
// Parameters:
// prediction: The prediction value for which to retrieve the color.
// Returns: An array containing the color and index associated with the prediction value.
get_PredictionColor(prediction) =>
arrColor = array.new_color(0)
array.push(arrColor, #FF0000) // 0
array.push(arrColor, #FF1000) // 1
array.push(arrColor, #FF2000) // 2
array.push(arrColor, #FF3000) // 3
array.push(arrColor, #FF4000) // 4
array.push(arrColor, #FF5000) // 5
array.push(arrColor, #FF6000) // 6
array.push(arrColor, #FF7000) // 7
array.push(arrColor, #FF8000) // 8
array.push(arrColor, #FF9000) // 9
array.push(arrColor, #0AAA00) // 10
array.push(arrColor, #1BBB10) // 11
array.push(arrColor, #2CCC20) // 12
array.push(arrColor, #3DDD30) // 13
array.push(arrColor, #5EEE50) // 14
array.push(arrColor, #6FFF60) // 15
array.push(arrColor, #7ABF70) // 16
array.push(arrColor, #8BCF80) // 17
array.push(arrColor, #9CDF90) // 18
array.push(arrColor, #90DFF9) // 19
distVal = prediction >= 10 or prediction <= -10 ? isNewSellSignal ? -10 : 9 : prediction
index = int(distVal + 10)
predictColor = array.get(arrColor, index)
[predictColor, index]
[predictColor, index] = get_PredictionColor(prediction) // Retrieve the color and index based on the prediction value
plotshape(isNewBuySignal ? low : na, 'Buy', shape.labelup, location.belowbar, color=predictColor, size=size.small, offset=0) // Plot a 'Buy' label shape with the predicted color
plotshape(isNewSellSignal ? high : na, 'Sell', shape.labeldown, location.abovebar, color=predictColor, size=size.small, offset=0) // Plot a 'Sell' label shape with the predicted color
// Function: window
// Purpose: Check if the current time is within the specified start and finish time range.
// Returns: True if the current time is within the range, false otherwise.
window() =>
time >= start and time <= finish ? true : false
longSignal = false
shortSignal = false
if window()
longSignal := isNewBuySignal // Set longSignal to the value of isNewBuySignal if the current time is within the window
shortSignal := isNewSellSignal // Set shortSignal to the value of isNewSellSignal if the current time is within the window
lastSignalWasBullish = ta.barssince(longSignal) < ta.barssince(shortSignal) // Check if the last signal was bullish
lastSignalWasBearish = ta.barssince(shortSignal) < ta.barssince(longSignal) // Check if the last signal was bearish
barsSinceRedEntry = ta.barssince(shortSignal) // Count the number of bars since the last short entry signal
barsSinceRedExit = ta.barssince(isBullishSmooth) // Count the number of bars since the last bearish exit signal
barsSinceGreenEntry = ta.barssince(longSignal) // Count the number of bars since the last long entry signal
barsSinceGreenExit = ta.barssince(isBearishSmooth) // Count the number of bars since the last bullish exit signal
isValidShortExit = barsSinceRedExit > barsSinceRedEntry // Check if the current short exit signal is valid
isValidLongExit = barsSinceGreenExit > barsSinceGreenEntry // Check if the current long exit signal is valid
endLongTradeDynamic = (isBullishSmooth and isValidLongExit[1]) // Check if the current condition indicates the end of a long trade
endShortTradeDynamic = (isBearishSmooth and isValidShortExit[1]) // Check if the current condition indicates the end of a short trade
// Function: winRate
// Purpose: Calculate the win rate percentage based on the number of winning trades and total trades.
// Parameters:
// winTrades: The number of winning trades.
// totalTrades: The total number of trades.
// Returns: The win rate percentage.
winRate(winTrades, totalTrades) => winTrades / totalTrades * 100
// Function: winRatio
// Purpose: Calculate the win-loss ratio percentage based on the number of winning trades and losing trades.
// Parameters:
// winTrades: The number of winning trades.
// lossTrades: The number of losing trades.
// Returns: The win-loss ratio percentage.
winRatio(winTrades, lossTrades) => winTrades / (winTrades + lossTrades) * 100
//====================================== Thanks to JDEHORTY For the backtesting approach==========//
//===============================================================================================//
// Function: backtest
// Purpose: Perform the backtesting calculations and return trade statistics.
// Parameters:
// high, low, open: Price data inputs for the backtest.
// startLongTrade, endLongTrade, startShortTrade, endShortTrade, isEarlySignalFlip: Signals and flags for the trades.
// maxBarsBackIndex, thisBarIndex: Bar index data for backtesting.
// src: Source data for market price.
// useWorstCase: Flag to determine if worst-case scenario should be considered for market price.
// window: Flag to indicate if the current time is within the specified window.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isEarlySignalFlip, maxBarsBackIndex, thisBarIndex, src, useWorstCase, window) =>
marketPrice = useWorstCase ? src : (high + low + open + open) / 4
var float start_long_trade = na
var float start_short_trade = na
var float total_long_profit = 0.0
var float total_short_profit = 0.0
var int wins = 0
var int losses = 0
var int trade_count = 0
var int early_signal_flip_count = 0
var bool tookProfit = false
lot_size = 1
if window
trade_count := 0
wins := 0
losses := 0
early_signal_flip_count := 0
if startLongTrade
start_short_trade := na
early_signal_flip_count := isEarlySignalFlip ? 1 : 0
start_long_trade := marketPrice
trade_count := 1
if endLongTrade
delta = marketPrice - start_long_trade
wins := delta > 0 ? 1 : 0
losses := delta < 0 ? 1 : 0
total_long_profit := delta * lot_size
if startShortTrade
start_long_trade := na
start_short_trade := marketPrice
trade_count := 1
if endShortTrade
early_signal_flip_count := isEarlySignalFlip ? 1 : 0
delta = start_short_trade - marketPrice
wins := delta > 0 ? 1 : 0
losses := delta < 0 ? 1 : 0
total_short_profit := delta * lot_size
tradeStatsHeader = "๐ CSM Strategy Stats (Assumption)"
longProfit = ta.cum(total_long_profit)
shortProfit = ta.cum(total_short_profit)
longShortProfit = longProfit + shortProfit
totalEarlySignalFlips = ta.cum(early_signal_flip_count)
totalWins = ta.cum(wins)
totalLosses = ta.cum(losses)
totalTrades = ta.cum(wins + losses)
winLossRatio = totalWins / totalTrades
winRate = totalWins / (totalWins + totalLosses)
[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate]
// Perform the backtest and store the trade statistics
[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate] = backtest(high, low, open, longSignal, endLongTradeDynamic, shortSignal, endShortTradeDynamic, isEarlySignalFlip, maxBarsBackIndex, bar_index, trend, false, window())
// The following can be used to display real-time trade stats. This can be a useful mechanism for obtaining real-time feedback during Feature Engineering. This does NOT replace the need to properly backtest.
// Note: In this context, a "Stop-Loss" is defined instances where the ML Signal prematurely flips directions before an exit signal can be generated.
//[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate] = ml.backtest(high, low, open, longSignal, endLongTradeDynamic, shortSignal, endShortTradeDynamic, isEarlySignalFlip, maxBarsBackIndex, bar_index, trend, false)
// Plotting the trade statistics in a table
tableData2 = table.new(table_position, columns=2, rows=7, frame_color=color.new(color.black, 100), frame_width=1, border_width=1, border_color= color.new(color.black, 100))
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winRate, stopLosses) =>
c_transparent = color.new(color.black, 100)
table.cell(tbl, 0, 0, tradeStatsHeader, text_halign=text.align_center, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 0, 1, 'Winrate', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 1, 1, str.tostring(totalWins / totalTrades, '#.#%'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 0, 2, 'Trades', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 1, 2, str.tostring(totalTrades, '#') + ' (' + str.tostring(totalWins, '#') + '|' + str.tostring(totalLosses, '#') + ')', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 0, 5, 'WL Ratio', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 1, 5, str.tostring(totalWins / totalLosses, '0.00'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 0, 6, 'Early Signal Flips', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
table.cell(tbl, 1, 6, str.tostring(totalEarlySignalFlips, '#'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.teal, text_size=table_text_size)
if barstate.islast
update_table(tableData2, tradeStatsHeader, totalTrades, totalWins, totalLosses, winRatio(totalWins,totalTrades), winRate(totalWins,totalLosses), totalEarlySignalFlips)
|
Sticky Notes v1.0 [NL] | https://www.tradingview.com/script/aE5qLEoR-Sticky-Notes-v1-0-NL/ | nikola_nl | https://www.tradingview.com/u/nikola_nl/ | 7 | 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=Nikola Lazic
//@version=5
indicator("Sticky Notes v1.0 [NL]", shorttitle = "Notes", overlay = true)
// Sentence input
sentence01 = input.string("First sentence", title = "Sentence 1", group = "Sentences")
sentence02 = input.string("Second sentence", title = "Sentence 2", group = "Sentences")
sentence03 = input.string("Third sentence", title = "Sentence 3", group = "Sentences")
sentence04 = input.string("Fourth sentence", title = "Sentence 4", group = "Sentences")
sentence05 = input.string("Fifth sentence", title = "Sentence 5", group = "Sentences")
sentence06 = input.string("Sixth sentence", title = "Sentence 6", group = "Sentences")
sentence07 = input.string("Seventh sentence", title = "Sentence 7", group = "Sentences")
sentence08 = input.string("Eighth sentence", title = "Sentence 8", group = "Sentences")
sentence09 = input.string("Ninth sentence", title = "Sentence 9", group = "Sentences")
sentence10 = input.string("Tenth sentence", title = "Sentence 10", group = "Sentences")
// Sticky Note Settings Input
tl1 = input.string("middle", title = "Note Position", options = ["top", "middle", "bottom"], group = "Sticky Note Settings", inline = "1")
tl2 = input.string("right", title = "", options = ["left", "center", "right"], group = "Sticky Note Settings", inline = "1")
note_color = input.color(color (#e6b905), title = "Note Color", group = "Sticky Note Settings")
// Font Input
font_size = input.string("Auto", title = "Font Size", options = ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group = "Font Settings")
font_type = input.string("Default", title = "Font Type", options = ["Default", "Monospace"], group = "Font Settings")
font_color = input.color(color.black, title = "Font Color", group = "Font Settings")
// Selected Font
selected_font = font_type == "Default" ? font.family_default : font.family_monospace
//Font Size
selected_size = font_size == "Auto" ? size.auto : font_size == "Huge" ? size.huge : font_size == "Large" ? size.large : font_size == "Normal" ? size.normal : font_size == "Small" ? size.small : font_size == "Tiny" ? size.tiny : na
// Table
var table t1 = table.new(tl1 + "_" + tl2, 1, 10)
// Writing rows in the table.
// If sentence is empty, then row will be excluded from the table
if barstate.islast
if not na(sentence01) and sentence01 != ""
table.cell(t1,0,0, text = sentence01 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence02) and sentence02 != ""
table.cell(t1,0,1, text = sentence02 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence03) and sentence03 != ""
table.cell(t1,0,2, text = sentence03 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence04) and sentence04 != ""
table.cell(t1,0,3, text = sentence04 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence05) and sentence05 != ""
table.cell(t1,0,4, text = sentence05 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence06) and sentence06 != ""
table.cell(t1,0,5, text = sentence06 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence07) and sentence07 != ""
table.cell(t1,0,6, text = sentence07 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence08) and sentence08 != ""
table.cell(t1,0,7, text = sentence08 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence09) and sentence09 != ""
table.cell(t1,0,8, text = sentence09 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font)
if not na(sentence10) and sentence10 != ""
table.cell(t1,0,9, text = sentence10 , bgcolor = note_color, text_color = font_color, text_halign = text.align_left, text_size = selected_size, text_font_family = selected_font) |
Volume accumulation [TCS] | VTA | https://www.tradingview.com/script/MXhudVcu-Volume-accumulation-TCS-VTA/ | zendrer | https://www.tradingview.com/u/zendrer/ | 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/
// ยฉ zendrer
//@version=5
indicator(shorttitle='TCSโขVOL ACC2', title='TCS โข VOLUME ACCUMULATION', precision=0, overlay =false)
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//INPUT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//MA
//----------------------------------------------------------------
x1 = input.int(15, minval = 2, maxval = 100, step = 1, title = "VOLUME LOOK-BACK", tooltip = "min : 2 - max : 100")
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//FUNCTION
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//VOL BUY-SELL
//----------------------------------------------------------------
buyVol = high[1] == low[1] ? 0 : volume[1] * (close[1] - low[1]) / (high[1] - low[1])
sellVol = high[1] == low[1] ? 0 : volume[1] * (high[1] - close[1]) / (high[1] - low[1])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol2 = high[2] == low[2] ? 0 : volume[2] * (close[2] - low[2]) / (high[2] - low[2])
sellVol2 = high[2] == low[2] ? 0 : volume[2] * (high[2] - close[2]) / (high[2] - low[2])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol3 = high[3] == low[3] ? 0 : volume[3] * (close[3] - low[3]) / (high[3] - low[3])
sellVol3 = high[3] == low[3] ? 0 : volume[3] * (high[3] - close[3]) / (high[3] - low[3])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol4 = high[4] == low[4] ? 0 : volume[4] * (close[4] - low[4]) / (high[4] - low[4])
sellVol4 = high[4] == low[4] ? 0 : volume[4] * (high[4] - close[4]) / (high[4] - low[4])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol5 = high[5] == low[5] ? 0 : volume[5] * (close[5] - low[5]) / (high[5] - low[5])
sellVol5 = high[5] == low[5] ? 0 : volume[5] * (high[5] - close[5]) / (high[5] - low[5])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol6 = high[6] == low[6] ? 0 : volume[6] * (close[6] - low[6]) / (high[6] - low[6])
sellVol6 = high[6] == low[6] ? 0 : volume[6] * (high[6] - close[6]) / (high[6] - low[6])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol7 = high[7] == low[7] ? 0 : volume[7] * (close[7] - low[7]) / (high[7] - low[7])
sellVol7 = high[7] == low[7] ? 0 : volume[7] * (high[7] - close[7]) / (high[7] - low[7])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol8 = high[8] == low[8] ? 0 : volume[8] * (close[8] - low[8]) / (high[8] - low[8])
sellVol8 = high[8] == low[8] ? 0 : volume[8] * (high[8] - close[8]) / (high[8] - low[8])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol9 = high[9] == low[9] ? 0 : volume[9] * (close[9] - low[9]) / (high[9] - low[9])
sellVol9 = high[9] == low[9] ? 0 : volume[9] * (high[9] - close[9]) / (high[9] - low[9])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol10 = high[10] == low[10] ? 0 : volume[10] * (close[10] - low[10]) / (high[10] - low[10])
sellVol10 = high[10] == low[10] ? 0 : volume[10] * (high[10] - close[10]) / (high[10] - low[10])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol11 = high[11] == low[11] ? 0 : volume[11] * (close[11] - low[11]) / (high[11] - low[11])
sellVol11 = high[11] == low[11] ? 0 : volume[11] * (high[11] - close[11]) / (high[11] - low[11])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol12 = high[12] == low[12] ? 0 : volume[12] * (close[12] - low[12]) / (high[12] - low[12])
sellVol12 = high[12] == low[12] ? 0 : volume[12] * (high[12] - close[12]) / (high[12] - low[12])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol13 = high[13] == low[13] ? 0 : volume[13] * (close[13] - low[13]) / (high[13] - low[13])
sellVol13 = high[13] == low[13] ? 0 : volume[13] * (high[13] - close[13]) / (high[13] - low[13])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol14 = high[14] == low[14] ? 0 : volume[14] * (close[14] - low[14]) / (high[14] - low[14])
sellVol14 = high[14] == low[14] ? 0 : volume[14] * (high[14] - close[14]) / (high[14] - low[14])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol15 = high[15] == low[15] ? 0 : volume[15] * (close[15] - low[15]) / (high[15] - low[15])
sellVol15 = high[15] == low[15] ? 0 : volume[15] * (high[15] - close[15]) / (high[15] - low[15])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol16 = high[16] == low[16] ? 0 : volume[16] * (close[16] - low[16]) / (high[16] - low[16])
sellVol16 = high[16] == low[16] ? 0 : volume[16] * (high[16] - close[16]) / (high[16] - low[16])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol17 = high[17] == low[17] ? 0 : volume[17] * (close[17] - low[17]) / (high[17] - low[17])
sellVol17 = high[17] == low[17] ? 0 : volume[17] * (high[17] - close[17]) / (high[17] - low[17])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol18 = high[18] == low[18] ? 0 : volume[18] * (close[18] - low[18]) / (high[18] - low[18])
sellVol18 = high[18] == low[18] ? 0 : volume[18] * (high[18] - close[18]) / (high[18] - low[18])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol19 = high[19] == low[19] ? 0 : volume[19] * (close[19] - low[19]) / (high[19] - low[19])
sellVol19 = high[19] == low[19] ? 0 : volume[19] * (high[19] - close[19]) / (high[19] - low[19])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol20 = high[20] == low[20] ? 0 : volume[20] * (close[20] - low[20]) / (high[20] - low[20])
sellVol20 = high[20] == low[20] ? 0 : volume[20] * (high[20] - close[20]) / (high[20] - low[20])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol21 = high[21] == low[21] ? 0 : volume[21] * (close[21] - low[21]) / (high[21] - low[21])
sellVol21 = high[21] == low[21] ? 0 : volume[21] * (high[21] - close[21]) / (high[21] - low[21])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol22 = high[22] == low[22] ? 0 : volume[22] * (close[22] - low[22]) / (high[22] - low[22])
sellVol22 = high[22] == low[22] ? 0 : volume[22] * (high[22] - close[22]) / (high[22] - low[22])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol23 = high[23] == low[23] ? 0 : volume[23] * (close[23] - low[23]) / (high[23] - low[23])
sellVol23 = high[23] == low[23] ? 0 : volume[23] * (high[23] - close[23]) / (high[23] - low[23])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol24 = high[24] == low[24] ? 0 : volume[24] * (close[24] - low[24]) / (high[24] - low[24])
sellVol24 = high[24] == low[24] ? 0 : volume[24] * (high[24] - close[24]) / (high[24] - low[24])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol25 = high[25] == low[25] ? 0 : volume[25] * (close[25] - low[25]) / (high[25] - low[25])
sellVol25 = high[25] == low[25] ? 0 : volume[25] * (high[25] - close[25]) / (high[25] - low[25])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol26 = high[26] == low[26] ? 0 : volume[26] * (close[26] - low[26]) / (high[26] - low[26])
sellVol26 = high[26] == low[26] ? 0 : volume[26] * (high[26] - close[26]) / (high[26] - low[26])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol27 = high[27] == low[27] ? 0 : volume[27] * (close[27] - low[27]) / (high[27] - low[27])
sellVol27 = high[27] == low[27] ? 0 : volume[27] * (high[27] - close[27]) / (high[27] - low[27])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol28 = high[28] == low[28] ? 0 : volume[28] * (close[28] - low[28]) / (high[28] - low[28])
sellVol28 = high[28] == low[28] ? 0 : volume[28] * (high[28] - close[28]) / (high[28] - low[28])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol29 = high[29] == low[29] ? 0 : volume[29] * (close[29] - low[29]) / (high[29] - low[29])
sellVol29 = high[29] == low[29] ? 0 : volume[29] * (high[29] - close[29]) / (high[29] - low[29])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol30 = high[30] == low[30] ? 0 : volume[30] * (close[30] - low[30]) / (high[30] - low[30])
sellVol30 = high[30] == low[30] ? 0 : volume[30] * (high[30] - close[30]) / (high[30] - low[30])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol31 = high[31] == low[31] ? 0 : volume[31] * (close[31] - low[31]) / (high[31] - low[31])
sellVol31 = high[31] == low[31] ? 0 : volume[31] * (high[31] - close[31]) / (high[31] - low[31])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol32 = high[32] == low[32] ? 0 : volume[32] * (close[32] - low[32]) / (high[32] - low[32])
sellVol32 = high[32] == low[32] ? 0 : volume[32] * (high[32] - close[32]) / (high[32] - low[32])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol33 = high[33] == low[33] ? 0 : volume[33] * (close[33] - low[33]) / (high[33] - low[33])
sellVol33 = high[33] == low[33] ? 0 : volume[33] * (high[33] - close[33]) / (high[33] - low[33])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol34 = high[34] == low[34] ? 0 : volume[34] * (close[34] - low[34]) / (high[34] - low[34])
sellVol34 = high[34] == low[34] ? 0 : volume[34] * (high[34] - close[34]) / (high[34] - low[34])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol35 = high[35] == low[35] ? 0 : volume[35] * (close[35] - low[35]) / (high[35] - low[35])
sellVol35 = high[35] == low[35] ? 0 : volume[35] * (high[35] - close[35]) / (high[35] - low[35])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol36 = high[36] == low[36] ? 0 : volume[36] * (close[36] - low[36]) / (high[36] - low[36])
sellVol36 = high[36] == low[36] ? 0 : volume[36] * (high[36] - close[36]) / (high[36] - low[36])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol37 = high[37] == low[37] ? 0 : volume[37] * (close[37] - low[37]) / (high[37] - low[37])
sellVol37 = high[37] == low[37] ? 0 : volume[37] * (high[37] - close[37]) / (high[37] - low[37])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol38 = high[38] == low[38] ? 0 : volume[38] * (close[38] - low[38]) / (high[38] - low[38])
sellVol38 = high[38] == low[38] ? 0 : volume[38] * (high[38] - close[38]) / (high[38] - low[38])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol39 = high[39] == low[39] ? 0 : volume[39] * (close[39] - low[39]) / (high[39] - low[39])
sellVol39 = high[39] == low[39] ? 0 : volume[39] * (high[39] - close[39]) / (high[39] - low[39])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol40 = high[40] == low[40] ? 0 : volume[40] * (close[40] - low[40]) / (high[40] - low[40])
sellVol40 = high[40] == low[40] ? 0 : volume[40] * (high[40] - close[40]) / (high[40] - low[40])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol41 = high[41] == low[41] ? 0 : volume[41] * (close[41] - low[41]) / (high[41] - low[41])
sellVol41 = high[41] == low[41] ? 0 : volume[41] * (high[41] - close[41]) / (high[41] - low[41])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol42 = high[42] == low[42] ? 0 : volume[42] * (close[42] - low[42]) / (high[42] - low[42])
sellVol42 = high[42] == low[42] ? 0 : volume[42] * (high[42] - close[42]) / (high[42] - low[42])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol43 = high[43] == low[43] ? 0 : volume[43] * (close[43] - low[43]) / (high[43] - low[43])
sellVol43 = high[43] == low[43] ? 0 : volume[43] * (high[43] - close[43]) / (high[43] - low[43])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol44 = high[44] == low[44] ? 0 : volume[44] * (close[44] - low[44]) / (high[44] - low[44])
sellVol44 = high[44] == low[44] ? 0 : volume[44] * (high[44] - close[44]) / (high[44] - low[44])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol45 = high[45] == low[45] ? 0 : volume[45] * (close[45] - low[45]) / (high[45] - low[45])
sellVol45 = high[45] == low[45] ? 0 : volume[45] * (high[45] - close[45]) / (high[45] - low[45])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol46 = high[46] == low[46] ? 0 : volume[46] * (close[46] - low[46]) / (high[46] - low[46])
sellVol46 = high[46] == low[46] ? 0 : volume[46] * (high[46] - close[46]) / (high[46] - low[46])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol47 = high[47] == low[47] ? 0 : volume[47] * (close[47] - low[47]) / (high[47] - low[47])
sellVol47 = high[47] == low[47] ? 0 : volume[47] * (high[47] - close[47]) / (high[47] - low[47])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol48 = high[48] == low[48] ? 0 : volume[48] * (close[48] - low[48]) / (high[48] - low[48])
sellVol48 = high[48] == low[48] ? 0 : volume[48] * (high[48] - close[48]) / (high[48] - low[48])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol49 = high[49] == low[49] ? 0 : volume[49] * (close[49] - low[49]) / (high[49] - low[49])
sellVol49 = high[49] == low[49] ? 0 : volume[49] * (high[49] - close[49]) / (high[49] - low[49])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol50 = high[50] == low[50] ? 0 : volume[50] * (close[50] - low[50]) / (high[50] - low[50])
sellVol50 = high[50] == low[50] ? 0 : volume[50] * (high[50] - close[50]) / (high[50] - low[50])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol51 = high[51] == low[51] ? 0 : volume[51] * (close[51] - low[51]) / (high[51] - low[51])
sellVol51 = high[51] == low[51] ? 0 : volume[51] * (high[51] - close[51]) / (high[51] - low[51])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol52 = high[52] == low[52] ? 0 : volume[52] * (close[52] - low[52]) / (high[52] - low[52])
sellVol52 = high[52] == low[52] ? 0 : volume[52] * (high[52] - close[52]) / (high[52] - low[52])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol53 = high[53] == low[53] ? 0 : volume[53] * (close[53] - low[53]) / (high[53] - low[53])
sellVol53 = high[53] == low[53] ? 0 : volume[53] * (high[53] - close[53]) / (high[53] - low[53])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol54 = high[54] == low[54] ? 0 : volume[54] * (close[54] - low[54]) / (high[54] - low[54])
sellVol54 = high[54] == low[54] ? 0 : volume[54] * (high[54] - close[54]) / (high[54] - low[54])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol55 = high[55] == low[55] ? 0 : volume[55] * (close[55] - low[55]) / (high[55] - low[55])
sellVol55 = high[55] == low[55] ? 0 : volume[55] * (high[55] - close[55]) / (high[55] - low[55])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol56 = high[56] == low[56] ? 0 : volume[56] * (close[56] - low[56]) / (high[56] - low[56])
sellVol56 = high[56] == low[56] ? 0 : volume[56] * (high[56] - close[56]) / (high[56] - low[56])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol57 = high[57] == low[57] ? 0 : volume[57] * (close[57] - low[57]) / (high[57] - low[57])
sellVol57 = high[57] == low[57] ? 0 : volume[57] * (high[57] - close[57]) / (high[57] - low[57])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol58 = high[58] == low[58] ? 0 : volume[58] * (close[58] - low[58]) / (high[58] - low[58])
sellVol58 = high[58] == low[58] ? 0 : volume[58] * (high[58] - close[58]) / (high[58] - low[58])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol59 = high[59] == low[59] ? 0 : volume[59] * (close[59] - low[59]) / (high[59] - low[59])
sellVol59 = high[59] == low[59] ? 0 : volume[59] * (high[59] - close[59]) / (high[59] - low[59])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol60 = high[60] == low[60] ? 0 : volume[60] * (close[60] - low[60]) / (high[60] - low[60])
sellVol60 = high[60] == low[60] ? 0 : volume[60] * (high[60] - close[60]) / (high[60] - low[60])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol61 = high[61] == low[61] ? 0 : volume[61] * (close[61] - low[61]) / (high[61] - low[61])
sellVol61 = high[61] == low[61] ? 0 : volume[61] * (high[61] - close[61]) / (high[61] - low[61])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol62 = high[62] == low[62] ? 0 : volume[62] * (close[62] - low[62]) / (high[62] - low[62])
sellVol62 = high[62] == low[62] ? 0 : volume[62] * (high[62] - close[62]) / (high[62] - low[62])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol63 = high[63] == low[63] ? 0 : volume[63] * (close[63] - low[63]) / (high[63] - low[63])
sellVol63 = high[63] == low[63] ? 0 : volume[63] * (high[63] - close[63]) / (high[63] - low[63])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol64 = high[64] == low[64] ? 0 : volume[64] * (close[64] - low[64]) / (high[64] - low[64])
sellVol64 = high[64] == low[64] ? 0 : volume[64] * (high[64] - close[64]) / (high[64] - low[64])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol65 = high[65] == low[65] ? 0 : volume[65] * (close[65] - low[65]) / (high[65] - low[65])
sellVol65 = high[65] == low[65] ? 0 : volume[65] * (high[65] - close[65]) / (high[65] - low[65])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol66 = high[66] == low[66] ? 0 : volume[66] * (close[66] - low[66]) / (high[66] - low[66])
sellVol66 = high[66] == low[66] ? 0 : volume[66] * (high[66] - close[66]) / (high[66] - low[66])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol67 = high[67] == low[67] ? 0 : volume[67] * (close[67] - low[67]) / (high[67] - low[67])
sellVol67 = high[67] == low[67] ? 0 : volume[67] * (high[67] - close[67]) / (high[67] - low[67])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol68 = high[68] == low[68] ? 0 : volume[68] * (close[68] - low[68]) / (high[68] - low[68])
sellVol68 = high[68] == low[68] ? 0 : volume[68] * (high[68] - close[68]) / (high[68] - low[68])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol69 = high[69] == low[69] ? 0 : volume[69] * (close[69] - low[69]) / (high[69] - low[69])
sellVol69 = high[69] == low[69] ? 0 : volume[69] * (high[69] - close[69]) / (high[69] - low[69])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol70 = high[70] == low[70] ? 0 : volume[70] * (close[70] - low[70]) / (high[70] - low[70])
sellVol70 = high[70] == low[70] ? 0 : volume[70] * (high[70] - close[70]) / (high[70] - low[70])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol71 = high[71] == low[71] ? 0 : volume[71] * (close[71] - low[71]) / (high[71] - low[71])
sellVol71 = high[71] == low[71] ? 0 : volume[71] * (high[71] - close[71]) / (high[71] - low[71])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol72 = high[72] == low[72] ? 0 : volume[72] * (close[72] - low[72]) / (high[72] - low[72])
sellVol72 = high[72] == low[72] ? 0 : volume[72] * (high[72] - close[72]) / (high[72] - low[72])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol73 = high[73] == low[73] ? 0 : volume[73] * (close[73] - low[73]) / (high[73] - low[73])
sellVol73 = high[73] == low[73] ? 0 : volume[73] * (high[73] - close[73]) / (high[73] - low[73])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol74 = high[74] == low[74] ? 0 : volume[74] * (close[74] - low[74]) / (high[74] - low[74])
sellVol74 = high[74] == low[74] ? 0 : volume[74] * (high[74] - close[74]) / (high[74] - low[74])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol75 = high[75] == low[75] ? 0 : volume[75] * (close[75] - low[75]) / (high[75] - low[75])
sellVol75 = high[75] == low[75] ? 0 : volume[75] * (high[75] - close[75]) / (high[75] - low[75])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol76 = high[76] == low[76] ? 0 : volume[76] * (close[76] - low[76]) / (high[76] - low[76])
sellVol76 = high[76] == low[76] ? 0 : volume[76] * (high[76] - close[76]) / (high[76] - low[76])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol77 = high[77] == low[77] ? 0 : volume[77] * (close[77] - low[77]) / (high[77] - low[77])
sellVol77 = high[77] == low[77] ? 0 : volume[77] * (high[77] - close[77]) / (high[77] - low[77])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol78 = high[78] == low[78] ? 0 : volume[78] * (close[78] - low[78]) / (high[78] - low[78])
sellVol78 = high[78] == low[78] ? 0 : volume[78] * (high[78] - close[78]) / (high[78] - low[78])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol79 = high[79] == low[79] ? 0 : volume[79] * (close[79] - low[79]) / (high[79] - low[79])
sellVol79 = high[79] == low[79] ? 0 : volume[79] * (high[79] - close[79]) / (high[79] - low[79])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol80 = high[80] == low[80] ? 0 : volume[80] * (close[80] - low[80]) / (high[80] - low[80])
sellVol80 = high[80] == low[80] ? 0 : volume[80] * (high[80] - close[80]) / (high[80] - low[80])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol81 = high[81] == low[81] ? 0 : volume[81] * (close[81] - low[81]) / (high[81] - low[81])
sellVol81 = high[81] == low[81] ? 0 : volume[81] * (high[81] - close[81]) / (high[81] - low[81])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol82 = high[82] == low[82] ? 0 : volume[82] * (close[82] - low[82]) / (high[82] - low[82])
sellVol82 = high[82] == low[82] ? 0 : volume[82] * (high[82] - close[82]) / (high[82] - low[82])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol83 = high[83] == low[83] ? 0 : volume[83] * (close[83] - low[83]) / (high[83] - low[83])
sellVol83 = high[83] == low[83] ? 0 : volume[83] * (high[83] - close[83]) / (high[83] - low[83])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol84 = high[84] == low[84] ? 0 : volume[84] * (close[84] - low[84]) / (high[84] - low[84])
sellVol84 = high[84] == low[84] ? 0 : volume[84] * (high[84] - close[84]) / (high[84] - low[84])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol85 = high[85] == low[85] ? 0 : volume[85] * (close[85] - low[85]) / (high[85] - low[85])
sellVol85 = high[85] == low[85] ? 0 : volume[85] * (high[85] - close[85]) / (high[85] - low[85])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol86 = high[86] == low[86] ? 0 : volume[86] * (close[86] - low[86]) / (high[86] - low[86])
sellVol86 = high[86] == low[86] ? 0 : volume[86] * (high[86] - close[86]) / (high[86] - low[86])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol87 = high[87] == low[87] ? 0 : volume[87] * (close[87] - low[87]) / (high[87] - low[87])
sellVol87 = high[87] == low[87] ? 0 : volume[87] * (high[87] - close[87]) / (high[87] - low[87])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol88 = high[88] == low[88] ? 0 : volume[88] * (close[88] - low[88]) / (high[88] - low[88])
sellVol88 = high[88] == low[88] ? 0 : volume[88] * (high[88] - close[88]) / (high[88] - low[88])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol89 = high[89] == low[89] ? 0 : volume[89] * (close[89] - low[89]) / (high[89] - low[89])
sellVol89 = high[89] == low[89] ? 0 : volume[89] * (high[89] - close[89]) / (high[89] - low[89])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol90 = high[90] == low[90] ? 0 : volume[90] * (close[90] - low[90]) / (high[90] - low[90])
sellVol90 = high[90] == low[90] ? 0 : volume[90] * (high[90] - close[90]) / (high[90] - low[90])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol91 = high[91] == low[91] ? 0 : volume[91] * (close[91] - low[91]) / (high[91] - low[91])
sellVol91 = high[91] == low[91] ? 0 : volume[91] * (high[91] - close[91]) / (high[91] - low[91])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol92 = high[92] == low[92] ? 0 : volume[92] * (close[92] - low[92]) / (high[92] - low[92])
sellVol92 = high[92] == low[92] ? 0 : volume[92] * (high[92] - close[92]) / (high[92] - low[92])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol93 = high[93] == low[93] ? 0 : volume[93] * (close[93] - low[93]) / (high[93] - low[93])
sellVol93 = high[93] == low[93] ? 0 : volume[93] * (high[93] - close[93]) / (high[93] - low[93])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol94 = high[94] == low[94] ? 0 : volume[94] * (close[94] - low[94]) / (high[94] - low[94])
sellVol94 = high[94] == low[94] ? 0 : volume[94] * (high[94] - close[94]) / (high[94] - low[94])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol95 = high[95] == low[95] ? 0 : volume[95] * (close[95] - low[95]) / (high[95] - low[95])
sellVol95 = high[95] == low[95] ? 0 : volume[95] * (high[95] - close[95]) / (high[95] - low[95])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol96 = high[96] == low[96] ? 0 : volume[96] * (close[96] - low[96]) / (high[96] - low[96])
sellVol96 = high[96] == low[96] ? 0 : volume[96] * (high[96] - close[96]) / (high[96] - low[96])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol97 = high[97] == low[97] ? 0 : volume[97] * (close[97] - low[97]) / (high[97] - low[97])
sellVol97 = high[97] == low[97] ? 0 : volume[97] * (high[97] - close[97]) / (high[97] - low[97])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol98 = high[98] == low[98] ? 0 : volume[98] * (close[98] - low[98]) / (high[98] - low[98])
sellVol98 = high[98] == low[98] ? 0 : volume[98] * (high[98] - close[98]) / (high[98] - low[98])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol99 = high[99] == low[99] ? 0 : volume[99] * (close[99] - low[99]) / (high[99] - low[99])
sellVol99 = high[99] == low[99] ? 0 : volume[99] * (high[99] - close[99]) / (high[99] - low[99])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol100 = high[100] == low[100] ? 0 : volume[100] * (close[100] - low[100]) / (high[100] - low[100])
sellVol100 = high[100] == low[100] ? 0 : volume[100] * (high[100] - close[100]) / (high[100] - low[100])
//----------------------------------------------------------------
//VOLUME LOOKBACK
//----------------------------------------------------------------
vol1 = buyVol
volm1 = sellVol
vol2 = vol1 + buyVol2
volm2 = volm1 + sellVol2
vol3 = vol2 + buyVol3
volm3 = volm2 + sellVol3
vol4 = vol3 + buyVol4
volm4 = volm3 + sellVol4
vol5 = vol4 + buyVol5
volm5 = volm4 + sellVol5
vol6 = vol5 + buyVol6
volm6 = volm5 + sellVol6
vol7 = vol6 + buyVol7
volm7 = volm6 + sellVol7
vol8 = vol7 + buyVol8
volm8 = volm7 + sellVol8
vol9 = vol8 + buyVol9
volm9 = volm8 + sellVol9
vol10 = vol9 + buyVol10
volm10 = volm9 + sellVol10
vol11 = vol10 + buyVol11
volm11 = volm10 + sellVol11
vol12 = vol11+ buyVol12
volm12 = volm11 + sellVol12
vol13 = vol12+ buyVol13
volm13 = volm12 + sellVol13
vol14 = vol13 + buyVol14
volm14 = volm13 + sellVol14
vol15 = vol14 + buyVol15
volm15 = volm14 + sellVol15
vol16 = vol15 + buyVol16
volm16 = volm15 + sellVol16
vol17 = vol16 + buyVol17
volm17 = volm16 + sellVol17
vol18 = vol17 + buyVol18
volm18 = volm17 + sellVol18
vol19 = vol18 + buyVol19
volm19 = volm18 + sellVol19
vol20 = vol19 + buyVol20
volm20 = volm19 + sellVol20
vol21 = vol20 + buyVol21
volm21 = volm20 + sellVol21
vol22 = vol21 + buyVol22
volm22 = volm21 + sellVol22
vol23 = vol22 + buyVol23
volm23 = volm22 + sellVol23
vol24 = vol23 + buyVol24
volm24 = volm23 + sellVol24
vol25 = vol24 + buyVol25
volm25 = volm24 + sellVol25
vol26 = vol25 + buyVol26
volm26 = volm25 + sellVol26
vol27 = vol26 + buyVol27
volm27 = volm26 + sellVol27
vol28 = vol27 + buyVol28
volm28 = volm27 + sellVol28
vol29 = vol28 + buyVol29
volm29 = volm28 + sellVol29
vol30 = vol29 + buyVol30
volm30 = volm29 + sellVol30
vol31 = vol30 + buyVol31
volm31 = volm30 + sellVol31
vol32 = vol31 + buyVol32
volm32 = volm31 + sellVol32
vol33 = vol32 + buyVol33
volm33 = volm32 + sellVol33
vol34 = vol33 + buyVol34
volm34 = volm33 + sellVol34
vol35 = vol34 + buyVol35
volm35 = volm34 + sellVol35
vol36 = vol35 + buyVol36
volm36 = volm35 + sellVol36
vol37 = vol36 + buyVol37
volm37 = volm36 + sellVol37
vol38 = vol37 + buyVol38
volm38 = volm37 + sellVol38
vol39 = vol38 + buyVol39
volm39 = volm38 + sellVol39
vol40 = vol39 + buyVol40
volm40 = volm39 + sellVol40
vol41 = vol40+ buyVol41
volm41 = volm40 + sellVol41
vol42 = vol41 + buyVol42
volm42 = volm41 + sellVol42
vol43 = vol42 + buyVol43
volm43 = volm42 + sellVol43
vol44 = vol43 + buyVol44
volm44 = volm43 + sellVol44
vol45 = vol44 + buyVol45
volm45 = volm44 + sellVol45
vol46 = vol45 + buyVol46
volm46 = volm45 + sellVol46
vol47 = vol46 + buyVol47
volm47 = volm46 + sellVol47
vol48 = vol47 + buyVol48
volm48 = volm47 + sellVol48
vol49 = vol48 + buyVol49
volm49 = volm48 + sellVol49
vol50 = vol49 + buyVol50
volm50 = volm49 + sellVol50
vol51 = vol50 + buyVol51
volm51 = volm50 + sellVol51
vol52 = vol51 + buyVol52
volm52 = volm51 + sellVol52
vol53 = vol52 + buyVol53
volm53 = volm52 + sellVol53
vol54 = vol53 + buyVol54
volm54 = volm53 + sellVol54
vol55 = vol54 + buyVol55
volm55 = volm54 + sellVol55
vol56 = vol55 + buyVol56
volm56 = volm55 + sellVol56
vol57 = vol56 + buyVol57
volm57 = volm56 + sellVol57
vol58 = vol57 + buyVol58
volm58 = volm57 + sellVol58
vol59 = vol58 + buyVol59
volm59 = volm58 + sellVol59
vol60 = vol59 + buyVol60
volm60 = volm59 + sellVol60
vol61 = vol60 + buyVol61
volm61 = volm60 + sellVol61
vol62 = vol61 + buyVol62
volm62 = volm61 + sellVol62
vol63 = vol62 + buyVol63
volm63 = volm62 + sellVol63
vol64 = vol63 + buyVol64
volm64 = volm63 + sellVol64
vol65 = vol64 + buyVol65
volm65 = volm64 + sellVol65
vol66 = vol65 + buyVol66
volm66 = volm65 + sellVol66
vol67 = vol66 + buyVol67
volm67 = volm66 + sellVol67
vol68 = vol67 + buyVol68
volm68 = volm67 + sellVol68
vol69 = vol68 + buyVol69
volm69 = volm68 + sellVol69
vol70 = vol69 + buyVol70
volm70 = volm69 + sellVol70
vol71 = vol70 + buyVol71
volm71 = volm70 + sellVol71
vol72 = vol71 + buyVol72
volm72 = volm71 + sellVol72
vol73 = vol72 + buyVol73
volm73 = volm72 + sellVol73
vol74 = vol73 + buyVol74
volm74 = volm73 + sellVol74
vol75 = vol74 + buyVol75
volm75 = volm74 + sellVol75
vol76 = vol75 + buyVol76
volm76 = volm75 + sellVol76
vol77 = vol76 + buyVol77
volm77 = volm76 + sellVol77
vol78 = vol77 + buyVol78
volm78 = volm77 + sellVol78
vol79 = vol78 + buyVol79
volm79 = volm78 + sellVol79
vol80 = vol79 + buyVol80
volm80 = volm79 + sellVol80
vol81 = vol80 + buyVol81
volm81 = volm80 + sellVol81
vol82 = vol81 + buyVol82
volm82 = volm81 + sellVol82
vol83 = vol82 + buyVol83
volm83 = volm82 + sellVol83
vol84 = vol83 + buyVol84
volm84 = volm83 + sellVol84
vol85 = vol84 + buyVol85
volm85 = volm84 + sellVol85
vol86 = vol85 + buyVol86
volm86 = volm85 + sellVol86
vol87 = vol86 + buyVol87
volm87 = volm86 + sellVol87
vol88 = vol87 + buyVol88
volm88 = volm87 + sellVol88
vol89 = vol88 + buyVol89
volm89 = volm88 + sellVol89
vol90 = vol89 + buyVol90
volm90 = volm89 + sellVol90
vol91 = vol90 + buyVol91
volm91 = volm90 + sellVol91
vol92 = vol91 + buyVol92
volm92 = volm91 + sellVol92
vol93 = vol92 + buyVol93
volm93 = volm92 + sellVol93
vol94 = vol93 + buyVol94
volm94 = volm93 + sellVol94
vol95 = vol94 + buyVol95
volm95 = volm94 + sellVol95
vol96 = vol95 + buyVol96
volm96 = volm95 + sellVol96
vol97 = vol96 + buyVol97
volm97 = volm96 + sellVol97
vol98 = vol97 + buyVol98
volm98 = volm97 + sellVol98
vol99 = vol98 + buyVol99
volm99 = volm98 + sellVol99
vol100 = vol99 + buyVol100
volm100 = volm99 + sellVol100
//----------------------------------------------------------------
//VOLUME DEFINTION
//----------------------------------------------------------------
voldefbull = (x1 == 1) ? vol1 :
(x1 == 2) ? vol2 :
(x1 == 3) ? vol3 :
(x1 == 4) ? vol4 :
(x1 == 5) ? vol5 :
(x1 == 6) ? vol6 :
(x1 == 7) ? vol7 :
(x1 == 8) ? vol8 :
(x1 == 9) ? vol9 :
(x1 == 10) ? vol10 :
(x1 == 11) ? vol11 :
(x1 == 12) ? vol12 :
(x1 == 13) ? vol13 :
(x1 == 14) ? vol14 :
(x1 == 15) ? vol15 :
(x1 == 16) ? vol16 :
(x1 == 17) ? vol17 :
(x1 == 18) ? vol18 :
(x1 == 19) ? vol19 :
(x1 == 20) ? vol20 :
(x1 == 21) ? vol21 :
(x1 == 22) ? vol22 :
(x1 == 23) ? vol23 :
(x1 == 24) ? vol24 :
(x1 == 25) ? vol25 :
(x1 == 26) ? vol26 :
(x1 == 27) ? vol27 :
(x1 == 28) ? vol28 :
(x1 == 29) ? vol29 :
(x1 == 30) ? vol30 :
(x1 == 31) ? vol31 :
(x1 == 32) ? vol32 :
(x1 == 33) ? vol33 :
(x1 == 34) ? vol34 :
(x1 == 35) ? vol35 :
(x1 == 36) ? vol36 :
(x1 == 37) ? vol37 :
(x1 == 38) ? vol38 :
(x1 == 39) ? vol39 :
(x1 == 40) ? vol40 :
(x1 == 41) ? vol41 :
(x1 == 42) ? vol42 :
(x1 == 43) ? vol43 :
(x1 == 44) ? vol44 :
(x1 == 45) ? vol45 :
(x1 == 46) ? vol46 :
(x1 == 47) ? vol47 :
(x1 == 48) ? vol48 :
(x1 == 49) ? vol49 :
(x1 == 50) ? vol50 :
(x1 == 51) ? vol51 :
(x1 == 52) ? vol52 :
(x1 == 53) ? vol53 :
(x1 == 54) ? vol54 :
(x1 == 55) ? vol55 :
(x1 == 56) ? vol56 :
(x1 == 57) ? vol57 :
(x1 == 58) ? vol58 :
(x1 == 59) ? vol59 :
(x1 == 60) ? vol60 :
(x1 == 61) ? vol61 :
(x1 == 62) ? vol62 :
(x1 == 63) ? vol63 :
(x1 == 64) ? vol64 :
(x1 == 65) ? vol65 :
(x1 == 66) ? vol66 :
(x1 == 67) ? vol67 :
(x1 == 68) ? vol68 :
(x1 == 69) ? vol69 :
(x1 == 70) ? vol70 :
(x1 == 71) ? vol71 :
(x1 == 72) ? vol72 :
(x1 == 73) ? vol73 :
(x1 == 74) ? vol74 :
(x1 == 75) ? vol75 :
(x1 == 76) ? vol76 :
(x1 == 77) ? vol77 :
(x1 == 78) ? vol78 :
(x1 == 79) ? vol79 :
(x1 == 80) ? vol80 :
(x1 == 81) ? vol81 :
(x1 == 82) ? vol82 :
(x1 == 83) ? vol83 :
(x1 == 84) ? vol84 :
(x1 == 85) ? vol85 :
(x1 == 86) ? vol86 :
(x1 == 87) ? vol87 :
(x1 == 88) ? vol88 :
(x1 == 89) ? vol89 :
(x1 == 90) ? vol90 :
(x1 == 91) ? vol91 :
(x1 == 92) ? vol92 :
(x1 == 93) ? vol93 :
(x1 == 94) ? vol94 :
(x1 == 95) ? vol95 :
(x1 == 96) ? vol96 :
(x1 == 97) ? vol97 :
(x1 == 98) ? vol98 :
(x1 == 99) ? vol99 :
(x1 == 100) ? vol100 : na
voldefbear = (x1 == 1) ? volm1 :
(x1 == 2) ? volm2 :
(x1 == 3) ? volm3 :
(x1 == 4) ? volm4 :
(x1 == 5) ? volm5 :
(x1 == 6) ? volm6 :
(x1 == 7) ? volm7 :
(x1 == 8) ? volm8 :
(x1 == 9) ? volm9 :
(x1 == 10) ? volm10 :
(x1 == 11) ? volm11 :
(x1 == 12) ? volm12 :
(x1 == 13) ? volm13 :
(x1 == 14) ? volm14 :
(x1 == 15) ? volm15 :
(x1 == 16) ? volm16 :
(x1 == 17) ? volm17 :
(x1 == 18) ? volm18 :
(x1 == 19) ? volm19 :
(x1 == 20) ? volm20 :
(x1 == 21) ? volm21 :
(x1 == 22) ? volm22 :
(x1 == 23) ? volm23 :
(x1 == 24) ? volm24 :
(x1 == 25) ? volm25 :
(x1 == 26) ? volm26 :
(x1 == 27) ? volm27 :
(x1 == 28) ? volm28 :
(x1 == 29) ? volm29 :
(x1 == 30) ? volm30 :
(x1 == 31) ? volm31 :
(x1 == 32) ? volm32 :
(x1 == 33) ? volm33 :
(x1 == 34) ? volm34 :
(x1 == 35) ? volm35 :
(x1 == 36) ? volm36 :
(x1 == 37) ? volm37 :
(x1 == 38) ? volm38 :
(x1 == 39) ? volm39 :
(x1 == 40) ? volm40 :
(x1 == 41) ? volm41 :
(x1 == 42) ? volm42 :
(x1 == 43) ? volm43 :
(x1 == 44) ? volm44 :
(x1 == 45) ? volm45 :
(x1 == 46) ? volm46 :
(x1 == 47) ? volm47 :
(x1 == 48) ? volm48 :
(x1 == 49) ? volm49 :
(x1 == 50) ? volm50 :
(x1 == 51) ? volm51 :
(x1 == 52) ? volm52 :
(x1 == 53) ? volm53 :
(x1 == 54) ? volm54 :
(x1 == 55) ? volm55 :
(x1 == 56) ? volm56 :
(x1 == 57) ? volm57 :
(x1 == 58) ? volm58 :
(x1 == 59) ? volm59 :
(x1 == 60) ? volm60 :
(x1 == 61) ? volm61 :
(x1 == 62) ? volm62 :
(x1 == 63) ? volm63 :
(x1 == 64) ? volm64 :
(x1 == 65) ? volm65 :
(x1 == 66) ? volm66 :
(x1 == 67) ? volm67 :
(x1 == 68) ? volm68 :
(x1 == 69) ? volm69 :
(x1 == 70) ? volm70 :
(x1 == 71) ? volm71 :
(x1 == 72) ? volm72 :
(x1 == 73) ? volm73 :
(x1 == 74) ? volm74 :
(x1 == 75) ? volm75 :
(x1 == 76) ? volm76 :
(x1 == 77) ? volm77 :
(x1 == 78) ? volm78 :
(x1 == 79) ? volm79 :
(x1 == 80) ? volm80 :
(x1 == 81) ? volm81 :
(x1 == 82) ? volm82 :
(x1 == 83) ? volm83 :
(x1 == 84) ? volm84 :
(x1 == 85) ? volm85 :
(x1 == 86) ? volm86 :
(x1 == 87) ? volm87 :
(x1 == 88) ? volm88 :
(x1 == 89) ? volm89 :
(x1 == 90) ? volm90 :
(x1 == 91) ? volm91 :
(x1 == 92) ? volm92 :
(x1 == 93) ? volm93 :
(x1 == 94) ? volm94 :
(x1 == 95) ? volm95 :
(x1 == 96) ? volm96 :
(x1 == 97) ? volm97 :
(x1 == 98) ? volm98 :
(x1 == 99) ? volm99 :
(x1 == 100) ? volm100 : na
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//PLOT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//VOL
//----------------------------------------------------------------
plot(voldefbull, title = 'BULLISH VOLUME', color = color.new(color.white,20), style=plot.style_columns, linewidth=2)
plot(voldefbear, title = 'BEARISH VOLUME', color = color.new(color.gray,20), style=plot.style_columns, linewidth=2)
plot(0, "TREND DETECTOR", color = close>close[x1] ? color.new(color.lime,0):color.new(color.purple,0), style = plot.style_circles, linewidth=2)
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//ALERTS
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//ALERTCONDITION
//----------------------------------------------------------------
alertlong = voldefbull > voldefbear and close > close[x1]
alertshort = voldefbull < voldefbear and close < close[x1]
alertcondition(alertlong, "Volume accumulation bullish", "Volume accumulation bullish")
alertcondition(alertshort, "Volume accumulation bearish", "Volume accumulation bearish")
//----------------------------------------------------------------
//END
|
VWAP Open Session Anchored by Hampeh | https://www.tradingview.com/script/Gw69Sz67-VWAP-Open-Session-Anchored-by-Hampeh/ | Hampeh | https://www.tradingview.com/u/Hampeh/ | 40 | 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 Open Session Anchored by Hampeh", "VWAP OPen Session", true)
// CONSTANTS
// COLORS
color night_color = #8E44AD
color evening_color = #4469ad
color morning_color = #44ad5b
// INPUTS
float source = input.source (hlc3, "Source", tooltip="", inline="", group="Volume Weighted Average Price")
int offset = input.int (0, "Offset", tooltip="", inline="", group="Volume Weighted Average Price")
bool bands = input.bool (false, "Band Multiplier", tooltip="", inline="0", group="Volume Weighted Average Price")
float multiplier = input.float (1, "", tooltip="", inline="0", group="Volume Weighted Average Price")
bool morning = input.bool (true, "Morning", tooltip="", inline="0", group="Session")
color morningColor = input.color (morning_color, "", tooltip="", inline="0", group="Session")
bool evening = input.bool (true, "Evening", tooltip="", inline="1", group="Session")
color eveningColor = input.color (evening_color, "", tooltip="", inline="1", group="Session")
bool night = input.bool (true, "Night", tooltip="", inline="0", group="Session")
color nightColor = input.color (night_color, "", tooltip="", inline="0", group="Session")
// CALCULATIONS
morningSession_full = input.session('1030-1230', 'Morning Session')
eveningSession_full = input.session('1430-1800', 'Evening Session')
nightSession_full = input.session('2100-2330', 'Night Session')
morningSession = time(timeframe.period, morningSession_full + ':1234567')
eveningSession = time(timeframe.period, eveningSession_full + ':1234567')
nightSession = time(timeframe.period, nightSession_full + ':1234567')
[morningVwap , morningUpper , morningLower ] = ta.vwap(source, morningSession [0] and not morningSession [1], multiplier)
[eveningVwap , eveningUpper , eveningLower ] = ta.vwap(source, eveningSession [0] and not eveningSession [1], multiplier)
[nightVwap , nightUpper , nightLower ] = ta.vwap(source, nightSession [0] and not nightSession [1], multiplier)
// PLOTS
plotMorningUpper = plot(morning and bands and morningSession ? morningUpper : na, "Morning Session VWAP Upper Band", morningColor, 1, plot.style_linebr, false, 0, offset)
plotMorningVwap = plot(morning and morningSession ? morningVwap : na, "Morning Session VWAP", morningColor, 2, plot.style_linebr, false, 0, offset)
plotMorningLower = plot(morning and bands and morningSession ? morningLower : na, "Morning Session VWAP Lower Band", morningColor, 1, plot.style_linebr, false, 0, offset)
fill(plotMorningUpper, plotMorningLower, color.new(morningColor, 95))
plotEveningUpper = plot(evening and bands and eveningSession ? eveningUpper : na, "Evening Session VWAP Upper Band", eveningColor, 1, plot.style_linebr, false, 0, offset)
plotEveningVwap = plot(evening and eveningSession ? eveningVwap : na, "Evening Session VWAP", eveningColor, 2, plot.style_linebr, false, 0, offset)
plotEveningLower = plot(evening and bands and eveningSession ? eveningLower : na, "Evening Session VWAP Lower Band", eveningColor, 1, plot.style_linebr, false, 0, offset)
fill(plotEveningUpper, plotEveningLower, color.new(eveningColor, 95))
plotNightUpper = plot(night and bands and nightSession ? nightUpper : na, "Night Session VWAP Upper Band", nightColor, 1, plot.style_linebr, false, 0, offset)
plotNightVwap = plot(night and nightSession ? nightVwap : na, "Night Session VWAP", nightColor, 2, plot.style_linebr, false, 0, offset)
plotNightLower = plot(night and bands and nightSession ? nightLower : na, "Night Session VWAP Lower Band", nightColor, 1, plot.style_linebr, false, 0, offset)
fill(plotNightUpper, plotNightLower, color.new(nightColor, 95)) |
Pearson's R Convergence Divergence | https://www.tradingview.com/script/PJpVj7HU-Pearson-s-R-Convergence-Divergence/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 79 | 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/
// ยฉ Gentleman-Goat
//@version=5
indicator(title="Pearson's R Convergence Divergence",shorttitle="PRCD",overlay=false)
linear_regression_group = "Linear Regression"
i_source_linreg = input.source(close,"Linear Regressions Source",group=linear_regression_group)
i_startPeriod_l1 = input.int(48,"Start Period L1 (Fast)",group=linear_regression_group)
i_startPeriod_l2 = input.int(96,"Start Period L2 (Slow)",group=linear_regression_group)
i_def_deviation_l1 = input.float(2, "Deviation Amount L1" , minval=0.1, step=0.1,group=linear_regression_group)
i_def_deviation_l2 = input.float(2, "Deviation Amount L2" , minval=0.1, step=0.1,group=linear_regression_group)
createLinReg(period,source,deviations,_byNum)=>
periodMinusOne = period-1
Ex = 0.0, Ey = 0.0, Ex2 = 0.0,Ey2 =0.0, Exy = 0.0, for i=0 to periodMinusOne by _byNum
closeI = nz(source[i]), Ex := Ex + i, Ey := Ey + closeI, Ex2 := Ex2 + (i * i),Ey2 := Ey2 + (closeI * closeI), Exy := Exy + (closeI * i)
ExT2 = math.pow(Ex,2.0) //Sum of X THEN Squared
EyT2 = math.pow(Ey,2.0) //Sym of Y THEN Squared
PearsonsR = (Exy - ((Ex*Ey)/period))/(math.sqrt(Ex2-(ExT2/period))*math.sqrt(Ey2-(EyT2/period)))
ExEx = Ex * Ex, slope = Ex2==ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0, for i=0 to periodMinusOne by _byNum
deviation := deviation + math.pow(nz(source[i]) - (intercept - slope * (bar_index[i])), 2.0)
deviation := deviations * math.sqrt(deviation / periodMinusOne)
startingPointY = linearRegression + slope * periodMinusOne
[PearsonsR,linearRegression,deviation,startingPointY]
[pearsonsR_l1,linearRegression_l1,deviation_l1,startingPointY_l1] = createLinReg(i_startPeriod_l1,i_source_linreg,i_def_deviation_l1,1)
[pearsonsR_l2,linearRegression_l2,deviation_l2,startingPointY_l2] = createLinReg(i_startPeriod_l2,i_source_linreg,i_def_deviation_l2,1)
macd = pearsonsR_l1 - pearsonsR_l2
col_grow_above = input.color(#FF5252, "Aboveโโโ
Grow", group="Histogram", inline="Above")
col_fall_above = input.color(#FFCDD2, "Fall", group="Histogram", inline="Above")
col_grow_below = input.color(#B2DFDB, "BelowโGrow", group="Histogram", inline="Below")
col_fall_below = input.color(#26A69A, "Fall", group="Histogram", inline="Below")
hist = pearsonsR_l1 > pearsonsR_l2 ? math.abs(pearsonsR_l1) - math.abs(pearsonsR_l2) : (math.abs(pearsonsR_l2) - math.abs(pearsonsR_l1)) * -1
upperChannelPrice_l1 = startingPointY_l1-(startingPointY_l1-(linearRegression_l1+deviation_l1))
lowerChannelPrice_l1 = startingPointY_l1-(startingPointY_l1-(linearRegression_l1-deviation_l1))
upperChannelPrice_l2 = startingPointY_l2-(startingPointY_l2-(linearRegression_l2+deviation_l2))
lowerChannelPrice_l2 = startingPointY_l2-(startingPointY_l2-(linearRegression_l2-deviation_l2))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
hline(0, linestyle=hline.style_dashed, color=color.white)
hline(-0.8, linestyle=hline.style_dashed, color=color.lime)
hline(0.8, linestyle=hline.style_dashed, color=color.red)
hline(1, linestyle=hline.style_solid, color=color.red)
hline(-1, linestyle=hline.style_solid, color=color.green)
plot( pearsonsR_l1,color=#2962FF,style=plot.style_linebr)
plot( pearsonsR_l2,color=#FF6D00,style=plot.style_linebr)
plot(ta.crossover(close,upperChannelPrice_l1) ? pearsonsR_l1 : na, color=color.green, style=plot.style_cross,linewidth = 3)
plot(ta.crossunder(close,lowerChannelPrice_l1) ? pearsonsR_l1 : na, color=color.red, style=plot.style_cross,linewidth = 3)
plot(ta.crossover(close,upperChannelPrice_l2) ? pearsonsR_l2 : na, color=color.green, style=plot.style_cross,linewidth = 3)
plot(ta.crossunder(close,lowerChannelPrice_l2) ? pearsonsR_l2 : na, color=color.red, style=plot.style_cross,linewidth = 3)
|
Take profit and Stop Loss ATR HL [Tcs] | ALGO | https://www.tradingview.com/script/euY17u48-Take-profit-and-Stop-Loss-ATR-HL-Tcs-ALGO/ | zendrer | https://www.tradingview.com/u/zendrer/ | 149 | 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/
// ยฉ zendrer
//@version=5
// One of the most famous SL or TP indicator developed on 3 levels, both long and short, to semplify the visualization of the target or multiple targets.
indicator(title="TCS โข TP/SL ATR+HL", shorttitle= "TCSโขTP/SL", overlay=true)
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//INPUT
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//ATR + LEVELS
//----------------------------------------------------------------
type = input.string(title='SL/TP', defval='ATR', options=['ATR', 'H-L'], group = "TP/SL")
atrlen = input(14, 'ATRโขLEN', group = "ATR TP/SL")
smoothing = input.string(title='ATRโขSmoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = "ATR TP/SL")
lines = input(true, "SHOW LEVELS", group = "ATR TP/SL")
bands = input(true, "SHOW BANDS", group = "ATR TP/SL")
labels = input(true, "SHOW LABELS", group = "ATR TP/SL")
SSLx = input(true, "", inline="1", group = "ATR TP/SL")
SSL = input.float(2.01, 'SHORT SLโขMlt', step=0.1, inline="1", group = "ATR TP/SL")
LSLx = input(true, "", inline="2", group = "ATR TP/SL")
LSL = input.float(2.01, 'LONG SLโขMlt', step=0.1, inline="2", group = "ATR TP/SL")
LTPx = input(true, "", inline="3", group = "ATR TP/SL")
LTP = input.float(2, 'LONG TPโขMlt 1', step=0.1, inline="3", group = "ATR TP/SL")
LTP1x = input(false, "", inline="4", group = "ATR TP/SL")
LTP1 = input.float(3, 'LONG TPโขMlt 2', step=0.1, inline="4", group = "ATR TP/SL")
LTP2x = input(false, "", inline="5", group = "ATR TP/SL")
LTP2 = input.float(4, 'LONG TPโขMlt 3', step=0.1, inline="5", group = "ATR TP/SL")
STPx = input(true, "", inline="6", group = "ATR TP/SL")
STP = input.float(2, 'SHORT TPโขMlt 1', step=0.1, inline="6", group = "ATR TP/SL")
STP1x = input(false, "", inline="7", group = "ATR TP/SL")
STP1 = input.float(3, 'SHORT TPโขMlt 2', step=0.1, inline="7", group = "ATR TP/SL")
STP2x = input(false, "", inline="8", group = "ATR TP/SL")
STP2 = input.float(4, 'SHORT TPโขMlt 3', step=0.1, inline="8", group = "ATR TP/SL")
//----------------------------------------------------------------
//----------------------------------------------------------------
// STRUCTURE H/L
//----------------------------------------------------------------
lB = input(20, title = "LOOKBACK", group = "HIGH-LOW TP/SL")
hx = input(true, "HIGH", group = "HIGH-LOW TP/SL")
lx = input(true, "LOW", group = "HIGH-LOW TP/SL")
rB = 1
//----------------------------------------------------------------
//----------------------------------------------------------------
//CRYPTO RISK CALC
//----------------------------------------------------------------
risk = input(3,"ACCOUNT RISK % ", group = "ACCOUNT RISK - CRYPTO")
account = input(10000,"ACCOUNT AMOUNT ", group = "ACCOUNT RISK - CRYPTO")
fees = input(0.07,"BROKER FEES ENTRY %", group = "ACCOUNT RISK - CRYPTO")
feesex = input(0.07,"BROKER FEES EXIT %", group = "ACCOUNT RISK - CRYPTO")
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//FUNCTION
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//ATR
//----------------------------------------------------------------
ma_function(source, atrlen) =>
if smoothing == 'RMA'
ta.rma(source, atrlen)
else
if smoothing == 'SMA'
ta.sma(source, atrlen)
else
if smoothing == 'EMA'
ta.ema(source, atrlen)
else
ta.wma(source, atrlen)
atr_slen = ma_function(ta.tr(true), atrlen)
//----------------------------------------------------------------
//ATR Up/Low Bands
//----------------------------------------------------------------
xLTP= LSL*LTP
xLTP1= LSL*LTP1
xLTP2= LSL*LTP2
xSTP= SSL*STP
xSTP1= SSL*STP1
xSTP2= SSL*STP2
SL_L=close - atr_slen * LSL
SL_S= atr_slen * SSL + close
TP_L1= atr_slen * xLTP + close
TP_L2= atr_slen * xLTP1 + close
TP_L3= atr_slen * xLTP2 + close
TP_S1= close - atr_slen * xSTP
TP_S2= close - atr_slen * xSTP1
TP_S3= close - atr_slen * xSTP2
//----------------------------------------------------------------
//HIGH-LOW
//----------------------------------------------------------------
hP = fixnan(ta.pivothigh(lB, rB)[1])
lP = fixnan(ta.pivotlow(lB, rB)[1])
//----------------------------------------------------------------
//SIZE CALC LONG
//----------------------------------------------------------------
changesl = (((close/SL_L)-1)*100)+fees
accval = risk*account
relative = (changesl*accval)/risk
accquant = accval/relative
//----------------------------------------------------------------
//SIZE CALC SHORT
//----------------------------------------------------------------
changesl1 = (((SL_S/close)-1)*100)+fees
accval1 = risk*account
relative1 = (changesl1*accval1)/risk
accquant1 = accval1/relative1
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//PLOT
//โขโขโขโขโขโขโขโขโขโขโขโขโข
//BANDS
//----------------------------------------------------------------
u = plot(SL_L, 'LONG SLโขMlt', color = type == 'ATR' ?(bands ? (LSLx ? color.new(color.white, 40) : na) : na) :na , style=plot.style_stepline)
l = plot(SL_S, 'SHORT SLโขMlt', color = type == 'ATR' ?(bands ? (SSLx ? color.new(color.white, 40) : na) : na) :na , style=plot.style_stepline)
u1 = plot(TP_L1, 'LONG TPโขMlt 1', color = type == 'ATR' ?(bands ? (LTPx ? color.new(color.lime, 20) : na) : na) :na , style=plot.style_stepline)
u2 = plot(TP_L2, 'LONG TPโขMlt 2', color = type == 'ATR' ?(bands ? (LTP1x ? color.new(color.lime, 40) : na) : na) :na , style=plot.style_stepline)
u3 = plot(TP_L3, 'LONG TPโขMlt 3', color = type == 'ATR' ?(bands ? (LTP2x ? color.new(color.lime, 60) : na) : na) :na , style=plot.style_stepline)
l1 = plot(TP_S1, 'SHORT TPโขMlt 1', color = type == 'ATR' ?(bands ? (STPx ? color.new(color.purple, 20) : na) : na) :na , style=plot.style_stepline)
l2 = plot(TP_S2, 'SHORT TPโขMlt 2', color = type == 'ATR' ?(bands ? (STP1x ? color.new(color.purple, 40) : na) : na) :na , style=plot.style_stepline)
l3 = plot(TP_S3, 'SHORT TPโขMlt 3', color = type == 'ATR' ?(bands ? (STP2x ? color.new(color.purple, 60) : na) : na) :na , style=plot.style_stepline)
//----------------------------------------------------------------
//PLOT HL
//----------------------------------------------------------------
Hl = type == 'H-L' ? line.new(bar_index+1,hP,bar_index+9,hP, xloc = xloc.bar_index, extend = extend.none, color = lines ? ( hx ? color.new(color.lime, 0) :na) : na, style = line.style_dashed) : na
Hll = type == 'H-L' ? (labels and hx ? label.new(bar_index+9, hP, color = color.new(color.white,100) , style = label.style_label_left, text="H-SL | "+str.tostring(hP), textcolor = color.lime, textalign = text.align_left) : na) : na
line.delete(Hl[1])
label.delete(Hll[1])
Ll = type == 'H-L' ? line.new(bar_index+1,lP,bar_index+9,lP, xloc = xloc.bar_index, extend = extend.none, color = lines ? ( lx ? color.new(color.purple, 0) :na) : na, style = line.style_dashed) : na
Lll = type == 'H-L' ? (labels and lx ? label.new(bar_index+9, lP, color = color.new(color.white,100) , style = label.style_label_left, text="L-SL | "+str.tostring(lP), textcolor = color.purple, textalign = text.align_left) : na) : na
line.delete(Ll[1])
label.delete(Lll[1])
//plot(hP, color=ta.change(hP) ? na : color.lime, linewidth=1, offset=-(rB+1), title="HIGH",style=plot.style_line)
//plot(lP, color=ta.change(lP) ? na : color.lime, linewidth=1, offset=-(rB+1), title="LOW",style=plot.style_line)
//----------------------------------------------------------------
//-----
//LINE
//----------------------------------------------------------------
ul = type == 'ATR' ? line.new(bar_index+1,SL_L[1],bar_index+9,SL_L[1], xloc = xloc.bar_index, extend = extend.none, color = lines ? (LSLx ? color.new(color.white, 40) : na) : na, style = line.style_dashed) : na
ull = type == 'ATR' ? (labels and LSLx ? label.new(bar_index+9, SL_L[1], color = color.new(color.white,100) , style = label.style_label_left, text="L-SL | "+str.tostring(LSL[1])+" | "+str.tostring(SL_L[1]), textcolor = color.gray, textalign = text.align_left) : na) : na
line.delete(ul[1])
label.delete(ull[1])
ll = type == 'ATR' ? line.new(bar_index+1,SL_S[1],bar_index+9,SL_S[1], xloc = xloc.bar_index, extend = extend.none, color = lines ? (SSLx ? color.new(color.white, 40) : na) : na, style = line.style_dashed) : na
lll = type == 'ATR' ? (labels and SSLx ? label.new(bar_index+9, SL_S[1], color =color.new(color.white,100), style = label.style_label_left, text="S-SL | "+str.tostring(SSL[1])+" | "+str.tostring(SL_S[1]), textcolor = color.gray, textalign = text.align_left) : na) : na
line.delete(ll[1])
label.delete(lll[1])
u1l = type == 'ATR' ? line.new(bar_index+1,TP_L1[1],bar_index+9,TP_L1[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (LTPx ? color.new(color.lime, 20) : na) : na, style = line.style_dashed) : na
u1ll = type == 'ATR' ? (labels and LTPx ? label.new(bar_index+9, TP_L1[1], color =color.new(color.white,100), style = label.style_label_left, text="L-TP1 | "+str.tostring(LTP[1])+" | "+str.tostring(TP_L1[1]), textcolor = color.new(color.lime, 20), textalign = text.align_left) : na) : na
line.delete(u1l[1])
label.delete(u1ll[1])
u2l = type == 'ATR' ? line.new(bar_index+1,TP_L2[1],bar_index+9,TP_L2[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (LTP1x ? color.new(color.lime, 40) : na) : na, style = line.style_dashed) : na
u2ll = type == 'ATR' ? (labels and LTP1x ? label.new(bar_index+9, TP_L2[1], color =color.new(color.white,100), style = label.style_label_left, text="L-TP2 | "+str.tostring(LTP1[1])+" | "+str.tostring(TP_L2[1]), textcolor = color.new(color.lime, 20), textalign = text.align_left) : na) : na
line.delete(u2l[1])
label.delete(u2ll[1])
u3l = type == 'ATR' ? line.new(bar_index+1,TP_L3[1],bar_index+9,TP_L3[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (LTP2x ? color.new(color.lime, 60) : na) : na, style = line.style_dashed) : na
u3ll = type == 'ATR' ? (labels and LTP2x ? label.new(bar_index+9, TP_L3[1], color =color.new(color.white,100), style = label.style_label_left, text="L-TP3 | "+str.tostring(LTP2[1])+" | "+str.tostring(TP_L3[1]), textcolor = color.new(color.lime, 20), textalign = text.align_left) : na) : na
line.delete(u3l[1])
label.delete(u3ll[1])
l1l = type == 'ATR' ? line.new(bar_index+1,TP_S1[1],bar_index+9,TP_S1[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (STPx ? color.new(color.purple, 20) : na) : na, style = line.style_dashed) : na
l1ll = type == 'ATR' ? (labels and STPx ? label.new(bar_index+9, TP_S1[1], color =color.new(color.white,100), style = label.style_label_left, text="S-TP1 | "+str.tostring(STP[1])+" | "+str.tostring(TP_S1[1]), textcolor = color.new(color.purple, 20), textalign = text.align_left) : na) : na
line.delete(l1l[1])
label.delete(l1ll[1])
l2l = type == 'ATR' ? line.new(bar_index+1,TP_S2[1],bar_index+9,TP_S2[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (STP1x ? color.new(color.purple, 40) : na) : na, style = line.style_dashed) : na
l2ll = type == 'ATR' ? (labels and STP1x ? label.new(bar_index+9, TP_S2[1], color =color.new(color.white,100), style = label.style_label_left, text="S-TP2 | "+str.tostring(STP1[1])+" | "+str.tostring(TP_S2[1]), textcolor = color.new(color.purple, 40), textalign = text.align_left) : na) : na
line.delete(l2l[1])
label.delete(l2ll[1])
l3l = type == 'ATR' ? line.new(bar_index+1,TP_S3[1],bar_index+9,TP_S3[1] , xloc = xloc.bar_index, extend = extend.none, color = lines ? (STP2x ? color.new(color.purple, 60) : na) : na, style = line.style_dashed) : na
l3ll = type == 'ATR' ? (labels and STP2x ? label.new(bar_index+9, TP_S3[1], color =color.new(color.white,100), style = label.style_label_left, text="S-TP3 | "+str.tostring(STP2[1])+" | "+str.tostring(TP_S3[1]), textcolor = color.new(color.purple, 60), textalign = text.align_left) : na) : na
line.delete(l3l[1])
label.delete(l3ll[1])
accqty = type == 'ATR' ? (labels and (LSLx or SSLx) ? label.new(bar_index+9, close[1], color =color.new(color.white,100), style = label.style_label_left, text="QTY x "+ "|LONG|" +str.tostring(accquant,"#.##") + " โข |SHORT|" +str.tostring(accquant1,"#.##"), textcolor = color.new(color.white, 20), textalign = text.align_left) : na) : na
label.delete(accqty[1])
//accqty1 = type == 'ATR' ? (labels and (LSLx or SSLx) ? label.new(bar_index+9, close[1], color =color.new(color.white,100), style = label.style_label_left, text="QTY. SHORT | "+ " x " +str.tostring(accquant1), textcolor = color.new(color.white, 20), textalign = text.align_left) : na) : na
//label.delete(accqty1[1]) |
Camac Const | https://www.tradingview.com/script/zVIBsbcb-Camac-Const/ | culturalCardin27605 | https://www.tradingview.com/u/culturalCardin27605/ | 8 | 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/
// ยฉ Majid Rajabi Vardanjani
//@version=4
study("Camac", overlay=true, max_labels_count=500)
Periods2 = 2
src2 = "hl2"
Multiplier2 = 1.0
changeATR2= true
Periods3 = 3
src3 = "hlc3"
Multiplier3 = 1.0
changeATR3= true
length = 1
mult = 1.8
O = open
H = high
L = low
C = close
HL2 = hl2
HLC3 = hlc3
OHLC4 = ohlc4
TR = tr
ATR2 = atr(Periods2)
ATR3 = atr(Periods3)
ATRCh = atr(length)
HighestCh = highest(length)
LowestCh = lowest(length)
buyLabelColor = input(color.green, "Buy Labels Color")
sellLabelColor = input(color.red, "Sell Labels Color")
B2 = "1"
B3 = "2"
CHB = "3"
S2 = "1"
S3 = "2"
CHS = "3"
displayST2Labels = input(true, "Display Super-Trend 2 Signals?", group="Display")
displayST3Labels = input(true, "Display Super-Trend 3 Signals?", group="Display")
displayChandelierLabels = input(true, "Display Chandelier-Exit Signals?", group="Display")
getSource(src, O, L, H, C, HL2, HLC3, OHLC4) =>
realSrc = O
if src == "low"
realSrc := L
else if src == "high"
realSrc := H
else if src == "close"
realSrc := C
else if src == "hl2"
realSrc := HL2
else if src == "hlc3"
realSrc := HLC3
else if src == "ohlc4"
realSrc := OHLC4
realSrc
// SuperTrend2 -----------------------------------------------------------------------------------------------------
atr22 = sma(TR, Periods2)
atr2= changeATR2 ? ATR2 : atr22
up2=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)-(Multiplier2*atr2)
up21 = nz(up2[1],up2)
up2 := C[1] > up21 ? max(up2,up21) : up2
dn2=getSource(src2, O, L, H, C, HL2, HLC3, OHLC4)+(Multiplier2*atr2)
dn21 = nz(dn2[1], dn2)
dn2 := C[1] < dn21 ? min(dn2, dn21) : dn2
trend2 = 1
trend2 := nz(trend2[1], trend2)
trend2 := trend2 == -1 and C > dn21 ? 1 : trend2 == 1 and C < up2 ? -1 : trend2
buySignal2 = trend2 == 1 and trend2[1] == -1
sellSignal2 = trend2 == -1 and trend2[1] == 1
// SuperTrend3 -----------------------------------------------------------------------------------------------------
atr32 = sma(TR, Periods3)
atr3= changeATR3 ? ATR3 : atr32
up3=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)-(Multiplier3*atr3)
up31 = nz(up3[1],up3)
up3 := C[1] > up31 ? max(up3,up31) : up3
dn3=getSource(src3, O, L, H, C, HL2, HLC3, OHLC4)+(Multiplier3*atr3)
dn31 = nz(dn3[1], dn3)
dn3 := C[1] < dn31 ? min(dn3, dn31) : dn3
trend3 = 1
trend3 := nz(trend3[1], trend3)
trend3 := trend3 == -1 and C > dn31 ? 1 : trend3 == 1 and C < up3 ? -1 : trend3
buySignal3 = trend3 == 1 and trend3[1] == -1
sellSignal3 = trend3 == -1 and trend3[1] == 1
// Chandelier -----------------------------------------------------------------------------------------------------
useClose = false
atr = mult * ATRCh
longStop = HighestCh - atr
longStopPrev = nz(longStop[1], longStop)
longStop := C[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = LowestCh + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := C[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := C > shortStopPrev ? 1 : C < longStopPrev ? -1 : dir
buySignal = dir == 1 and dir[1] == -1
sellSignal = dir == -1 and dir[1] == 1
// Signals ==============================
buyText = "\n"
sellText = "\n"
if buySignal2 and displayST2Labels
buyText := buyText + B2 + "\n"
if buySignal and displayChandelierLabels
buyText := buyText + CHB + "\n"
if buySignal3 and displayST3Labels
buyText := buyText + B3 + "\n"
if sellSignal2 and displayST2Labels
sellText := sellText + S2 + "\n"
if sellSignal and displayChandelierLabels
sellText := sellText + CHS + "\n"
if sellSignal3 and displayST3Labels
sellText := sellText + S3 + "\n"
buySignals = ((buySignal3 and displayST3Labels) or (buySignal and displayChandelierLabels) or (buySignal2 and displayST2Labels))
sellSignals = ((sellSignal3 and displayST3Labels) or (sellSignal and displayChandelierLabels) or (sellSignal2 and displayST2Labels))
if buySignals
label.new(bar_index, L, buyText, color=buyLabelColor, textcolor=color.white, style=label.style_label_up, size=size.small)
alert(buyText, alert.freq_once_per_bar_close)
if sellSignals
label.new(bar_index, H, sellText, color=sellLabelColor, textcolor=color.white, style=label.style_label_down, size=size.small)
alert(sellText, alert.freq_once_per_bar_close)
|
Moving Averages + BB & R.VWAP StDev (multi-tf) | https://www.tradingview.com/script/nNEHQnKV-Moving-Averages-BB-R-VWAP-StDev-multi-tf/ | Yatagarasu_ | https://www.tradingview.com/u/Yatagarasu_/ | 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/
//@version=5
indicator("MA โข Yata",
overlay = true)
// ------------------------------------------------
groupRV = "Rolling VWAP & Standard Deviation Bands"
// ------------------------------------------------
show_rVWAP = input(false, title="VWAP:" , inline="RV1", group=groupRV)
showSTDEV = input(false, title="St. Dev. Bands |" , inline="RV2", group=groupRV)
rolling_period = input(200, title="" , inline="RV1", group=groupRV)
src_rVWAP = input(hlc3, title="" , inline="RV1", group=groupRV)
fillSTDEV = input(true , title="Fill |", inline="RV2", group=groupRV)
showrL = input(false , title="Lines:", inline="RV2", group=groupRV)
Lwidth_rVWAP = input.int(1, minval=0 , title="Width" , inline="RV2", group=groupRV)
showrLC = showrL ? display.all : display.none
stDevMultiplier_1 = input.float(0.5 , step=0.1, title="Deviation 1", inline="StDev1", group=groupRV)
stDevMultiplier_2 = input.float(0.618 , step=0.1, title="Deviation 2", inline="StDev1", group=groupRV)
stDevMultiplier_3 = input.float(1 , step=0.1, title="Deviation 3", inline="StDev2", group=groupRV)
stDevMultiplier_4 = input.float(1.5 , step=0.1, title="Deviation 4", inline="StDev2", group=groupRV)
stDevMultiplier_5 = input.float(1.618 , step=0.1, title="Deviation 5", inline="StDev3", group=groupRV)
stDevMultiplier_6 = input.float(2 , step=0.1, title="Deviation 6", inline="StDev3", group=groupRV)
rVWAP_color = input.color(color.new(color.silver, 70) , title="Colors: VWAP" , inline="RV3", group=groupRV)
up_color = input.color(color.red , title="Upper" , inline="RV3", group=groupRV)
lw_color = input.color(color.blue , title="Lower" , inline="RV3", group=groupRV)
Vstyle = input(true, title="Circles line", inline="RV3", group=groupRV)
VstyleC = Vstyle ? plot.style_circles : plot.style_line
// ------------------------------------------------
rVWAP(length) =>
float p = na
float vol = na
float sn = na
p_ = src_rVWAP * volume
p := nz(p[1]) + p_ - nz(p_[length])
vol := nz(vol[1]) + volume - nz(volume[length])
v = p / vol
sn_ = volume * (src_rVWAP - nz(v[1])) * (src_rVWAP - v)
sn := nz(sn[1]) + sn_ - nz(sn_[length])
std = math.sqrt(sn / vol)
[v, std]
[vwap_r, std_r] = rVWAP(rolling_period)
// ------------------------------------------------
resrVWAP = input.timeframe("", title="", inline="RV1", group=groupRV)
mtfrVWAP = request.security(syminfo.tickerid, resrVWAP, vwap_r, gaps=barmerge.gaps_off)
mtfSTD = request.security(syminfo.tickerid, resrVWAP, std_r, gaps=barmerge.gaps_off)
plot(show_rVWAP ? mtfrVWAP : na, title = "VWAP - Rolling", color=rVWAP_color, linewidth=Lwidth_rVWAP, style=VstyleC)
// ------------------------------------------------
fb_transp = input.float(100, minval=0, maxval=100, title="Transparency", inline="RV4", group=groupRV)
fb_step = input.float(5, minval=0, maxval=100, title="Step", inline="RV4", group=groupRV)
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)
// ------------------------------------------------
rV_stdevU1 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_1 * mtfSTD : na, title="rVWAP - STDEV +1", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevU2 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_2 * mtfSTD : na, title="rVWAP - STDEV +2", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevU3 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_3 * mtfSTD : na, title="rVWAP - STDEV +3", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevU4 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_4 * mtfSTD : na, title="rVWAP - STDEV +4", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevU5 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_5 * mtfSTD : na, title="rVWAP - STDEV +5", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevU6 = plot(showSTDEV ? mtfrVWAP + stDevMultiplier_6 * mtfSTD : na, title="rVWAP - STDEV +6", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD1 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_1 * mtfSTD : na, title="rVWAP - STDEV -1", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD2 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_2 * mtfSTD : na, title="rVWAP - STDEV -2", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD3 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_3 * mtfSTD : na, title="rVWAP - STDEV -3", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD4 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_4 * mtfSTD : na, title="rVWAP - STDEV -4", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD5 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_5 * mtfSTD : na, title="rVWAP - STDEV -5", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
rV_stdevD6 = plot(showSTDEV ? mtfrVWAP - stDevMultiplier_6 * mtfSTD : na, title="rVWAP - STDEV -6", color=color.new(color.silver, 85), style=plot.style_line, linewidth=Lwidth_rVWAP, display=showrLC)
// ------------------------------------------------
fill(rV_stdevU1, rV_stdevD1, title="rVWAP - STDEV +-1", color=color.new(color.silver, 95), display=display.none)
fill(rV_stdevU2, rV_stdevU1, title="rVWAP - STDEV +2", color= fillSTDEV ? fill_col_up : na)
fill(rV_stdevU3, rV_stdevU2, title="rVWAP - STDEV +3", color= fillSTDEV ? fill_col_up2 : na)
fill(rV_stdevU4, rV_stdevU3, title="rVWAP - STDEV +4", color= fillSTDEV ? fill_col_up3 : na)
fill(rV_stdevU5, rV_stdevU4, title="rVWAP - STDEV +5", color= fillSTDEV ? fill_col_up4 : na)
fill(rV_stdevU6, rV_stdevU5, title="rVWAP - STDEV +6", color= fillSTDEV ? fill_col_up5 : na)
fill(rV_stdevD2, rV_stdevD1, title="rVWAP - STDEV -2", color= fillSTDEV ? fill_col_down : na)
fill(rV_stdevD3, rV_stdevD2, title="rVWAP - STDEV -3", color= fillSTDEV ? fill_col_down2 : na)
fill(rV_stdevD4, rV_stdevD3, title="rVWAP - STDEV -4", color= fillSTDEV ? fill_col_down3 : na)
fill(rV_stdevD5, rV_stdevD4, title="rVWAP - STDEV -5", color= fillSTDEV ? fill_col_down4 : na)
fill(rV_stdevD6, rV_stdevD5, title="rVWAP - STDEV -6", color= fillSTDEV ? fill_col_down5 : na)
// -----------------------
groupMA = "Moving Average"
groupMA1 = "MA 0-9"
groupMA2 = "MA A-G"
// -----------------------
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)
"HMA" => ta.hma(source, length)
"ALMA" => ta.alma(source, length, 0.85, 6.0)
// -----------------------
trend_flip = input.int (2, minval=0 , title="Flip trend periods" , inline="MA01", group=groupMA)
src = input (close , title="Source" , inline="MA01", group=groupMA)
//ribbon_colorup = input.color (color.new(#00FEEF, 95) , title="Ribbon Colors: Bullish", inline="MA02", group=groupMA)
//ribbon_colordn = input.color (color.new(#E21B22, 95) , title="Bearish" , inline="MA02", group=groupMA)
show19 = input.bool (true , title="Show 0-9 |" , inline="MA02", group=groupMA)
showAF = input.bool (false , title="Show A-G |" , inline="MA03", group=groupMA)
//only_fill = input.bool (false , title="Hide MA Lines" , inline="MA04", group=groupMA)
only_fill = false
price = plot(close, title="Price", color=color.silver, display=display.none)
// -----------------------
visible0 = input.bool(false , title="MA 0:" , inline="MA0" , group=groupMA1)
//visiblefill0 = input.bool(false, title="Show MA Fill", inline="MA0A" , group=groupMA1)
line_width0 = input.int(1, minval=0, title="Line: width", inline="MA0A" , group=groupMA1)
visible1 = input.bool(true , title="MA 1:" , inline="MA1" , group=groupMA1)
//visiblefill1 = input.bool(false, title="Show MA Fill", inline="MA1A" , group=groupMA1)
line_width1 = input.int(1, minval=0, title="Line: width", inline="MA1A" , group=groupMA1)
visible2 = input.bool(true , title="MA 2:" , inline="MA2" , group=groupMA1)
//visiblefill2 = input.bool(false, title="Show MA Fill", inline="MA2A" , group=groupMA1)
line_width2 = input.int(1, minval=0, title="Line: width", inline="MA2A" , group=groupMA1)
visible3 = input.bool(true , title="MA 3:" , inline="MA3" , group=groupMA1)
//visiblefill3 = input.bool(false, title="Show MA Fill", inline="MA3A" , group=groupMA1)
line_width3 = input.int(1, minval=0, title="Line: width", inline="MA3A" , group=groupMA1)
visible4 = input.bool(true , title="MA 4:" , inline="MA4" , group=groupMA1)
//visiblefill4 = input.bool(false, title="Show MA Fill", inline="MA4A" , group=groupMA1)
line_width4 = input.int(1, minval=0, title="Line: width", inline="MA4A" , group=groupMA1)
visible5 = input.bool(true , title="MA 5:" , inline="MA5" , group=groupMA1)
//visiblefill5 = input.bool(false, title="Show MA Fill", inline="MA5A" , group=groupMA1)
line_width5 = input.int(1, minval=0, title="Line: width", inline="MA5A" , group=groupMA1)
visible6 = input.bool(true , title="MA 6:" , inline="MA6" , group=groupMA1)
//visiblefill6 = input.bool(false, title="Show MA Fill", inline="MA6A" , group=groupMA1)
line_width6 = input.int(1, minval=0, title="Line: width", inline="MA6A" , group=groupMA1)
visible7 = input.bool(true, title="MA 7:" , inline="MA7" , group=groupMA1)
//visiblefill7 = input.bool(false, title="Show MA Fill", inline="MA7A" , group=groupMA1)
line_width7 = input.int(1, minval=0, title="Line: width", inline="MA7A" , group=groupMA1)
visible8 = input.bool(false, title="MA 8:" , inline="MA8" , group=groupMA1)
//visiblefill8 = input.bool(false, title="Show MA Fill", inline="MA8A" , group=groupMA1)
line_width8 = input.int(1, minval=0, title="Line: width", inline="MA8A" , group=groupMA1)
visible9 = input.bool(false, title="MA 9:" , inline="MA9" , group=groupMA1)
//visiblefill9 = input.bool(false, title="Show MA Fill", inline="MA9A" , group=groupMA1)
line_width9 = input.int(1, minval=0, title="Line: width", inline="MA9A" , group=groupMA1)
visible10 = input.bool(true, title="MA A:" , inline="MA10" , group=groupMA2)
//visiblefill10 = input.bool(false, title="Show MA Fill", inline="MA10A" , group=groupMA2)
line_width10 = input.int(1, minval=0, title="Line: width", inline="MA10A" , group=groupMA2)
visible11 = input.bool(true, title="MA B:" , inline="MA11" , group=groupMA2)
//visiblefill11 = input.bool(false, title="Show MA Fill", inline="MA11A" , group=groupMA2)
line_width11 = input.int(1, minval=0, title="Line: width", inline="MA11A" , group=groupMA2)
visible12 = input.bool(true, title="MA C:" , inline="MA12" , group=groupMA2)
//visiblefill12 = input.bool(false, title="Show MA Fill", inline="MA12A" , group=groupMA2)
line_width12 = input.int(1, minval=0, title="Line: width", inline="MA12A" , group=groupMA2)
visible13 = input.bool(true, title="MA D:" , inline="MA13" , group=groupMA2)
//visiblefill13 = input.bool(false, title="Show MA Fill", inline="MA13A" , group=groupMA2)
line_width13 = input.int(1, minval=0, title="Line: width", inline="MA13A" , group=groupMA2)
visible14 = input.bool(true, title="MA E:" , inline="MA14" , group=groupMA2)
//visiblefill14 = input.bool(false, title="Show MA Fill", inline="MA14A" , group=groupMA2)
line_width14 = input.int(1, minval=0, title="Line: width", inline="MA14A" , group=groupMA2)
visible15 = input.bool(true, title="MA F:" , inline="MA15" , group=groupMA2)
//visiblefill15 = input.bool(false, title="Show MA Fill", inline="MA15A" , group=groupMA2)
line_width15 = input.int(1, minval=0, title="Line: width", inline="MA15A" , group=groupMA2)
visible16 = input.bool(true, title="MA G:" , inline="MA16" , group=groupMA2)
//visiblefill16 = input.bool(false, title="Show MA Fill", inline="MA16A" , group=groupMA2)
line_width16 = input.int(1, minval=0, title="Line: width", inline="MA16A" , group=groupMA2)
// -----------------------
len0 = input.int(5 , minval=1, title="", inline="MA0", group=groupMA1)
len1 = input.int(9 , minval=1, title="", inline="MA1", group=groupMA1)
len2 = input.int(21 , minval=1, title="", inline="MA2", group=groupMA1)
len3 = input.int(34 , minval=1, title="", inline="MA3", group=groupMA1)
len4 = input.int(50 , minval=1, title="", inline="MA4", group=groupMA1)
len5 = input.int(100 , minval=1, title="", inline="MA5", group=groupMA1)
len6 = input.int(200 , minval=1, title="", inline="MA6", group=groupMA1)
len7 = input.int(400 , minval=1, title="", inline="MA7", group=groupMA1)
len8 = input.int(144 , minval=1, title="", inline="MA8", group=groupMA1)
len9 = input.int(233 , minval=1, title="", inline="MA9", group=groupMA1)
len10 = input.int(21 , minval=1, title="", inline="MA10", group=groupMA2)
len11 = input.int(34 , minval=1, title="", inline="MA11", group=groupMA2)
len12 = input.int(50 , minval=1, title="", inline="MA12", group=groupMA2)
len13 = input.int(100 , minval=1, title="", inline="MA13", group=groupMA2)
len14 = input.int(144 , minval=1, title="", inline="MA14", group=groupMA2)
len15 = input.int(200 , minval=1, title="", inline="MA15", group=groupMA2)
len16 = input.int(400 , minval=1, title="", inline="MA16", group=groupMA2)
// -----------------------
maType0 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA0", group=groupMA1)
maType1 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA1", group=groupMA1)
maType2 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA2", group=groupMA1)
maType3 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA3", group=groupMA1)
maType4 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA4", group=groupMA1)
maType5 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA5", group=groupMA1)
maType6 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA6", group=groupMA1)
maType7 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA7", group=groupMA1)
maType8 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA8", group=groupMA1)
maType9 = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA9", group=groupMA1)
maType10 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA10", group=groupMA2)
maType11 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA11", group=groupMA2)
maType12 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA12", group=groupMA2)
maType13 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA13", group=groupMA2)
maType14 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA14", group=groupMA2)
maType15 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA15", group=groupMA2)
maType16 = input.string("ALMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "LSMA", "HMA", "ALMA"], inline="MA16", group=groupMA2)
// -----------------------
up_color0 = input.color(color.new(#FD63B0, 70), title="", inline="MA0A", group=groupMA1)
up_color1 = input.color(color.new(#E12D7B, 70), title="", inline="MA1A", group=groupMA1)
up_color2 = input.color(color.new(#F67B52, 70), title="", inline="MA2A", group=groupMA1)
up_color3 = input.color(color.new(#EDCD3B, 70), title="", inline="MA3A", group=groupMA1)
up_color4 = input.color(color.new(#3BBC54, 70), title="", inline="MA4A", group=groupMA1)
up_color5 = input.color(color.new(#30A0F5, 70), title="", inline="MA5A", group=groupMA1)
up_color6 = input.color(color.new(#8C3ED1, 70), title="", inline="MA6A", group=groupMA1)
up_color7 = input.color(color.new(#6365CF, 70), title="", inline="MA7A", group=groupMA1)
up_color8 = input.color(color.new(#77B9E0, 70), title="", inline="MA8A", group=groupMA1)
up_color9 = input.color(color.new(#BA7DDB, 70), title="", inline="MA9A", group=groupMA1)
up_color10 = input.color(color.new(#E12D7B, 70), title="", inline="MA10A", group=groupMA2)
up_color11 = input.color(color.new(#F67B52, 70), title="", inline="MA11A", group=groupMA2)
up_color12 = input.color(color.new(#EDCD3B, 70), title="", inline="MA12A", group=groupMA2)
up_color13 = input.color(color.new(#3BBC54, 70), title="", inline="MA13A", group=groupMA2)
up_color14 = input.color(color.new(#30A0F5, 70), title="", inline="MA14A", group=groupMA2)
up_color15 = input.color(color.new(#8C3ED1, 70), title="", inline="MA15A", group=groupMA2)
up_color16 = input.color(color.new(#6365CF, 70), title="", inline="MA16A", group=groupMA2)
down_color0 = input.color(color.new(#FD63B0, 85), title="", inline="MA0A", group=groupMA1)
down_color1 = input.color(color.new(#E12D7B, 85), title="", inline="MA1A", group=groupMA1)
down_color2 = input.color(color.new(#F67B52, 85), title="", inline="MA2A", group=groupMA1)
down_color3 = input.color(color.new(#EDCD3B, 85), title="", inline="MA3A", group=groupMA1)
down_color4 = input.color(color.new(#3BBC54, 85), title="", inline="MA4A", group=groupMA1)
down_color5 = input.color(color.new(#30A0F5, 85), title="", inline="MA5A", group=groupMA1)
down_color6 = input.color(color.new(#8C3ED1, 85), title="", inline="MA6A", group=groupMA1)
down_color7 = input.color(color.new(#6365CF, 85), title="", inline="MA7A", group=groupMA1)
down_color8 = input.color(color.new(#77B9E0, 85), title="", inline="MA8A", group=groupMA1)
down_color9 = input.color(color.new(#BA7DDB, 85), title="", inline="MA9A", group=groupMA1)
down_color10 = input.color(color.new(#E12D7B, 85), title="", inline="MA10A", group=groupMA2)
down_color11 = input.color(color.new(#F67B52, 85), title="", inline="MA11A", group=groupMA2)
down_color12 = input.color(color.new(#EDCD3B, 85), title="", inline="MA12A", group=groupMA2)
down_color13 = input.color(color.new(#3BBC54, 85), title="", inline="MA13A", group=groupMA2)
down_color14 = input.color(color.new(#30A0F5, 85), title="", inline="MA14A", group=groupMA2)
down_color15 = input.color(color.new(#8C3ED1, 85), title="", inline="MA15A", group=groupMA2)
down_color16 = input.color(color.new(#6365CF, 85), title="", inline="MA16A", group=groupMA2)
// -----------------------
ma0 = ma(src, len0, maType0)
ma1 = ma(src, len1, maType1)
ma2 = ma(src, len2, maType2)
ma3 = ma(src, len3, maType3)
ma4 = ma(src, len4, maType4)
ma5 = ma(src, len5, maType5)
ma6 = ma(src, len6, maType6)
ma7 = ma(src, len7, maType7)
ma8 = ma(src, len8, maType8)
ma9 = ma(src, len9, maType9)
ma10 = ma(src, len10, maType10)
ma11 = ma(src, len11, maType11)
ma12 = ma(src, len12, maType12)
ma13 = ma(src, len13, maType13)
ma14 = ma(src, len14, maType14)
ma15 = ma(src, len15, maType15)
ma16 = ma(src, len16, maType16)
// -----------------------
tf19 = input.bool (false, title="Override timeframe", inline="MA02", group=groupMA)
tfAF = input.bool (false, title="Override timeframe", inline="MA03", group=groupMA)
res19 = input.timeframe("", title="", inline="MA02", group=groupMA)
resAF = input.timeframe("", title="", inline="MA03", group=groupMA)
res0 = tf19 ? res19 : input.timeframe("", title="", inline="MA0", group=groupMA1)
res1 = tf19 ? res19 : input.timeframe("", title="", inline="MA1", group=groupMA1)
res2 = tf19 ? res19 : input.timeframe("", title="", inline="MA2", group=groupMA1)
res3 = tf19 ? res19 : input.timeframe("", title="", inline="MA3", group=groupMA1)
res4 = tf19 ? res19 : input.timeframe("", title="", inline="MA4", group=groupMA1)
res5 = tf19 ? res19 : input.timeframe("", title="", inline="MA5", group=groupMA1)
res6 = tf19 ? res19 : input.timeframe("", title="", inline="MA6", group=groupMA1)
res7 = tf19 ? res19 : input.timeframe("", title="", inline="MA7", group=groupMA1)
res8 = tf19 ? res19 : input.timeframe("", title="", inline="MA8", group=groupMA1)
res9 = tf19 ? res19 : input.timeframe("", title="", inline="MA9", group=groupMA1)
res10 = tfAF ? resAF : input.timeframe("", title="", inline="MA10", group=groupMA2)
res11 = tfAF ? resAF : input.timeframe("", title="", inline="MA11", group=groupMA2)
res12 = tfAF ? resAF : input.timeframe("", title="", inline="MA12", group=groupMA2)
res13 = tfAF ? resAF : input.timeframe("", title="", inline="MA13", group=groupMA2)
res14 = tfAF ? resAF : input.timeframe("", title="", inline="MA14", group=groupMA2)
res15 = tfAF ? resAF : input.timeframe("", title="", inline="MA15", group=groupMA2)
res16 = tfAF ? resAF : input.timeframe("", title="", inline="MA16", group=groupMA2)
maT0 = request.security(syminfo.tickerid, res0, ma0, gaps=barmerge.gaps_off)
maT1 = request.security(syminfo.tickerid, res1, ma1, gaps=barmerge.gaps_off)
maT2 = request.security(syminfo.tickerid, res2, ma2, gaps=barmerge.gaps_off)
maT3 = request.security(syminfo.tickerid, res3, ma3, gaps=barmerge.gaps_off)
maT4 = request.security(syminfo.tickerid, res4, ma4, gaps=barmerge.gaps_off)
maT5 = request.security(syminfo.tickerid, res5, ma5, gaps=barmerge.gaps_off)
maT6 = request.security(syminfo.tickerid, res6, ma6, gaps=barmerge.gaps_off)
maT7 = request.security(syminfo.tickerid, res7, ma7, gaps=barmerge.gaps_off)
maT8 = request.security(syminfo.tickerid, res8, ma8, gaps=barmerge.gaps_off)
maT9 = request.security(syminfo.tickerid, res9, ma9, gaps=barmerge.gaps_off)
maT10 = request.security(syminfo.tickerid, res10, ma10, gaps=barmerge.gaps_off)
maT11 = request.security(syminfo.tickerid, res11, ma11, gaps=barmerge.gaps_off)
maT12 = request.security(syminfo.tickerid, res12, ma12, gaps=barmerge.gaps_off)
maT13 = request.security(syminfo.tickerid, res13, ma13, gaps=barmerge.gaps_off)
maT14 = request.security(syminfo.tickerid, res14, ma14, gaps=barmerge.gaps_off)
maT15 = request.security(syminfo.tickerid, res15, ma15, gaps=barmerge.gaps_off)
maT16 = request.security(syminfo.tickerid, res16, ma16, gaps=barmerge.gaps_off)
// -----------------------
plot_color0 = show19 and visible0 ? maT0 >= maT0[trend_flip] ? up_color0 : down_color0 : na
plot_color1 = show19 and visible1 ? maT1 >= maT1[trend_flip] ? up_color1 : down_color1 : na
plot_color2 = show19 and visible2 ? maT2 >= maT2[trend_flip] ? up_color2 : down_color2 : na
plot_color3 = show19 and visible3 ? maT3 >= maT3[trend_flip] ? up_color3 : down_color3 : na
plot_color4 = show19 and visible4 ? maT4 >= maT4[trend_flip] ? up_color4 : down_color4 : na
plot_color5 = show19 and visible5 ? maT5 >= maT5[trend_flip] ? up_color5 : down_color5 : na
plot_color6 = show19 and visible6 ? maT6 >= maT6[trend_flip] ? up_color6 : down_color6 : na
plot_color7 = show19 and visible7 ? maT7 >= maT7[trend_flip] ? up_color7 : down_color7 : na
plot_color8 = show19 and visible8 ? maT8 >= maT8[trend_flip] ? up_color8 : down_color8 : na
plot_color9 = show19 and visible9 ? maT9 >= maT9[trend_flip] ? up_color9 : down_color9 : na
plot_color10 = showAF and visible10 ? maT10 >= maT10[trend_flip] ? up_color10 : down_color10 : na
plot_color11 = showAF and visible11 ? maT11 >= maT11[trend_flip] ? up_color11 : down_color11 : na
plot_color12 = showAF and visible12 ? maT12 >= maT12[trend_flip] ? up_color12 : down_color12 : na
plot_color13 = showAF and visible13 ? maT13 >= maT13[trend_flip] ? up_color13 : down_color13 : na
plot_color14 = showAF and visible14 ? maT14 >= maT14[trend_flip] ? up_color14 : down_color14 : na
plot_color15 = showAF and visible15 ? maT15 >= maT15[trend_flip] ? up_color15 : down_color15 : na
plot_color16 = showAF and visible16 ? maT16 >= maT16[trend_flip] ? up_color16 : down_color16 : na
map0 = plot(maT0, title="MA 0", style=plot.style_line, color= only_fill ? na : plot_color0, linewidth=line_width0)
map1 = plot(maT1, title="MA 1", style=plot.style_line, color= only_fill ? na : plot_color1, linewidth=line_width1)
map2 = plot(maT2, title="MA 2", style=plot.style_line, color= only_fill ? na : plot_color2, linewidth=line_width2)
map3 = plot(maT3, title="MA 3", style=plot.style_line, color= only_fill ? na : plot_color3, linewidth=line_width3)
map4 = plot(maT4, title="MA 4", style=plot.style_line, color= only_fill ? na : plot_color4, linewidth=line_width4)
map5 = plot(maT5, title="MA 5", style=plot.style_line, color= only_fill ? na : plot_color5, linewidth=line_width5)
map6 = plot(maT6, title="MA 6", style=plot.style_line, color= only_fill ? na : plot_color6, linewidth=line_width6)
map7 = plot(maT7, title="MA 7", style=plot.style_line, color= only_fill ? na : plot_color7, linewidth=line_width7)
map8 = plot(maT8, title="MA 8", style=plot.style_line, color= only_fill ? na : plot_color8, linewidth=line_width8)
map9 = plot(maT9, title="MA 9", style=plot.style_line, color= only_fill ? na : plot_color9, linewidth=line_width9)
map10 = plot(maT10, title="MA 10", style=plot.style_line, color= only_fill ? na : plot_color10, linewidth=line_width10)
map11 = plot(maT11, title="MA 11", style=plot.style_line, color= only_fill ? na : plot_color11, linewidth=line_width11)
map12 = plot(maT12, title="MA 12", style=plot.style_line, color= only_fill ? na : plot_color12, linewidth=line_width12)
map13 = plot(maT13, title="MA 13", style=plot.style_line, color= only_fill ? na : plot_color13, linewidth=line_width13)
map14 = plot(maT14, title="MA 14", style=plot.style_line, color= only_fill ? na : plot_color14, linewidth=line_width14)
map15 = plot(maT15, title="MA 15", style=plot.style_line, color= only_fill ? na : plot_color15, linewidth=line_width15)
map16 = plot(maT16, title="MA 16", style=plot.style_line, color= only_fill ? na : plot_color16, linewidth=line_width16)
// -----------------------
//ma1color = (close > maT1 ? ribbon_colorup : ribbon_colordn)
//ma2color = (close > maT2 ? ribbon_colorup : ribbon_colordn)
//ma3color = (close > maT3 ? ribbon_colorup : ribbon_colordn)
//ma4color = (close > maT4 ? ribbon_colorup : ribbon_colordn)
//ma5color = (close > maT5 ? ribbon_colorup : ribbon_colordn)
//ma6color = (close > maT6 ? ribbon_colorup : ribbon_colordn)
//ma7color = (close > maT7 ? ribbon_colorup : ribbon_colordn)
//ma8color = (close > maT8 ? ribbon_colorup : ribbon_colordn)
//ma9color = (close > maT9 ? ribbon_colorup : ribbon_colordn)
//ma10color = (close > maT10 ? ribbon_colorup : ribbon_colordn)
//ma11color = (close > maT11 ? ribbon_colorup : ribbon_colordn)
//ma12color = (close > maT12 ? ribbon_colorup : ribbon_colordn)
//ma13color = (close > maT13 ? ribbon_colorup : ribbon_colordn)
//ma14color = (close > maT14 ? ribbon_colorup : ribbon_colordn)
//ma15color = (close > maT15 ? ribbon_colorup : ribbon_colordn)
//fill(price, map1, visible1 and visiblefill1 ? ma1color : na, title="MA Fill 1")
//fill(price, map2, visible2 and visiblefill2 ? ma2color : na, title="MA Fill 2")
//fill(price, map3, visible3 and visiblefill3 ? ma3color : na, title="MA Fill 3")
//fill(price, map4, visible4 and visiblefill4 ? ma4color : na, title="MA Fill 4")
//fill(price, map5, visible5 and visiblefill5 ? ma5color : na, title="MA Fill 5")
//fill(price, map6, visible6 and visiblefill6 ? ma6color : na, title="MA Fill 6")
//fill(price, map7, visible7 and visiblefill7 ? ma7color : na, title="MA Fill 7")
//fill(price, map8, visible8 and visiblefill8 ? ma8color : na, title="MA Fill 8")
//fill(price, map9, visible9 and visiblefill9 ? ma9color : na, title="MA Fill 9")
//fill(price, map10, visible10 and visiblefill10 ? ma9color : na, title="MA Fill 10")
//fill(price, map11, visible11 and visiblefill11 ? ma9color : na, title="MA Fill 11")
//fill(price, map12, visible12 and visiblefill12 ? ma9color : na, title="MA Fill 12")
//fill(price, map13, visible13 and visiblefill13 ? ma9color : na, title="MA Fill 13")
//fill(price, map14, visible14 and visiblefill14 ? ma9color : na, title="MA Fill 14")
//fill(price, map15, visible15 and visiblefill15 ? ma9color : na, title="MA Fill 15")
// ------------------------
groupBB = "Bollinger Bands"
// ------------------------
visibleBB = input.bool (false , title="Boll.:" , inline="BB1", group=groupBB)
lengthBB = input.int (20, minval=1 , title="" , inline="BB1", group=groupBB)
srcBB = input (close , title="" , inline="BB1", group=groupBB)
resBB = input.timeframe ("" , title="" , inline="BB1", group=groupBB)
mult = input.float (2.0 , title="Standard Dev." , inline="BB2", group=groupBB)
basis = ta.sma(srcBB, lengthBB)
dev = mult * ta.stdev(srcBB, lengthBB)
offset = input.int(0, minval=-500, maxval=500, title="Offset", inline="BB2", group=groupBB)
BB_color = input.color(color.new(color.silver, 97), title="|", 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 , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Basis")
p1 = plot(visibleBB ? MTFupper : na , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Upper")
p2 = plot(visibleBB ? MTFlower : na , color=color.new(color.silver, 95), offset=offset, display=display.none, title="BB - Lower")
fill(p1, p2, color=BB_color, title="BB - Background") |
Monthly Gain in percentage | https://www.tradingview.com/script/L8KKGAlx-Monthly-Gain-in-percentage/ | k_vipz88 | https://www.tradingview.com/u/k_vipz88/ | 11 | 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/
// ยฉ k_vipz88
//@version=5
indicator(title = "Monthly Gain", shorttitle = "MonthlyGain[%]", overlay = false, timeframe = "D")
current = high
previous = low
days = 0
smallest_sample = input.int(22)
for i = smallest_sample to 200 by 1
previous := low[i]
days := i
if high[i-smallest_sample] < low[i]
break
percentage = (current - previous) * 22 * 100/(previous * days)
plot(percentage) |
XAUXXX | https://www.tradingview.com/script/6Fi0dsso-XAUXXX/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 16 | 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("XAUXXX")
metal=input.string("XAU",title="Precious Metal",options=["XAU","XAG","XPT"]) // Precious metal selection (Gold,Silver,Platinum)
[gold_O,gold_H,gold_L,gold_C]=request.security(metal+"USD",timeframe.period,[open,high,low,close]) // OHLC data of Precious metal priced in USD for long term historical data
str=input.string( "CAD","Desired Currency Prefix",options=["CAD","EUR","JPY","GBP","SEK","AUD","NZD","CHF","INR","CNY","HKD","BRL","MXN","TRY","ZAR","RON"])// 3 Letter currency identifier selection
pair="USD"+str // string for FX pair of USD in selected currency
[fx_O,fx_H,fx_L,fx_C]=request.security(pair ,timeframe.period,[open,high,low,close]) // OHLC data for fx pair
o=fx_O*gold_O // \ OHLC data from the selected metal is multiplied
h=fx_H*gold_H // \ _ by the corresponding fx OHLC data to get the
l=fx_L*gold_L // / price of selected precious metal in the desired
c=fx_C*gold_C // / currency
color=o<c?input.color(#acfb00,"Up Candle Color"):input.color(#ff0000,"Down Candle Color") // Color for use in plotting of candles
plotcandle(o,h,l,c,"Metal Price", color=color,wickcolor=color,bordercolor=color) // Plot Candle using the products from multiplying gold OHLC by fx OHLC |
Hourly Midline | https://www.tradingview.com/script/HApefmy9-Hourly-Midline/ | sabricat | https://www.tradingview.com/u/sabricat/ | 39 | 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/
// ยฉ sabricat
//@version=5
indicator("Hourly Midline", overlay=true, max_lines_count=500)
src = input.string('High & Low', options=['High & Low', 'Open & Close'], title='Source')
width = input.int(2, title="Line width")
col = input.color(color.blue, title="Line color")
dc = input.bool(false, title="Show 1H candle levels")
f(src) =>
v_ = src == 'High & Low' ? ((high - low) / 2 + low) : (math.abs((close - open) / 2) + math.min(close, open))
lh_ = src == 'High & Low' ? high : math.max(open, close)
ll_ = src == 'High & Low' ? low : math.min(open, close)
[v_, lh_, ll_]
[v, lh, ll] = request.security(syminfo.tickerid, '60', f(src))
nh = ta.change(hour)
var line li = na
var line lih = na
var line lil = na
if not na(li)
li.set_y1(v)
li.set_y2(v)
li.set_x2(time)
if dc
lih.set_y1(lh)
lih.set_y2(lh)
lih.set_x2(time)
lil.set_y1(ll)
lil.set_y2(ll)
lil.set_x2(time)
if na(li) or nh
li := line.new(time, v, time, v, xloc=xloc.bar_time, width=width, color=col)
if dc
lih := line.new(time, lh, time, lh, xloc=xloc.bar_time, width=1, color=color.green, style=line.style_dotted)
lil := line.new(time, ll, time, ll, xloc=xloc.bar_time, width=1, color=color.red, style=line.style_dotted)
|
Candle Pattern Probability | https://www.tradingview.com/script/6eggpYJr-Candle-Pattern-Probability/ | omararturo | https://www.tradingview.com/u/omararturo/ | 20 | 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/
// ยฉ omararturo
//@version=5
indicator("Candle Pattern Probability", overlay = true)
//var insideDayGroup = "Inside Day"
//input(true, "Inside Day", "Show/Hide Inside Day Candle Pattern")
//input(true, "Engulfing")
// We use `var` to only initialize the table on the first bar.
var table dashboard = table.new(position.top_right, 10, 10, bgcolor = color.white, frame_color = color.gray, border_width = 1, border_color = color.gray)
// Inside Day Probability
var IDFCount = 0
var IDFBullishCount = 0
var IDFBullishSuccessCount = 0
var IDFBearishCount = 0
var IDFBearishSuccessCount = 0
IDFBullishSuccess = false
IDFBearishSuccess = false
insideDay = (high[3] > high[2]) and (low[3] < low[2])
bullish = (low[2] > low[1] and high[2] > high[1]) and (low[2] < close[1] and high[2] > close[1]) and (high[2] > open[1] and low[2] < open[1])
if (insideDay and bullish)
IDFBullishCount += 1
if (low[1] <= low and high[1] <= high)
IDFBullishSuccess := true
IDFBullishSuccessCount += 1
barcolor(IDFBullishSuccess ? color.lime : na, 0)
bearish = (high[2] < high[1] and low[2] < low[1]) and (high[2] > close[1] and low[2] < close[1]) and (high[2] > open[1] and low[2] < open[1])
if (insideDay and bearish)
IDFBearishCount += 1
if (high[1] >= high and low[1] >= low)
IDFBearishSuccess := true
IDFBearishSuccessCount += 1
IDF = (insideDay and (bullish or bearish))
if (IDF)
IDFCount += 1
barcolor(IDF ? color.yellow : na, -2)
// Engulfing
var engulfingCount = 0
var bullishEngulfingCount = 0
var bearishEngulfingCount = 0
//If current high bigger or equal than previous AND current low smaller or equal than previous AND current close bigger than previous high THEN True
bullishEngulfing = high >= high[1] and low <= low[1] and
close > close[1]
if (bullishEngulfing)
engulfingCount += 1
bullishEngulfingCount += 1
barcolor(bullishEngulfing ? color.blue : na, 0)
//If current high bigger or equal than previous high AND current low smaller or equal than previous low AND current close smaller than previous low THEN True
bearishEngulfing = high >= high[1] and low <= low[1] and
close < close[1]
if (bearishEngulfing)
engulfingCount += 1
bearishEngulfingCount += 1
barcolor(bearishEngulfing ? color.blue : na, 0)
if barstate.islast
// We only populate the table on the last bar.
table.cell(dashboard, 0, 0, "Pattern")
table.cell(dashboard, 1, 0, "Count")
table.cell(dashboard, 2, 0, "Bullish")
table.cell(dashboard, 3, 0, "Bullish Success %")
table.cell(dashboard, 4, 0, "Bearish")
table.cell(dashboard, 5, 0, "Bearish Success %")
// Inside Day
table.cell(dashboard, 0, 1, "Inside Day")
table.cell(dashboard, 1, 1, str.tostring(IDFCount))
table.cell(dashboard, 2, 1, str.tostring(IDFBullishCount))
table.cell(dashboard, 3, 1, str.tostring(math.round(IDFBullishSuccessCount * 100 / IDFBullishCount, 2)))
table.cell(dashboard, 4, 1, str.tostring(IDFBearishCount))
table.cell(dashboard, 5, 1, str.tostring(math.round(IDFBearishSuccessCount * 100 / IDFBearishCount, 2)))
// Engulfing
table.cell(dashboard, 0, 2, "Engulfing")
table.cell(dashboard, 1, 2, str.tostring(engulfingCount))
table.cell(dashboard, 2, 2, str.tostring(bullishEngulfingCount))
table.cell(dashboard, 3, 2, "Coming soon")
table.cell(dashboard, 4, 2, str.tostring(bearishEngulfingCount))
table.cell(dashboard, 5, 2, "Coming soon")
|
On-Balance Accumulation Distribution (Volume-Weighted) | https://www.tradingview.com/script/hgbhJQQB-On-Balance-Accumulation-Distribution-Volume-Weighted/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 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/
// ยฉ LeafAlgo
//@version=5
indicator("On-Balance Accumulation Distribution (Volume-Weighted)", overlay=false)
length = input.int(40, minval=1, title="Length")
volumeFactor = input(1.0, title="Volume Factor")
// Calculate OBAD
obad = math.sum(volume * close * volumeFactor * ta.change(close), length)
obadSignal = ta.sma(obad, 9)
// Visualization Enhancements
obadColor = obad >= obadSignal ? color.lime : color.fuchsia
obadbgColor = obad >= obadSignal ? color.new(color.lime, 70) : color.new(color.fuchsia, 70)
obadsigColor = obadSignal > 0 ? color.green : color.maroon
barcolor(obadColor)
bgcolor(obadbgColor)
// Plotting
plot(obad, color=color.blue, linewidth=2, style = plot.style_histogram, title="OBAD Histogram")
plot(obad, color=color.blue, linewidth=2, title='OBAD Line')
plot(obadSignal, color=obadsigColor, linewidth=4, title="OBAD Signal")
// Signal Line Crossovers
obadCrossAbove = ta.crossover(obad, obadSignal)
obadCrossBelow = ta.crossunder(obad, obadSignal)
// Other Plotting Options
hline(0, "Zero Line", color=color.gray) |
ADW - Colour Trend | https://www.tradingview.com/script/AFZ7CFdm-ADW-Colour-Trend/ | Tradespot | https://www.tradingview.com/u/Tradespot/ | 29 | 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/
// ยฉ Andrew Wilkinson
//@version=5
indicator(title='ADW - Colour Trend', overlay=true)
f_p(_length, price) =>
float _max = ta.highest(_length)
float _min = ta.lowest(_length)
100 * (price - _max) / (_max - _min)
int length = input(12)
bool show_barcolor = input(true)
var float cycle_avg = na
var int cycle_counter = na
var int cycle_count = na
var int cycle_trend = 1
var color cycle_col = na
float ph = f_p(length, high)
float pl = f_p(length, low)
float avg = math.avg(ph, pl)
float mean = ta.cum(avg) / (bar_index + 1)
if cycle_trend < 0 and ph >= 0.0
cycle_counter := 0
cycle_trend := 1
cycle_col := color.lime
cycle_count := nz(cycle_count) + 1
cycle_avg *= (1 - 2 / cycle_count) + nz(cycle_counter[1]) * (2 / cycle_count)
cycle_avg
if cycle_trend > 0 and pl <= -100.0
cycle_counter := 0
cycle_trend := -1
cycle_col := color.red
cycle_count := nz(cycle_count) + 1
cycle_avg *= (1 - 2 / cycle_count) + nz(cycle_counter[1]) * (2 / cycle_count)
cycle_avg
color col = na
if show_barcolor
col := avg > -40 ? color.green : avg < -60 ? color.red : color.silver
barcolor(col)
bull_trend = col[1] != color.green and col == color.green
bear_trend = col[1] != color.red and col == color.red
no_trend = col[1] != color.silver and col == color.silver
alertcondition(bull_trend, title='Bull Trend', message='Trend has flipped in bullish favour')
alertcondition(bear_trend, title='Bear Trend', message='Trend has flipped in bearish favour')
alertcondition(no_trend, title='No Trend', message='No strong trend in favour') |
ADW - Momentum | https://www.tradingview.com/script/p8CsPGUb-ADW-Momentum/ | Tradespot | https://www.tradingview.com/u/Tradespot/ | 25 | 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/
// ยฉ Andrew Wilkinson
//@version=5
indicator(title='ADW - Momentum', overlay=false)
// ----------------------- INPUTS -----------------------
Len = input.int(100, title='RMI: Averaging Length', minval=1)
Mom = input.int(2, title='RMI: Momentum Lookback', minval=1)
OVB = input.int(80, title='RMI: Upper Boundary', minval=51, maxval=100)
OVS = input.int(20, title='RMI: Lower Boundary', minval=0, maxval=49)
// EMA Lengths
emaLen1 = input.int(5, title='EMA: Fast Signal', minval=1)
emaLen2 = input.int(12, title='EMA: Standard Signal', minval=1)
emaLen3 = input.int(26, title='EMA: Slow Signal', minval=1)
// Colors inputs
color_rmi = input.color(color.black, title="Color RMI")
color_slow_ma = input.color(color.red, title="Color Slow MA")
color_fill = input.color(color.green, title="Color Fill")
// ----------------------- RMI CALCULATION -----------------------
emaInc = ta.ema(math.max(close - close[Mom], 0), Len)
emaDec = ta.ema(math.max(close[Mom] - close, 0), Len)
RMI = emaDec == 0 ? 0 : 100 - 100 / (1 + emaInc / emaDec)
// ----------------------- PLOTTING -----------------------
plot(OVB, title='OverB', color=color.new(color.black, 0))
plot(OVS, title='OverS', color=color.new(color.black, 0))
hline(50, linestyle=hline.style_dashed)
r1 = plot(RMI, color=color.new(color_rmi, 0), linewidth=1)
// EMAs calculations
fastmaOut = ta.ema(RMI, emaLen1)
standardmaOut = ta.ema(RMI, emaLen2)
slowmaOut = ta.ema(RMI, emaLen3)
m3 = plot(slowmaOut, title='Slow MA', style=plot.style_line, color=color.new(color_slow_ma, 0), linewidth=1)
fill(r1, m3, color=color.new(color_fill, 70))
// ----------------------- CONDITIONS -----------------------
uparrow = RMI > slowmaOut
downarrow = RMI < slowmaOut
buycond = uparrow
sellcond = downarrow
// ----------------------- ALERTS -----------------------
alertcondition(buycond, title='Bull', message='Momentum has flipped bullish')
alertcondition(sellcond, title='Bear', message='Momentum has flipped bearish.')
|
Cumulative TICK [Pt] | https://www.tradingview.com/script/h8gUCab1-Cumulative-TICK-Pt/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 153 | 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
//@version=5
indicator(title='Cumulative TICK [Pt]', shorttitle='CumTICK[Pt]', overlay=false)
tick_src = input.string("USI:TICK", "TICK Source", options = ["USI:TICK", "USI:TICKQ", "USI:TICKI", "USI:TICKA"])
candle_src = input.string('Close', 'TICK Data', options = ['Close', 'Open', 'hl2', 'ohlc4', 'hlc3'])
show_ma = input.bool(false, "Apply SMA | length", inline = 'ma')
ma_len = input.int(5, '', inline = 'ma')
t1 = time(timeframe.period, "0930-1600:23456", "America/New_York")
//get TICK data
[tickO, tickH, tickL, tickC, tickHL2, tickOHLC4, tickHLC3] = request.security(tick_src, timeframe.period, [open, high, low, close, hl2, ohlc4, hlc3])
cumTICK_src = switch candle_src
'Close' => tickC
'Open' => tickO
'hl2' => tickHL2
'ohlc4' => tickOHLC4
'hlc3' => tickHLC3
// Cumulative TICK ----------------------------------
var cumTICK = 0.0
if t1
cumTICK += cumTICK_src
if not t1 or session.islastbar_regular
cumTICK := 0
cumTICK_ma = show_ma ? ta.sma(cumTICK, ma_len) : cumTICK
plot(cumTICK_ma, "Cumulative TICK", cumTICK_ma > 0 and cumTICK_ma < cumTICK_ma[1] ? color.new(color.green,80) : cumTICK_ma > 0 and cumTICK_ma >= cumTICK_ma[1] ? color.new(color.green,50) : cumTICK_ma < 0 and cumTICK_ma < cumTICK_ma[1] ? color.new(color.red, 50) : color.new(color.red, 80), style = plot.style_columns)
bgcolor(not t1 ? color.new(color.white,95) : na, title = 'After-hour Background Color') |
Lot Size Calculator | https://www.tradingview.com/script/4B29SAi2-Lot-Size-Calculator/ | melodicfish | https://www.tradingview.com/u/melodicfish/ | 189 | 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/
// ยฉ melodicfish
//@version=5
indicator("Lot Size Calculator", shorttitle = "Lot Calculator", overlay=true)
// Inputs
gr3="----------------------Trade Settings---------------------"
cur=input.string("USD",title="Account Base Currency",options=["USD","EUR","GBP","CAD","AUD"],inline="Acc",group=gr3)
qty=input.int(100000,title="Units per Lot",options=[1,10,100,1000,10000,100000],tooltip = "Example Forex set to 100,000",inline="Acc",group=gr3)
bal=input.float(50000.00,title="Account Balance",group=gr3)
riskcent=input.float(1.0,title="Account Risk % ",inline="Risk",group=gr3)
target=input.float(1.0,title="Reward Ratio",tooltip = "Risk to Reward ratio. Ex: 1.5:1R",inline="Risk",group=gr3)
gr4="----------------------Trade Box Location Settings---------------------"
p1=input.price(100.0,title="Entry Price Level",tooltip = "Select Entry Price Level on Chart",confirm = true, inline = "p1",group = gr4)
st=input.time(timestamp("1 Jan 2023"), "Trade Box Edge 1", confirm=true,inline = "p1",group = gr4)
p2=input.price(50.0,title="Stop Loss Price Level",tooltip = "Select Stop Loss Price Level on Chart ",confirm = true,inline = "p2")
et=input.time(timestamp("2 Jan 2023"), "Trade Box Edge 2", confirm=true,inline = "p2")
gr1="----------------------Trade Box Settings---------------------"
rBoxCol=input.color(color.rgb(255, 82, 82, 80),title="Risk Box Color",inline="box",group=gr1)
tBoxCol=input.color(color.rgb(33, 149, 243, 80),title="Target Box Color",inline="box",group=gr1)
ext=input.string(extend.none,title="Extend Trade Box",options=[extend.right,extend.left,extend.both,extend.none],inline="box")
gr2="--------------------------Data Table Settings--------------------------"
dashTitleCol=input.color(color.rgb(52, 106, 150),title="Table Title Cell Color",inline="table",group=gr2)
dashDataCol=input.color(color.rgb(145, 165, 181),title="Data Cell",inline="table",group=gr2)
dashTextCol=input.color(color.rgb(0, 0, 0),title="Text",inline="table",group=gr2)
dashBDCol=input.color(color.rgb(16, 26, 62),title="Border",inline="table",group=gr2)
dashBDwth=input.int(1,title="Table Border Width",inline = "Table2")
tableLoc=input.string(position.top_right,title="Table Position",options=[position.top_right,position.middle_right,position.bottom_right,position.top_left,position.middle_left,position.bottom_left],inline="Table2")
// Logic
riskval= math.abs(p1-p2)
riskcent:=math.abs(riskcent)/100
vt= request.security(syminfo.currency==cur?syminfo.tickerid:str.tostring(cur)+syminfo.currency, timeframe.period, close)
notsame=syminfo.currency==cur?false:true
var int decimals = str.length(str.tostring(syminfo.mintick))-2
var RiskBox= box.new(st,p1,et,p2,xloc = xloc.bar_time)
var TargetBox= box.new(st,p2,et,p1,xloc = xloc.bar_time)
var targetVal=0.0
risk=bal*riskcent
DperP=risk/ ((p1-p2)*qty)
if notsame==true
DperP:=DperP*vt
var lots= 0.0
//Box
if barstate.islast
lots:=math.round(math.abs(DperP),3)
box.set_left(RiskBox,st)
box.set_right(RiskBox,et)
box.set_top(RiskBox,p1)
box.set_bottom(RiskBox,p2)
box.set_bgcolor(RiskBox,rBoxCol)
box.set_border_color(RiskBox,rBoxCol)
box.set_left(TargetBox,st)
box.set_right(TargetBox,et)
box.set_bgcolor(TargetBox,tBoxCol)
box.set_border_color(TargetBox,tBoxCol)
if p1>p2
targetVal:= p1+ (riskval*math.abs(target))
box.set_top(TargetBox,targetVal)
box.set_bottom(TargetBox,p1)
else
targetVal:=p1-(riskval*math.abs(target))
box.set_top(TargetBox,p1)
box.set_bottom(TargetBox, targetVal)
box.set_extend(RiskBox,ext)
box.set_extend(TargetBox,ext)
//Table
var dash=table.new(position = position.top_right, columns = 2, rows= 7,frame_width = 5 )
if barstate.islast
table.cell( dash, column = 1, row = 0, text = "Account Balance",text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left )
table.cell(dash, column = 1, row = 1, text = "Account Risk %",text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell(dash, column = 1, row = 2, text = "Cash at Risk" ,text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell( dash, column = 1, row = 3, text = "Entry Price",text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell(dash, column = 1, row = 4, text = "Stop Loss Price " ,text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell(dash, column = 1, row = 5, text = "Target Price" ,text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell(dash, column = 1, row = 6, text = "Lots" ,text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_left)
table.cell( dash, column = 0, row = 0, text ="$ "+ str.tostring(bal) +" " +cur,text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right )
table.cell(dash, column = 0, row = 1, text = "% "+ str.tostring(riskcent*100),text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right)
table.cell(dash, column = 0, row = 2, text = "$ "+ str.tostring(risk),text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right)
table.cell( dash, column = 0, row = 3, text = str.tostring(math.round(p1,4)),text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right)
table.cell(dash, column = 0, row = 4, text = str.tostring(math.round(p2,4)), text_color = dashTextCol, bgcolor=dashTitleCol, text_halign = text.align_right)
table.cell(dash, column = 0, row = 5, text = str.tostring(math.round(targetVal,4)),text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right)
table.cell(dash, column = 0, row = 6, text =str.tostring(lots), text_color = dashTextCol, bgcolor=dashDataCol, text_halign = text.align_right)
table.set_border_color(dash,dashBDCol)
table.set_border_width(dash,dashBDwth)
table.set_position(dash,tableLoc) |
Anchored VWAP Pinch & Handoff, Intervals, and Signals | https://www.tradingview.com/script/VYu6A3GB-Anchored-VWAP-Pinch-Handoff-Intervals-and-Signals/ | allanster | https://www.tradingview.com/u/allanster/ | 1,058 | 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 on TradingView
//@version=5
indicator("Anchored VWAP Pinch & Handoff, Intervals, and Signals", 'Price', overlay = true, max_lines_count = 500, max_labels_count = 500)
evnHi = timestamp("10 Nov 2021 00:00 +0000") // default event for AVWAP hi
evnLo = timestamp("21 Sep 2021 00:00 +0000") // default event for AVWAP lo
evnHO = timestamp("24 Jan 2022 00:00 +0000") // default event for AVWAP handoff
colHi = #ff00664d // default color for AVWAP event hi
colLo = #ff00ff4d // default color for AVWAP event lo
colHO = #9900ff4d // default color for AVWAP handoff
col1D = #0000ffb3 // default color for AVWAP daily
col2D = #00ffffb3 // default color for AVWAP previous daily
col1W = #00ff00b3 // default color for AVWAP weekly
col1M = #ffff00b3 // default color for AVWAP monthly
col3M = #ff6600b3 // default color for AVWAP quarterly
col1Y = #ff0000b3 // default color for AVWAP yearly
colrd = #1E56DAff // default color for AVWAP dividends
colre = #04806Bff // default color for AVWAP earnings #cc2f3cff
colrs = #fb8c00ff // default color for AVWAP splits
colah = #f23645ff // default color for AVWAP auto1
colal = #089981ff // default color for AVWAP auto2
toolD = "[Event Date] [Event Time]\nSet the desired Date & Time or drag the vertical anchor line to a significant Event on chart."
toolE = "[Source] [Zone Type] [Zone Width] [Color]\nSet the anchored VWAP's desired Source, Zone Type, Zone Width, and Color."
toolI = "[Source] [Interval] [Line Width] [Color]\nSet the periodic VWAP's desired Source, Interval, Line Width, and Color."
toolA = "[Signal] [Source] [Line Width] [Color]\nSet the automatic VWAP's desired Signal, Source, Line Width, and Color."
toolS = "[Length] [Bars Left] [Bars Right]\nSet the desired Length applicable for Highest, Lowest, Highest Volume " +
", and Lowest Volume. Set the desired number of Bars Left & Bars Right applicable for Pivot Hi or Pivot Lo."
// inputs pinch & handoff
dateH = input.time (evnHi, 'Event Hi', tooltip = toolD, confirm = false)
sho_H = input.bool (true, 'Show', inline = 'A')
src_H = input.source (hlc3, '', inline = 'A')
zon_H = input.string ('% Above', '', inline = 'A',
options = ['Off', '% Above', '% Below', '% Dual', 'StDev Above', 'StDev Below', 'StDev Dual'])
fct_H = input.float (3, '', minval = 0, step = 0.1, inline = 'A')
col_H = input.color (colHi, '', tooltip = toolE, inline = 'A')
dateL = input.time (evnLo, 'Event Lo', tooltip = toolD, confirm = false)
sho_L = input.bool (true, 'Show', inline = 'B')
src_L = input.source (hlc3, '', inline = 'B')
zon_L = input.string ('% Below', '', inline = 'B',
options = ['Off', '% Above', '% Below', '% Dual', 'StDev Above', 'StDev Below', 'StDev Dual'])
fct_L = input.float (3, '', minval = 0, step = 0.1, inline = 'B')
col_L = input.color (colLo, '', tooltip = toolE, inline = 'B')
dateC = input.time (evnHO, 'HandOff', tooltip = toolD, confirm = false)
sho_C = input.bool (true, 'Show', inline = 'C')
src_C = input.source (hlc3, '', inline = 'C')
zon_C = input.string ('% Below', '', inline = 'C',
options = ['Off', '% Above', '% Below', '% Dual', 'StDev Above', 'StDev Below', 'StDev Dual'])
fct_C = input.float (3, '', minval = 0, step = 0.1, inline = 'C')
col_C = input.color (colHO, '', tooltip = toolE, inline = 'C')
// inputs intervals
sho_D = input.bool (false, 'Show', inline = 'D', group = 'Intervals')
src_D = input.source (hlc3, '', inline = 'D', group = 'Intervals')
res_D = input.timeframe('D', '', inline = 'D', group = 'Intervals')
wid_D = input.int (2, '', minval = 0, inline = 'D', group = 'Intervals')
col_D = input.color (col1D, '', tooltip = toolI, inline = 'D', group = 'Intervals')
sho_P = input.bool (false, 'Show', inline = 'P', group = 'Intervals')
src_P = input.source (hlc3, '', inline = 'P', group = 'Intervals')
res_P = input.timeframe('2D', '', inline = 'P', group = 'Intervals')
wid_P = input.int (2, '', minval = 0, inline = 'P', group = 'Intervals')
col_P = input.color (col2D, '', tooltip = toolI, inline = 'P', group = 'Intervals')
sho_W = input.bool (false, 'Show', inline = 'W', group = 'Intervals')
src_W = input.source (hlc3, '', inline = 'W', group = 'Intervals')
res_W = input.timeframe('W', '', inline = 'W', group = 'Intervals')
wid_W = input.int (2, '', minval = 0, inline = 'W', group = 'Intervals')
col_W = input.color (col1W, '', tooltip = toolI, inline = 'W', group = 'Intervals')
sho_M = input.bool (false, 'Show', inline = 'M', group = 'Intervals')
src_M = input.source (hlc3, '', inline = 'M', group = 'Intervals')
res_M = input.timeframe('M', '', inline = 'M', group = 'Intervals')
wid_M = input.int (2, '', minval = 0, inline = 'M', group = 'Intervals')
col_M = input.color (col1M, '', tooltip = toolI, inline = 'M', group = 'Intervals')
sho_Q = input.bool (false, 'Show', inline = 'Q', group = 'Intervals')
src_Q = input.source (hlc3, '', inline = 'Q', group = 'Intervals')
res_Q = input.timeframe('3M', '', inline = 'Q', group = 'Intervals')
wid_Q = input.int (2, '', minval = 0, inline = 'Q', group = 'Intervals')
col_Q = input.color (col3M, '', tooltip = toolI, inline = 'Q', group = 'Intervals')
sho_Y = input.bool (false, 'Show', inline = 'Y', group = 'Intervals')
src_Y = input.source (hlc3, '', inline = 'Y', group = 'Intervals')
res_Y = input.timeframe('12M', '', inline = 'Y', group = 'Intervals')
wid_Y = input.int (2, '', minval = 0, inline = 'Y', group = 'Intervals')
col_Y = input.color (col1Y, '', tooltip = toolI, inline = 'Y', group = 'Intervals')
sho_d = input.bool (false, 'Show', inline = 'd', group = 'Intervals')
src_d = input.source (hlc3, '', inline = 'd', group = 'Intervals')
res_d = input.string ('Dividends', '', inline = 'd', group = 'Intervals',
options = ['Dividends'])
wid_d = input.int (2, '', minval = 0, inline = 'd', group = 'Intervals')
col_d = input.color (colrd, '', tooltip = toolI, inline = 'd', group = 'Intervals')
sho_e = input.bool (false, 'Show', inline = 'e', group = 'Intervals')
src_e = input.source (hlc3, '', inline = 'e', group = 'Intervals')
res_e = input.string ('Earnings', '', inline = 'e', group = 'Intervals',
options = ['Earnings'])
wid_e = input.int (2, '', minval = 0, inline = 'e', group = 'Intervals')
col_e = input.color (colre, '', tooltip = toolI, inline = 'e', group = 'Intervals')
shoEO = input.bool (true, 'Show Earnings Offsetโโโ', inline = 'E', group = 'Intervals')
adjEO = input.int (0, '', tooltip = '[Show Label] [Offset]', inline = 'E', group = 'Intervals')
sho_s = input.bool (false, 'Show', inline = 's', group = 'Intervals')
src_s = input.source (hlc3, '', inline = 's', group = 'Intervals')
res_s = input.string ('Splits', '', inline = 's', group = 'Intervals',
options = ['Splits'])
wid_s = input.int (2, '', minval = 0, inline = 's', group = 'Intervals')
col_s = input.color (colrs, '', tooltip = toolI, inline = 's', group = 'Intervals')
// inputs auto
shoAH = input.bool (false, 'Show', inline = 'H', group = 'Auto')
typAH = input.string ('Highest', '', tooltip = toolA, inline = 'H', group = 'Auto',
options = ['Highest', 'Lowest', 'Highest Volume', 'Lowest Volume', 'Pivot High', 'Pivot Low'])
srcAH = input.source (high, '', inline = 'H', group = 'Auto')
widAH = input.int (2, '', minval = 1, inline = 'H', group = 'Auto')
colAH = input.color (colah, '', inline = 'H', group = 'Auto')
lenAH = input.int (14, 'SignalBars', minval = 1, inline = 'h', group = 'Auto')
plbAH = input.int (2, '', minval = 0, inline = 'h', group = 'Auto')
prbAH = input.int (2, '', minval = 0, tooltip = toolS, inline = 'h', group = 'Auto')
shoAL = input.bool (false, 'Show', inline = 'L', group = 'Auto')
typAL = input.string ('Lowest', '', tooltip = toolA, inline = 'L', group = 'Auto',
options = ['Highest', 'Lowest', 'Highest Volume', 'Lowest Volume', 'Pivot High', 'Pivot Low'])
srcAL = input.source (low, '', inline = 'L', group = 'Auto')
widAL = input.int (2, '', minval = 1, inline = 'L', group = 'Auto')
colAL = input.color (colal, '', inline = 'L', group = 'Auto')
lenAL = input.int (14, 'SignalBars', minval = 1, inline = 'l', group = 'Auto')
plbAL = input.int (2, '', minval = 0, inline = 'l', group = 'Auto')
prbAL = input.int (2, '', minval = 0, tooltip = toolS, inline = 'l', group = 'Auto')
// returns event avwap tuples with upper/lower specified in percent or standard deviation
avwap(price, anchor, shift, factor) =>
begin = time == anchor
[avwap, stdvU, stdvL] = ta.vwap(price, begin, factor)
zoneA = float(na)
zoneB = float(na)
if shift == '% Above' or shift == '% Dual'
zoneA := ta.vwap((1 + factor / 100) * price, begin)
if shift == '% Below' or shift == '% Dual'
zoneB := ta.vwap((1 - factor / 100) * price, begin)
if shift == 'StDev Above' or shift == 'StDev Dual'
zoneA := stdvU
if shift == 'StDev Below' or shift == 'StDev Dual'
zoneB := stdvL
[avwap, zoneA, zoneB]
[vwapH, zonHA, zonHB] = avwap(src_H, dateH, zon_H, fct_H)
[vwapL, zonLA, zonLB] = avwap(src_L, dateL, zon_L, fct_L)
[vwapC, zonCA, zonCB] = avwap(src_C, dateC, zon_C, fct_C)
// plot event avwap tuples
pltHV = plot(sho_H ? vwapH : na, 'Hi VWAP Line', color.new(col_H, 0), 2)
pltHA = plot(sho_H ? zonHA : na, 'Hi VWAP Uppr', color.new(col_H, 100))
pltHB = plot(sho_H ? zonHB : na, 'Hi VWAP Lowr', color.new(col_H, 100))
fill(pltHV, pltHA, col_H)
fill(pltHV, pltHB, col_H)
pltLV = plot(sho_L ? vwapL : na, 'Lo VWAP Line', color.new(col_L, 0), 2)
pltLA = plot(sho_L ? zonLA : na, 'Lo VWAP Uppr', color.new(col_L, 100))
pltLB = plot(sho_L ? zonLB : na, 'Lo VWAP Lowr', color.new(col_L, 100))
fill(pltLV, pltLA, col_L)
fill(pltLV, pltLB, col_L)
pltCV = plot(sho_C ? vwapC : na, 'HO VWAP Line', color.new(col_C, 0), 2)
pltCA = plot(sho_C ? zonCA : na, 'HO VWAP Uppr', color.new(col_C, 100))
pltCB = plot(sho_C ? zonCB : na, 'HO VWAP Lowr', color.new(col_C, 100))
fill(pltCV, pltCA, col_C)
fill(pltCV, pltCB, col_C)
// returns intervals avwap
shoTF(res) => timeframe.in_seconds(timeframe.period) < timeframe.in_seconds(res)
vwapD = sho_D and shoTF(res_D) ? ta.vwap(src_D, timeframe.change(res_D)) : float(na)
vwapP = sho_P and shoTF(res_P) ? ta.vwap(src_P, timeframe.change(res_P)) : float(na)
vwapW = sho_W and shoTF(res_W) ? ta.vwap(src_W, timeframe.change(res_W)) : float(na)
vwapM = sho_M and shoTF(res_M) ? ta.vwap(src_M, timeframe.change(res_M)) : float(na)
vwapQ = sho_Q and shoTF(res_Q) ? ta.vwap(src_Q, timeframe.change(res_Q)) : float(na)
vwapY = sho_Y and shoTF(res_Y) ? ta.vwap(src_Y, timeframe.change(res_Y)) : float(na)
f_des(_type) => // returns true when _type event occurs
tkrID =
_type == 'Dividends' ? __dividends_tickerid(syminfo.tickerid) :
_type == 'Earnings' ? __earnings_tickerid(syminfo.tickerid) :
_type == 'Splits' ? __splits_tickerid(syminfo.tickerid) :
string(na)
exprn =
_type == 'Dividends' or _type == 'Splits' ? high :
_type == 'Earnings' ? time :
float(na)
event = request.security(tkrID, 'D', exprn, lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
shift = _type == 'Earnings' and adjEO != 0 ? adjEO * timeframe.in_seconds(timeframe.period) * 1000 : 0
renew =
_type == 'Dividends' or _type == 'Splits' ? event != event[1] :
_type == 'Earnings' ? time_close[1] <= event + shift and event + shift < time_close :
bool(na)
if _type == 'Earnings' and shoEO and renew
label.new(bar_index, low, 'E', xloc.bar_index, yloc.belowbar, #3f3f3f, textcolor = #ffffff)
renew
vwapd = sho_d ? ta.vwap(src_d, f_des('Dividends')) : float(na)
vwape = sho_e ? ta.vwap(src_e, f_des('Earnings')) : float(na)
vwaps = sho_s ? ta.vwap(src_s, f_des('Splits')) : float(na)
// plot interval avwap
plt1D = plot(vwapD, 'DTD VWAP Line', col_D, wid_D)
plt2D = plot(vwapP, 'PTD VWAP Line', col_P, wid_P)
plt1W = plot(vwapW, 'WTD VWAP Line', col_W, wid_W)
plt1M = plot(vwapM, 'MTD VWAP Line', col_M, wid_M)
plt3M = plot(vwapQ, 'QTD VWAP Line', col_Q, wid_Q)
plt1Y = plot(vwapY, 'YTD VWAP Line', col_Y, wid_Y)
plt_d = plot(vwapd, 'DVD VWAP Line', col_d, wid_d)
plt_e = plot(vwape, 'ERN VWAP Line', col_e, wid_e)
plt_s = plot(vwaps, 'SPL VWAP Line', col_s, wid_s)
// returns auto vwaps from signals within lengths of bars or pivots
svwap(
show1, source1, signal1, length1, barsL1, barsR1, color1, width1,
show2, source2, signal2, length2, barsL2, barsR2, color2, width2) =>
idxCB = bar_index // index current bar
valS1 = float(na) // value signal source1
idxS1 = int(na) // index signal source1
sS1V1 = float(na) // sum of source1 * volume1
sVol1 = float(na) // sum of volume1
valP1 = float(na) // previous value of svwap1
valC1 = float(na) // current value of svwap1
valS2 = float(na) // value signal source2
idxS2 = int(na) // index signal source2
sS2V2 = float(na) // sum of source2 * volume2
sVol2 = float(na) // sum of volume2
valP2 = float(na) // previous value of svwap2
valC2 = float(na) // current value of svwap2
lines = line(na) // lines drawn for each bar of avwap
if not show1 and not show2
valC1 := float(na)
valC2 := float(na)
else
a_allLines = line.all // garbage collection
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
if show1 // calc auto vwap1
valS1 :=
signal1 == 'Highest' ? ta.highest(source1, length1) :
signal1 == 'Lowest' ? ta.lowest (source1, length1) :
signal1 == 'Highest Volume' ? ta.highest(volume, length1) :
signal1 == 'Lowest Volume' ? ta.lowest (volume, length1) :
signal1 == 'Pivot High' ?
ta.valuewhen(not na(ta.pivothigh(source1, barsL1, barsR1)), source1[barsR1], 0) :
signal1 == 'Pivot Low' ?
ta.valuewhen(not na(ta.pivotlow (source1, barsL1, barsR1)), source1[barsR1], 0) :
float(na)
if signal1 == 'Highest' or signal1 == 'Lowest'
for i = 0 to length1 - 1
if source1[i] == valS1
idxS1 := bar_index[i]
break
if signal1 == 'Highest Volume' or signal1 == 'Lowest Volume'
for i = 0 to length1 - 1
if volume[i] == valS1
idxS1 := bar_index[i]
break
if signal1 == 'Pivot High' or signal1 == 'Pivot Low'
idxS1 :=
signal1 == 'Pivot High' ?
ta.valuewhen(not na(ta.pivothigh(source1, barsL1, barsR1)), bar_index[barsR1], 0) :
signal1 == 'Pivot Low' ?
ta.valuewhen(not na(ta.pivotlow (source1, barsL1, barsR1)), bar_index[barsR1], 0) :
int(na)
nBars = 1 + idxCB - idxS1
for i = nBars - 1 to 0 // draw lines for current event vwap
sS1V1 := nz(sS1V1) + nz(source1[i] * volume[i])
sVol1 := nz(sVol1) + nz(volume[i])
valP1 := nz(valC1, na)
valC1 := sS1V1 / sVol1
lines := line.new(idxCB - i - 1, valP1, idxCB - i, valC1, xloc.bar_index, extend.none, color1, width = width1)
if show2 // calc auto vwap2
valS2 :=
signal2 == 'Highest' ? ta.highest(source2, length2) :
signal2 == 'Lowest' ? ta.lowest (source2, length2) :
signal2 == 'Highest Volume' ? ta.highest(volume, length2) :
signal2 == 'Lowest Volume' ? ta.lowest (volume, length2) :
signal2 == 'Pivot High' ?
ta.valuewhen(not na(ta.pivothigh(source2, barsL2, barsR2)), source1[barsR2], 0) :
signal2 == 'Pivot Low' ?
ta.valuewhen(not na(ta.pivotlow (source2, barsL2, barsR2)), source1[barsR2], 0) :
float(na)
if signal2 == 'Highest' or signal2 == 'Lowest'
for i = 0 to length2 - 1
if source2[i] == valS2
idxS2 := bar_index[i]
break
if signal2 == 'Highest Volume' or signal2 == 'Lowest Volume'
for i = 0 to length2 - 1
if volume[i] == valS2
idxS2 := bar_index[i]
break
if signal2 == 'Pivot High' or signal2 == 'Pivot Low'
idxS2 :=
signal2 == 'Pivot High' ?
ta.valuewhen(not na(ta.pivothigh(source2, barsL2, barsR2)), bar_index[barsR2], 0) :
signal2 == 'Pivot Low' ?
ta.valuewhen(not na(ta.pivotlow (source2, barsL2, barsR2)), bar_index[barsR2], 0) :
int(na)
nBars = 1 + idxCB - idxS2
for i = nBars - 1 to 0 // draw lines for current event vwap
sS2V2 := nz(sS2V2) + nz(source2[i] * volume[i])
sVol2 := nz(sVol2) + nz(volume[i])
valP2 := nz(valC2, na)
valC2 := sS2V2 / sVol2
lines := line.new(idxCB - i - 1, valP2, idxCB - i, valC2, xloc.bar_index, extend.none, color2, width = width2)
[valC1, valC2]
[vwap1, vwap2] = svwap(
shoAH, srcAH, typAH, lenAH, plbAH, prbAH, colAH, widAH,
shoAL, srcAL, typAL, lenAL, plbAL, prbAL, colAL, widAL)
plot(vwap1, 'Auto1 VWAP Line', display = display.data_window)
plot(vwap2, 'Auto2 VWAP Line', display = display.data_window) |
Moving Average Contrarian Indicator | https://www.tradingview.com/script/T9QXtBlL-Moving-Average-Contrarian-Indicator/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 187 | 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/
// ยฉ LeafAlgo
//@version=5
indicator("Moving Average Contrarian Indicator", overlay=false)
length = input(40, "Moving Average Length")
src = close
// Calculate moving average
ma = ta.sma(src, length)
// Calculate distance from price to moving average
distance = src - ma
// Calculate normalized MACI
distance_min = ta.lowest(distance, length)
distance_max = ta.highest(distance, length)
maci = ((distance - distance_min) / (distance_max - distance_min)) * 100
// Determine barcolor and background color conditions
maci_sma = ta.sma(maci, length)
barC = maci > maci_sma and maci > 30 ? color.lime : maci < maci_sma and maci < 70 ? color.fuchsia : color.yellow
backC = maci > maci_sma and maci > 30 ? color.new(color.lime, 80) : maci < maci_sma and maci < 70 ? color.new(color.fuchsia, 80) : color.new(color.yellow, 80)
// Color
barcolor(barC)
bgcolor(backC, transp=70)
// Plotting
plot(maci, title="MACI", color=barC, style=plot.style_histogram, linewidth=4)
plot(maci_sma, title='MACI SMA', color=color.maroon, linewidth=2)
// Overbought and oversold levels
hline(70, "Overbought", color=color.fuchsia)
hline(30, "Oversold", color=color.lime) |
Moving Average Reversals [QuantVue] | https://www.tradingview.com/script/54tj7Dnp-Moving-Average-Reversals-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 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/
// ยฉ AlgoBuddy
//@version=5
indicator("Moving Average Reversals", shorttitle = 'Moving Average Reversals', precision = 2)
//inputs
var g1 = 'Moving Average'
imatype = input.string(defval = 'EMA', title = 'MA Type', options = ['EMA', 'SMA', 'HMA', 'WMA', 'VWMA'], inline = '1', group = g1)
imalength = input.int(21, 'MA Length', minval = 1, maxval = 300, step = 1, inline = '1', group = g1)
isrc = input.source(defval = close, title ='Source To Meassure Distance From ', inline = '2', group = g1, tooltip = 'Select the source to calculate it\'s distance from the moving average')
extColor = input.color(color.rgb(255,0,0), 'Extended Color', inline = '3', group = g1)
inColor = input.color(color.rgb(0,255,0), 'In Range Color', inline = '3', group = g1)
var g2 = 'Extensions'
showExt = input.bool(true, 'Highlight Highest Extensions Up and Down', group = g2)
extDown = input.color(color.new(color.aqua,70), 'Highest Extension Down', group = g2)
extUp = input.color(color.new(color.maroon,70), 'Highest Extension Up', group = g2)
var g3 = 'Moving Average of Extensions'
showMa2 = input.bool(true, 'Show Moving Average of Extensions', inline = '1', group = g3)
ma2Len = input.int(10, 'Length', inline = '2', group = g3)
ma2Color = input.color(color.orange, 'Color', inline = '2', group = g3)
// get the ma
ma = switch imatype
'EMA' => ta.ema(close, imalength)
'SMA' => ta.sma(close, imalength)
'HMA' => ta.hma(close, imalength)
'WMA' => ta.wma(close, imalength)
'VWMA' => ta.vwma(close, imalength)
// calculate the distance from the source to the moving average
distance = ((isrc / ma) - 1) * 100
extensionMa = ta.sma(distance, ma2Len)
//find the highest and lowest extensions from the selected MA over the past year
lowest = ta.lowest(distance,252)
highest = ta.highest(distance,252)
//create the gradient color
gradient = distance > 0 ? color.from_gradient(distance, 0, highest, inColor, extColor) : color.from_gradient(distance, lowest, 0, extColor, inColor)
//plots
plot(distance, "Distance From Ma", style= plot.style_columns, linewidth = 4, color = gradient)
plot(showMa2 ? extensionMa : na, 'Extension MA', color = ma2Color)
bgcolor(showExt and distance == highest ? extUp : showExt and distance == lowest ? extDown : na) |
Discrete Fourier Transform Overlay [wbburgin] | https://www.tradingview.com/script/gThgCf69-Discrete-Fourier-Transform-Overlay-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 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/
// ยฉ wbburgin
//@version=5
indicator('Discrete Fourier Transform Overlay [wbburgin]', shorttitle='DFT Overlay [wbburgin]', overlay=true,
max_bars_back=2000, max_lines_count=500)
import jdehorty/KernelFunctions/2 as kernel
DFT(x, y, Nx, _dir) =>
float _arg = 0.0
float _cos = 0.0
float _sin = 0.0
float xArr_i = 0.0
float yArr_i = 0.0
xArr = array.new_float(array.size(x))
yArr = array.new_float(array.size(y))
for i = 0 to Nx - 1 by 1
xArr_i := 0.0
yArr_i := 0.0
kx = float(i) / float(Nx)
_arg := -_dir * 2 * math.pi * kx
for k = 0 to Nx - 1 by 1
_cos := math.cos(k * _arg)
_sin := math.sin(k * _arg)
xArr_i += array.get(x, k) * _cos - array.get(y, k) * _sin
yArr_i += array.get(x, k) * _sin + array.get(y, k) * _cos
yArr_i
array.set(xArr, i, xArr_i)
array.set(yArr, i, yArr_i)
if _dir == 1
for i = 0 to Nx - 1 by 1
array.set(x, i, array.get(xArr, i) / float(Nx))
array.set(y, i, array.get(yArr, i) / float(Nx))
else
for i = 0 to Nx - 1 by 1
array.set(x, i, array.get(xArr, i))
array.set(y, i, array.get(yArr, i))
//======================================================================================================================
// INPUTS
//======================================================================================================================
N = input.int(20,"Fourier Period")
xval = input.source(close,"Fourier X Series",tooltip = "i.e. the source of the discrete Fourier"+
" transform (with the Y Series being the bars through time.)")
highlighting = input.bool(true,"Highlighting")
smoothing = input.int(10,"Kernel Smoothing")
//======================================================================================================================
// CALCULATIONS
//======================================================================================================================
// Fourier transform
x = array.new_float(N, 0.0)
y = array.new_float(N, 0.0)
for i = 0 to N - 1
array.set(x, i, xval[i])
array.set(y, i, 0.0)
DFT(x, y, N, 1)
mag = array.new_float(N, 0.0)
for i = 0 to N - 1
mag_i = math.sqrt(math.pow(array.get(x, i), 2) + math.pow(array.get(y, i), 2))
array.set(mag, i, mag_i)
dft = array.get(mag,0)
dfts = kernel.rationalQuadratic(dft,25,1,smoothing)
//======================================================================================================================
// DISPLAY
//======================================================================================================================
ft = plot(dft, "DFT", color= color.white)
fts = plot(dfts, "Smoothing", color = dfts > dft ? color.red : color.lime)
fill(ft,fts,color = highlighting and dfts > dft ? color.new(color.red,75) : highlighting and dfts < dft ? color.new(color.lime,75) : na) |
Projected Volume | https://www.tradingview.com/script/ZcV62bqJ-Projected-Volume/ | gabasco | https://www.tradingview.com/u/gabasco/ | 30 | 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/
// ยฉ gabasco
//@version=5
indicator(title="Projected Volume", overlay=false, format = format.volume, max_bars_back=5000)
// 1. Input
volumeTypeInput = input.string(defval="Financial", title="Volume Type", options=["Financial", "Quantity"], group="Settings")
maTypeInput = input.string(defval="SMA", title="Type", options=["SMA", "EMA", "WMA", "RMA", "HMA", "VWMA", "SWMA"], group="Moving Average")
maLengthInput = input.int(defval=20, title="Length", minval=1, step=1, group="Moving Average")
maShowInput = input.bool(defval=true, title="Show", group="Moving Average")
tradingHoursInput = input.float(defval=24.0, title="Trading Hours", minval=0.5, maxval=24, step=0.5, tooltip="Affects only the daily timeframe", group="1-day timeframe (only)")
// 2. Variables
color realColor = close > open ? color.rgb(146, 210, 204) : color.rgb(247, 169, 167)
color projectedColor = color.rgb(181, 182, 187)
float realVol = 0.0
float cumVol = 0.0
float projectedVol = 0.0
float tf = 0
float tradingMinutes = tradingHoursInput * 60
float dayInMinutes = 1440
// 3 . Functions
getMA(maType, maLen) =>
switch maType
"SMA" => ta.sma(realVol, maLen)
"EMA" => ta.ema(realVol, maLen)
"WMA" => ta.wma(realVol, maLen)
"RMA" => ta.rma(realVol, maLen)
"HMA" => ta.hma(realVol, maLen)
"VWMA" => ta.vwma(realVol, maLen)
"SWMA" => ta.swma(realVol)
// 4. Calculations
if timeframe.isdaily
tf := timeframe.in_seconds(timeframe.period) * tradingMinutes / dayInMinutes
else
tf := timeframe.in_seconds(timeframe.period)
elapsedTime = (timenow - time) / 1000
if volumeTypeInput == "Financial"
projectedVol := volume * close * tf / elapsedTime
realVol := volume * close
else
projectedVol := volume * tf / elapsedTime
realVol := volume
// Check for error
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
ma = getMA(maTypeInput, maLengthInput)
// 5. Drawings
plot(barstate.islast ? projectedVol : na, title="Projected", color=barstate.islast ? projectedColor: realColor, style = plot.style_columns)
plot(realVol, color=realColor, title="Real", style = plot.style_columns)
plot(maShowInput ? ma : na, title="MA", color=color.blue, linewidth=1) |
Stochastic [Tcs] | OSC | https://www.tradingview.com/script/jDMLUxYJ-Stochastic-Tcs-OSC/ | zendrer | https://www.tradingview.com/u/zendrer/ | 34 | 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/
// ยฉ zendrer
//@version=5
indicator("TCS โข STOCH", overlay = false)
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//INPUT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//----------------------------------------------------------------
length = input.int(15, 'Length', minval=1)
src = input(close, 'Source')
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//FUNCTION
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//STOCH RSI
//----------------------------------------------------------------
rsi = ta.rsi(src,length )
rsima = ta.ema(rsi, length)
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
k = ta.sma(ta.stoch(rsi, rsi, rsi, length), smoothK)
d = ta.sma(k, smoothD)
//----------------------------------------------------------------
//TRIGGER
//----------------------------------------------------------------
triggerx = (ta.ema(ta.rsi(ta.ema(src, length/2), length), length/2))
trigger = (ta.vwma(ta.stoch(triggerx, triggerx, triggerx, length), length))
trigger1 = (ta.vwma(ta.stoch(triggerx, triggerx, triggerx, length), length)) + 80
trigger2 = (ta.vwma(ta.stoch(triggerx, triggerx, triggerx, length), length)) - 80
trigma = ta.stoch(trigger,trigger,trigger,length)
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//PLOT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//----------------------------------------------------------------
A = plot(trigma, color= color.new(color.gray,80))
B = plot(trigger , color=color.new(color.white,80))
C = plot(trigger1 , "oversold", color=(trigger1) > 100 ? na : color.new(color.purple,100), editable=false)
D = plot(trigger2 , "overbought", color=(trigger2) < 0 ? na : color.new(color.lime,100), editable=false)
E = plot(0, color = color.new(color.white,100), editable=false)
F = plot(100, color = color.new(color.white,100), editable=false)
fill(E, D, color = (trigger2) < 0 ? na : (trigger2 > trigger2[1] ? color.new(color.lime,10) : color.new(color.lime,60)))
fill(F, C, color = (trigger1) > 100 ? na : (trigger1 < trigger1[1] ? color.new(color.purple,10) : color.new(color.purple,60)))
fill(A,B, color = trigger > trigma ? color.new(color.gray,30) :color.new(color.white,30))
hline(100)
hline(0)
plot(ta.crossunder(k,d) and k > 60 and trigma > 99 and trigger > 90 ? trigger : na, color = color.purple , style = plot.style_cross, linewidth = 3, editable=false)
plot(ta.crossover(k,d) and k < 40 and trigma < 1 and trigger < 35 ? trigger : na, color = color.lime , style = plot.style_circles, linewidth = 3, editable=false)
plot(ta.crossunder(k,d) and k > 60 and trigma > 99 and trigger > 65 ? trigger : na, color = color.purple , style = plot.style_circles, linewidth = 3, editable=false)
//plot(trigger < 50 and ta.crossunder(trigger,trigma) or ta.crossover(trigger,0) and rsi > 55 and rsi > rsima and trigger < trigma and trigger1 > trigger1[1] and trigger1 < 100 ? trigger : na, color = color.lime , style = plot.style_circles, linewidth = 3, editable=false)
//plot(trigger > 50 and ta.crossover(trigger,trigma) or ta.crossunder(trigger,100) and rsi < 55 and rsi < rsima and trigger > trigma and trigger2 < trigger2[1] and trigger2 > 0 ? trigger : na, color = color.purple , style = plot.style_circles, linewidth = 3, editable=false)
//plot(ta.crossover(trigma,trigger1) and rsi > 47 and rsi > rsima ? trigger : na, color = color.lime , style = plot.style_cross, linewidth = 3, editable=false)
//plot(ta.crossunder(trigma,trigger2) and rsi < 47 and rsi < rsima ? trigger : na, color = color.purple , style = plot.style_cross, linewidth = 3, editable=false)
//----------------------------------------------------------------
//END |
Advanced Choppiness Indicator with CPMA | https://www.tradingview.com/script/JeNcCUxP-Advanced-Choppiness-Indicator-with-CPMA/ | chhagansinghmeena | https://www.tradingview.com/u/chhagansinghmeena/ | 82 | 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/
// ยฉ chhagansinghmeena
//@version=5
indicator("Advanced Choppiness Indicator with CPMA", format=format.price, precision=0, timeframe="", timeframe_gaps=true)
// Import necessary scripts
import chhagansinghmeena/BankNifty_CSM/16 as CSM
// This is an Advanced Choppiness Indicator with CPMA (Conceptive Price Moving Average).
// It calculates the choppiness index and detects choppy zones in the market based on ATR (Average True Range) and CPMA.
// The indicator also provides a custom trend calculation using CPMA and plots the results on the chart.
// It includes a range box that highlights the choppy zones and provides visual cues for trend determination.
// Summary:
// This script calculates the choppiness index and detects choppy zones based on the ATR and CPMA indicators.
// It also provides a custom trend calculation using CPMA and plots the results on the chart.
// Choppy zones are highlighted with a range box, and trend determination is based on the CPMA angle and choppiness thresholds.
// To use this indicator, apply it to your chart and observe the choppy zones and trend indications.
// Adjust the input parameters (ATR length, CPMA length, thresholds) according to your preferences and trading strategy.
// Choppy zones indicate periods of low momentum and erratic price movement, while trends indicate sustained price direction.
// Use this information to make informed trading decisions, such as avoiding choppy zones and taking trades in the direction of the trend.
// Choppiness Calculation
length = input.int(14, minval=1, title="ATR Length")
candleBodySize = input.int(10, minval=1, title="Candle Body Size")
cpma_length = input.int(14, minval=1, title="CPMA Length", tooltip="This is a custom trend indicator. It provides better support and resistance levels than SMA or EMA.")
// Choppy Zone Thresholds
choppyThresholdHigh = input(60, title="Choppy Zone High Threshold")
choppyThresholdLow = input(40, title="Choppy Zone Low Threshold")
//Chopiness calculation
trueRange = ta.tr(true)
atrValue = ta.sma(trueRange, length)
highestHigh = ta.highest(high, length)
lowestLow = ta.lowest(low, length)
span = 25 / (highestHigh - lowestLow) * lowestLow
choppiness = atrValue / (highestHigh - lowestLow) * 100
// Conceptive Price Moving Average (CPMA) Calculation
CPMA = CSM.CSM_CPMA(length = cpma_length)
// Calculate the angle of CPMA
x1_CPMA = 0
x2_CPMA = 1
y1_CPMA = 0
y2_CPMA = (CPMA[1] - CPMA) / hlc3 * span
c_CPMA = math.sqrt((x2_CPMA - x1_CPMA)*(x2_CPMA - x1_CPMA) + (y2_CPMA - y1_CPMA)*(y2_CPMA - y1_CPMA))
emaAngle_1 = math.round(180 * math.acos((x2_CPMA - x1_CPMA)/c_CPMA) / math.pi)
emaAngle = y2_CPMA > 0 ? -emaAngle_1 : emaAngle_1
// Determine Choppy Zones
isChoppy = choppiness >= choppyThresholdLow and choppiness <= choppyThresholdHigh
candleBody = math.abs(close - open)
isGapTrending = math.abs(CPMA - close) < (candleBodySize + 4) or (candleBody <= candleBodySize and candleBody[1] <= candleBodySize)
// Determine Trend
// Thanks For LUX ALGO for gradient display idea.
[cpmaPlotVal, colorUp] = CSM.getGradientColor(isFirstbar = barstate.isfirst, src = ta.rsi(CPMA,cpma_length)/100 , length = cpma_length, isSmoothed = true) //getSmoothedValue(src = ta.rsi(CPMA,cpma_length)/100, length = cpma_length)
Is_choppiness = isGapTrending or isChoppy or emaAngle < 0 and emaAngle > -3
// Plotting
plot(Is_choppiness ? 1 : na, color=color.yellow, style=plot.style_areabr, title = "Chopiness Area")
plot(not Is_choppiness ? cpmaPlotVal : na , color= colorUp , style=plot.style_histogram , title = "Histogram Trend")
plot(cpmaPlotVal, color= close > CPMA ? color.green : color.red , style=plot.style_line, title = "Trend Line", linewidth = 2) |
LNL Scalper Arrows | https://www.tradingview.com/script/2uF32Xaq-LNL-Scalper-Arrows/ | lnlcapital | https://www.tradingview.com/u/lnlcapital/ | 236 | 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
//
// LNL Scalper Arrows
//
// The indicator consist of various different types of candlestick patterns that are truly time tested by multiptle veteran traders. These arrows are a combination
// of short-term scalping strategies taught by Linda Raschke & a trader that goes by name Quant Trade Edge. These strategies/patterns occur regularly within the
// markets. They offer high probability quick [scalping] moves during the trending days. These four patterns are based on pure price action, no oscillators, no trend
// no momentum indicators involved. Trend (ema) is there just as a simple trending gauge. This is not even an indicator but rather a collection of candlestick patterns.
//
// LNL Scalper Arrows were designed specifically for intra-day trading. Mostly useful for the futures but also stocks as well. These arrows can work anywhere between
// the fast-moving 512 or 1600 tick charts to a 1min, 2min and up to 5min or 10min charts.
//
// Inspired by Linda Bradford Raschke & Quant Trade Edge
//
// Created by L&L Capital
//
indicator("LNL Scalper Arrows",shorttitle = "LNL Scalper Arrows", overlay = true)
// Inputs
string TailSignalType = input.string("Signal", "Tail Signal Type", options = ["Signal", "SignalBrake"],tooltip = "The Trigger can be viewed in two different ways: #1 Signal: Plots the trigger before the triggerbar, basically right when the pattern is formed but not yet triggered. The signal is triggered once the next candle break the high or low of the current candle. #2 SignalBrake: Plots the trigger afte the break of the high or low of the actual pattern. It is basically a candle after the signal candle. (Signal is better for trading because it gives you time to prepare for the actual break of the high or low = the actual signal. SignalBrake is great for looking back in history only for the patterns that actually traded).")
string ScalpSignalType = input.string("Signal", "Scalp Signal Type", options = ["Signal", "SignalBrake"],tooltip = "The Trigger can be viewed in two different ways: #1 Signal: Plots the trigger before the triggerbar, basically right when the pattern is formed but not yet triggered. The signal is triggered once the next candle break the high or low of the current candle. #2 SignalBrake: Plots the trigger afte the break of the high or low of the actual pattern. It is basically a candle after the signal candle. (Signal is better for trading because it gives you time to prepare for the actual break of the high or low = the actual signal. SignalBrake is great for looking back in history only for the patterns that actually traded).")
string HoagieSignalType = input.string("Signal", "Hoagie Signal Type", options = ["Signal", "SignalBrake"],tooltip = "The Trigger can be viewed in two different ways: #1 Signal: Plots the trigger before the triggerbar, basically right when the pattern is formed but not yet triggered. The signal is triggered once the next candle break the high or low of the current candle. #2 SignalBrake: Plots the trigger afte the break of the high or low of the actual pattern. It is basically a candle after the signal candle. (Signal is better for trading because it gives you time to prepare for the actual break of the high or low = the actual signal. SignalBrake is great for looking back in history only for the patterns that actually traded).")
string UmbrellaSignalType = input.string("Signal", "Umbrella Signal Type", options = ["Signal", "SignalBrake"],tooltip = "The Trigger can be viewed in two different ways: #1 Signal: Plots the trigger before the triggerbar, basically right when the pattern is formed but not yet triggered. The signal is triggered once the next candle break the high or low of the current candle. #2 SignalBrake: Plots the trigger afte the break of the high or low of the actual pattern. It is basically a candle after the signal candle. (Signal is better for trading because it gives you time to prepare for the actual break of the high or low = the actual signal. SignalBrake is great for looking back in history only for the patterns that actually traded).")
TrendStrength = input(20,title = "Trend Strength",tooltip = "Trend Strength: Adjustable length for the Trend Gauge (exponential moving average). Although there is no ideal ema length. Frequently used lenghts are: 8,9,10,13,20,21,34")
PinBarBTWRatio = input.float(2.5,step = 0.5,title = "PinBar BTW Ratio",tooltip = "PinBar (Body-To-Wick) Ratio: You can set the size of the body of a pin bar candle for Eat the Tail and Umbrella patterns.PinBar BTW Ratio measures the ratio between the wick & the body of the candle. Ref. interval 2.0 - 5.0 (ideal pin bar is 2.0 - 3.0)")
ATRLength = input(7,title = "ATR Length",tooltip = "ATR Length: Adjustable Length for the ATR Label (table) in the top corner. This length also moves with the Target & Stop values. Default is set to 7 period ATR.")
RoundNumbersTo = input(2,title = "Round Numbers To",tooltip = "Round Numbers To: Customizable decimal numbers in the ATR Label. Some instruments have much smaller tick size. Such as crude oil or bonds. For NQ trading use 0 (round numbers).")
TargetATR = input(2,title = "Target = ATR /",tooltip = "TargetATR: Adjustable target formula. Default is ATR devided by 2.")
StopATR = input(1,title = "Stop = ATR *",tooltip = "StopATR: Adjustable stop formula. Default is ATR times 1 or TargetATR times 2.")
// Functions & Definitons
iTelo = math.abs(close-open)
bPinUp = (((high - low) / (iTelo)) > PinBarBTWRatio) and math.max(open,close)<high-((high-low)/2)
bPinDown = (((high - low)/(iTelo)) > PinBarBTWRatio) and math.min(open,close)>low+((high-low)/2)
bSignalUp = bPinUp
bSignalDown = bPinDown
up = bSignalUp ? high : na
down = bSignalDown ? high : na
greenbar = close > open
redbar = close < open
ema8 = ta.ema(close,8)
trendd = ta.ema(close,TrendStrength)
[Mid1, Kup, Kdn] = ta.kc(close, 21, 1.0)
[Mid2, KUP, KDN] = ta.kc(close, 21, 1.5)
// Tail Arrows [Eat The Tail]
TailUp = if TailSignalType == "Signal"
bPinUp and hl2[1] > ema8 and high[2] < high[1] and hl2 > ema8 and hl2 > Kup
else if TailSignalType == "SignalBrake"
high > up[1] and hl2 > hl2[1] and high[2] < high[1] and hl2[1] > ema8 and hl2 > ema8 and hl2 > Kup
TailDown = if TailSignalType == "Signal"
bPinDown and hl2[1] < ema8 and low[2] > low[1] and hl2 < ema8 and hl2 < KDN
else if TailSignalType == "SignalBrake"
high < down[1] and hl2 < hl2[1] and low[2] > low[1] and hl2[1] < ema8 and hl2 < ema8 and hl2 < KDN
plotshape(TailUp,title='Tail Up',style=shape.triangleup,location=location.belowbar,color=#8cff00,size=size.small,display=display.none)
plotshape(TailDown,title='Tail Down',style=shape.triangledown,location=location.abovebar,color=#faa1a4,size=size.small,display=display.none)
// Scalp Arrows [Scallops]
ScalpUp = if ScalpSignalType == "Signal"
close > open and low < low[1] and high < high[1] and hl2 > trendd
else if ScalpSignalType == "SignalBrake"
close[1] > open[1] and low[1] < low[2] and high[1] < high[2] and hl2[1] > trendd and high > high[1]
ScalpDown = if ScalpSignalType == "Signal"
close < open and low > low[1] and high > high[1] and hl2 < trendd
else if ScalpSignalType == "SignalBrake"
close[1] < open[1] and low[1] > low[2] and high[1] > high[2] and hl2[1] < trendd and low < low[1]
plotshape(ScalpUp,title='Scalp Up',style=shape.triangleup,location=location.belowbar,color=#27c22e,size=size.small)
plotshape(ScalpDown,title='Scalp Down',style=shape.triangledown,location=location.abovebar,color=#ff0000,size=size.small)
// Hoagie Arrows [Hoagies]
HoagieUp = if HoagieSignalType == "Signal"
high < high[1] and low > low[1] and high[1] < high[2] and low[1] > low[2] and hl2 > trendd
else if HoagieSignalType == "SignalBrake"
high[1] < high[2] and low[1] > low[2] and high[2] < high[3] and low[2] > low[3] and high > high[3] and hl2 > trendd
HoagieDown = if HoagieSignalType == "Signal"
low > low[1] and high < high[1] and low[1] > low[2] and high[1] < high[2] and hl2 < trendd
else if HoagieSignalType == "SignalBrake"
low[1] > low[2] and high[1] < high[2] and low[2] > low[3] and high[2] < high[3] and low < low[3] and hl2 < trendd
plotshape(HoagieUp,title='Hoagie Up',style=shape.triangleup,location=location.belowbar,color=color.purple,size=size.small)
plotshape(HoagieDown,title='Hoagie Down',style=shape.triangledown,location=location.abovebar,color=color.purple,size=size.small)
// Umbrella Arrows [Umbrellas]
UmbrellaUp = if UmbrellaSignalType == "Signal"
(open >= close[1]) and (close >= close[1]) and (high <= high[1]) and (low >= low[1]) and (close[1] > open[1]) and (close-open+close[1]) - (open[1]/high-low+high[1]-low[1]) > 0.5 and (low > trendd)
else if UmbrellaSignalType == "SignalBrake"
(open[1] >= close[2]) and (close[1] >= close[2]) and (high[1] <= high[2]) and (low[1] >= low[2]) and (close[2] > open[2]) and (close[1]-open[1]+close[2]) - (open[1]/high[1]-low[1]+high[2]-low[2]) > 0.5 and (low > trendd)
UmbrellaDown = if UmbrellaSignalType == "Signal"
(open <= close[1]) and (close <= close[1]) and (high >= high[1]) and (low <= low[1]) and (close[1] < open[1]) and (close-open+close[1]) - (open[1]/high-low+high[1]-low[1]) > 0.5 and (high < trendd)
else if UmbrellaSignalType == "SignalBrake"
(open[1] <= close[2]) and (close[1] <= close[2]) and (high[1] >= high[2]) and (low[1] <= low[2]) and (close[2] < open[2]) and (close[1]-open[1]+close[2]) - (open[1]/high[1]-low[1]+high[2]-low[2]) > 0.5 and (high < trendd)
plotshape(UmbrellaUp,title='Umbrella Up',style=shape.triangleup,location=location.belowbar,color=#0033c1,size=size.small)
plotshape(UmbrellaDown,title='Umbrella Down',style=shape.triangledown,location=location.abovebar,color=#0033c1,size=size.small)
// Inside Outside Bars
OutUp = greenbar and (high > high[1]) and (low < low[1]) and (close > high[1]) and (open < open[1]) and KUP
OutDn = redbar and (low < low[1]) and (high > high[1]) and (close < low[1]) and (open > open[1]) and KDN
plotchar(OutUp,title = "Outside Up Bar",char = 'ห
',location = location.belowbar,size = size.tiny,color = color.white,display = display.none)
plotchar(OutDn,title = "Outside Down Bar",char = 'ห',location = location.abovebar,size = size.tiny,color = color.white,display = display.none)
// Trend Gauge [Enhanced EMA]
avg = ta.ema(close,TrendStrength)
rsi = ta.rsi(close,30)
TrendColor = avg < open and avg < close and rsi > 50 ? #27c22e : avg > open and avg > close and rsi < 50 ? #ff0000 : color.gray
plot(avg,title = "Trend",color = TrendColor,linewidth = 2)
// ATR & Target & Stop Label Calculations
atr = ta.atr(ATRLength)
target = atr / TargetATR
stop = atr * StopATR
Table = table.new(position = position.top_right, columns=8, rows=1, bgcolor=color.gray)
if barstate.islast
table.cell(table_id=Table, column=1, row=0, text=string ("ATR:"), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=color.yellow)
table.cell(table_id=Table, column=2, row=0, text=str.tostring(math.round(atr,RoundNumbersTo)), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=color.yellow)
table.cell(table_id=Table, column=3, row=0, text=string ("Target:"), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=#27c22e)
table.cell(table_id=Table, column=4, row=0, text=str.tostring(math.round(target,RoundNumbersTo)), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=#27c22e)
table.cell(table_id=Table, column=5, row=0, text=string ("Stop:"), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=#ff0000)
table.cell(table_id=Table, column=6, row=0, text=str.tostring(math.round(stop,RoundNumbersTo)), height=0, text_color=color.rgb(0, 0, 0), text_halign=text.align_center, text_size = size.auto, text_valign= text.align_center, bgcolor=#ff0000) |
D-BoT Alpha Volume Spike | https://www.tradingview.com/script/LY4cxqZO/ | Genesis-Trader | https://www.tradingview.com/u/Genesis-Trader/ | 79 | 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/
// ยฉ atnx
//@version=5
indicator(shorttitle='Alpha Vol Spk', title='D-BoT Alpha Volume Spike', overlay = true)
// User Settings
overbought_limit = input(70, title="Overbought")
oversold_limit = input(30, title="Oversold")
volume_multiplier = 1
volume_ma_length = 100
volume_spike_multiple = 2
lookback_period = 720
use_extremities_confirmation = input(defval = false, title = 'Aลฤฑrฤฑlฤฑk Onayฤฑ Al?')
//// Calculate Supertrend
// User Settings
supertrend_atr_period1 = input(1, "Supertrend ATR Length 1")
supertrend_atr_period2 = input(2, "Supertrend ATR Length 2")
supertrend_atr_period3 = input(3, "Supertrend ATR Length 3")
supertrend_factor1 = input.float(1.5, "Factor", step = 0.01)
supertrend_factor2 = input.float(1.2, "Factor", step = 0.01)
supertrend_factor3 = input.float(0.9, "Factor", step = 0.01)
// Calculate Supertrends
[supertrend_value1, trend_direction1] = ta.supertrend(supertrend_factor1, supertrend_atr_period1)
[supertrend_value2, trend_direction2] = ta.supertrend(supertrend_factor2, supertrend_atr_period2)
[supertrend_value3, trend_direction3] = ta.supertrend(supertrend_factor3, supertrend_atr_period3)
//
// Candle calculations
high_ = high[1] > high[2] and high[1] > high[0]
low_ = low[1] < low[2] and low[1] < low[0]
// Volume check
// Is volume sufficiently greater than its MA?
vol_ = volume > ta.sma(volume, volume_ma_length) * volume_multiplier
isBearish = high_ and vol_[1]
isBullish = low_ and vol_[1]
//Inputs
//ADX
ADX_length = input(14, title="ADX Length")
trueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
dmp = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
dmn = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
smoothedTrueRange = ta.sma(trueRange, ADX_length)
smoothedDMP = ta.sma(dmp, ADX_length)
smoothedDMN = ta.sma(dmn, ADX_length)
DIPlus = smoothedDMP / smoothedTrueRange * 100
DIMinus = smoothedDMN / smoothedTrueRange * 100
DIPlusMinus = DIPlus - DIMinus
diPlusMinusFiltered = ta.sma(DIPlusMinus, ADX_length)
diPlus = ta.sma(DIPlus, ADX_length)
diMinus = ta.sma(DIMinus, ADX_length)
//Volume Spikes
vol = ta.median(volume, lookback_period)
up = false
down = false
if volume > vol*volume_spike_multiple and diPlus > diMinus
up := true
else if volume > vol*volume_spike_multiple and diMinus > diPlus
down := true
////////ek filtre RSI MFI
//"Relative Strength Index"
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI-MFI Filter")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
up_rsi = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down_rsi = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down_rsi == 0 ? 100 : up_rsi == 0 ? 0 : 100 - (100 / (1 + up_rsi / down_rsi))
//Money Flow Index
length = input.int(title="MFI Length", defval=14, minval=1, maxval=2000)
src = hlc3
mfi = ta.mfi(src, length)
// Combined Al-Sat Signals{
trendBuy = false
trendSell = false
if use_extremities_confirmation
if isBullish and up and not (trend_direction2 < 0) and (rsi<oversold_limit) //and (mfi>rsi)
trendBuy := true
else if use_extremities_confirmation == false
if isBullish and up and not (trend_direction2 < 0) //and (mfi>rsi)
trendBuy := true
if use_extremities_confirmation
if isBearish and down and (mfi<rsi) and (trend_direction2 < 0) and (rsi>overbought_limit)
trendSell := true
else if use_extremities_confirmation == false
if isBearish and down and (mfi<rsi) and (trend_direction2 < 0)
trendSell := true
// Plot Shapes
plotshape(trendBuy, title = "Al Sinyali", style = shape.labelup, location = location.belowbar, color = color.new(#5ae64d, 13), size = size.small)
plotshape(trendSell, title = "Sat Sinyali", style = shape.labeldown, location = location.abovebar, color = color.new(#fb4646, 18), size = size.small)
/// Calculate Transparency Levels
distance1 = math.abs(close - supertrend_value1)
transparency_level1 = 98
if (distance1 < 1)
transparency_level1 := 95
else if (distance1 < 2)
transparency_level1 := 90
distance2 = math.abs(close - supertrend_value2)
transparency_level2 = 95
if (distance2 < 1)
transparency_level2 := 95
else if (distance2 < 2)
transparency_level2 := 90
distance3 = math.abs(close - supertrend_value3)
transparency_level3 = 92
if (distance3 < 1)
transparency_level3 := 95
else if (distance3 < 2)
transparency_level3 := 90
// Plot Supertrend Lines
bodyMiddle = plot((open + close) / 2, display=display.none)
uptrend_line1 = plot(trend_direction1 < 0 ? supertrend_value1 : na, "Up Trend", color = color.new(color.green, transparency_level1), style=plot.style_steplinebr)
downtrend_line1 = plot(trend_direction1 < 0? na : supertrend_value1, "Down Trend", color = color.new(color.red, transparency_level1), style=plot.style_steplinebr)
fill(bodyMiddle, uptrend_line1, color.new(color.green, transparency_level1), fillgaps=false)
fill(bodyMiddle, downtrend_line1, color.new(color.red, transparency_level1), fillgaps=false)
uptrend_line2 = plot(trend_direction2 < 0 ? supertrend_value2 : na, "Up Trend", color = color.new(color.green, transparency_level2), style=plot.style_linebr)
downtrend_line2 = plot(trend_direction2 < 0? na : supertrend_value2, "Down Trend", color = color.new(color.red, transparency_level2), style=plot.style_linebr)
fill(bodyMiddle, uptrend_line2, color.new(color.green, transparency_level2), fillgaps=false)
fill(bodyMiddle, downtrend_line2, color.new(color.red, transparency_level2), fillgaps=false)
uptrend_line3 = plot(trend_direction3 < 0 ? supertrend_value3 : na, "Up Trend", color = color.new(color.green, transparency_level3), style=plot.style_linebr)
downtrend_line3 = plot(trend_direction3 < 0? na : supertrend_value3, "Down Trend", color = color.new(color.red, transparency_level3), style=plot.style_linebr)
fill(bodyMiddle, uptrend_line3, color.new(color.green, transparency_level3), fillgaps=false)
fill(bodyMiddle, downtrend_line3, color.new(color.red, transparency_level3), fillgaps=false)
|
Vector2DrawLine | https://www.tradingview.com/script/r3tQhf4o-Vector2DrawLine/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 16 | library | 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/
// ยฉ RicardoSantos
//@version=5
// @description Extends line type with methods for Vector2 and Segment2.
library('Vector2DrawLine')
//#region Imports:
import RicardoSantos/CommonTypesMath/1 as TMath
import RicardoSantos/Vector2/1 as Vector2
//#endregion
//#region ~~~ Constructor:
// new () {
// @function Draws a line using Segment type to hold its coordinate properties..
// @param origin Vector2 . Origin vector of the line.
// @param target Vector2 . Target vector of the line.
// @param xloc string
// @param extend string
// @param color color
// @param style string
// @param width int
// @returns line object
export new (TMath.Vector2 origin, TMath.Vector2 target, string xloc = 'bi', string extend = 'n', color color = #2196f3, string style = 'sol', int width = 1) =>
line.new(
x1 = int(origin.x),
y1 = origin.y,
x2 = int(target.x),
y2 = target.y,
xloc = xloc,
extend = extend,
color = color,
style = style,
width = width
)
// @function Draws a line using Segment type to hold its coordinate properties..
// @param segment Segment2 . Segment with positional coordinates.
// @param xloc string
// @param extend string
// @param color color
// @param style string
// @param width int
// @returns line object
export new (TMath.Segment2 segment, string xloc = 'bi', string extend = 'n', color color = #2196f3, string style = 'sol', int width = 1) =>
line.new(
x1 = int(segment.origin.x),
y1 = segment.origin.y,
x2 = int(segment.target.x),
y2 = segment.target.y,
xloc = xloc,
extend = extend,
color = color,
style = style,
width = width
)
// }
//#endregion
//#region ~~~ Methods:
// rotate_around () {
// @function Instance method to rotate line around center vector (modifies input line).
// @param this line . Line object.
// @param center Vector2 . Center of rotation.
// @param angle float . Rotation angle in degrees.
// @returns line. Rotated line object.
export method rotate_around (line this, TMath.Vector2 center, float angle) =>
TMath.Vector2 _a = Vector2.rotate_around(Vector2.new(this.get_x1(), this.get_y1()), center, angle)
TMath.Vector2 _b = Vector2.rotate_around(Vector2.new(this.get_x2(), this.get_y2()), center, angle)
this.set_xy1(int(_a.x), _a.y)
this.set_xy2(int(_b.x), _b.y)
this
// }
//#endregion
rotation = input.float(0.0, step=5.0)
a = Vector2.new(bar_index+0.0, 0.0)
b = Vector2.new(bar_index+10.0, 10.0)
c = Vector2.new(bar_index+0.0, 10.0)
s = TMath.Segment2.new(a, b)
if barstate.islast
la = new(s)
lb = new(b, c)
lb.rotate_around(b, rotation) |
AlphaTrend - Screener | https://www.tradingview.com/script/kv8N05R7-AlphaTrend-Screener/ | KivancOzbilgic | https://www.tradingview.com/u/KivancOzbilgic/ | 4,963 | 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/
// Created & Developed by : Kฤฑvanรง รzbilgiรง (@KivancOzbilgic)
// Screener Panel & Adjustments: @dg_factor
//@version=5
indicator('AlphaTrend - Screener', overlay=true, format=format.price, precision=2)
src = input.source(title='Source', defval=close, group='ALPHATREND')
AP = input.int(title='Length', defval=14, group='ALPHATREND')
coeff = input.float(title='Multiplier', defval=1.0, step=0.1, group='ALPHATREND')
novolumedata = input.bool(title='Change Calculation (No Volume Data)', defval=false, group='ALPHATREND')
showsignalsk = input(title='Show Signals ', defval=true, group='ALPHATREND')
ATR = ta.sma(ta.tr, AP)
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
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])
direction = 0
direction := buySignalk and O1 > K2 ? 1 : sellSignalk and O2 > K1 ? -1 : direction[1]
k1 = plot(AlphaTrend, title='AlphaTrend', color=#0022fc, linewidth=3)
k2 = plot(AlphaTrend[2], title='Trigger', color=#fc0400, linewidth=3)
fill(k1, k2, title='Fill Color', color=color1)
plotshape(showsignalsk and buySignalk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na, title='BUY', text='BUY', location=location.absolute, style=shape.labelup, size=size.tiny, color=#0022FC, textcolor=color.white)
plotshape(showsignalsk and sellSignalk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na, title='SELL', text='SELL', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.maroon, textcolor=color.white)
string gr_sc = 'SCREENER'
string gr_sy = 'SYMBOL'
string t00 = 'Alpha Trend Screener'
color c00 = #686868
lb_sh = input.bool(title='Show Label', defval=true, group=gr_sc)
lb_xa = input.int(title='Horizontal Axis', defval=20, group=gr_sc, tooltip='Label Position x Axis')
lb_ya = input.int(title='Vertical Axis', defval=1, group=gr_sc, tooltip='Label Position y Axis')
lb_sz = input.string(title='Label Size', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], defval='Normal', group=gr_sc)
lb_cl = input.color(title='Colours', defval=#00bb00, group=gr_sc, inline='0')
lb_cs = input.color(title='', defval=#ff0000, group=gr_sc, inline='0')
sh01 = input.bool(title='01', defval=true, group=gr_sy, inline="01")
sh02 = input.bool(title='02', defval=true, group=gr_sy, inline="02")
sh03 = input.bool(title='03', defval=true, group=gr_sy, inline="03")
sh04 = input.bool(title='04', defval=true, group=gr_sy, inline="04")
sh05 = input.bool(title='05', defval=true, group=gr_sy, inline="05")
sh06 = input.bool(title='06', defval=true, group=gr_sy, inline="06")
sh07 = input.bool(title='07', defval=true, group=gr_sy, inline="07")
sh08 = input.bool(title='08', defval=true, group=gr_sy, inline="08")
sh09 = input.bool(title='09', defval=true, group=gr_sy, inline="09")
sh10 = input.bool(title='10', defval=true, group=gr_sy, inline="10")
sh11 = input.bool(title='11', defval=false, group=gr_sy, inline="11")
sh12 = input.bool(title='12', defval=false, group=gr_sy, inline="12")
sh13 = input.bool(title='13', defval=false, group=gr_sy, inline="13")
sh14 = input.bool(title='14', defval=false, group=gr_sy, inline="14")
sh15 = input.bool(title='15', defval=false, group=gr_sy, inline="15")
sh16 = input.bool(title='16', defval=false, group=gr_sy, inline="16")
sh17 = input.bool(title='17', defval=false, group=gr_sy, inline="17")
sh18 = input.bool(title='18', defval=false, group=gr_sy, inline="18")
sh19 = input.bool(title='19', defval=false, group=gr_sy, inline="19")
sh20 = input.bool(title='20', defval=false, group=gr_sy, inline="20")
tf01 = input.timeframe(title='', defval='', group=gr_sy, inline="01")
tf02 = input.timeframe(title='', defval='', group=gr_sy, inline="02")
tf03 = input.timeframe(title='', defval='', group=gr_sy, inline="03")
tf04 = input.timeframe(title='', defval='', group=gr_sy, inline="04")
tf05 = input.timeframe(title='', defval='', group=gr_sy, inline="05")
tf06 = input.timeframe(title='', defval='', group=gr_sy, inline="06")
tf07 = input.timeframe(title='', defval='', group=gr_sy, inline="07")
tf08 = input.timeframe(title='', defval='', group=gr_sy, inline="08")
tf09 = input.timeframe(title='', defval='', group=gr_sy, inline="09")
tf10 = input.timeframe(title='', defval='', group=gr_sy, inline="10")
tf11 = input.timeframe(title='', defval='', group=gr_sy, inline="11")
tf12 = input.timeframe(title='', defval='', group=gr_sy, inline="12")
tf13 = input.timeframe(title='', defval='', group=gr_sy, inline="13")
tf14 = input.timeframe(title='', defval='', group=gr_sy, inline="14")
tf15 = input.timeframe(title='', defval='', group=gr_sy, inline="15")
tf16 = input.timeframe(title='', defval='', group=gr_sy, inline="16")
tf17 = input.timeframe(title='', defval='', group=gr_sy, inline="17")
tf18 = input.timeframe(title='', defval='', group=gr_sy, inline="18")
tf19 = input.timeframe(title='', defval='', group=gr_sy, inline="19")
tf20 = input.timeframe(title='', defval='', group=gr_sy, inline="20")
s01 = input.symbol(title='', group=gr_sy, inline='01', defval='BINANCE:BTCUSDT')
s02 = input.symbol(title='', group=gr_sy, inline='02', defval='BINANCE:ETHUSDT')
s03 = input.symbol(title='', group=gr_sy, inline='03', defval='BINANCE:BNBUSDT')
s04 = input.symbol(title='', group=gr_sy, inline='04', defval='BINANCE:ADAUSDT')
s05 = input.symbol(title='', group=gr_sy, inline='05', defval='BINANCE:AVAXUSDT')
s06 = input.symbol(title='', group=gr_sy, inline='06', defval='BINANCE:CHZUSDT')
s07 = input.symbol(title='', group=gr_sy, inline='07', defval='BINANCE:DOGEUSDT')
s08 = input.symbol(title='', group=gr_sy, inline='08', defval='BINANCE:SOLUSDT')
s09 = input.symbol(title='', group=gr_sy, inline='09', defval='BINANCE:TRXUSDT')
s10 = input.symbol(title='', group=gr_sy, inline='10', defval='BINANCE:XRPUSDT')
s11 = input.symbol(title='', group=gr_sy, inline='11', defval='NASDAQ:AAPL')
s12 = input.symbol(title='', group=gr_sy, inline='12', defval='NASDAQ:TSLA')
s13 = input.symbol(title='', group=gr_sy, inline='13', defval='NASDAQ:AMZN')
s14 = input.symbol(title='', group=gr_sy, inline='14', defval='NASDAQ:GOOGL')
s15 = input.symbol(title='', group=gr_sy, inline='15', defval='NASDAQ:NVDA')
s16 = input.symbol(title='', group=gr_sy, inline='16', defval='NASDAQ:META')
s17 = input.symbol(title='', group=gr_sy, inline='17', defval='NYSE:C')
s18 = input.symbol(title='', group=gr_sy, inline='18', defval='NASDAQ:NFLX')
s19 = input.symbol(title='', group=gr_sy, inline='19', defval='NYSE:BABA')
s20 = input.symbol(title='', group=gr_sy, inline='20', defval='NASDAQ:ABNB')
f_screener(s) =>
int x = na
int y = na
z = color(na)
if s
x := direction
y := ta.barssince(x != x[1])
z := x == 1 ? lb_cl : x == -1 ? lb_cs : c00
[x, y, z]
//
f_bars(x) =>
r = ' [' + str.tostring(x) + '] '
//
f_size(x) =>
x == 'Tiny' ? size.tiny :
x == 'Small' ? size.small :
x == 'Normal' ? size.normal :
x == 'Large' ? size.large :
x == 'Huge' ? size.huge : size.auto
//
f_label(l, t, c) =>
r = string(na)
for i = l*2 to 0
r += '\n\n'
r += t
var label lb = na
label.delete(lb)
fix_allign = ta.highest(200)
lb := lb_sh ? label.new(
x=bar_index + lb_xa,
y=bar_index > 200 ? fix_allign * (1 + lb_ya / 1000) : hl2 * (1 + lb_ya / 1000),
text=r, textcolor=c, textalign=text.align_right,
style=label.style_label_left, size=f_size(lb_sz), color=#00000000) : na
[a01, b01, c01] = request.security(s01, tf01, f_screener(sh01))
[a02, b02, c02] = request.security(s02, tf02, f_screener(sh02))
[a03, b03, c03] = request.security(s03, tf03, f_screener(sh03))
[a04, b04, c04] = request.security(s04, tf04, f_screener(sh04))
[a05, b05, c05] = request.security(s05, tf05, f_screener(sh05))
[a06, b06, c06] = request.security(s06, tf06, f_screener(sh06))
[a07, b07, c07] = request.security(s07, tf07, f_screener(sh07))
[a08, b08, c08] = request.security(s08, tf08, f_screener(sh08))
[a09, b09, c09] = request.security(s09, tf09, f_screener(sh09))
[a10, b10, c10] = request.security(s10, tf10, f_screener(sh10))
[a11, b11, c11] = request.security(s11, tf11, f_screener(sh11))
[a12, b12, c12] = request.security(s12, tf12, f_screener(sh12))
[a13, b13, c13] = request.security(s13, tf13, f_screener(sh13))
[a14, b14, c14] = request.security(s14, tf14, f_screener(sh14))
[a15, b15, c15] = request.security(s15, tf15, f_screener(sh15))
[a16, b16, c16] = request.security(s16, tf16, f_screener(sh16))
[a17, b17, c17] = request.security(s17, tf17, f_screener(sh17))
[a18, b18, c18] = request.security(s18, tf18, f_screener(sh18))
[a19, b19, c19] = request.security(s19, tf19, f_screener(sh19))
[a20, b20, c20] = request.security(s20, tf20, f_screener(sh20))
t01 = a01 == 1 ? 'โฒ' + f_bars(b01) + s01 : a01 == -1 ? 'โผ' + f_bars(b01) + s01 : 'โ ' + f_bars(b01) + s01
t02 = a02 == 1 ? 'โฒ' + f_bars(b02) + s02 : a02 == -1 ? 'โผ' + f_bars(b02) + s02 : 'โ ' + f_bars(b02) + s02
t03 = a03 == 1 ? 'โฒ' + f_bars(b03) + s03 : a03 == -1 ? 'โผ' + f_bars(b03) + s03 : 'โ ' + f_bars(b03) + s03
t04 = a04 == 1 ? 'โฒ' + f_bars(b04) + s04 : a04 == -1 ? 'โผ' + f_bars(b04) + s04 : 'โ ' + f_bars(b04) + s04
t05 = a05 == 1 ? 'โฒ' + f_bars(b05) + s05 : a05 == -1 ? 'โผ' + f_bars(b05) + s05 : 'โ ' + f_bars(b05) + s05
t06 = a06 == 1 ? 'โฒ' + f_bars(b06) + s06 : a06 == -1 ? 'โผ' + f_bars(b06) + s06 : 'โ ' + f_bars(b06) + s06
t07 = a07 == 1 ? 'โฒ' + f_bars(b07) + s07 : a07 == -1 ? 'โผ' + f_bars(b07) + s07 : 'โ ' + f_bars(b07) + s07
t08 = a08 == 1 ? 'โฒ' + f_bars(b08) + s08 : a08 == -1 ? 'โผ' + f_bars(b08) + s08 : 'โ ' + f_bars(b08) + s08
t09 = a09 == 1 ? 'โฒ' + f_bars(b09) + s09 : a09 == -1 ? 'โผ' + f_bars(b09) + s09 : 'โ ' + f_bars(b09) + s09
t10 = a10 == 1 ? 'โฒ' + f_bars(b10) + s10 : a10 == -1 ? 'โผ' + f_bars(b10) + s10 : 'โ ' + f_bars(b10) + s10
t11 = a11 == 1 ? 'โฒ' + f_bars(b11) + s11 : a11 == -1 ? 'โผ' + f_bars(b11) + s11 : 'โ ' + f_bars(b11) + s11
t12 = a12 == 1 ? 'โฒ' + f_bars(b12) + s12 : a12 == -1 ? 'โผ' + f_bars(b12) + s12 : 'โ ' + f_bars(b12) + s12
t13 = a13 == 1 ? 'โฒ' + f_bars(b13) + s13 : a13 == -1 ? 'โผ' + f_bars(b13) + s13 : 'โ ' + f_bars(b13) + s13
t14 = a14 == 1 ? 'โฒ' + f_bars(b14) + s14 : a14 == -1 ? 'โผ' + f_bars(b14) + s14 : 'โ ' + f_bars(b14) + s14
t15 = a15 == 1 ? 'โฒ' + f_bars(b15) + s15 : a15 == -1 ? 'โผ' + f_bars(b15) + s15 : 'โ ' + f_bars(b15) + s15
t16 = a16 == 1 ? 'โฒ' + f_bars(b16) + s16 : a16 == -1 ? 'โผ' + f_bars(b16) + s16 : 'โ ' + f_bars(b16) + s16
t17 = a17 == 1 ? 'โฒ' + f_bars(b17) + s17 : a17 == -1 ? 'โผ' + f_bars(b17) + s17 : 'โ ' + f_bars(b17) + s17
t18 = a18 == 1 ? 'โฒ' + f_bars(b18) + s18 : a18 == -1 ? 'โผ' + f_bars(b18) + s18 : 'โ ' + f_bars(b18) + s18
t19 = a19 == 1 ? 'โฒ' + f_bars(b19) + s19 : a19 == -1 ? 'โผ' + f_bars(b19) + s19 : 'โ ' + f_bars(b19) + s19
t20 = a20 == 1 ? 'โฒ' + f_bars(b20) + s20 : a20 == -1 ? 'โผ' + f_bars(b20) + s20 : 'โ ' + f_bars(b20) + s20
f_label(0, t00, c00)
f_label(1, t01, c01)
f_label(2, t02, c02)
f_label(3, t03, c03)
f_label(4, t04, c04)
f_label(5, t05, c05)
f_label(6, t06, c06)
f_label(7, t07, c07)
f_label(8, t08, c08)
f_label(9, t09, c09)
f_label(10, t10, c10)
f_label(11, t11, c11)
f_label(12, t12, c12)
f_label(13, t13, c13)
f_label(14, t14, c14)
f_label(15, t15, c15)
f_label(16, t16, c16)
f_label(17, t17, c17)
f_label(18, t18, c18)
f_label(19, t19, c19)
f_label(20, t20, c20) |
Textmate Language for Pine Script v5 2023-05 | https://www.tradingview.com/script/O6LCkLTf-Textmate-Language-for-Pine-Script-v5-2023-05/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 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/
// ยฉ kaigouthro
o = ''
//@version=5
o := " โโโ โโโ โโโ โโโ โโโโโ โโโ โโโ โโโ โโโโ โโโ โโ โโโ โโโ โโโ โโโ "
o := " โโโ โโโ โโโ โโโ โโโโโ โโโ โโโ โโโ โโโโ โโโ โโ โโโ โโโ โโโ โโโ "
o := " "
o := " โโ โโโ โโโโ โโโ โโโ โโโ โโโ โ โโโ โโโ โโโ โ โโโ โโโ โโโ "
o := " โโ โโโ โโโโ โโโ โโโ โโโ โโโ โ โโโ โโโ โโโ โ โโโ โโโ โโโ "
o := " "
indicator("Textmate Language for Pine Script v5 2023-05", "", true)
// {
// "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
// "name": "Pine Script",
// "scopeName": "source.pine",
// "patterns": [
// {
// "captures": {
// "0": { "name": "comment.line.double-slash.pine" },
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "comment.line.double-slash.pine" },
// "3": { "name": "constant.numeric.pine" },
// "4": { "name": "comment.line.double-slash.pine" }
// },
// "match": "(^\/\/)[\\t ]*(ยฉ)[\\t ]*([a-zA-Z_][a-zA-Z0-9_]*)(.*)"
// },
// {
// "captures": {
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "entity.name.tag.pine" },
// "3": { "name": "entity.name.label.pine" },
// "4": { "name": "keyword.operator.assignment.pine" },
// "5": { "name": "constant.numeric.pine" }
// },
// "match": "(^\/\/)(@)(version)(=)(5)"
// },
// {
// "captures": {
// "0": { "name": "comment.line.double-slash.pine" },
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "constant.numeric.pine" },
// "3": { "name": "support.pine.pine" },
// "4": { "name": "support.pine.pine" },
// "5": { "name": "support.pine.pine" }
// },
// "match": "(?<=^)(\/\/\\s*)(โ)(https://www\\.tradingview\\.com)([\\w.,@?^=%&:/~+#-\\{]*[\\}\\w@?^=%&/~+#-])([a-zA-Z_][a-zA-Z0-9_]*)(?=.*\\n)"
// },
// {
// "captures": {
// "0": { "name": "keyword.control.import.pine" },
// "1": { "name": "support.class.imported.pine" },
// "2": { "name": "storage.type.pine" },
// "3": { "name": "constant.numeric.pine" },
// "4": { "name": "storage.type.pine.pine" },
// "5": { "name": "entity.name.tag.pine" }
// },
// "match": "(?<=^)(import)\\s+(\\w+)\\/(\\w+)\\/\\d+(\\s+as\\s+(\\w+))?.*(?=\\n)"
// },
// { "include": "#annotations" },
// { "include": "#markup" },
// { "include": "#strings" },
// { "include": "#keywords" },
// { "include": "#types" },
// { "include": "#constants" },
// { "include": "#functions" },
// { "include": "#storage" },
// { "include": "#variables" },
// { "include": "#numbers" },
// { "include": "#operators" },
// { "include": "#punctuation" }
// ],
// "repository": {
// "markup": {
// "patterns": [
// {
// "begin": "(?<=^)\/\/\\s*(?=[^@])",
// "patterns": [
// {
// "name": "markup.bold",
// "match": "\\*\\*[^\\n\\*]+\\*\\*+"
// },
// {
// "name": "markup.heading.pine",
// "match": "#+\\s+.*$"
// },
// {
// "name": "markup.quote",
// "match": "(?<=\/\/\\s+)-\\s[^\\n]*$"
// },
// {
// "name": "markup.underline",
// "match": "_[^\\_\\s]+_"
// },
// {
// "name": "markup.italic",
// "match": "\\*[^\\s\\*]+\\*"
// },
// {
// "begin": "(?<=^\/\/)```\\w*",
// "patterns": [
// { "include": "#strings" },
// { "include": "#keywords" },
// { "include": "#types" },
// { "include": "#constants" },
// { "include": "#functions" },
// { "include": "#storage" },
// { "include": "#variables" },
// { "include": "#numbers" },
// { "include": "#operators" }
// ],
// "end": "(?<=^\/\/)```|^(?=(\\w|\/\/\\s*@))"
// }
// ],
// "end": "^(?=(\\w|\/\/\\s*@))"
// }
// ]
// },
// "annotations": {
// "patterns": [
// {
// "begin": "(?<=^)(\/\/\\s*)(@)(type|description|function|returns)(\\s+[a-zA-Z_][a-zA-Z_0-9]*)?",
// "beginCaptures": {
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "entity.name.tag.pine" },
// "3": { "name": "entity.name.label.pine" }
// },
// "patterns": [
// { "include": "#markup" },
// { "include": "#annotation_types" }
// ],
// "end": "(?<=^)(?=\\b|\/\/\\s*@)",
// "endCaptures": { "1": { "name": "punctuation.definition.entity.pine" } }
// },
// {
// "begin": "(?<=^)(\/\/[\\t ]*)?(@)(?:(field|param)\\s+([a-zA-Z_][a-zA-Z0-9_]*))",
// "beginCaptures": {
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "entity.name.tag.pine" },
// "3": { "name": "entity.name.label.pine" },
// "4": { "name": "entity.name.parameter.pine" }
// },
// "patterns": [ { "include": "#annotation_types" } ],
// "end": "(?<=^)(?=\\b|\/\/\\s*@)",
// "endCaptures": { "1": { "name": "punctuation.definition.entity.pine" } }
// },
// {
// "begin": "(?:(\/\/\\s*)(@)(?:(variable)\\s+([a-zA-Z_][a-zA-Z0-9_]*)))",
// "beginCaptures": {
// "1": { "name": "comment.line.double-slash.pine" },
// "2": { "name": "entity.name.tag.pine" },
// "3": { "name": "markup.heading.pine" },
// "4": { "name": "entity.name.parameter.pine" }
// },
// "patterns": [ { "include": "#annotation_types" } ],
// "end": "(?<=^)(?=\\b|\/\/\\s*@)",
// "endCaptures": { "1": { "name": "punctuation.definition.entity.pine" } }
// }
// ]
// },
// "annotation_types": {
// "patterns": [
// {
// "begin": "(?<=\\()",
// "beginCaptures": { "0": { "name": "punctuation.definition.group.pine" } },
// "patterns": [
// {
// "captures": {
// "1": { "name": "storage.type.array.matrix.pine" },
// "3": { "name": "support.class.imported.pine" },
// "5": { "name": "support.class.imported.pine" },
// "4": { "name": "support.type.pine" },
// "6": { "name": "support.type.pine" },
// "8": { "name": "storage.type.pine" },
// "9": { "name": "support.variable.pine" }
// },
// "match": "(?<=)\\s*(\\b(((array|matrix)<([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)>|([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)[\\t ]*(\\[\\])?)))\\s*(?=\\))"
// },
// { "include": "#markup" }
// ],
// "end": "(?=\\))",
// "endCaptures": { "0": { "name": "punctuation.definition.group.pine" } }
// }
// ]
// },
// "constants": {
// "patterns": [
// {
// "name": "variable.language.pine",
// "match": "(?: (?<!\\w)(adjustment\\.(dividends|none|splits)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(alert\\.(freq_all|freq_once_per_bar|freq_once_per_bar_close)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(barmerge\\.(gaps_off|gaps_on|lookahead_off|lookahead_on)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(barstate\\.(isconfirmed|isfirst|ishistory|islast|islastconfirmedhistory|isnew|isrealtime)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(box\\.(all)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(chart\\.(bg_color|fg_color|is_heikinashi|is_kagi|is_linebreak|is_pnf|is_range|is_renko|is_standard|left_visible_bar_time|right_visible_bar_time)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(color\\.(aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(currency\\.(AUD|BTC|CAD|CHF|ETH|EUR|GBP|HKD|INR|JPY|KRW|MYR|NOK|NONE|NZD|RUB|SEK|SGD|TRY|USD|USDT|ZAR)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(dayofweek\\.(friday|monday|saturday|sunday|thursday|tuesday|wednesday)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(display\\.(all|data_window|none|pane|price_scale|status_line)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(dividends\\.(gross|net)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(earnings\\.(actual|estimate|standardized)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(extend\\.(both|left|none|right)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(font\\.(family_default|family_monospace)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(format\\.(inherit|mintick|percent|price|volume)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(hline\\.(style_dashed|style_dotted|style_solid)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(label\\.(all|style_arrowdown|style_arrowup|style_circle|style_cross|style_diamond|style_flag|style_label_center|style_label_down|style_label_left|style_label_lower_left|style_label_lower_right|style_label_right|style_label_up|style_label_upper_left|style_label_upper_right|style_none|style_square|style_text_outline|style_triangledown|style_triangleup|style_xcross)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(line\\.(all|style_arrow_both|style_arrow_left|style_arrow_right|style_dashed|style_dotted|style_solid)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(linefill\\.(all)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(location\\.(abovebar|absolute|belowbar|bottom|top)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(math\\.(e|phi|pi|rphi)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(order\\.(ascending|descending)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(plot\\.(style_area|style_areabr|style_circles|style_columns|style_cross|style_histogram|style_line|style_linebr|style_stepline|style_stepline_diamond|style_steplinebr)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(position\\.(bottom_center|bottom_left|bottom_right|middle_center|middle_left|middle_right|top_center|top_left|top_right)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(scale\\.(left|none|right)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(session\\.(extended|isfirstbar|isfirstbar_regular|islastbar|islastbar_regular|ismarket|ispostmarket|ispremarket|regular)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(shape\\.(arrowdown|arrowup|circle|cross|diamond|flag|labeldown|labelup|square|triangledown|triangleup|xcross)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(size\\.(auto|huge|large|normal|small|tiny)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(splits\\.(denominator|numerator)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(strategy\\.(account_currency|cash|closedtrades|commission\\.(cash_per_contract|cash_per_order|percent)|direction\\.(all|long|short)|equity|eventrades|fixed|grossloss|grossprofit|initial_capital|long|losstrades|max_contracts_held_all|max_contracts_held_long|max_contracts_held_short|max_drawdown|max_runup|netprofit|oca\\.(cancel|none|reduce)|openprofit|opentrades|percent_of_equity|position_avg_price|position_entry_name|position_size|short|wintrades)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(syminfo\\.(basecurrency|country|currency|description|industry|mintick|pointvalue|prefix|root|sector|session|ticker|tickerid|timezone|type|volumetype)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(ta\\.(accdist|iii|nvi|obv|pvi|pvt|tr|vwap|wad|wvad)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(table\\.(all)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(text\\.(align_bottom|align_center|align_left|align_right|align_top|wrap_auto|wrap_none)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(timeframe\\.(isdaily|isdwm|isintraday|isminutes|ismonthly|isseconds|isweekly|multiplier|period)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(xloc\\.(bar_index|bar_time)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(yloc\\.(abovebar|belowbar|price)\\b)(?!\\w|\\s*\\())"
// },
// {
// "name": "variable.language.pine",
// "match": "(?:(?<!\\w)(bar_index|close|dayofmonth|dayofweek|high|hl2|hlc3|hlcc4|hour|last_bar_index|last_bar_time|low|minute|month|na|ohlc4|open|second|time|time_close|time_tradingday|timenow|volume|weekofyear|year)\\b(?!\\w|\\s*\\())"
// }
// ]
// },
// "escaped_char": {
// "match": "\\\\(?:[\\\\abfnrtv'\"])",
// "name": "string.regex.escape.pine"
// },
// "functions": {
// "patterns": [
// {
// "match": "(?<=^)(indicator|library|strategy|study)\\s*(?=\\()",
// "name": "support.constant.pine"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(array\\.(abs|avg|binary_search|binary_search_leftmost|binary_search_rightmost|clear|concat|copy|covariance|every|fill|first|from|get|includes|indexof|insert|join|last|lastindexof|max|median|min|mode|new_bool|new_box|new_color|new_float|new_int|new_label|new_line|new_linefill|new_string|new_table|new<type>|percentile_linear_interpolation|percentile_nearest_rank|percentrank|pop|push|range|remove|reverse|set|shift|size|slice|some|sort|sort_indices|standardize|stdev|sum|unshift|variance)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(box\\.(copy|delete|get_bottom|get_left|get_right|get_top|new|set_bgcolor|set_border_color|set_border_style|set_border_width|set_bottom|set_extend|set_left|set_lefttop|set_right|set_rightbottom|set_text|set_text_color|set_text_font_family|set_text_halign|set_text_size|set_text_valign|set_text_wrap|set_top)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(color\\.(b|from_gradient|g|new|r|rgb|t)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(input\\.(bool|color|float|int|price|session|source|string|symbol|text_area|time|timeframe)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(label\\.(copy|delete|get_text|get_x|get_y|new|set_color|set_size|set_style|set_text|set_text_font_family|set_textalign|set_textcolor|set_tooltip|set_x|set_xloc|set_xy|set_y|set_yloc)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(line\\.(copy|delete|get_price|get_x1|get_x2|get_y1|get_y2|new|set_color|set_extend|set_style|set_width|set_x1|set_x2|set_xloc|set_xy1|set_xy2|set_y1|set_y2)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(linefill\\.(delete|get_line1|get_line2|new|set_color)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(math\\.(abs|acos|asin|atan|avg|ceil|cos|exp|floor|log|log10|max|min|pow|random|round|round_to_mintick|sign|sin|sqrt|sum|tan|todegrees|toradians)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(matrix\\.(add_col|add_row|avg|col|columns|concat|copy|det|diff|eigenvalues|eigenvectors|elements_count|fill|get|inv|is_antidiagonal|is_antisymmetric|is_binary|is_diagonal|is_identity|is_square|is_stochastic|is_symmetric|is_triangular|is_zero|kron|max|median|min|mode|mult|new<type>|pinv|pow|rank|remove_col|remove_row|reshape|reverse|row|rows|set|sort|submatrix|sum|swap_columns|swap_rows|trace|transpose)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(request\\.(currency_rate|dividends|earnings|economic|financial|quandl|security|security_lower_tf|splits)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(runtime\\.(error)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(str\\.(contains|endswith|format|format_time|length|lower|match|pos|replace|replace_all|split|startswith|substring|tonumber|tostring|upper)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(strategy\\.(cancel|cancel_all|close|close_all|closedtrades\\.(commission|entry_bar_index|entry_comment|entry_id|entry_price|entry_time|exit_bar_index|exit_comment|exit_id|exit_price|exit_time|max_drawdown|max_runup|profit|size)|convert_to_account|convert_to_symbol|entry|exit|opentrades\\.(commission|entry_bar_index|entry_comment|entry_id|entry_price|entry_time|max_drawdown|max_runup|profit|size)|order|risk\\.(allow_entry_in|max_cons_loss_days|max_drawdown|max_intraday_filled_orders|max_intraday_loss|max_position_size))\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(syminfo\\.(prefix|ticker)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(ta\\.(alma|atr|barssince|bb|bbw|cci|change|cmo|cog|correlation|cross|crossover|crossunder|cum|dev|dmi|ema|falling|highest|highestbars|hma|kc|kcw|linreg|lowest|lowestbars|macd|max|median|mfi|min|mode|mom|percentile_linear_interpolation|percentile_nearest_rank|percentrank|pivot_point_levels|pivothigh|pivotlow|range|rising|rma|roc|rsi|sar|sma|stdev|stoch|supertrend|swma|tr|tsi|valuewhen|variance|vwap|vwma|wma|wpr)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(table\\.(cell|cell_set_bgcolor|cell_set_height|cell_set_text|cell_set_text_color|cell_set_text_font_family|cell_set_text_halign|cell_set_text_size|cell_set_text_valign|cell_set_tooltip|cell_set_width|clear|delete|merge_cells|new|set_bgcolor|set_border_color|set_border_width|set_frame_color|set_frame_width|set_position)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(ticker\\.(heikinashi|kagi|linebreak|modify|new|pointfigure|renko|standard)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(timeframe\\.(change|in_seconds)\\b)(?=\\s*\\())"
// },
// {
// "name": "support.function.pine",
// "match": "(?:(?<!\\w)(alert|alertcondition|barcolor|bgcolor|bool|box|color|dayofmonth|dayofweek|fill|fixnan|float|hline|hour|indicator|input|int|label|library|line|linefill|max_bars_back|minute|month|na|nz|plot|plotarrow|plotbar|plotcandle|plotchar|plotshape|second|strategy|string|table|time|time_close|timestamp|weekofyear|year)\\b(?=\\s*\\())"
// },
// {
// "begin": "(?<=^)(export\\s+)?(method\\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=\\()",
// "beginCaptures": {
// "1": { "name": "keyword.import.pine" },
// "2": { "name": "keyword.operator.pine" },
// "3": { "name": "entity.name.function.pine" }
// },
// "end": "=>",
// "endCaptures": { "0": { "name": "keyword.operator.end.pine" } },
// "patterns": [
// {
// "begin": "\\(",
// "beginCaptures": { "0": { "name": "punctuation.definition.parameters.begin.pine" } },
// "end": "\\)",
// "endCaptures": {
// "1": { "name": "punctuation.definition.parameters.end.pine" },
// "2": { "name": "punctuation.separator.pine" }
// },
// "patterns": [
// {
// "match": "(?:(series\\s+|simple\\s+)?(?:(?:(array|matrix)<([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)>|([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)\\s*(\\[\\])?)\\s+)?)([a-zA-Z_][a-zA-Z0-9_]*)(?:\\s*(=)\\s*(?:('.*'|\\\".*\\\")|([-+]?\\d*\\.?\\d+(?:[eE][-+]?\\d+)|#[a-fA-F0-9]+)|((?:[a-zA-Z_][a-zA-Z0-9_]*\\.)*[a-zA-Z_][a-zA-Z0-9_]*)))?\\s*(?=,|\\))",
// "captures": {
// "1": { "name": "keyword.operator.pine" },
// "2": { "name": "keyword.pine" },
// "3": { "name": "storage.type.pine" },
// "4": { "name": "support.type.pine" },
// "5": { "name": "storage.type.pine" },
// "6": { "name": "support.type.pine" },
// "7": { "name": "storage.type.pine" },
// "8": { "name": "support.variable.pine" },
// "9": { "name": "keyword.operator.type.pine" },
// "10": { "name": "string.quoted.pine" },
// "11": { "name": "constant.numeric.pine" },
// "12": { "name": "variable.language.pine" }
// }
// }
// ]
// }
// ]
// },
// {
// "match": "(?:([a-zA-Z_][a-zA-Z0-9_]*(?:\\.))?([a-zA-Z_][a-zA-Z0-9_]*(?:\\.))*)?([a-zA-Z_][a-zA-Z0-9_]*)(?:<([a-zA-Z_][a-zA-Z0-9_]*(?:\\.))?([a-zA-Z_][a-zA-Z0-9_]*)>)?\\s*(?=\\()",
// "captures": {
// "1": { "name": "entity.name.namespace.pine" },
// "2": { "name": "support.constant.pine" },
// "3": { "name": "entity.name.function.pine" },
// "4": { "name": "storage.type.pine" },
// "5": { "name": "storage.type.pine" },
// "6": { "name": "support.function.pine" }
// }
// }
// ]
// },
// "types": {
// "patterns": [
// {
// "begin": "(?<=^)(export[\\t ]+)?(type)[\\t ]+([a-zA-Z_][a-zA-Z_0-9]*)",
// "beginCaptures": {
// "1": { "name": "keyword.control.import.pine" },
// "2": { "name": "entity.name.type.udt.pine" },
// "3": { "name": "entity.name.tag.pine" }
// },
// "patterns": [
// {
// "match": "^\\s+(?:(?:(?:(array|matrix)<([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)>|([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)\\s*(\\[\\])?)\\s+))([a-zA-Z_][a-zA-Z0-9_]*[\\t ]*)(?:\\s*(=)\\s*(?:('.*'|\\\".*\\\")|([-+]?\\d*\\.?\\d+(?:[eE][-+]?\\d+)|#[a-fA-F0-9]+)|((?:[a-zA-Z_][a-zA-Z0-9_]*\\.)*[a-zA-Z_][a-zA-Z0-9_]*)))?",
// "captures": {
// "1": { "name": "keyword.pine" },
// "2": { "name": "storage.type.pine" },
// "3": { "name": "support.type.pine" },
// "4": { "name": "storage.type.pine" },
// "5": { "name": "support.type.pine" },
// "6": { "name": "storage.type.pine" },
// "7": { "name": "support.variable.pine" },
// "8": { "name": "keyword.operator.type.pine" },
// "9": { "name": "string.quoted.pine" },
// "10": { "name": "constant.numeric.pine" },
// "11": { "name": "variable.language.pine" }
// }
// }
// ],
// "end": "(?<=^)(?=\\b|\/\/\\s*@)",
// "endCaptures": { "0": { "name": "string.end.pine" } }
// }
// ]
// },
// "keywords": {
// "patterns": [
// {
// "match": "\\b(if|else|for|while|switch)\\b",
// "name": "keyword.control.conditional.pine"
// },
// {
// "match": "\\b(var|varip|by|to|in|or|and|not|series|simple)\\b",
// "name": "keyword.pine"
// },
// {
// "match": "\\b(continue|break)\\b",
// "name": "keyword.operator.pine"
// }
// ]
// },
// "numbers": {
// "patterns": [
// {
// "match": "(\\b(?:[+-]?\\d*\\.?\\d+([Ee][+-]?\\d+)?)\\b|#[a-fA-F0-9]+\\b)",
// "name": "constant.numeric.pine"
// }
// ]
// },
// "operators": {
// "patterns": [
// {
// "name": "keyword.control.pine",
// "match": "(=>)"
// },
// {
// "match": "(\\-\\=|\\+\\=|\\*\\=|/=|%=)",
// "name": "keyword.operator.assignment.pine"
// },
// {
// "match": "(\\-|\\+|\\*|/|%)",
// "name": "keyword.operator.arithmetic.pine"
// },
// {
// "match": "(==|!=|<=|>=|<|>|:=)",
// "name": "keyword.operator.comparison.pine"
// },
// {
// "match": "(\\?|\\:)",
// "name": "keyword.operator.conditional.pine"
// },
// {
// "match": "(\\=)",
// "name": "keyword.control.pine"
// }
// ]
// },
// "storage": {
// "patterns": [
// {
// "captures": {
// "1": { "name": "storage.type.array.matrix.pine" },
// "3": { "name": "support.class.imported.pine" },
// "5": { "name": "support.class.imported.pine" },
// "4": { "name": "support.type.pine" },
// "6": { "name": "support.type.pine" },
// "8": { "name": "storage.type.pine" },
// "9": { "name": "support.variable.pine" }
// },
// "match": "(?:\\b(((array|matrix)<([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)>|([a-zA-Z_][a-zA-Z_0-9]*\\.)?([a-zA-Z_][a-zA-Z_0-9]*)[\\t ]*(\\[\\])?)))\\s+([a-zA-Z_][a-zA-Z0-9_]*\\s*(?=\\=))"
// },
// {
// "begin": "(\\b(var|varip)\\s+)",
// "beginCaptures": {
// "1": { "name": "keyword.declaration.pine" },
// "2": { "name": "storage.type.pine" },
// "3": { "name": "support.variable.other" }
// },
// "patterns": [
// { "include": "#variables" },
// { "include": "#storage" }
// ],
// "end": "(?<=(var|varip)\\s+[^\\n]+)(?=[^-:/*+%]\\=))",
// "endCaptures": { "1": { "name": "keyword.operator.assignment.pine" } }
// },
// {
// "begin": "\\[",
// "beginCaptures": { "0": { "name": "punctuation.definition.array.begin.pine" } },
// "end": "\\]",
// "endCaptures": { "0": { "name": "punctuation.definition.array.end.pine" } },
// "patterns": [
// { "include": "#constants" },
// { "include": "#strings" },
// { "include": "#numbers" },
// { "include": "#operators" },
// { "include": "#functions" },
// { "include": "#variables" }
// ]
// }
// ]
// },
// "variables": {
// "patterns": [
// {
// "match": "(?:\\b(([a-zA-Z_][a-zA-Z0-9_]*\\.)(?:([a-zA-Z_][a-zA-Z0-9_]*)\\.)*)?([a-zA-Z_][a-zA-Z0-9_]*)\\b\\s*(?!\\())",
// "captures": {
// "2": { "name": "entity.other.inherited-class.pine" },
// "3": { "name": "variable.other.constant.pine" },
// "1": { "name": "entity.other.attribute-name.pine" },
// "0": { "name": "language.variable.other.pine" }
// }
// }
// ]
// },
// "strings": {
// "patterns": [
// {
// "begin": "(\")",
// "beginCaptures": { "1": { "name": "string.begin.pine" } },
// "end": "(\"|$)",
// "endCaptures": { "1": { "name": "string.end.pine" } },
// "patterns": [
// {
// "match": "(?<=\")[^\"\\n]+(?=\\n|\")",
// "name": "string.double.pine"
// }
// ],
// "name": "string.pine"
// },
// {
// "begin": "(')",
// "beginCaptures": { "1": { "name": "string.begin.pine" } },
// "end": "('|$)",
// "endCaptures": { "1": { "name": "string.end.pine" } },
// "patterns": [
// {
// "match": "(?<=')[^'\\n]+(?=\\n|')",
// "name": "string.single.pine"
// }
// ],
// "name": "string.single.pine"
// }
// ]
// },
// "punctuation": {
// "patterns": [
// {
// "match": "(,|\\.|:|\\(|\\)|\\[|\\])",
// "name": "punctuation.separator.pine"
// }
// ]
// }
// }
// }
plot(0,'o',na) |
Buyside & Sellside Liquidity [LuxAlgo] | https://www.tradingview.com/script/Qk4vBbfL-Buyside-Sellside-Liquidity-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 6,677 | 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("Buyside & Sellside Liquidity [LuxAlgo]", "LuxAlgo - Buyside & Sellside Liquidity", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_bars_back = 3000)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
liqGrp = 'Liquidity Detection'
liqLen = input.int (7, title = 'Detection Length', minval = 3, maxval = 13, inline = 'LIQ', group = liqGrp)
liqMar = 10 / input.float (6.9, 'Margin', minval = 4, maxval = 9, step = 0.1, inline = 'LIQ', group = liqGrp)
liqBuy = input.bool (true, 'Buyside Liquidity Zones, Margin', inline = 'Buyside', group = liqGrp)
marBuy = input.float(2.3, '', minval = 1.5, maxval = 10, step = .1, inline = 'Buyside', group = liqGrp)
cLIQ_B = input.color (color.new(#4caf50, 0), '', inline = 'Buyside', group = liqGrp)
liqSel = input.bool (true, 'Sellside Liquidity Zones, Margin', inline = 'Sellside', group = liqGrp)
marSel = input.float(2.3, '', minval = 1.5, maxval = 10, step = .1, inline = 'Sellside', group = liqGrp)
cLIQ_S = input.color (color.new(#f23645, 0), '', inline = 'Sellside', group = liqGrp)
lqVoid = input.bool (false, 'Liquidity Voids, Bullish', inline = 'void', group = liqGrp)
cLQV_B = input.color (color.new(#4caf50, 0), '', inline = 'void', group = liqGrp)
cLQV_S = input.color (color.new(#f23645, 0), 'Bearish', inline = 'void', group = liqGrp)
lqText = input.bool (false, 'Label', inline = 'void', group = liqGrp)
mode = input.string('Present', title = 'Mode', options =['Present', 'Historical'], inline = 'MOD', group = liqGrp)
visLiq = input.int (3, 'ย ย ย ย # Visible Levels', minval = 1, maxval = 50, inline = 'MOD', group = liqGrp)
//-----------------------------------------------------------------------------}
//General Calculations
//-----------------------------------------------------------------------------{
maxSize = 50
atr = ta.atr(10)
atr200 = ta.atr(200)
per = mode == 'Present' ? last_bar_index - bar_index <= 500 : true
//-----------------------------------------------------------------------------}
//User Defined Types
//-----------------------------------------------------------------------------{
// @type used to store pivot high/low data
//
// @field d (array<int>) The array where the trend direction is to be maintained
// @field x (array<int>) The array where the bar index value of pivot high/low is to be maintained
// @field y (array<float>) The array where the price value of pivot high/low is to be maintained
type ZZ
int [] d
int [] x
float [] y
// @type bar properties with their values
//
// @field o (float) open price of the bar
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field i (int) index of the bar
type bar
float o = open
float h = high
float l = low
float c = close
int i = bar_index
// @type liquidity object definition
//
// @field bx (box) box maitaing the liquity level margin extreme levels
// @field bxz (box) box maitaing the liquity zone margin extreme levels
// @field bxt (box) box maitaing the labels
// @field brZ (bool) mainains broken zone status
// @field brL (bool) mainains broken level status
// @field ln (line) maitaing the liquity level line
// @field lne (line) maitaing the liquity extended level line
type liq
box bx
box bxz
box bxt
bool brZ
bool brL
line ln
line lne
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var ZZ aZZ = ZZ.new(
array.new <int> (maxSize, 0),
array.new <int> (maxSize, 0),
array.new <float>(maxSize, na)
)
bar b = bar.new()
var liq[] b_liq_B = array.new<liq> (1, liq.new(box(na), box(na), box(na), false, false, line(na), line(na)))
var liq[] b_liq_S = array.new<liq> (1, liq.new(box(na), box(na), box(na), false, false, line(na), line(na)))
var b_liq_V = array.new_box()
var int dir = na, var int x1 = na, var float y1 = na, var int x2 = na, var float y2 = na
//-----------------------------------------------------------------------------}
//Functions/methods
//-----------------------------------------------------------------------------{
// @function maintains arrays
// it prepends a `value` to the arrays and removes their oldest element at last position
// @param aZZ (UDT<array<int>, array<int>, array<float>>) The UDT obejct of arrays
// @param _d (array<int>) The array where the trend direction is maintained
// @param _x (array<int>) The array where the bar index value of pivot high/low is maintained
// @param _y (array<float>) The array where the price value of pivot high/low is maintained
//
// @returns none
method in_out(ZZ aZZ, int _d, int _x, float _y) =>
aZZ.d.unshift(_d), aZZ.x.unshift(_x), aZZ.y.unshift(_y), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
// @function (build-in) sets the maximum number of bars that is available for historical reference
max_bars_back(time, 1000)
//-----------------------------------------------------------------------------}
//Calculations
//-----------------------------------------------------------------------------{
x2 := b.i - 1
ph = ta.pivothigh(liqLen, 1)
pl = ta.pivotlow (liqLen, 1)
if ph
dir := aZZ.d.get(0)
x1 := aZZ.x.get(0)
y1 := aZZ.y.get(0)
y2 := nz(b.h[1])
if dir < 1
aZZ.in_out(1, x2, y2)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if per
count = 0
st_P = 0.
st_B = 0
minP = 0.
maxP = 10e6
for i = 0 to maxSize - 1
if aZZ.d.get(i) == 1
if aZZ.y.get(i) > ph + (atr / liqMar)
break
else
if aZZ.y.get(i) > ph - (atr / liqMar) and aZZ.y.get(i) < ph + (atr / liqMar)
count += 1
st_B := aZZ.x.get(i)
st_P := aZZ.y.get(i)
if aZZ.y.get(i) > minP
minP := aZZ.y.get(i)
if aZZ.y.get(i) < maxP
maxP := aZZ.y.get(i)
if count > 2
getB = b_liq_B.get(0)
if st_B == getB.bx.get_left()
getB.bx.set_top(math.avg(minP, maxP) + (atr / liqMar))
getB.bx.set_rightbottom(b.i + 10, math.avg(minP, maxP) - (atr / liqMar))
else
b_liq_B.unshift(
liq.new(
box.new(st_B, math.avg(minP, maxP) + (atr / liqMar), b.i + 10, math.avg(minP, maxP) - (atr / liqMar), bgcolor=color(na), border_color=color(na)),
box.new(na, na, na, na, bgcolor = color(na), border_color = color(na)),
box.new(st_B, st_P, b.i + 10, st_P, text = 'Buyside liquidity', text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_bottom, text_color = color.new(cLIQ_B, 25), bgcolor = color(na), border_color = color(na)),
false,
false,
line.new(st_B , st_P, b.i - 1, st_P, color = color.new(cLIQ_B, 0)),
line.new(b.i - 1, st_P, na , st_P, color = color.new(cLIQ_B, 0), style = line.style_dotted))
)
alert('buyside liquidity level detected/updated for ' + syminfo.ticker)
if b_liq_B.size() > visLiq
getLast = b_liq_B.pop()
getLast.bx.delete()
getLast.bxz.delete()
getLast.bxt.delete()
getLast.ln.delete()
getLast.lne.delete()
if pl
dir := aZZ.d.get (0)
x1 := aZZ.x.get (0)
y1 := aZZ.y.get (0)
y2 := nz(b.l[1])
if dir > -1
aZZ.in_out(-1, x2, y2)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if per
count = 0
st_P = 0.
st_B = 0
minP = 0.
maxP = 10e6
for i = 0 to maxSize - 1
if aZZ.d.get(i) == -1
if aZZ.y.get(i) < pl - (atr / liqMar)
break
else
if aZZ.y.get(i) > pl - (atr / liqMar) and aZZ.y.get(i) < pl + (atr / liqMar)
count += 1
st_B := aZZ.x.get(i)
st_P := aZZ.y.get(i)
if aZZ.y.get(i) > minP
minP := aZZ.y.get(i)
if aZZ.y.get(i) < maxP
maxP := aZZ.y.get(i)
if count > 2
getB = b_liq_S.get(0)
if st_B == getB.bx.get_left()
getB.bx.set_top(math.avg(minP, maxP) + (atr / liqMar))
getB.bx.set_rightbottom(b.i + 10, math.avg(minP, maxP) - (atr / liqMar))
else
b_liq_S.unshift(
liq.new(
box.new(st_B, math.avg(minP, maxP) + (atr / liqMar), b.i + 10, math.avg(minP, maxP) - (atr / liqMar), bgcolor=color(na), border_color=color(na)),
box.new(na, na, na, na, bgcolor=color(na), border_color=color(na)),
box.new(st_B, st_P, b.i + 10, st_P, text = 'Sellside liquidity', text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_top, text_color = color.new(cLIQ_S, 25), bgcolor=color(na), border_color=color(na)),
false,
false,
line.new(st_B , st_P, b.i - 1, st_P, color = color.new(cLIQ_S, 0)),
line.new(b.i - 1, st_P, na , st_P, color = color.new(cLIQ_S, 0), style = line.style_dotted))
)
alert('sellside liquidity level detected/updated for ' + syminfo.ticker)
if b_liq_S.size() > visLiq
getLast = b_liq_S.pop()
getLast.bx.delete()
getLast.bxz.delete()
getLast.bxt.delete()
getLast.ln.delete()
getLast.lne.delete()
for i = 0 to b_liq_B.size() - 1
x = b_liq_B.get(i)
if not x.brL
x.lne.set_x2(b.i)
if b.h > x.bx.get_top()
x.brL := true
x.brZ := true
alert('buyside liquidity level breached for ' + syminfo.ticker)
x.bxz.set_lefttop(b.i - 1, math.min(x.ln.get_y1() + marBuy * (atr), b.h))
x.bxz.set_rightbottom(b.i + 1, x.ln.get_y1())
x.bxz.set_bgcolor(color.new(cLIQ_B, liqBuy ? 73 : 100))
else if x.brZ
if b.l > x.ln.get_y1() - marBuy * (atr) and b.h < x.ln.get_y1() + marBuy * (atr)
x.bxz.set_right(b.i + 1)
x.bxz.set_top(math.max(b.h, x.bxz.get_top()))
if liqBuy
x.lne.set_x2(b.i + 1)
else
x.brZ := false
for i = 0 to b_liq_S.size() - 1
x = b_liq_S.get(i)
if not x.brL
x.lne.set_x2(b.i)
if b.l < x.bx.get_bottom()
x.brL := true
x.brZ := true
alert('sellside liquidity level breached for ' + syminfo.ticker)
x.bxz.set_lefttop(b.i - 1, x.ln.get_y1())
x.bxz.set_rightbottom(b.i + 1, math.max(x.ln.get_y1() - marSel * (atr), b.l))
x.bxz.set_bgcolor(color.new(cLIQ_S, liqSel ? 73 : 100))
else if x.brZ
if b.l > x.ln.get_y1() - marSel * (atr) and b.h < x.ln.get_y1() + marSel * (atr)
x.bxz.set_rightbottom(b.i + 1, math.min(b.l, x.bxz.get_bottom()))
if liqSel
x.lne.set_x2(b.i + 1)
else
x.brZ := false
if lqVoid and per
bull = b.l - b.h[2] > atr200 and b.l > b.h[2] and b.c[1] > b.h[2]
bear = b.l[2] - b.h > atr200 and b.h < b.l[2] and b.c[1] < b.l[2]
if bull
l = 13
if bull[1]
st = math.abs(b.l - b.l[1]) / l
for i = 0 to l - 1
array.push(b_liq_V, box.new(b.i - 2, b.l[1] + i * st, b.i, b.l[1] + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
else
st = math.abs(b.l - b.h[2]) / l
for i = 0 to l - 1
if lqText and i == 0
array.push(b_liq_V, box.new(b.i - 2, b.h[2] + i * st, b.i, b.h[2] + (i + 1) * st, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_bottom, text_color = na, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
else
array.push(b_liq_V, box.new(b.i - 2, b.h[2] + i * st, b.i, b.h[2] + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_B, 90) ))
if bear
l = 13
if bear[1]
st = math.abs(b.h[1] - b.h) / l
for i = 0 to l - 1
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
else
st = math.abs(b.l[2] - b.h) / l
for i = 0 to l - 1
if lqText and i == l - 1
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_top, text_color = na, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
else
array.push(b_liq_V, box.new(b.i - 2, b.h + i * st, b.i, b.h + (i + 1) * st, border_color = na, bgcolor = color.new(cLQV_S, 90) ))
if b_liq_V.size() > 0
qt = b_liq_V.size()
for bn = qt - 1 to 0
if bn < b_liq_V.size()
cb = b_liq_V.get(bn)
ba = math.avg(cb.get_bottom(), cb.get_top())
if math.sign(b.c[1] - ba) != math.sign(b.c - ba) or math.sign(b.c[1] - ba) != math.sign(b.l - ba) or math.sign(b.c[1] - ba) != math.sign(b.h - ba)
b_liq_V.remove(bn)
else
cb.set_right(b.i + 1)
if b.i - cb.get_left() > 21
cb.set_text_color(color.new(color.gray, 25))
//-----------------------------------------------------------------------------} |
[DIP] Inverse BB/Bollinger highlight for bars | https://www.tradingview.com/script/DXXrzwY4-DIP-Inverse-BB-Bollinger-highlight-for-bars/ | Mr_Dip | https://www.tradingview.com/u/Mr_Dip/ | 51 | 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/
// ยฉ Yubu
//@version=5
indicator(title='[DIP] Inverse BB Highlight', shorttitle='[DIP] Bar Highlight (v1.0)', overlay=true, max_labels_count = 500)
// Functions
bb(float source, simple int period, int offset = 0) =>
// BB Calc
ma = ta.sma(source, period)
std = ta.stdev(source, period)
std2_lower = ma + (-2 + offset) * std
std2_upper = ma + (2 + offset) * std
std3_lower = ma + (-3 + offset) * std
std3_upper = ma + (3 + offset) * std
// Output
[ma, std2_lower, std2_upper, std3_lower, std3_upper]
// Inputs
timeframe = input.timeframe(title='Timeframe', defval='', group='General', inline='1')
source = input.source(title='', defval=close, group='General', inline='1')
// BB Input
bb_group = 'Bollinger Band'
bool bb_enabled = input.bool(defval = false, title='Show BB', group=bb_group, inline = '10', tooltip = 'Enable Bollinger Band Visualization')
color bb_color = input.color(defval = color.rgb(0, 255, 255, 66), title='', group=bb_group, inline = '10')
int bb_period = input.int(defval=110, title='BB Period', group=bb_group)
int bb_offset = input.int(defval=0, minval=-5, maxval=5, title='BB Offset', group=bb_group, tooltip = 'Add or subtract a deviation from the bollinger band, this can help visualize a directional bias on markets with a strong trend.' )
// Color Input
color_group = 'Style Settings'
override = input.bool(defval = true, inline = '30', title = '', group = color_group)
override_color = input.color(defval = color.rgb(255, 255, 255, 90), inline = '30', title = 'Override Color', tooltip = 'If enabled, overrides the default bar color inside the bollinger bands.', group = color_group)
aboveBB_color = input.color(defval = color.red, title = 'Above BB Color', group = color_group)
belowBB_color = input.color(defval = color.green, title = 'Below BB Color', group = color_group)
transBB_color = input.color(defval = color.rgb(255, 255, 255, 70), title = 'Cross BB Color', group = color_group)
// BB Calc
[bb_ma, bb2_low, bb2_up, bb3_low, bb3_up] = request.security(syminfo.tickerid, timeframe, bb(source, bb_period, bb_offset))
// BB Output
// plot_base_ma = plot(bb_ma, color=color.new(bb_color, 50), linewidth=2, title='BB Base MA')
plot_upper_std_2 = plot(bb_enabled ? bb2_up : na, color=color.new(bb_color, 70), title='BB Upper')
plot_lower_std_2 = plot(bb_enabled ? bb2_low : na, color=color.new(bb_color, 70), title='BB Lower')
fill(plot_upper_std_2, plot_lower_std_2, color = color.new(bb_color, 96), fillgaps=true)
// Bar Color
aboveBB = close > bb2_up and open > bb2_up
belowBB = close < bb2_low and open < bb2_low
transBB = (open < bb2_up and close > bb2_up) or (open > bb2_up and close < bb2_up) or (open > bb2_low and close < bb2_low) or (open < bb2_low and close > bb2_low)
BC = aboveBB ? aboveBB_color : belowBB ? belowBB_color : transBB ? transBB_color : override ? override_color : na
barcolor(color = BC, display = display.all) |
Volume-Weighted RSI with Adaptive Smoothing | https://www.tradingview.com/script/47DVxkap-Volume-Weighted-RSI-with-Adaptive-Smoothing/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 115 | 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/
// ยฉ LeafAlgo
//@version=5
indicator("Volume-Weighted RSI with Adaptive Smoothing", overlay=false)
length = input.int(14, minval=1, title="Length")
// Calculate RSI
rsi_source = ta.change(close)
up = ta.rma(math.max(rsi_source, 0), length)
down = ta.rma(-math.min(rsi_source, 0), length)
rsi = 100 - (100 / (1 + up / down))
// Calculate Volume-Weighted RSI
vwap = ta.sma(close * volume, length) / ta.sma(volume, length)
vwap_source = ta.change(vwap)
vwap_up = ta.rma(math.max(vwap_source, 0), length)
vwap_down = ta.rma(-math.min(vwap_source, 0), length)
vwap_rsi = 100 - (100 / (1 + vwap_up / vwap_down))
// Adaptive Smoothing
adaptive_smoothing = input.bool(true, title="Adaptive Smoothing")
smoothing_length = input.int(5, minval=1, title="Smoothing Length")
smooth_vwap_rsi = adaptive_smoothing ? ta.sma(vwap_rsi, smoothing_length) : vwap_rsi
// Coloration
rsiColor = rsi >= smooth_vwap_rsi ? color.lime : color.fuchsia
backColor = smooth_vwap_rsi >= 70 ? color.new(color.lime, 80) : smooth_vwap_rsi <= 30 ? color.new(color.fuchsia, 80) : color.new(color.yellow, 80)
barC = smooth_vwap_rsi >= 70 ? color.lime : smooth_vwap_rsi <= 30 ? color.fuchsia : color.yellow
// Plotting
plot(rsi, color=rsiColor, linewidth=4, title="RSI")
plot(smooth_vwap_rsi, color=color.maroon, linewidth=1, style=plot.style_histogram, title="Volume-Weighted RSI Histogram")
plot(smooth_vwap_rsi, color=color.maroon, linewidth=1, title='Volume-Weighted RSI Line')
bgcolor(backColor)
barcolor(barC)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
hline(50)
|
[Mad] Liquidation Levels | https://www.tradingview.com/script/9pCNeK2e-Mad-Liquidation-Levels/ | djmad | https://www.tradingview.com/u/djmad/ | 286 | 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(title='[Mad] Liquidation Levels Standalone ', shorttitle='[Mad] Liquidation Levels SA', overlay=true , max_boxes_count=500, max_lines_count=500)
import djmad/Liquidationline/3 as LILI
float f_leverage_1 = input.float(50, "Leverage 1", minval=0, maxval=100 ,step = 1, group='Leverage 1')
color col_lev_1 = input(color.rgb(231, 65, 65, 20), group='Leverage 1')
int thinkness_1 = input.int(1,"Thickness of lines 1", minval = -1, group='Leverage 1')
float f_leverage_2 = input.float(25, "Leverage 2", minval=0, maxval=100 ,step = 1, group='Leverage 2')
color col_lev_2 = input(color.rgb(225, 236, 72, 50), group='Leverage 2')
int thinkness_2 = input.int(1,"Thickness of lines 2", minval = -1, group='Leverage 2')
bool priceorliq = input.bool(false, "Position or Liq", group='leverage')
float maintainance = input.float(50, "Exchange margin maintainance %", minval=0, maxval=100 ,group='common',step = 1)
bool killonlowhigh = input.bool(true, "Kill on LOW/HIGH", tooltip = "how is a relevant liquidation handled, by high/low or by the close value")
int maximumlines = math.floor(input.int(500,"Maximum amount of lines")/4)
int minimumlength = input.int(10,"Minimum Length of liquidated lines", minval = -1, tooltip = "set this parameter to disable the small line cleanup, as longer the minimum length as more historic lines will remain")
float factor = input.float(1.03,"minimum shrink/raise of the close for new line draw",step = 0.01, minval = 1.0, group='Indicator settings')
string indicator_sel = input.string("Bollinger",options = ["Bollinger","MACD","EMACROSS","SMACROSS"], group='Indicator settings')
string mtf_lvl = input.timeframe("", title="Custom TF",group='Indicator settings')
int length1 = input.int(20, title="Ma-Length_1",minval = 1)
int length2 = input.int(40, title="Ma-Length_2",minval = 1)
int length3 = input.int(10, title="Sig-Length_2",minval = 1)
bool Show_L1 = input.bool(false, "Show L1 Bollingers",group='Indicator settings')
bool Show_L2 = input.bool(true, "Show L2 Bollingers",group='Indicator settings')
bool Show_L3 = input.bool(true, "Show L3 Bollingers",group='Indicator settings')
/////////////////////////////////
var bool LOCK = false
var float lastprice = na
var float timeperbar = 0.0000001
//run the timeperbar only as long till relevant data is aviable ( 100 bars to get the value, incl. 100 bars reserve)
if bar_index < 200
timeperbar := LILI.f_getbartime()
//init {
var LILI.Liquidationline[] Liqui_Line_L_1 = array.new <LILI.Liquidationline>()
var LILI.Liquidationline[] Liqui_Line_S_1 = array.new <LILI.Liquidationline>()
var LILI.Liquidationline[] Liqui_Line_L_2 = array.new <LILI.Liquidationline>()
var LILI.Liquidationline[] Liqui_Line_S_2 = array.new <LILI.Liquidationline>()
set_l_1 = LILI.Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage_1,
maintainance= maintainance,
line_active= true,
line_color= col_lev_1,
line_thickness= thinkness_1,
line_style= line.style_solid,
line_direction= "long",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
set_s_1 = LILI.Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage_1,
maintainance= maintainance,
line_active= true,
line_color= col_lev_1,
line_thickness= thinkness_1,
line_style= line.style_solid,
line_direction= "short",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
set_l_2 = LILI.Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage_2,
maintainance= maintainance,
line_active= true,
line_color= col_lev_2,
line_thickness= thinkness_2,
line_style= line.style_solid,
line_direction= "long",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
set_s_2 = LILI.Liquidationline.new(
creationtime= time,
stoptime = time,
price= close,
leverage= f_leverage_2,
maintainance= maintainance,
line_active= true,
line_color= col_lev_2,
line_thickness= thinkness_2,
line_style= line.style_solid,
line_direction= "short",
line_finished= false,
text_active= true,
text_size= size.normal,
text_color= color.white
)
//}
//input.string("Bollinger",options = ["Bollinger","MACD","EMACROSS"], group='Indicator settings')
get_boll(simple int _length1, simple float _multiplier, simple string _timeframe) =>
request.security(syminfo.tickerid,_timeframe,ta.bb(close,_length1,_multiplier), barmerge.gaps_off, barmerge.lookahead_off)
get_macd(simple int _length1, simple int _length2, simple int _length3, simple string _timeframe) =>
request.security(syminfo.tickerid,_timeframe,ta.macd(close,_length1,_length2, _length3), barmerge.gaps_off, barmerge.lookahead_off)
get_emacross(simple int _length1, simple int _length2, simple string _timeframe) =>
request.security(syminfo.tickerid,_timeframe,ta.cross(ta.ema(close,_length1),ta.ema(close,_length2)), barmerge.gaps_off, barmerge.lookahead_off)
get_smacross(simple int _length1, simple int _length2, simple string _timeframe) =>
request.security(syminfo.tickerid,_timeframe,ta.cross(ta.sma(close,_length1),ta.sma(close,_length2)), barmerge.gaps_off, barmerge.lookahead_off)
[a1,b1,c1] = get_boll(_length1 = length1, _multiplier = 1, _timeframe = mtf_lvl)
[a2,b2,c2] = get_boll(_length1 = length1, _multiplier = 2, _timeframe = mtf_lvl)
[a3,b3,c3] = get_boll(_length1 = length1, _multiplier = 3, _timeframe = mtf_lvl)
[a4,b4,c4] = get_macd(_length1 = length1, _length2 = length2, _length3 = length3, _timeframe = mtf_lvl)
a5 = get_emacross(_length1 = length1, _length2 = length2, _timeframe = mtf_lvl)
a6 = get_smacross(_length1 = length1, _length2 = length2, _timeframe = mtf_lvl)
alert_1 = switch indicator_sel
"Bollinger" => ((Show_L1? ta.crossunder(close,c1) or ta.crossover(close,a1) :false) or
(Show_L2? ta.crossunder(close,c2) or ta.crossover(close,a2) :false) or
(Show_L3? ta.crossunder(close,c3) or ta.crossover(close,a3) :false))
"MACD" => ta.cross(a4, b4)
"EMACROSS" => a5
"SMACROSS" => a6
if close > lastprice * factor or close < lastprice / factor
LOCK := false
if alert_1 and
LOCK == false
LOCK := true
lastprice := close
LILI.f_liqline_add(_Liqui_Line = Liqui_Line_L_1, linetoadd = set_l_1,_limit = maximumlines)
LILI.f_liqline_add(_Liqui_Line = Liqui_Line_S_1, linetoadd = set_s_1,_limit = maximumlines)
LILI.f_liqline_add(_Liqui_Line = Liqui_Line_L_2, linetoadd = set_l_2,_limit = maximumlines)
LILI.f_liqline_add(_Liqui_Line = Liqui_Line_S_2, linetoadd = set_s_2,_limit = maximumlines)
LILI.f_liqline_draw(_Liqui_Line = Liqui_Line_L_1, _priceorliq = priceorliq)
LILI.f_liqline_draw(_Liqui_Line = Liqui_Line_S_1, _priceorliq = priceorliq)
LILI.f_liqline_draw(_Liqui_Line = Liqui_Line_L_2, _priceorliq = priceorliq)
LILI.f_liqline_draw(_Liqui_Line = Liqui_Line_S_2, _priceorliq = priceorliq)
LILI.f_liqline_update(_Liqui_Line = Liqui_Line_L_1, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar)
LILI.f_liqline_update(_Liqui_Line = Liqui_Line_S_1, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar)
LILI.f_liqline_update(_Liqui_Line = Liqui_Line_L_2, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar)
LILI.f_liqline_update(_Liqui_Line = Liqui_Line_S_2, _killonlowhigh = killonlowhigh, _minlength = minimumlength, _timeperbar = timeperbar) |
Kernel Regression Toolkit | https://www.tradingview.com/script/ARPbTa5N-Kernel-Regression-Toolkit/ | veryfid | https://www.tradingview.com/u/veryfid/ | 927 | 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/
// ยฉ jdehorty ยฉ veryfid
//@version=5
indicator(title='Kernel Regression Toolkit', shorttitle='kreg', overlay=true)
import veryfid/KernelFunctionsFilters/1 as kreg
// For more information on this technique refer to to the original open source indicator by @jdehorty located here:
// https://www.tradingview.com/script/AWNvbPRM-Nadaraya-Watson-Rational-Quadratic-Kernel-Non-Repainting/
// Nadaraya-Watson Kernel Regression Settings
src = input(close)
filt1 = input.string("Smooth", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 1 - Fast", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type1 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 1 - Fast", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h = input.int(3, 'Lookback Window', minval=3, group="Kernel Regression 1 - Fast", inline="k")
r = input.float(1., 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 1 - Fast", inline="k1")
x = input.int(2, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 1 - Fast", inline="k1")
lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='k1', group="Kernel Regression 1 - Fast")
filt2 = input.string("Smooth", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 2 - Medium", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type2 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 2 - Medium", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h2 = input.int(8, 'Lookback Window', minval=3, tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group="Kernel Regression 2 - Medium", inline="k")
r2 = input.float(1., 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 2 - Medium", inline="kernel2")
x2 = input.int(20, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 2 - Medium", inline="kernel2")
lag2 = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='kernel2', group='Kernel Regression 2 - Medium')
filt3 = input.string("Smooth", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 3 - Slow", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type3 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 3 - Slow", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h3 = input.int(200, 'Lookback Window', minval=3, tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group="Kernel Regression 3 - Slow", inline="k")
r3 = input.float(1., 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 3 - Slow", inline="kernel3")
x3 = input.int(500, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 3 - Slow", inline="kernel3")
lag3 = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='kernel3', group='Kernel Regression 3 - Slow')
filt4 = input.string("Smooth", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 4 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type4 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 4 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h4 = input.int(30, 'Lookback Window', minval=3, group="Kernel Regression 4 - Mono", inline="k")
r4 = input.float(8., 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 4 - Mono", inline="k1")
x4 = input.int(35, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 4 - Mono", inline="k1")
lag4 = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='k1', group="Kernel Regression 4 - Mono")
filt5 = input.string("Smooth", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 5 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type5 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 5 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h5 = input.int(69, 'Lookback Window', minval=3, group="Kernel Regression 5 - Mono", inline="k")
r5 = input.float(1, 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 5 - Mono", inline="k1")
x5 = input.int(500, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 5 - Mono", inline="k1")
lag5 = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='k1', group="Kernel Regression 5 - Mono")
filt6 = input.string("Zero Lag", options = ["No Filter", "Smooth", "Zero Lag"],title = "",group ="Kernel Regression 6 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
type6 = input.string("Rational Quadratic", options = ["Rational Quadratic", "Gaussian", "Periodic", "Locally Periodic"],title = "",group ="Kernel Regression 6 - Mono", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
h6 = input.int(200, 'Lookback Window', minval=3, group="Kernel Regression 6 - Mono", inline="k")
r6 = input.float(1., 'Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group="Kernel Regression 6 - Mono", inline="k1")
x6 = input.int(500, "Level", tooltip='Bar index on which to start regression. Controls how tightly fit the kernel estimate is to the data. Smaller values are a tighter fit. Larger values are a looser fit. Recommended range: 2-25', group="Kernel Regression 6 - Mono", inline="k1")
lag6 = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='k1', group="Kernel Regression 6 - Mono")
ksrc = kreg.rationalQuadratic(close, 3, 1, 1, "No FIlter")
line1 = type1 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h, r, x, filt1) : type1 == "Gaussian" ? kreg.gaussian(src, h-lag, x, filt1) : type1 == "Periodic" ? kreg.periodic(src, h, lag, x, filt1) : type1 == "Locally Periodic" ? kreg.locallyPeriodic(src, h, lag, x, filt1) : na
line2 = type2 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h2, r2, x2, filt2) : type2 == "Gaussian" ? kreg.gaussian(src, h2-lag2, x2, filt2) : type2 == "Periodic" ? kreg.periodic(src, h2, lag2, x2, filt2) : type2 == "Locally Periodic" ? kreg.locallyPeriodic(src, h2, lag2, x2, filt2) : na
line3 = type3 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h3, r3, x3, filt3) : type3 == "Gaussian" ? kreg.gaussian(src, h3-lag3, x3, filt3) : type3 == "Periodic" ? kreg.periodic(src, h3, lag3, x3, filt3) : type3 == "Locally Periodic" ? kreg.locallyPeriodic(src, h3, lag3, x3, filt3) : na
line4 = type4 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h4, r4, x4, filt4) : type4 == "Gaussian" ? kreg.gaussian(src, h4-lag4, x4, filt4) : type4 == "Periodic" ? kreg.periodic(src, h4, lag4, x4, filt4) : type4 == "Locally Periodic" ? kreg.locallyPeriodic(src, h4, lag4, x4, filt4) : na
line5 = type5 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h5, r5, x5, filt5) : type5 == "Gaussian" ? kreg.gaussian(src, h5-lag5, x5, filt5) : type5 == "Periodic" ? kreg.periodic(src, h5, lag5, x5, filt5) : type5 == "Locally Periodic" ? kreg.locallyPeriodic(src, h5, lag5, x5, filt5) : na
line6 = type6 == "Rational Quadratic" ? kreg.rationalQuadratic(src, h6, r6, x6, filt6) : type6 == "Gaussian" ? kreg.gaussian(src, h6-lag6, x6, filt6) : type6 == "Periodic" ? kreg.periodic(src, h6, lag6, x6, filt6) : type6 == "Locally Periodic" ? kreg.locallyPeriodic(src, h6, lag6, x6, filt6) : na
usej1 = input(false,"Show J line 1",group ="J Line 1", inline = "k")
jline1src1 = input.string("Line 2", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close"],title = "",group ="J Line 1", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
jline1src2 = input.string("Line 4", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close"],title = "",group ="J Line 1", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
jline1a = jline1src1 == "Line 1" ? line1 : jline1src1 == "Line 2" ? line2 : jline1src1 == "Line 3" ? line3 : jline1src1 == "Line 4" ? line4 : jline1src1 == "Line 5" ? line5 : jline1src1 == "Line 6" ? line6 : jline1src1 == "Close" ? close : jline1src1 == "Ksrc" ? ksrc : ksrc
jline1b = jline1src2 == "Line 1" ? line1 : jline1src2 == "Line 2" ? line2 : jline1src2 == "Line 3" ? line3 : jline1src2 == "Line 4" ? line4 : jline1src2 == "Line 5" ? line5 : jline1src2 == "Line 6" ? line6 : jline1src2 == "Close" ? close : jline1src2 == "Ksrc" ? ksrc : ksrc
jline1 = kreg.j(jline1a,jline1b)
usej2 = input(false,"Show J line 2",group ="J Line 2", inline = "k")
jline2src1 = input.string("Line 3", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close", "J Line 1"],title = "",group ="J Line 2", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
jline2src2 = input.string("Line 5", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close", "J Line 1"],title = "",group ="J Line 2", inline = "k", tooltip = "Select Kernel Regression type from dropdown box. The Lookback Window is the number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50 ")
jline2a = jline2src1 == "Line 1" ? line1 : jline2src1 == "Line 2" ? line2 : jline2src1 == "Line 3" ? line3 : jline2src1 == "Line 4" ? line4 : jline2src1 == "Line 5" ? line5 : jline2src1 == "Line 6" ? line6 : jline2src1 == "Close" ? close : jline2src1 == "J Line 1" ? jline1 : ksrc
jline2b = jline2src2 == "Line 1" ? line1 : jline2src2 == "Line 2" ? line2 : jline2src2 == "Line 3" ? line3 : jline2src2 == "Line 4" ? line4 : jline2src2 == "Line 5" ? line5 : jline2src2 == "Line 6" ? line6 : jline2src2 == "Close" ? close : jline2src2 == "J Line 1" ? jline1 : ksrc
jline2 = kreg.j(jline2a,jline2b)
useblend = input(false,"Show",group ="Blend Two Lines", inline = "k")
blendsrc1 = input.string("Line 2", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close"],title = "",group ="Blend Two Lines", inline = "k", tooltip = "Select two Kernel Regression lines you would like to blend from the dropdown box. Adjust the percentage of the blend from 0-100%. It is also possible to overdrive the blend by pushing it over 100")
blendsrc2 = input.string("Line 4", options = ["Line 1", "Line 2", "Line 3", "Line 4", "Line 5", "Line 6","Close"],title = "",group ="Blend Two Lines", inline = "k")
blenda = blendsrc1 == "Line 1" ? line1 : blendsrc1 == "Line 2" ? line2 : blendsrc1 == "Line 3" ? line3 : blendsrc1 == "Line 4" ? line4 : blendsrc1 == "Line 5" ? line5 : blendsrc1 == "Line 6" ? line6 : blendsrc1 == "Close" ? close : blendsrc1 == "Ksrc" ? ksrc : ksrc
blendb = blendsrc2 == "Line 1" ? line1 : blendsrc2 == "Line 2" ? line2 : blendsrc2 == "Line 3" ? line3 : blendsrc2 == "Line 4" ? line4 : blendsrc2 == "Line 5" ? line5 : blendsrc2 == "Line 6" ? line6 : blendsrc2 == "Close" ? close : blendsrc2 == "Ksrc" ? ksrc : ksrc
weight = input(50,"",group ="Blend Two Lines", inline = "k")
weightcalc = weight/100
blend = blenda*weightcalc + blendb * (1 - weightcalc)
plot(line1,"Line1", color= line1 > line1[1] ? color.teal : color.red, linewidth=2)
plot(line2,"Line2", color= line2 > line2[1] ? color.teal : color.red , linewidth=2)
plot(line3,"Line3", color= line3 > line3[1] ? color.teal : color.red , linewidth=2)
plot(line4,"Line4", color= color.gray, linewidth=1)
plot(line5,"Line5", color= color.gray, linewidth=1)
plot(line6,"Line6", color= color.gray, linewidth=1)
plot(usej1 ? jline1 : na,"j1",color = color.white)
plot(usej2 ? jline2 : na,"j2",color = color.white)
plot(useblend ? blend : na,"Blend")
|
Inside Day Probability | https://www.tradingview.com/script/Xi1B0w5H-Inside-Day-Probability/ | omararturo | https://www.tradingview.com/u/omararturo/ | 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/
// ยฉ omararturo
//@version=5
indicator("Inside Day Probability", overlay = true)
// We use `var` to only initialize the table on the first bar.
var table dashboard = table.new(position.top_right, 3, 3, bgcolor = color.white, frame_color = color.gray, border_width = 1, border_color = color.gray)
var IDFCount = 0
var IDFBullishCount = 0
var IDFBullishSuccessCount = 0
var IDFBearishCount = 0
var IDFBearishSuccessCount = 0
IDFBullishSuccess = false
IDFBearishSuccess = false
insideDay = (high[3] > high[2]) and (low[3] < low[2])
bullish = (low[2] > low[1] and high[2] > high[1]) and (low[2] < close[1] and high[2] > close[1]) and (high[2] > open[1] and low[2] < open[1])
if (insideDay and bullish)
IDFBullishCount += 1
if (low[1] <= low and high[1] <= high)
IDFBullishSuccess := true
IDFBullishSuccessCount += 1
barcolor(IDFBullishSuccess ? color.lime : na, 0)
bearish = (high[2] < high[1] and low[2] < low[1]) and (high[2] > close[1] and low[2] < close[1]) and (high[2] > open[1] and low[2] < open[1])
if (insideDay and bearish)
IDFBearishCount += 1
if (high[1] >= high and low[1] >= low)
IDFBearishSuccess := true
IDFBearishSuccessCount += 1
barcolor(IDFBearishSuccess ? color.white : na, 0)
IDF = (insideDay and (bullish or bearish))
if (IDF)
IDFCount += 1
barcolor(IDF ? color.yellow : na, -2)
if barstate.islast
// We only populate the table on the last bar.
table.cell(dashboard, 0, 0, "Inside Day")
table.cell(dashboard, 1, 0, str.tostring(IDFCount))
table.cell(dashboard, 2, 0, "Success %")
table.cell(dashboard, 0, 1, "Inside Day Bullish")
table.cell(dashboard, 1, 1, str.tostring(IDFBullishCount))
table.cell(dashboard, 2, 1, str.tostring(IDFBullishSuccessCount * 100 / IDFBullishCount))
table.cell(dashboard, 0, 2, "Inside Day Bearish")
table.cell(dashboard, 1, 2, str.tostring(IDFBearishCount))
table.cell(dashboard, 2, 2, str.tostring(IDFBearishSuccessCount * 100 / IDFBearishCount))
|
Ultimate Correlation Coefficient | https://www.tradingview.com/script/CAbB35hR-Ultimate-Correlation-Coefficient/ | Celestial-Eye | https://www.tradingview.com/u/Celestial-Eye/ | 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/
// ยฉ Celestial-Eye
//@version=5
indicator("Ultimate Correlation Coefficient", shorttitle = "UCC", format = format.price, precision = 2)
//symbolInput = input.symbol("INDEX:BTCUSD", "Main Comparison", confirm = true)
symbolInput1 = input.symbol("SP:SPX", "Symbol", confirm = true)
symbolInput2 = input.symbol("TVC:DXY", "Symbol", confirm = true)
symbolInput3 = input.symbol("CURRENCYCOM:GOLD", "Symbol", confirm = true)
symbolInput4 = input.symbol("TVC:US10Y", "Symbol", confirm = true)
symbolInput5 = input.symbol("TVC:VIX", "Symbol", confirm = true)
sourceInput = input.source(close, "Source")
//not implemented yet
//showSPX = input.bool(true, "show SPX", inline = "g", group = "r")
//showDXY = input.bool(true, "show DXY", inline = "g", group = "r")
//showGOLD = input.bool(true, "show GOLD", inline = "g", group = "r")
//showUS10Y = input.bool(true, "show US10Y", inline = "g", group = "r")
//showVIX = input.bool(true, "show VIX", inline = "g", group = "r")
//different lengths
length15 = 15
length30 = 30
length60 = 60
length90 = 90
length120 = 120
length180 = 180
length360 = 360
length600= 600
length1000 = 1000
// This takes into account additional settings enabled on chart, e.g. divident adjustment or extended session
adjustedSeries1 = ticker.modify(symbolInput1)
adjustedSeries2 = ticker.modify(symbolInput2)
adjustedSeries3 = ticker.modify(symbolInput3)
adjustedSeries4 = ticker.modify(symbolInput4)
adjustedSeries5 = ticker.modify(symbolInput5)
requestedData1 = request.security(adjustedSeries1, timeframe.period, sourceInput)
requestedData2 = request.security(adjustedSeries2, timeframe.period, sourceInput)
requestedData3 = request.security(adjustedSeries3, timeframe.period, sourceInput)
requestedData4 = request.security(adjustedSeries4, timeframe.period, sourceInput)
requestedData5 = request.security(adjustedSeries5, timeframe.period, sourceInput)
correlation151 = ta.correlation(sourceInput, requestedData1, length15)
correlation152 = ta.correlation(sourceInput, requestedData2, length15)
correlation153 = ta.correlation(sourceInput, requestedData3, length15)
correlation154 = ta.correlation(sourceInput, requestedData4, length15)
correlation155 = ta.correlation(sourceInput, requestedData5, length15)
correlation301 = ta.correlation(sourceInput, requestedData1, length30)
correlation302 = ta.correlation(sourceInput, requestedData2, length30)
correlation303 = ta.correlation(sourceInput, requestedData3, length30)
correlation304 = ta.correlation(sourceInput, requestedData4, length30)
correlation305 = ta.correlation(sourceInput, requestedData5, length30)
correlation601 = ta.correlation(sourceInput, requestedData1, length60)
correlation602 = ta.correlation(sourceInput, requestedData2, length60)
correlation603 = ta.correlation(sourceInput, requestedData3, length60)
correlation604 = ta.correlation(sourceInput, requestedData4, length60)
correlation605 = ta.correlation(sourceInput, requestedData5, length60)
correlation901 = ta.correlation(sourceInput, requestedData1, length90)
correlation902 = ta.correlation(sourceInput, requestedData2, length90)
correlation903 = ta.correlation(sourceInput, requestedData3, length90)
correlation904 = ta.correlation(sourceInput, requestedData4, length90)
correlation905 = ta.correlation(sourceInput, requestedData5, length90)
correlation1201 = ta.correlation(sourceInput, requestedData1, length120)
correlation1202 = ta.correlation(sourceInput, requestedData2, length120)
correlation1203 = ta.correlation(sourceInput, requestedData3, length120)
correlation1204 = ta.correlation(sourceInput, requestedData4, length120)
correlation1205 = ta.correlation(sourceInput, requestedData5, length120)
correlation1801 = ta.correlation(sourceInput, requestedData1, length180)
correlation1802 = ta.correlation(sourceInput, requestedData2, length180)
correlation1803 = ta.correlation(sourceInput, requestedData3, length180)
correlation1804 = ta.correlation(sourceInput, requestedData4, length180)
correlation1805 = ta.correlation(sourceInput, requestedData5, length180)
correlation3601 = ta.correlation(sourceInput, requestedData1, length360)
correlation3602 = ta.correlation(sourceInput, requestedData2, length360)
correlation3603 = ta.correlation(sourceInput, requestedData3, length360)
correlation3604 = ta.correlation(sourceInput, requestedData4, length360)
correlation3605 = ta.correlation(sourceInput, requestedData5, length360)
correlation6001 = ta.correlation(sourceInput, requestedData1, length600)
correlation6002 = ta.correlation(sourceInput, requestedData2, length600)
correlation6003 = ta.correlation(sourceInput, requestedData3, length600)
correlation6004 = ta.correlation(sourceInput, requestedData4, length600)
correlation6005 = ta.correlation(sourceInput, requestedData5, length600)
correlation10001 = ta.correlation(sourceInput, requestedData1, length1000)
correlation10002 = ta.correlation(sourceInput, requestedData2, length1000)
correlation10003 = ta.correlation(sourceInput, requestedData3, length1000)
correlation10004 = ta.correlation(sourceInput, requestedData4, length1000)
correlation10005 = ta.correlation(sourceInput, requestedData5, length1000)
//Plot
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(correlation151, "SPX", color = color.red, display = display.status_line)
plot(correlation301, "SPX", color = color.red, display = display.status_line)
plot(correlation601, "SPX", color = color.red, display = display.status_line)
plot(correlation901, "SPX", color = color.red, display = display.status_line)
plot(correlation1201, "SPX", color = color.red, display = display.status_line)
plot(correlation1801, "SPX", color = color.red, display = display.status_line)
plot(correlation3601, "SPX", color = color.red, display = display.status_line)
plot(correlation6001, "SPX", color = color.red, display = display.status_line)
plot(correlation10001, "SPX", color = color.red, display = display.status_line)
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(correlation152, "DXY", color = color.green, display = display.status_line)
plot(correlation302, "DXY", color = color.green, display = display.status_line)
plot(correlation602, "DXY", color = color.green, display = display.status_line)
plot(correlation902, "DXY", color = color.green, display = display.status_line)
plot(correlation1202, "DXY", color = color.green, display = display.status_line)
plot(correlation1802, "DXY", color = color.green, display = display.status_line)
plot(correlation3602, "DXY", color = color.green, display = display.status_line)
plot(correlation6002, "DXY", color = color.green, display = display.status_line)
plot(correlation10002, "DXY", color = color.green, display = display.status_line)
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(correlation153, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation303, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation603, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation903, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation1203, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation1803, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation3603, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation6003, "GOLD", color = color.yellow, display = display.status_line)
plot(correlation10003, "GOLD", color = color.yellow, display = display.status_line)
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(correlation154, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation304, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation604, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation904, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation1204, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation1804, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation3604, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation6004, "US10Y", color = color.fuchsia, display = display.status_line)
plot(correlation10004, "US10Y", color = color.fuchsia, display = display.status_line)
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(correlation155, "VIX", color = color.blue, display = display.status_line)
plot(correlation305, "VIX", color = color.blue, display = display.status_line)
plot(correlation605, "VIX", color = color.blue, display = display.status_line)
plot(correlation905, "VIX", color = color.blue, display = display.status_line)
plot(correlation1205, "VIX", color = color.blue, display = display.status_line)
plot(correlation1805, "VIX", color = color.blue, display = display.status_line)
plot(correlation3605, "VIX", color = color.blue, display = display.status_line)
plot(correlation6005, "VIX", color = color.blue, display = display.status_line)
plot(correlation10005, "VIX", color = color.blue, display = display.status_line)
plot(0.000, color = color.new(color.black, 50), display = display.none)
plot(math.avg(correlation151,correlation301,correlation601,correlation901,correlation1201,correlation1801,correlation3601,correlation6001,correlation10001), "Average SPX", color = color.red, display = display.all - display.status_line)
plot(math.avg(correlation152,correlation302,correlation602,correlation902,correlation1202,correlation1802,correlation3602,correlation6002,correlation10002), "Average DXY", color = color.green, display = display.all - display.status_line)
plot(math.avg(correlation153,correlation303,correlation603,correlation903,correlation1203,correlation1803,correlation3603,correlation6003,correlation10003), "Average GOLD", color = color.yellow, display = display.all - display.status_line)
plot(math.avg(correlation154,correlation304,correlation604,correlation904,correlation1204,correlation1804,correlation3604,correlation6004,correlation10004), "AverageUS10Y", color = color.fuchsia, display = display.all - display.status_line)
plot(math.avg(correlation155,correlation305,correlation605,correlation905,correlation1205,correlation1805,correlation3605,correlation6005,correlation10005), "Average VIX", color = color.blue, display = display.all - display.status_line)
hline(1)
hline(0, color = color.new(color.gray, 50))
hline(-1) |
Liquidity Zones[Angel Algo] | https://www.tradingview.com/script/tpX18Ujf-Liquidity-Zones-Angel-Algo/ | AngelAlgo | https://www.tradingview.com/u/AngelAlgo/ | 165 | 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("Liquidity Zones[Angel Algo]", overlay = true)
// Inputs
window = input(20, "Period")
bar_coloring = input(false, "Bar coloring")
sr_coloring = input(false, "Support/Resistance coloring")
highest_liquidity_zones = input(true, "Display high liquidity zones")
lowest_liquidity_levels = input(false, "Display low liquidity levels")
// Calculate the highest volume in the rolling window
highest_volume = ta.highest(volume,window)
// Calculate the lowest volume in the rolling window
lowest_volume = ta.lowest(volume,window)
// Calculate the high and the low of the candle with the highest volume
high_vol = ta.valuewhen(volume == highest_volume, high, 0)
low_vol = ta.valuewhen(volume == highest_volume, low, 0)
// Calculate the lowest and the highest liquidity level
lowest_liquidity_level = ta.valuewhen(volume == lowest_volume, ohlc4, 0)
highest_liquidity_level = ta.valuewhen(volume == highest_volume, ohlc4, 0)
// Define a conditional color for the bar coloring
bar_color = close > high_vol ? color.green : close < low_vol ? color.red : color.blue
// Define a conditional color for the support/resistance coloring
zone_fill_color = (open > high_vol) and (close > high_vol) ? color.green :
(open < low_vol) and (close < low_vol) ? color.red : color.blue
// Define a conditional color for liquidity zones and levels
conditional_color = volume == highest_volume ? color.new(color.blue,100)
: color.new(zone_fill_color,80)
if sr_coloring == false
conditional_color := volume == highest_volume ? color.new(color.blue,100)
: color.new(color.blue,80)
if highest_liquidity_zones == false
conditional_color := color.new(color.black,100)
conditional_color2 = volume == lowest_volume ? color.new(color.red,100)
: color.new(color.red,50)
if sr_coloring == false
conditional_color2 := volume == lowest_volume ? color.new(color.red,100)
: color.new(color.red,50)
if lowest_liquidity_levels == false
conditional_color2 := color.new(color.black,100)
// Define upper and lower bounds for the Smart Money Zone
u1 = plot(high_vol, style = plot.style_stepline,
color = color.new(color.black,100))
u2 = plot(low_vol, style = plot.style_stepline,
color = color.new(color.black,100))
// Plot high liquidity zones
fill(u1,u2, color =conditional_color)
// Bar coloring
barcolor(bar_coloring ? bar_color : na)
// Plot low and high liquidity levels
plot(lowest_liquidity_level, color = conditional_color2)
plot(highest_liquidity_level, color = conditional_color)
// Trading alerts
// Define signal condition
alert_condition = (open > high_vol) and (close > high_vol) ? "bullish" :
(open < low_vol) and (close < low_vol) ? "bearish" : na
// Define trading alerts conditions
alertcondition( alert_condition == "bullish" ,"bullish signal", "bullish signal")
alertcondition( alert_condition == "bearish" ,"bearish signal", "bearish signal")
|
Step RSI [Loxx] | https://www.tradingview.com/script/ysqnT8IX-Step-RSI-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 146 | 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("Step RSI [Loxx]")
greencolor = #2DD204
redcolor = #D2042D
stepMACalc(float rsi, simple int size)=>
float smax = rsi + 2.0 * size
float smin = rsi - 2.0 * size
var trend = 0
float result = 0
if nz(trend[1]) <= 0 and rsi > nz(smax[1])
trend := 1
if nz(trend[1]) >= 0 and rsi < nz(smin[1])
trend := -1
if trend > 0
if smin < nz(smin[1])
smin := nz(smin[1])
result := smin + size
else
if smax > nz(smax[1])
smax := nz(smax[1])
result := smax - size
result
slowRSI(float src, simple int per)=>
float up = 0
float dn = 0
float alpha = (1 / per)
for k = 0 to per - 1
float diff = nz(src[k]) - nz(src[k+1])
if diff > 0
up += diff
else
dn -= diff
float rma2 = ta.rma(100 * up / (up + dn), per)
float rsival = (up + dn) == 0 ? 50 : rma2
rsival
src = input.source(close, "Source", group = "Basic Settings")
rsiper = input.int(14, "RSI Period", group = "Basic Settings")
stpsize = input.int(5, "Step Size", group = "Basic Settings")
bool colorbars = input.bool(true, "Color bars?", group = "UI Options")
bool showSigs = input.bool(false, "Show signals?", group = "UI Options")
rsiout = slowRSI(src, rsiper)
fasttrend = stepMACalc(rsiout, stpsize)
colorout = rsiout > fasttrend ? greencolor : redcolor
plot(rsiout, color = colorout, linewidth = 2)
plot(fasttrend, color = color.white)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(rsiout, fasttrend)
goShort = ta.crossunder(rsiout, fasttrend)
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="Step RSI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Step RSI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
SMT Divergences [LuxAlgo] | https://www.tradingview.com/script/ecEI56ff-SMT-Divergences-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,849 | 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("SMT Divergences [LuxAlgo]", "LuxAlgo - SMT Divergences", overlay = true, max_lines_count = 500, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input.int(3, 'Pivot Lookback', minval = 2)
//Symbol A
useSym1 = input(true, 'Comparison Symbol', inline = 'symA')
sym1 = input.symbol('CME_MINI_DL:ES1!', '', inline = 'symA')
//Symbol B
useSym2 = input(true, 'Comparison Symbol', inline = 'symB')
sym2 = input.symbol('CBOT_MINI_DL:YM1!', '', inline = 'symB')
//Style
bullDivCss = input.color(#ff1100, 'Swing High', group = 'Style')
bearDivCss = input.color(#2157f3, 'Swing Low', group = 'Style')
//Dashboard
showDash = input(false, 'Show Dashboard' , group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Dashboard')
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
n = bar_index
get_hl() => [high, low, close]
//Swing highs divergences
get_divergence(ph, y2, sym_y2, css)=>
var float y1 = na
var float sym_y1 = na
var int x1 = na
var smt = 0
if y2 != y2[1] and sym_y2 != sym_y2[1]
//Test for SMT
if (y2 - y1) * (sym_y2 - sym_y1) < 0
line.new(n[length], y2, x1, y1, color = css)
smt += 1
sym_y1 := sym_y2
y1 := y2
x1 := n[length]
else if (ph and y2 > y2[1]) or (not ph and y2 < y2[1])
sym_y1 := na
y1 := y2
x1 := n[length]
smt
//-----------------------------------------------------------------------------}
//Main variables
//-----------------------------------------------------------------------------{
var phN = 0, var plN = 0
var ph_smt1 = 0.
var pl_smt1 = 0.
var ph_smt2 = 0.
var pl_smt2 = 0.
ticker1 = syminfo.ticker(sym1)
ticker2 = syminfo.ticker(sym2)
//-----------------------------------------------------------------------------}
//Detect swing highs/lows and divergences
//-----------------------------------------------------------------------------{
ph = fixnan(ta.pivothigh(length, length))
pl = fixnan(ta.pivotlow(length, length))
phN += ph != ph[1] ? 1 : 0
plN += pl != pl[1] ? 1 : 0
//Comparison symbol pivots
[h1, l1, c1] = request.security(sym1, timeframe.period, get_hl())
[h2, l2, c2] = request.security(sym2, timeframe.period, get_hl())
//Detect swing high divergences
if useSym1
sym_ph1 = fixnan(ta.pivothigh(h1, length, length))
sym_pl1 = fixnan(ta.pivotlow(l1, length, length))
ph_smt1 := get_divergence(true, ph, sym_ph1, bullDivCss)
pl_smt1 := get_divergence(false, pl, sym_pl1, bearDivCss)
if useSym2
sym_ph2 = fixnan(ta.pivothigh(h2, length, length))
sym_pl2 = fixnan(ta.pivotlow(l2, length, length))
ph_smt2 := get_divergence(true, ph, sym_ph2, bullDivCss)
pl_smt2 := get_divergence(false, pl, sym_pl2, bearDivCss)
txt = ''
if ph != ph[1]
if ph_smt1 > ph_smt1[1]
txt += ticker1
if ph_smt2 > ph_smt2[1]
txt += txt != '' ? ' | ' : ''
txt += ticker2
if txt != ''
label.new(n[length], ph, txt
, color = bullDivCss
, style = label.style_label_down
, textcolor = color.white
, size = size.tiny)
else
if pl_smt1 > pl_smt1[1]
txt += ticker1
if pl_smt2 > pl_smt2[1]
txt += txt != '' ? ' | ' : ''
txt += ticker2
if txt != ''
label.new(n[length], pl, txt
, color = bearDivCss
, style = label.style_label_up
, textcolor = color.white
, size = size.tiny)
//-----------------------------------------------------------------------------}
//Tables
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 3, 3
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if barstate.isfirst and showDash
tb.cell(1, 0, 'Swing High', text_color = color.white)
tb.cell(2, 0, 'Swing Low', text_color = color.white)
tb.cell(0, 1, ticker1, text_color = color.white)
tb.cell(0, 2, ticker2, text_color = color.white)
if barstate.islast and showDash
//Symbol 1
tb.cell(1, 1, str.format('{0} ({1, number, percent})', ph_smt1, ph_smt1 / phN)
, text_color = bullDivCss)
tb.cell(2, 1, str.format('{0} ({1, number, percent})', pl_smt1, pl_smt1 / plN)
, text_color = bearDivCss)
//Symbol 2
tb.cell(1, 2, str.format('{0} ({1, number, percent})', ph_smt2, ph_smt2 / phN)
, text_color = bullDivCss)
tb.cell(2, 2, str.format('{0} ({1, number, percent})', pl_smt2, pl_smt2 / plN)
, text_color = bearDivCss)
//-----------------------------------------------------------------------------} |
Predictive Pivot Points based on Technicals | https://www.tradingview.com/script/9KoxRx42-Predictive-Pivot-Points-based-on-Technicals/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 65 | 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("Predictive Pivot Points with Stat Display and Similarity Identification [SS]", shorttitle = "Predictive Pivot Points [SS]", overlay=true, max_bars_back = 500, max_labels_count = 500)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Tooltips ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
t1 = "Sets the bar lookback length for pivot points, defualt is 10:10"
t2 = "Sets the lookback length for the arrays"
t3 = "Sets the Source for the RSI"
t4 = "Sets the Source for the Stocahstics"
t5 = "Sets the Source for the MFI"
t6 = "Sets the Length for the MFI"
t7 = "Sets the threshold to look for similar technical indicators. This threshold will apply to MFI, Stochastics and RSI. The Default is 2 and 2, so it will look for +/- 2 points of the previous Pivot."
t9 = "Will look for all similar pivot indicators, including RSI, Stochastics, Volume and MFI"
t10 = "Will only show identical instances where MFI, Stochastics and RSI are similar within the threshold limits. Volume is NOT included."
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Groups ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
g1 = "Pivots"
g2 = "Inputs"
g3 = "Technicals"
g4 = "Thresholds"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Technicals ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
leftbars = input.int(10, "Left Bars", tooltip = t1, group = g1)
rightbars = input.int(10, "Right Bars", tooltip = t1, group = g1)
len = input.int(500, "Lookback Length", tooltip = t2, group = g2)
rsisource = input.source(close, "RSI Source", tooltip = t3, group = g3)
rsilen = input.int(14, "RSI Length", tooltip=t7, group = g3)
stosource = input.source(close, "Stochastic Source", tooltip = t4, group = g3)
stolen = input.int(14, "Stochastic Length", tooltip = t6, group = g3)
mfisource = input.source(close, "MFI Source", tooltip = t5, group = g3)
mfilen = input.int(14, "MFI Length", tooltip = t6, group = g3)
plusrng = input.int(2, "Upper Threshold", tooltip = t7, group = g4)
minusrng = input.int(2, "Lower Threshold", tooltip = t7, group = g4)
showpivots = input.bool(false, "Show Pivots", group = g1)
showlikersi = input.bool(true, "Show Like RSI Pivots", tooltip = t9, group = g1)
showlikemfi = input.bool(true, "Show Like MFI Pivots", tooltip = t9, group = g1)
showlikesto = input.bool(true, "Show Like Stochastic Pivots", tooltip = t9, group = g1)
showlikevolume = input.bool(true, "Show Like Volume Pivots", tooltip = t9, group = g1)
showidentical = input.bool(true, "Show Identical Instances", tooltip = t10, group = g1)
piv_high = ta.pivothigh(high, leftbars, rightbars)
piv_low = ta.pivotlow(low, leftbars, rightbars)
rsi = ta.rsi(rsisource, rsilen)
sto = ta.stoch(stosource, high, low, stolen)
mfi = ta.mfi(mfisource, mfilen)
if piv_high and showpivots
label.new(x=bar_index, y=high, text="Pivot High " + str.tostring(close) + "\n RSI: " + str.tostring(math.round(rsi,2)) + "\n Stoch: " + str.tostring(math.round(sto,2)) + "\n MFI: " + str.tostring(math.round(mfi,2)) + "\n Volume: " + str.tostring(volume), color=color.white, textcolor = color.black)
if piv_low and showpivots
label.new(x=bar_index, y=high, text="Pivot Low " + str.tostring(close) + "\n RSI: " + str.tostring(math.round(rsi,2)) + "\n Stoch: " + str.tostring(math.round(sto,2)) + "\n MFI: " + str.tostring(math.round(mfi,2)) + "\n Volume: " + str.tostring(volume), color=color.white, textcolor = color.black)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Store Historic Data ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pivot_hi_rsi = array.new_float()
pivot_hi_vol = array.new_float()
pivot_hi_mfi = array.new_float()
pivot_hi_sto = array.new_float()
pivot_lo_rsi = array.new_float()
pivot_lo_vol = array.new_float()
pivot_lo_mfi = array.new_float()
pivot_lo_sto = array.new_float()
bar_index_limit = bar_index <= 5000 ? bar_index : 5000
for i = 14 to len
if piv_high
array.push(pivot_hi_rsi, rsi[i])
array.push(pivot_hi_vol, volume[i])
array.push(pivot_hi_mfi, mfi[i])
array.push(pivot_hi_sto, sto[i])
if piv_low
array.push(pivot_lo_rsi, rsi[i])
array.push(pivot_lo_vol, volume[i])
array.push(pivot_lo_mfi, mfi[i])
array.push(pivot_lo_sto, sto[i])
var float last_pivot_hi_rsi = na
var float last_pivot_hi_vol = na
var float last_pivot_hi_mfi = na
var float last_pivot_hi_sto = na
var float last_pivot_lo_rsi = na
var float last_pivot_lo_vol = na
var float last_pivot_lo_mfi = na
var float last_pivot_lo_sto = na
var float pivot_hi_rsi_equal = na
var float pivot_lo_rsi_equal = na
var float pivot_hi_mfi_equal = na
var float pivot_lo_mfi_equal = na
var float pivot_hi_sto_equal = na
var float pivot_lo_sto_equal = na
var float rsi_counter_hi = 0
var float rsi_counter_lo = 0
var float mfi_counter_hi = 0
var float mfi_counter_lo = 0
var float sto_counter_hi = 0
var float sto_counter_lo = 0
if array.size(pivot_hi_rsi) > 0
last_pivot_hi_rsi := array.get(pivot_hi_rsi, array.size(pivot_hi_rsi) - 1)
for i = 0 to array.size(pivot_hi_rsi) - 1
if math.abs(rsi[1] - array.get(pivot_hi_rsi, i)) <= plusrng
pivot_hi_rsi_equal := rsi[1]
else
pivot_hi_rsi_equal := 0
if array.size(pivot_hi_vol) > 0
last_pivot_hi_vol := array.get(pivot_hi_vol, array.size(pivot_hi_vol) - 1)
if array.size(pivot_hi_mfi) > 0
last_pivot_hi_mfi := array.get(pivot_hi_mfi, array.size(pivot_hi_mfi) - 1)
for i = 0 to array.size(pivot_hi_mfi) - 1
if math.abs(mfi[1] - array.get(pivot_hi_mfi, i)) <= plusrng
pivot_hi_mfi_equal := mfi[1]
else
pivot_hi_mfi_equal := 0
if array.size(pivot_hi_sto) > 0
last_pivot_hi_sto := array.get(pivot_hi_sto, array.size(pivot_hi_sto) - 1)
for i = 0 to array.size(pivot_hi_sto) - 1
if math.abs(sto[1] - array.get(pivot_hi_sto, i)) <= plusrng
pivot_hi_sto_equal := sto[1]
else
pivot_hi_sto_equal := 0
//
if array.size(pivot_lo_rsi) > 0
last_pivot_lo_rsi := array.get(pivot_lo_rsi, array.size(pivot_lo_rsi) - 1)
for i = 0 to array.size(pivot_lo_rsi) - 1
if math.abs(rsi[1] - array.get(pivot_lo_rsi, i)) <= plusrng
pivot_lo_rsi_equal := rsi[1]
else
pivot_lo_rsi_equal := 0
if array.size(pivot_lo_vol) > 0
last_pivot_lo_vol := array.get(pivot_lo_vol, array.size(pivot_lo_vol) - 1)
if array.size(pivot_lo_mfi) > 0
last_pivot_lo_mfi := array.get(pivot_lo_mfi, array.size(pivot_lo_mfi) - 1)
for i = 0 to array.size(pivot_lo_mfi) - 1
if math.abs(mfi[1] - array.get(pivot_lo_mfi, i)) <= plusrng
pivot_lo_mfi_equal := mfi[1]
else
pivot_lo_mfi_equal := 0
if array.size(pivot_lo_sto) > 0
last_pivot_lo_sto := array.get(pivot_lo_sto, array.size(pivot_lo_sto) - 1)
for i = 0 to array.size(pivot_lo_sto) - 1
if math.abs(sto[1] - array.get(pivot_lo_sto, i)) <= plusrng
pivot_lo_sto_equal := sto[1]
else
pivot_lo_sto_equal := 0
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Pivot Assessments ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool rsi_equal_piv_hi = rsi >= last_pivot_hi_rsi - minusrng and rsi <= last_pivot_hi_rsi + plusrng
bool sto_equal_piv_hi = sto >= last_pivot_hi_sto - minusrng and sto <= last_pivot_hi_sto + plusrng
bool mfi_equal_piv_hi = mfi >= last_pivot_hi_mfi - minusrng and mfi <= last_pivot_hi_mfi + plusrng
bool vol_equal_piv_hi = volume == last_pivot_hi_vol
bool all_3_piv_hi = rsi_equal_piv_hi and sto_equal_piv_hi and mfi_equal_piv_hi
bool rsi_equal_piv_lo = rsi >= last_pivot_lo_rsi - minusrng and rsi <= last_pivot_lo_rsi + plusrng
bool sto_equal_piv_lo = sto >= last_pivot_lo_sto - minusrng and sto <= last_pivot_lo_sto + plusrng
bool mfi_equal_piv_lo = mfi >= last_pivot_lo_mfi - minusrng and mfi <= last_pivot_lo_mfi + plusrng
bool vol_equal_piv_lo = volume == last_pivot_lo_vol
bool all_3_piv_lo = rsi_equal_piv_lo and sto_equal_piv_lo and mfi_equal_piv_lo
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Plots ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var int rsi_hi_counter = 0
if rsi_equal_piv_hi and showlikersi
rsi_counter_hi := rsi_counter_hi + 1
if rsi_counter_hi >= 10
label.new(x=bar_index, y=high, text="RSI Pivot High Similar: \n " + str.tostring(math.round(rsi,2)), color=color.white, textcolor = color.black)
rsi_counter_hi := 0
if pivot_hi_rsi_equal > 0
rsi_hi_counter := rsi_hi_counter + 1
if rsi_hi_counter >= 10
rsi_hi_counter := 0
label.new(x=bar_index, y=high, text="RSI Pivot High Similar: \n " + str.tostring(math.round(rsi,2)), color=color.white, textcolor = color.black)
var int sto_hi_counter = 0
if sto_equal_piv_hi and showlikesto
sto_counter_hi := sto_counter_hi + 1
if sto_counter_hi >= 10
label.new(x=bar_index, y=high, text="Sto Pivot High Similar: \n " + str.tostring(math.round(sto,2)), color=color.white, textcolor = color.black)
sto_counter_hi := 0
if pivot_hi_sto_equal > 0
sto_hi_counter := sto_hi_counter + 1
if sto_hi_counter >= 10
sto_hi_counter := 0
label.new(x=bar_index, y=high, text="Stochastic Pivot High Similar: \n " + str.tostring(math.round(sto,2)), color=color.white, textcolor = color.black)
var int mfi_hi_counter = 0
if mfi_equal_piv_hi and showlikemfi
mfi_counter_hi := mfi_counter_hi + 1
if mfi_counter_hi >= 10
label.new(x=bar_index, y=high, text="MFI Pivot High Similar: \n " + str.tostring(math.round(mfi,2)), color=color.white, textcolor = color.black)
mfi_counter_hi := 0
if pivot_hi_mfi_equal > 0
mfi_hi_counter := mfi_hi_counter + 1
if mfi_hi_counter >= 10
mfi_hi_counter := 0
label.new(x=bar_index, y=high, text="MFI Pivot High Similar: \n " + str.tostring(math.round(mfi,2)), color=color.white, textcolor = color.black)
if vol_equal_piv_hi and showlikevolume
label.new(x=bar_index, y=high, text="Volume Pivot High Similar: \n " + str.tostring(math.round(volume,2)), color=color.white, textcolor = color.black)
if all_3_piv_hi and showidentical
label.new(x=bar_index, y=high, text="RSI, Sto and MFI similar to \n previous pivot high", color=color.white, textcolor = color.black)
var int rsi_lo_counter = 0
if rsi_equal_piv_lo and showlikersi
rsi_counter_lo := rsi_counter_lo + 1
if rsi_counter_lo >= 10
label.new(x=bar_index, y=high, text="RSI Pivot Low Similar: \n " + str.tostring(math.round(rsi,2)), color=color.white, textcolor = color.black)
rsi_counter_lo := 0
if pivot_lo_rsi_equal > 0
rsi_lo_counter := rsi_lo_counter + 1
if rsi_lo_counter >= 10
rsi_lo_counter := 0
label.new(x=bar_index, y=high, text="RSI Pivot Low Similar: \n " + str.tostring(math.round(rsi,2)), color=color.white, textcolor = color.black)
var int sto_lo_counter = 0
if sto_equal_piv_lo and showlikesto
sto_counter_lo := sto_counter_lo + 1
if sto_counter_lo >=10
label.new(x=bar_index, y=high, text="Sto Pivot Low Similar: \n " + str.tostring(math.round(sto,2)), color=color.white, textcolor = color.black)
sto_counter_lo := 0
if pivot_lo_sto_equal > 0
sto_lo_counter := sto_lo_counter + 1
if sto_lo_counter >= 10
sto_lo_counter := 0
label.new(x=bar_index, y=high, text="Sto Pivot Low Similar: \n " + str.tostring(math.round(sto,2)), color=color.white, textcolor = color.black)
var int mfi_lo_counter = 0
if mfi_equal_piv_lo and showlikemfi
mfi_counter_lo := mfi_counter_lo + 1
if mfi_counter_lo >= 10
label.new(x=bar_index, y=high, text="MFI Pivot Low Similar: \n " + str.tostring(math.round(mfi,2)), color=color.white, textcolor = color.black)
mfi_counter_lo := 0
if pivot_lo_mfi_equal > 0
mfi_lo_counter := mfi_lo_counter + 1
if mfi_lo_counter >= 10
mfi_lo_counter := 0
label.new(x=bar_index, y=high, text="MFI Pivot Low Similar: \n " + str.tostring(math.round(mfi,2)), color=color.white, textcolor = color.black)
if vol_equal_piv_lo and showlikevolume
label.new(x=bar_index, y=high, text="Volume Pivot Low Similar: \n " + str.tostring(math.round(volume,2)), color=color.white, textcolor = color.black)
if all_3_piv_lo and showidentical
label.new(x=bar_index, y=high, text="RSI, Sto and MFI similar to \n previous pivot low", color=color.white, textcolor = color.black)
|
Volatility Compression Breakout | https://www.tradingview.com/script/Lc8WH9UF-Volatility-Compression-Breakout/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 491 | 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/
// ยฉ LeafAlgo
//@version=5
indicator("Volatility Compression Breakout", overlay=true)
// Volatility Compression Parameters
compressionPeriod = input(20, "Compression Period")
compressionMultiplier = input(1.5, "Compression Multiplier")
// Trend Filter Parameters
emaPeriod = input(50, "EMA Period")
// Calculate ATR and Keltner Channels
atr = ta.atr(14)
keltnerMiddle = ta.sma(close, compressionPeriod)
keltnerUpper = keltnerMiddle + (compressionMultiplier * atr)
keltnerLower = keltnerMiddle - (compressionMultiplier * atr)
// Calculate Standard Deviation
stdDev = ta.stdev(close, compressionPeriod)
// Calculate Trend Filter
ema = ta.ema(close, emaPeriod)
// Determine Breakout Conditions
breakoutUp = high > keltnerUpper + stdDev and close > ema and close[1] <= ema[1]
breakoutDown = low < keltnerLower - stdDev and close < ema and close[1] >= ema[1]
// Plot Breakout Shapes
plotshape(breakoutUp, "Long Entry", shape.triangleup, location.belowbar, color=color.green, size=size.large)
plotshape(breakoutDown, "Short Entry", shape.triangledown, location.abovebar, color=color.red, size=size.large)
// Color
kcColor = close > keltnerMiddle ? color.lime : color.fuchsia
emaColor = close > ema ? color.lime : color.fuchsia
barC = close > ema and close > keltnerMiddle ? color.lime : close > keltnerMiddle and close < ema ? color.yellow : close < keltnerMiddle and close > ema ? color.yellow : color.fuchsia
barcolor(barC)
// Plot Keltner Channels
plot(keltnerUpper, color=color.aqua, linewidth=2, title="Keltner Upper")
plot(keltnerLower, color=color.aqua, linewidth=2, title="Keltner Lower")
plot(keltnerMiddle, color=kcColor, linewidth=4, title="Keltner Middle")
plot(keltnerUpper + stdDev, color=color.aqua, linewidth=2, title="Keltner Upper StdDev")
plot(keltnerLower - stdDev, color=color.aqua, linewidth=2, title="Keltner Lower StdDev")
// Plot Trend Filter
plot(ema, color=emaColor, linewidth=4, title="Trend Filter") |
ATR Daily Band | https://www.tradingview.com/script/1SARnwTf-ATR-Daily-Band/ | andrew51228 | https://www.tradingview.com/u/andrew51228/ | 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/
// ยฉ andrew51228
//@version=5
indicator("ATR Daily Band", overlay=true)
length = input.int(title="Length", defval=14, minval=1)
myColor = input.color(title="Color", defval=color.new(#d3b4b4, 0))
atr = request.security(syminfo.tickerid, "1D", ta.atr(14), lookahead=barmerge.lookahead_on)
dailyOpen = request.security(syminfo.tickerid, "1D", open, lookahead=barmerge.lookahead_on)
dailyClose = request.security(syminfo.tickerid, "1D", close)
dailyCloseOffset = request.security(syminfo.tickerid, "1D", close[1])
//dailyClose = 336
// plot(ta.rma(ta.tr(true) + dailyClose, length), title = "ATR", color=color.new(#B71C1C, 0))
plot(barstate.isrealtime ? dailyCloseOffset + atr : dailyClose + atr, color=myColor)
plot(barstate.isrealtime ? dailyCloseOffset - atr : dailyClose - atr, color=myColor)
//plot(dailyClose + atr, color=myColor)
//plot(dailyClose - atr, color=myColor)
//label.new(time[0], dailyOpen + atr, str.format("{0}", dailyOpen + atr), xloc = xloc.bar_index, style = label.style_none)
is_first_bar = hour(time) == 9 and minute(time) == 30 and dayofmonth(timenow) == dayofmonth(time) and month(timenow) == month(time) and year(timenow) == year(time)
if is_first_bar
upLabel = label.new(x=bar_index, y=dailyClose + atr,text=str.format("{0,number,#.##} +{1,number,#.##}%", dailyClose+atr, atr/dailyClose*100), textcolor=color.white, xloc=xloc.bar_index, color=myColor, style=label.style_label_lower_right, size=size.normal)
dnLabel = label.new(x=bar_index, y=dailyClose - atr,text=str.format("{0,number,#.##} -{1,number,#.##}%", dailyClose-atr, atr/dailyClose*100), textcolor=color.white, xloc=xloc.bar_index, color=myColor, style=label.style_label_upper_right, size=size.normal)
// plot(close)
// upper = ta.sma(close + atr, 200)
// lower = ta.sma(close - atr, 200)
// plot(upper, title = "+ATR", color=color.new(#d3b4b4, 0))
// plot(lower, title = "-ATR", color=color.new(#d3b4b4, 0))
|
Nonlinear Regression, Zero-lag Moving Average [Loxx] | https://www.tradingview.com/script/R94i54w7-Nonlinear-Regression-Zero-lag-Moving-Average-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 240 | 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("Nonlinear Regression, Zero-lag Moving Average [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
color greencolor = #2DD204
color redcolor = #D2042D
zlma(float src, simple int per)=>
float sum = 0
float sumw = 0
float weight = 0
float lwma1 = 0.
float out = 0.
for k = 0 to per - 1
weight := per - k
sumw += weight
sum += weight * nz(src[k])
lwma1 := sum / sumw
sumw := 0
sum := 0
for k = 0 to per - 1
weight := per - k
sumw += weight
sum += weight * nz(lwma1[k])
out := sum / sumw
out
nonLinearRegression(float src, simple int per)=>
float AvgX = 0
float AvgY = 0
float[] nlrXValue = array.new<float>(per, 0)
float[] nlrYValue = array.new<float>(per, 0)
for i = 0 to per - 1
array.set(nlrXValue, i, i)
array.set(nlrYValue, i, nz(src[i]))
AvgX += array.get(nlrXValue, i)
AvgY += array.get(nlrYValue, i)
AvgX /= per
AvgY /= per
float SXX = 0
float SXY = 0
float SYY = 0
float SXX2 = 0
float SX2X2 = 0
float SYX2 = 0
for i = 0 to per - 1
float XM = array.get(nlrXValue, i) - AvgX
float YM = array.get(nlrYValue, i) - AvgY
float XM2 = array.get(nlrXValue, i) * array.get(nlrXValue, i) - AvgX * AvgX
SXX += XM * XM
SXY += XM * YM
SYY += YM * YM
SXX2 += XM * XM2
SX2X2 += XM2 * XM2
SYX2 += YM * XM2
float tmp = 0
float ACoeff = 0
float BCoeff = 0
float CCoeff = 0
tmp := SXX * SX2X2 - SXX2 * SXX2
if tmp != 0
BCoeff := (SXY * SX2X2 - SYX2 * SXX2) / tmp
CCoeff := (SXX * SYX2 - SXX2 * SXY) / tmp
ACoeff := AvgY - BCoeff * AvgX - CCoeff * AvgX * AvgX
tmp := ACoeff + CCoeff
tmp
float src = input.source(close, "Source", group = "Basic Settings")
int zlmaper = input.int(15, "Zero-lag Moving Average Period", group = "Basic Settings")
int regressionper = input.int(15, "Nonlinear Regression Period", group = "Basic Settings")
bool colorbars = input.bool(true, title='Color bars', group = "UI Options")
bool showSigs = input.bool(true, title='Show signals', group = "UI Options")
float out = nonLinearRegression(zlma(src, zlmaper), regressionper)
float sig = out[1]
color colorout = out > sig ? greencolor : redcolor,
plot(out, "Nonlinear Regression, Zero-lag Moving Average [Loxx]", color = colorout, linewidth = 3)
barcolor(colorout)
bool goLong = ta.crossover(out, sig)
bool goShort = ta.crossunder(out, 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 = "Nonlinear Regression, Zero-lag Moving Average [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "Nonlinear Regression, Zero-lag Moving Average [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
Chilllax Moving Averages with Qullamaggie colors | https://www.tradingview.com/script/slh7RiUb-Chilllax-Moving-Averages-with-Qullamaggie-colors/ | chilllaxtrader | https://www.tradingview.com/u/chilllaxtrader/ | 251 | 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/
// ยฉ chilllaxtrader
//@version=4
study(title="Chilllax Moving Averages with Qullamaggie colors", shorttitle="ChillLax Moving Averages", overlay=true)
// Display 2 MAs, default is 10d sma and 20d sma. You can choose any length. Choose sma, or ema. Choose ma of Open, High, Low, or Close
// Color code is based on Qullamaggie's idea:
// Dark green = 10d ma > 20d ma, and both trending up
// Light green = 10d ma > 20d ma, but only 10d ma trending up
// Yellow = 10d ma > 20d ma, but neither trending up
// Trend is comparing the ma from X trendlen days ago. Default to 5 days ago.
yourmama = input(title='', options=['SMA', 'EMA'], defval='SMA', group='Moving Averages Type')
ma1 = input(10, minval=1, title="First MA length")
src1 = input(close, title="OHLC")
out1 = yourmama == 'SMA' ? sma(src1, ma1) : yourmama == 'EMA' ? ema(src1, ma1) : na
ma2 = input(20, minval=0, title="Second MA length")
src2 = input(close, title="OHLC")
out2 = yourmama == 'SMA' ? sma(src2, ma2) : yourmama == 'EMA' ? ema(src2, ma2) : na
plot(out1, color=color.red)
plot(out2, color=color.black)
// the number of bars to determine uptrend, if trendlen is 5, and if today's ma is higher than 5 days ago's ma, then it is an uptrend
trendlen = input(5, minval=1, title="number of bars to determine uptrend")
over = out1 > out2
out1up = out1 > out1[trendlen]
out2up = out2 > out2[trendlen]
green = out1 > out2 and out1up and out2up
lightgreen = out1 > out2 and out1up and not out2up
yellow = out1 > out2 and not out1up and not out2up
bgColor = (green ? color.new(color.rgb(0, 150, 0), 50) : lightgreen ? color.new(color.rgb(0, 255, 0), 80) : yellow ? color.new(color.yellow, 80) : na)
bgcolor(color=bgColor)
|
Fierytrading: Volatility Depth | https://www.tradingview.com/script/zT89OfA8-Fierytrading-Volatility-Depth/ | FieryTrading | https://www.tradingview.com/u/FieryTrading/ | 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/
// ยฉ FieryTrading
//@version=5
indicator("FT Volatility Depth", overlay = false, precision=4)
length = input.int(7)
lower = ta.lowest(low, length)
higher = ta.highest(high, length)
depth = (higher-lower)/lower
extreme_vol = color.red
high_vol = color.orange
normal_vol = color.yellow
low_vol = color.green
bar_color = depth>=0.25 ? extreme_vol : depth>=0.125 and depth<0.25 ? high_vol : depth>=0.05 and depth<0.125 ? normal_vol : low_vol
plot(depth, linewidth = 2, color = bar_color, style = plot.style_histogram)
alertcondition(bar_color==extreme_vol, "Extreme Volatility")
alertcondition(bar_color==high_vol, "High Volatility")
alertcondition(bar_color==normal_vol, "Normal Volatility")
alertcondition(bar_color==low_vol, "Low Volatility") |
TG - Stock price at particular bar | https://www.tradingview.com/script/XVKC2Jm4-TG-Stock-price-at-particular-bar/ | thiyagarajan_gunasekaran | https://www.tradingview.com/u/thiyagarajan_gunasekaran/ | 3 | 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/
// ยฉ thiyagarajan_gunasekaran
//@version=4
study(title="Script day value", overlay=true)
//indicator(title="Script day value", shorttitle="SDV", overlay=true, timeframe="D")
dur = input(title="Time frame", type=input.string, defval='D')
barInt = input(title="No of bars back", type=input.integer, defval=1)
curbarInt = input(title="Current bar", type=input.integer, defval=1)
scr_label = '\nSymbol Value: \n'
secVal1 = security(syminfo.tickerid, dur, close[barInt])
curVal1 = security(syminfo.tickerid, dur, close[curbarInt])
scr_label := secVal1 > 0 ? scr_label + syminfo.tickerid + '\n Old value : ' + tostring(secVal1) + '\n New value : ' + tostring(curVal1) + '\n': scr_label
lab_l = label.new(bar_index, bar_index, scr_label,color = color.white, textcolor = color.black, size= size.normal, textalign = text.align_left, style = label.style_label_up, yloc = yloc.belowbar)
label.delete(lab_l[1])
plot(0, transp=100)
|
ICT HTF Liquidity Levels /w Alert [MsF] | https://www.tradingview.com/script/tXI6v3fU/ | Trader_Morry | https://www.tradingview.com/u/Trader_Morry/ | 405 | 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/
// @ Trader_Morry
//@version=5
indicator("ICT HTF Liquidity Levels /w Alert [MsF]", "HTF Liquidity Alert", overlay=true, max_lines_count=500)
//--------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------
// var START_OFFSET = 0
// var END_OFFSET = 25
//--------------------------------------------------------------------
// Inputs
//--------------------------------------------------------------------
var g_htf = "HTF Liquidity"
var g_intraday = "Intraday Liquidity"
var g_purged = "Purged Liquidity"
var g_luquidityline = "Liquidity line"
i_isDailyEnabled = input (true, "Daily", inline="Daily", group=g_htf)
i_dailyAboveLiquidityColor = input (color.new(#8931ac, 35), "", inline="Daily", group=g_htf)
i_dailyBelowLiquidityColor = input (color.new(#8931ac, 35), "", inline="Daily", group=g_htf)
i_dailyWidth = input (2, "Width", inline="Daily", group=g_htf)
i_isWeeklyEnabled = input (true, "Weekly", inline="Weekly", group=g_htf)
i_weeklyAboveLiquidityColor = input (color.new(#3e76d6, 46), "", inline="Weekly", group=g_htf)
i_weeklyBelowLiquidityColor = input (color.new(#3e76d6, 46), "", inline="Weekly", group=g_htf)
i_weeklyWidth = input (5, "Width", inline="Weekly", group=g_htf)
i_isMonthlyEnabled = input (true, "Monthly", inline="Monthly", group=g_htf)
i_monthlyAboveLiquidityColor = input (color.rgb(102, 33, 33, 46), "", inline="Monthly", group=g_htf)
i_monthlyBelowLiquidityColor = input (color.rgb(102, 33, 33, 46), "", inline="Monthly", group=g_htf)
i_monthlyWidth = input (10, "Width", inline="Monthly", group=g_htf)
i_is1HEnabled = input (true, "1H", inline="1H", group=g_intraday)
i_1HAboveLiquidityColor = input (color.rgb(231, 173, 74, 32), "", inline="1H", group=g_intraday)
i_1HBelowLiquidityColor = input (color.rgb(231, 173, 74, 32), "", inline="1H", group=g_intraday)
i_1HWidth = input (1, "Width", inline="1H", group=g_intraday)
i_is4HEnabled = input (true, "4H", inline="4H", group=g_intraday)
i_4HAboveLiquidityColor = input (color.rgb(29, 90, 47, 32), "", inline="4H", group=g_intraday)
i_4HBelowLiquidityColor = input (color.rgb(29, 90, 47, 32), "", inline="4H", group=g_intraday)
i_4HWidth = input (1, "Width", inline="4H", group=g_intraday)
i_purgedLevelColor = input (color.new(color.gray, 70), "Color", group=g_purged)
i_purgedLevelStyle = input.string ("Dashed", "Style", ["Solid", "Dashed", "Dotted"], group=g_purged)
i_showPurgeDaily = input (false, "Show Purge Daily", group=g_purged)
i_showPurgeWeekly = input (false, "Show Purge Weekly", group=g_purged)
i_showPurgeMonthly = input (false, "Show Purge Monthly", group=g_purged)
i_showPurge1H = input (false, "Show Purge 1H", group=g_purged)
i_showPurge4H = input (false, "Show Purge 4H", group=g_purged)
i_purgedCleanUpTiming = input.timeframe("D", "Clean Up", group=g_purged, tooltip = "Select when to clean up the purge line")
START_OFFSET = input (0, "START OFFSET", group=g_luquidityline, tooltip = "Liquidity line drawing start position. Enter the offset from the latest bar.")
END_OFFSET = input (25, "END OFFSET", group=g_luquidityline, tooltip = "Liquidity line drawing end position. Enter the offset from the latest bar.")
disp_line_max = input.int (3, "Max number of lines", minval=1, maxval=10, group=g_luquidityline, tooltip = "Enter the maximum number of liquidity lines.")
//--------------------------------------------------------------------
// Variables declarations
//--------------------------------------------------------------------
var highsArray = array.new_float()
var lowsArray = array.new_float()
var highLinesArray = array.new_line()
var lowLinesArray = array.new_line()
var purgedLinesArray = array.new_line()
var float dayHigh = na
var float dayLow = na
var highsTFnumArray = array.new_int()
var lowsTFnumArray = array.new_int()
var purgedTFnumArray = array.new_int()
int TF_D = 1
int TF_W = 2
int TF_M = 3
int TF_240 = 4
int TF_60 = 5
[prevDayHigh, prevDayLow] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[prevWeekHigh, prevWeekLow] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[prevMonthHigh, prevMonthLow] = request.security(syminfo.tickerid, "M", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[prev4HHigh, prev4HLow] = request.security(syminfo.tickerid, "240", [high[1], low[1]], lookahead=barmerge.lookahead_on)
[prev1HHigh, prev1HLow] = request.security(syminfo.tickerid, "60", [high[1], low[1]], lookahead=barmerge.lookahead_on)
//--------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------
f_drawLine(float _y, color _c, int _w=1) => line.new(bar_index, _y, bar_index, _y, color=_c, width=_w)
f_create(float _high, float _low, color _upperColor, color _lowerColor, int _linewidth, int aTFnum) =>
array.push(highsArray, _high)
array.push(lowsArray, _low)
array.push(highLinesArray, f_drawLine(_high, _upperColor, _linewidth))
array.push(lowLinesArray, f_drawLine(_low, _lowerColor, _linewidth))
array.push(highsTFnumArray, aTFnum)
array.push(lowsTFnumArray, aTFnum)
f_updateStickyLevels(array<line> _levels) =>
for _line in _levels
line.set_x1(_line, bar_index + START_OFFSET)
line.set_x2(_line, bar_index + END_OFFSET)
f_moveLevel(array<line> _from, array<line> _to, line _level, int _index) =>
array.push(_to, _level)
array.remove(_from, _index)
f_highlightPurgedLevel(line _level) =>
_style = i_purgedLevelStyle == "Solid" ? line.style_solid : i_purgedLevelStyle == "Dashed" ? line.style_dashed : line.style_dotted
line.set_color(_level, i_purgedLevelColor)
line.set_style(_level, _style)
f_updateUpperLevels(float _high, array<float> _highs, array<line> _levels, array<line> _purgedLevels) =>
while array.min(_highs) < _high
for [_index, _value] in _highs
if _high > _value
_line = array.get(_levels, _index)
f_highlightPurgedLevel(_line)
f_moveLevel(_levels, _purgedLevels, _line, _index)
array.push(purgedTFnumArray, array.get(highsTFnumArray, _index))
array.remove(_highs, _index)
array.remove(highsTFnumArray, _index)
f_updateLowerLevels(float _low, array<float> _lows, array<line> _levels, array<line> _purgedLevels) =>
while array.max(_lows) > _low
for [_index, _value] in _lows
if _low < _value
_line = array.get(_levels, _index)
f_highlightPurgedLevel(_line)
f_moveLevel(_levels, _purgedLevels, _line, _index)
array.push(purgedTFnumArray, array.get(lowsTFnumArray, _index))
array.remove(_lows, _index)
array.remove(lowsTFnumArray, _index)
f_clearLevels(array<line> _levels) =>
while array.size(_levels) > 0
for [_index, _line] in _levels
line.delete(array.remove(_levels, _index))
array.remove(purgedTFnumArray, _index)
f_isHigherTimeframe(string _timeframe) => timeframe.in_seconds() <= timeframe.in_seconds(_timeframe)
//--------------------------------------------------------------------
// Logic
//--------------------------------------------------------------------
// Create levels on historical bars
if i_is1HEnabled and f_isHigherTimeframe("60") and ta.change(time("60"))
f_create(prev1HHigh, prev1HLow, i_1HAboveLiquidityColor, i_1HBelowLiquidityColor, i_1HWidth, TF_60)
if i_is4HEnabled and f_isHigherTimeframe("240") and ta.change(time("240"))
f_create(prev4HHigh, prev4HLow, i_4HAboveLiquidityColor, i_4HBelowLiquidityColor, i_4HWidth, TF_240)
if i_isDailyEnabled and f_isHigherTimeframe("D") and ta.change(time("D"))
f_create(prevDayHigh, prevDayLow, i_dailyAboveLiquidityColor, i_dailyBelowLiquidityColor, i_dailyWidth, TF_D)
if i_isWeeklyEnabled and f_isHigherTimeframe("W") and ta.change(time("W"))
f_create(prevWeekHigh, prevWeekLow, i_weeklyAboveLiquidityColor, i_weeklyBelowLiquidityColor, i_weeklyWidth, TF_W)
if i_isMonthlyEnabled and f_isHigherTimeframe("M") and ta.change(time("M"))
f_create(prevMonthHigh, prevMonthLow, i_monthlyAboveLiquidityColor, i_monthlyBelowLiquidityColor, i_monthlyWidth, TF_M)
// Update levels positions to "stick" at the right of the latest bar
if barstate.islast
f_updateStickyLevels(highLinesArray)
f_updateStickyLevels(lowLinesArray)
f_updateStickyLevels(purgedLinesArray)
// Set and highlight, immediately, levels that got their liquidity taken
f_updateUpperLevels(high, highsArray, highLinesArray, purgedLinesArray)
f_updateLowerLevels(low, lowsArray, lowLinesArray, purgedLinesArray)
// Clean up, at the end of each day, levels that had their liquidity taken
if ta.change(time(i_purgedCleanUpTiming))
f_clearLevels(purgedLinesArray)
//--------------------------------------------------------------------
// Alerts
//--------------------------------------------------------------------
var crossedAboveDaily = false
var crossedBelowDaily = false
var crossedAboveWeekly = false
var crossedBelowWeekly = false
var crossedAboveMonthly = false
var crossedBelowMonthly = false
var crossedAbove4H = false
var crossedBelow4H = false
var crossedAbove1H = false
var crossedBelow1H = false
var _diffHighDaily = 0.0
var _diffLowDaily = 0.0
var _diffHighWeekly = 0.0
var _diffLowWeekly = 0.0
var _diffHighMonthly = 0.0
var _diffLowMonthly = 0.0
var _diffHigh4H = 0.0
var _diffLow4H = 0.0
var _diffHigh1H = 0.0
var _diffLow1H = 0.0
// Daily Line Crossed Alert
crossedAboveDaily := i_isDailyEnabled and _diffHighDaily > 0.0 ? ta.crossover(high, _diffHighDaily) : false
crossedBelowDaily := i_isDailyEnabled and _diffLowDaily > 0.0 ? ta.crossunder(low, _diffLowDaily) : false
// Weekly Line Crossed Alert
crossedAboveWeekly := i_isWeeklyEnabled and _diffHighWeekly > 0.0 ? ta.crossover(high, _diffHighWeekly) : false
crossedBelowWeekly := i_isWeeklyEnabled and _diffLowWeekly > 0.0 ? ta.crossunder(low, _diffLowWeekly) : false
// Monthly Line Crossed Alert
crossedAboveMonthly := i_isMonthlyEnabled and _diffHighMonthly > 0.0 ? ta.crossover(high, _diffHighMonthly) : false
crossedBelowMonthly := i_isMonthlyEnabled and _diffLowMonthly > 0.0 ? ta.crossunder(low, _diffLowMonthly) : false
// 4H Line Crossed Alert
crossedAbove4H := i_is4HEnabled and _diffHigh4H > 0.0 ? ta.crossover(high, _diffHigh4H) : false
crossedBelow4H := i_is4HEnabled and _diffLow4H > 0.0 ? ta.crossunder(low, _diffLow4H) : false
// 1H Line Crossed Alert
crossedAbove1H := i_is1HEnabled and _diffHigh1H > 0.0 ? ta.crossover(high, _diffHigh1H) : false
crossedBelow1H := i_is1HEnabled and _diffLow1H > 0.0 ? ta.crossunder(low, _diffLow1H) : false
alertcondition(crossedAboveDaily,title='Daily Liquidity Line Crossed Above',message='Daily Liquidity Line Crossed Above!')
alertcondition(crossedBelowDaily,title='Daily Liquidity Line Crossed Below',message='Daily Liquidity Line Crossed Below!')
alertcondition(crossedAboveWeekly,title='Weekly Liquidity Line Crossed Above',message='Weekly Liquidity Line Crossed Above!')
alertcondition(crossedBelowWeekly,title='Weekly Liquidity Line Crossed Below',message='Weekly Liquidity Line Crossed Below!')
alertcondition(crossedAboveMonthly,title='Monthly Liquidity Line Crossed Above',message='Monthly Liquidity Line Crossed Above!')
alertcondition(crossedBelowMonthly,title='Monthly Liquidity Line Crossed Below',message='Monthly Liquidity Line Crossed Below!')
alertcondition(crossedAbove4H,title='4H Liquidity Line Crossed Above',message='4H Liquidity Line Crossed Above!')
alertcondition(crossedBelow4H,title='4H Liquidity Line Crossed Below',message='4H Liquidity Line Crossed Below!')
alertcondition(crossedAbove1H,title='1H Liquidity Line Crossed Above',message='1H Liquidity Line Crossed Above!')
alertcondition(crossedBelow1H,title='1H Liquidity Line Crossed Below',message='1H Liquidity Line Crossed Below!')
// High/LowโยชpivotโรฐBreakโยทโรฉลฝลพยAโzโรฑโร โรHigh/Lowโร โขรโรญโรโรโยตโรโยขโฐiโฐโโรโรโยขโรโยฏโรโยข
// โยปโรหรยAล eTFโรฦAฦโฐย[ฦgโรคล rโรยรโlโรฦAฦโฐย[ฦgโยปโรจลรฃโรยsโยคยยจฦAฦโฐย[ฦgโยปโรจโรHigh/lowยXยVโOโรโlโร
ยsโยคยB
f_getDiffHigh(int aTFnum) =>
oDiffHighVal = 0.0
if array.size(highsTFnumArray) > 2 and array.size(highsArray) > 2
for i = 0 to array.size(highsTFnumArray)-1
// ยร
ยVโยฉโรงโรโรโรโยขโยญ
_index = array.size(highsTFnumArray)-1-i
if array.get(highsTFnumArray, _index) == aTFnum
oDiffHighVal := array.get(highsArray, _index)
break
oDiffHighVal
f_getDiffLow(int aTFnum) =>
oDiffLowVal = 0.0
if array.size(lowsTFnumArray) > 2 and array.size(lowsArray) > 2
for i = 0 to array.size(lowsTFnumArray)-1
// ยร
ยVโยฉโรงโรโรโรโยขโยญ
_index = array.size(lowsTFnumArray)-1-i
if array.get(lowsTFnumArray, _index) == aTFnum
oDiffLowVal := array.get(lowsArray, _index)
break
oDiffLowVal
// ล eTFโรฦAฦโฐย[ฦgโรคล rโรยรโl
_diffHighDaily := f_getDiffHigh(TF_D)
_diffLowDaily := f_getDiffLow(TF_D)
_diffHighWeekly := f_getDiffHigh(TF_W)
_diffLowWeekly := f_getDiffLow(TF_W)
_diffHighMonthly := f_getDiffHigh(TF_M)
_diffLowMonthly := f_getDiffLow(TF_M)
_diffHigh4H := f_getDiffHigh(TF_240)
_diffLow4H := f_getDiffLow(TF_240)
_diffHigh1H := f_getDiffHigh(TF_60)
_diffLow1H := f_getDiffLow(TF_60)
//--------------------------------------------------------------------
// Limiting last 3 liquidity
//--------------------------------------------------------------------
// var disp_line_max =3 // last 3
_cntHighDaily = 0
_cntLowDaily = 0
_cntHighWeekly = 0
_cntLowWeekly = 0
_cntHighMonthly = 0
_cntLowMonthly = 0
_cntHigh4H = 0
_cntLow4H = 0
_cntHigh1H = 0
_cntLow1H = 0
if array.size(highsTFnumArray) > 2 and array.size(highLinesArray) > 2
for i = 0 to array.size(highsTFnumArray)-1
// ยร
ยVโยฉโรงโรโรโรโยขโยญ
_index = array.size(highsTFnumArray)-1-i
if array.get(highsTFnumArray, _index) == TF_D
_cntHighDaily := _cntHighDaily + 1
if _cntHighDaily <= disp_line_max
line.set_color(array.get(highLinesArray, _index), i_dailyAboveLiquidityColor)
else
line.set_color(array.get(highLinesArray, _index), color.new(i_dailyAboveLiquidityColor, 100))
if array.get(highsTFnumArray, _index) == TF_W
_cntHighWeekly := _cntHighWeekly + 1
if _cntHighWeekly <= disp_line_max
line.set_color(array.get(highLinesArray, _index), i_weeklyAboveLiquidityColor)
else
line.set_color(array.get(highLinesArray, _index), color.new(i_weeklyAboveLiquidityColor, 100))
if array.get(highsTFnumArray, _index) == TF_M
_cntHighMonthly := _cntHighMonthly + 1
if _cntHighMonthly <= disp_line_max
line.set_color(array.get(highLinesArray, _index), i_monthlyAboveLiquidityColor)
else
line.set_color(array.get(highLinesArray, _index), color.new(i_monthlyAboveLiquidityColor, 100))
if array.get(highsTFnumArray, _index) == TF_240
_cntHigh4H := _cntHigh4H + 1
if _cntHigh4H <= disp_line_max
line.set_color(array.get(highLinesArray, _index), i_4HAboveLiquidityColor)
else
line.set_color(array.get(highLinesArray, _index), color.new(i_4HAboveLiquidityColor, 100))
if array.get(highsTFnumArray, _index) == TF_60
_cntHigh1H := _cntHigh1H + 1
if _cntHigh1H <= disp_line_max
line.set_color(array.get(highLinesArray, _index), i_1HAboveLiquidityColor)
else
line.set_color(array.get(highLinesArray, _index), color.new(i_1HAboveLiquidityColor, 100))
if array.size(lowsTFnumArray) > 2 and array.size(lowLinesArray) > 2
for i = 0 to array.size(lowsTFnumArray)-1
// ยร
ยVโยฉโรงโรโรโรโยขโยญ
_index = array.size(lowsTFnumArray)-1-i
if array.get(lowsTFnumArray, _index) == TF_D
_cntLowDaily := _cntLowDaily + 1
if _cntLowDaily <= disp_line_max
line.set_color(array.get(lowLinesArray, _index), i_dailyBelowLiquidityColor)
else
line.set_color(array.get(lowLinesArray, _index), color.new(i_dailyBelowLiquidityColor, 100))
if array.get(lowsTFnumArray, _index) == TF_W
_cntLowWeekly := _cntLowWeekly + 1
if _cntLowWeekly <= disp_line_max
line.set_color(array.get(lowLinesArray, _index), i_weeklyBelowLiquidityColor)
else
line.set_color(array.get(lowLinesArray, _index), color.new(i_weeklyBelowLiquidityColor, 100))
if array.get(lowsTFnumArray, _index) == TF_M
_cntLowMonthly := _cntLowMonthly + 1
if _cntLowMonthly <= disp_line_max
line.set_color(array.get(lowLinesArray, _index), i_monthlyBelowLiquidityColor)
else
line.set_color(array.get(lowLinesArray, _index), color.new(i_monthlyBelowLiquidityColor, 100))
if array.get(lowsTFnumArray, _index) == TF_240
_cntLow4H := _cntLow4H + 1
if _cntLow4H <= disp_line_max
line.set_color(array.get(lowLinesArray, _index), i_4HBelowLiquidityColor)
else
line.set_color(array.get(lowLinesArray, _index), color.new(i_4HBelowLiquidityColor, 100))
if array.get(lowsTFnumArray, _index) == TF_60
_cntLow1H := _cntLow1H + 1
if _cntLow1H <= disp_line_max
line.set_color(array.get(lowLinesArray, _index), i_1HBelowLiquidityColor)
else
line.set_color(array.get(lowLinesArray, _index), color.new(i_1HBelowLiquidityColor, 100))
//--------------------------------------------------------------------
// Show/Hide Purged Lines
//--------------------------------------------------------------------
if array.size(purgedTFnumArray) > 2 and array.size(purgedLinesArray) > 2
for _index = 0 to array.size(purgedTFnumArray)-1
if array.get(purgedTFnumArray, _index) == TF_D
if i_showPurgeDaily
line.set_color(array.get(purgedLinesArray, _index), color.new(#8931ac, 35))
else
line.set_color(array.get(purgedLinesArray, _index), color.new(color.new(#8931ac, 35), 100))
if array.get(purgedTFnumArray, _index) == TF_W
if i_showPurgeWeekly
line.set_color(array.get(purgedLinesArray, _index), color.new(#3e76d6, 46))
else
line.set_color(array.get(purgedLinesArray, _index), color.new(color.new(#3e76d6, 46), 100))
if array.get(purgedTFnumArray, _index) == TF_M
if i_showPurgeMonthly
line.set_color(array.get(purgedLinesArray, _index),color.rgb(102, 33, 33, 46))
else
line.set_color(array.get(purgedLinesArray, _index), color.new(color.rgb(102, 33, 33, 46), 100))
if array.get(purgedTFnumArray, _index) == TF_240
if i_showPurge4H
line.set_color(array.get(purgedLinesArray, _index), color.rgb(29, 90, 47, 32))
else
line.set_color(array.get(purgedLinesArray, _index), color.new(color.rgb(29, 90, 47, 32), 100))
if array.get(purgedTFnumArray, _index) == TF_60
if i_showPurge1H
line.set_color(array.get(purgedLinesArray, _index), color.rgb(231, 173, 74, 32))
else
line.set_color(array.get(purgedLinesArray, _index), color.new(color.rgb(231, 173, 74, 32), 100))
// // Market Structure Break - MBS //
// // User inputs
// var g_msb = "Market Structure Break - MBS"
// var len = input.int(20, minval=1, title='Loopback', group = g_msb)
// var mult = 1 //input.float(1, minval=0.1, title='Multipler', group = g_msb)
// bullish_MSB_Color = input.color(color.green, title='Bullish MSB Color', inline='Bullish MSB Style', group = g_msb)
// bearish_MSB_Color = input.color(color.red, title='Bearish MSB Color', inline='Bearish MSB Style', group = g_msb)
// bullish_MSB_Width = input.int(1, minval=1, maxval = 5, title='Line Width', inline='Bullish MSB Style', group = g_msb)
// bearish_MSB_Width = input.int(1, minval=1, maxval = 5, title='Line Width', inline='Bearish MSB Style', group = g_msb)
// // 2nd script Function to detect swing highs and lows
// f_swingHighLow(_src, _len) =>
// _sw = high >= ta.highest(high, _len)
// _lw = low <= ta.lowest(low, _len)
// [_sw, _lw]
// // Calculation of swing highs and lows
// [sh, sl] = f_swingHighLow(close, len)
// // Identify market structure break
// break_up = sh and sh[1] == false and close > high[1] * mult
// break_down = sl and sl[1] == false and close < low[1] * mult
// // Draw lines on market structure break
// var line bullish_MSB = na
// var line bearish_MSB = na
// var float highest_MSB = na
// var float lowest_MSB = na
// if break_up
// // Find the bar_index where the swing high is and draw a line until the candle CLOSES ABOVE the market structure
// for i = 1 to 100 by 1
// if sh[i]
// bullish_MSB := line.new(bar_index[i], high[i], bar_index, high[i], color=bullish_MSB_Color, width=bullish_MSB_Width)
// highest_MSB := high[i]
// break
// if break_down
// // Find the bar_index where the swing low is and draw a line until the candle CLOSES BELOW the market structure
// for i = 1 to 100 by 1
// if sl[i]
// bearish_MSB := line.new(bar_index[i], low[i], bar_index, low[i], color=bearish_MSB_Color, width=bearish_MSB_Width)
// lowest_MSB := low[i]
// break
// User input
var g_msb = "Market Structure Break - MBS"
msb_fvg = input.bool(true, "show MSB", group = g_msb)
point_method = input.string(title = "Pivot Method", defval = "Candle Wicks", options = ["Candle Wicks", "Candle Body"], group = g_msb)
left_bars = input.int(title = "Sensitivity", defval = 16, minval = 2, inline = "Pivot Length", group = g_msb)
right_bars = left_bars//input.int(title = "Rightbars", defval = 5, minval = 2, inline = "Pivot Length", group = g_msb)
line_width = input.int(title = "Line Width", defval = 1, group = g_msb)
// Global variables/arrays
high_source = point_method == "Candle Body" ? (close > open ? close : open) : high
low_source = point_method == "Candle Body" ? (close < open ? close : open) : low
fixed_pivot_high = fixnan(ta.pivothigh(high_source, left_bars, right_bars))
fixed_pivot_low = fixnan(ta.pivotlow(low_source, left_bars, right_bars))
green_candle = close > open
red_candle = close < open
green_engulf = green_candle and red_candle[1] and close > open[1]
red_engulf = red_candle and green_candle[1] and close < open[1]
var red_lines = array.new_line()
var red_breakout = array.new_int()
var red_bounce = array.new_int()
var green_lines = array.new_line()
var green_breakout = array.new_int()
var green_bounce = array.new_int()
green_breakout_trigger = false
green_rejection_trigger = false
red_breakout_trigger = false
red_rejection_trigger = false
// Main operation
if barstate.isconfirmed and msb_fvg
if array.size(red_lines) > 0
for i = array.size(red_lines) - 1 to 0
line.set_x2(array.get(red_lines, i), bar_index)
if high >= line.get_y1(array.get(red_lines, i)) and close > line.get_y1(array.get(red_lines, i)) and array.get(red_breakout, i) == 0
red_breakout_trigger := true
array.set(red_breakout, i, 1)
else
if high >= line.get_y1(array.get(red_lines, i)) and close < line.get_y1(array.get(red_lines, i)) and red_engulf and array.get(red_bounce, i) == 0 and array.get(red_breakout, i) == 0
red_rejection_trigger := true
array.set(red_bounce, i, 1)
if array.size(green_lines) > 0
for i = array.size(green_lines) - 1 to 0
line.set_x2(array.get(green_lines, i), bar_index)
if low <= line.get_y1(array.get(green_lines, i)) and close < line.get_y1(array.get(green_lines, i)) and array.get(green_breakout, i) == 0
green_breakout_trigger := true
array.set(green_breakout, i, 1)
else
if low <= line.get_y1(array.get(green_lines, i)) and close > line.get_y1(array.get(green_lines, i)) and green_engulf and array.get(green_bounce, i) == 0 and array.get(green_breakout, i) == 0
green_rejection_trigger := true
array.set(green_bounce, i, 1)
if ta.change(fixed_pivot_high) != 0
if array.size(red_lines) > 0
line.set_x2(array.get(red_lines, 0), bar_index - right_bars)
array.clear(red_lines)
array.clear(red_breakout)
array.clear(red_bounce)
array.unshift(red_lines, line.new(x1 = bar_index - right_bars, y1 = fixed_pivot_high, x2 = bar_index, y2 = fixed_pivot_high, xloc = xloc.bar_index, color = color.red, width = line_width))
array.unshift(red_breakout, 0)
array.unshift(red_bounce, 0)
if ta.change(fixed_pivot_low) != 0
if array.size(green_lines) > 0
line.set_x2(array.get(green_lines, 0), bar_index - right_bars)
array.clear(green_lines)
array.clear(green_breakout)
array.clear(green_bounce)
array.unshift(green_lines, line.new(x1 = bar_index - right_bars, y1 = fixed_pivot_low, x2 = bar_index, y2 = fixed_pivot_low, xloc = xloc.bar_index, color = color.green, width = line_width))
array.unshift(green_breakout, 0)
array.unshift(green_bounce, 0)
// Shapes
plotshape(series = red_breakout_trigger, title = "Red Breakout", style = shape.xcross, location = location.belowbar, color = color.red, text = "Break", textcolor = color.red, size = size.tiny, show_last = 20000)
plotshape(series = red_rejection_trigger, title = "Red Rejection", style = shape.xcross, location = location.abovebar, color = color.red, text = "Bounce", textcolor = color.red, size = size.tiny, show_last = 20000)
plotshape(series = green_breakout_trigger, title = "Green Breakout", style = shape.xcross, location = location.abovebar, color = color.green, text = "Break", textcolor = color.green, size = size.tiny, show_last = 20000)
plotshape(series = green_rejection_trigger, title = "Green Rejection", style = shape.xcross, location = location.belowbar, color = color.green, text = "Bounce", textcolor = color.green, size = size.tiny, show_last = 20000)
// Alert conditions
alertcondition(condition = red_breakout_trigger, title = "Red Breakout")
alertcondition(condition = red_rejection_trigger, title = "Red Rejection/Bounce")
alertcondition(condition = green_breakout_trigger, title = "Green Breakout")
alertcondition(condition = green_rejection_trigger, title = "Green Rejection/Bounce")
// Displacement //
var g_displacement = "Displacement for FVG"
displacement_fvg = input.bool(true, "show Displacement", group = g_displacement)
require_fvg = input.bool(true, "Require FVG", group = g_displacement)
disp_type = input.string("Open to Close", "Displacement Type", options = ['Open to Close', 'High to Low'], group = g_displacement)
std_len = input.int(100, minval = 1, title = "Displacement Length", tooltip = "How far back the script will look to determine the candle range standard deviation", group = g_displacement)
std_x = input.int(4, minval = 0, title = "Displacement Strength", group = g_displacement)
disp_color = input.color(color.yellow, "Bar Color", group = g_displacement)
candle_range = disp_type == "Open to Close" ? math.abs(open - close) : high - low
std = ta.stdev(candle_range, std_len) * std_x
fvg = close[1] > open[1] ? high[2] < low[0] : low[2] > high[0]
displacement = require_fvg ? candle_range[1] > std[1] and fvg : candle_range > std
barcolor(displacement and displacement_fvg? disp_color : na, offset = require_fvg ? -1 : na)
alertcondition(displacement and displacement_fvg, title = "Displacement occured")
|
Adaptive Gaussian Moving Average | https://www.tradingview.com/script/th7NZUPM-Adaptive-Gaussian-Moving-Average/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 231 | 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/
// ยฉ LeafAlgo
//@version=5
indicator("Adaptive Gaussian Moving Average", overlay=true)
length = input.int(14, minval=1, title="Length")
adaptive = input.bool(true, title="Adaptive Parameters")
volatilityPeriod = input.int(20, minval=1, title="Volatility Period")
// Calculate Gaussian Moving Average
gma = 0.0
sumOfWeights = 0.0
sigma = adaptive ? ta.stdev(close, volatilityPeriod) : input.float(1.0, minval=0.1, title="Standard Deviation")
for i = 0 to length - 1
weight = math.exp(-math.pow(((i - (length - 1)) / (2 * sigma)), 2) / 2)
value = ta.highest(close, i + 1) + ta.lowest(close, i + 1)
gma := gma + (value * weight)
sumOfWeights := sumOfWeights + weight
gma := (gma / sumOfWeights) / 2
gmaColor = close >= gma ? color.lime : color.fuchsia
plot(gma, color=gmaColor, linewidth=2, title="Gaussian Moving Average")
barcolor(gmaColor) |
Pi - Intraday High-Low Predictor | https://www.tradingview.com/script/mz2OHJSc-Pi-Intraday-High-Low-Predictor/ | Keanu_ritz | https://www.tradingview.com/u/Keanu_ritz/ | 197 | 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("Pi - Intraday High-Low Predictor", overlay=true)
//==================================================================================================================================================================================================================//
//===========================๐ฆ๐๐ถ๐๐_๐
๐พ๐ฏ๐ Pi - Intraday High-Low Predictor Code Start - Keanu_RiTz{===========================//
// ---- Table Settings Start {----//
ShowpTable = input(title="Show Pi predicted High/Low Levels in a Table", defval=true , group="Pi - Intraday High-Low Predictor")
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="Pi - Intraday High-Low Predictor")
text_size = input.session('Normal',"Table Size" ,options=["Tiny","Small","Normal","Large"] , group="Pi - Intraday High-Low Predictor")
bg_col = input.color(color.new(color.blue,90),"Table Background Color", group="Pi - Intraday High-Low Predictor")
txt_col = input.color(color.new(color.white,45),"Table Text Color", group="Pi - Intraday High-Low Predictor")
// ---- Table Settings End ----}//
showDH = input(true, title='Show Predicted-High from Day-Low', group='Pi - Intraday High-Low Predictor')
showDL = input(true, title='Show Predicted-Low from Day-High', group='Pi - Intraday High-Low Predictor')
ORtf = input.session(title = "Opening Range period", defval='5', options= ['5','10','15','30','45','60','75','90','120','240'], group='Pi - Intraday High-Low Predictor')
showHDHLR = input(true, title='Show Historical Predicted High-Low Range', group='Pi - Intraday High-Low Predictor')
FillsHL = input(true, title='Fill Small range Predicted High-Low', group='Pi - Intraday High-Low Predictor')
FilllHL = input(true, title='Fill Range Predicted High-Low', group='Pi - Intraday High-Low Predictor')
FillLHL = input(true, title='Fill Large range Predicted High-Low', group='Pi - Intraday High-Low Predictor')
HlvlColor = input.color(color.new(#78fa04,45),"Color for High Levels", group="Pi - Intraday High-Low Predictor")
LlvlColor = input.color(color.new(#fa2f04,45),"Color for Low Levels", group="Pi - Intraday High-Low Predictor")
HHlvlColor = input.color(color.new(#78fa04,75),"Color for Historical High Levels", group="Pi - Intraday High-Low Predictor")
HLlvlColor = input.color(color.new(#fa2f04,75),"Color for Historical Low Levels", group="Pi - Intraday High-Low Predictor")
HTxtColor = input.color(color.new(#78fa04,35),"Color for High Levels Text", group="Pi - Intraday High-Low Predictor")
LTxtColor = input.color(color.new(#fa2f04,35),"Color for Low Levels Text", group="Pi - Intraday High-Low Predictor")
phlline_style = input.string("Dotted", options=["Dotted", "Dashed" , "Solid"], title="Line Style", group="Pi - Intraday High-Low Predictor")
phllabel_size = input.string("small", options=["auto", "tiny", "small", "normal", "large", "huge"], title="Label size", group="Pi - Intraday High-Low Predictor")
phll_size = phllabel_size == "auto" ? size.auto : phllabel_size == "tiny" ? size.tiny : phllabel_size == "small" ? size.small : phllabel_size == "normal" ? size.normal : phllabel_size == "large" ? size.large : size.huge
phlposition_labels = input.string("Left", "Labels Position", options=["Left", "Right"], group="Pi - Intraday High-Low Predictor")
[Dopen, Dclose] = request.security(syminfo.tickerid, 'D', [time, time_close], lookahead=barmerge.lookahead_on)
[dhigh, dlow] = request.security(syminfo.tickerid, 'D', [high, low], lookahead=barmerge.lookahead_on)
var phllstyle = ""
var phll_pos = 0
if phlline_style == "Dotted"
phllstyle := line.style_dotted
else if phlline_style == "Dashed"
phllstyle := line.style_dashed
else if phlline_style == "Solid"
phllstyle := line.style_solid
if phlposition_labels == "Left"
phll_pos := Dopen
else if phlposition_labels == "Right"
phll_pos := Dclose
var float ORHigh = 0.00
var float ORLow = 0.00
var float ORange = 0.00
var float DsRange = 0.00
var float DRange = 0.00
var float DLRange = 0.00
var float DsrHigh = 0.00
var float DrHigh = 0.00
var float DLrHigh = 0.00
var float DsrLow = 0.00
var float DrLow = 0.00
var float DLrLow = 0.00
is_Newbar(res) => ta.change(time(res)) != 0
getBarmergeSeries(tickerid,exp, timeFrame) => request.security(tickerid, timeFrame, exp, barmerge.gaps_off, barmerge.lookahead_on)
_High = getBarmergeSeries(syminfo.tickerid, ta.valuewhen(is_Newbar('D'), high, 0), ORtf)
_Low = getBarmergeSeries(syminfo.tickerid, ta.valuewhen(is_Newbar('D'), low, 0), ORtf)
ORHigh := _High
ORLow := _Low
ORange := ORHigh - ORLow
DRange := ORange * 3.14
DsRange := DRange / 2
DLRange := DRange + DsRange
DsrHigh := dlow + DsRange
DrHigh := dlow + DRange
DLrHigh := dlow + DLRange
DsrLow := dhigh - DsRange
DrLow := dhigh - DRange
DLrLow := dhigh - DLRange
if showDH and timeframe.isintraday
_piDsrHigh = line.new(Dopen, DsrHigh, Dclose, DsrHigh, xloc.bar_time, color=HlvlColor, style=phllstyle, width=2)
line.delete(_piDsrHigh[1])
l_DsrHigh = label.new(phll_pos, DsrHigh, text="Small Range - High ["+str.tostring(DsrHigh, format.mintick)+"]", xloc=xloc.bar_time, textcolor=HTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DsrHigh[1])
_piDrHigh = line.new(Dopen, DrHigh, Dclose, DrHigh, xloc.bar_time, color=HlvlColor, style=phllstyle, width=2)
line.delete(_piDrHigh[1])
l_DrHigh = label.new(phll_pos, DrHigh, text="Range - High ["+str.tostring(DrHigh, format.mintick)+"]", xloc=xloc.bar_time, textcolor=HTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DrHigh[1])
_piDLrHigh = line.new(Dopen, DLrHigh, Dclose, DLrHigh, xloc.bar_time, color=HlvlColor, style=phllstyle, width=2)
line.delete(_piDLrHigh[1])
l_DLrHigh = label.new(phll_pos, DLrHigh, text="Large Range - High ["+str.tostring(DLrHigh, format.mintick)+"]", xloc=xloc.bar_time, textcolor=HTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DLrHigh[1])
if showDL and timeframe.isintraday
_DsrLow = line.new(Dopen, DsrLow, Dclose, DsrLow, xloc.bar_time, color=LlvlColor, style=phllstyle, width=2)
line.delete(_DsrLow[1])
l_DsrLow = label.new(phll_pos, DsrLow, text="Small Range - Low ["+str.tostring(DsrLow, format.mintick)+"]", xloc=xloc.bar_time, textcolor=LTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DsrLow[1])
_DrLow = line.new(Dopen, DrLow, Dclose, DrLow, xloc.bar_time, color=LlvlColor, style=phllstyle, width=2)
line.delete(_DrLow[1])
l_DrLow = label.new(phll_pos, DrLow, text="Range - Low ["+str.tostring(DrLow, format.mintick)+"]", xloc=xloc.bar_time, textcolor=LTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DrLow[1])
_DLrLow = line.new(Dopen, DLrLow, Dclose, DLrLow, xloc.bar_time, color=LlvlColor, style=phllstyle, width=2)
line.delete(_DLrLow[1])
l_DLrLow = label.new(phll_pos, DLrLow, text="Large Range - Low ["+str.tostring(DLrLow, format.mintick)+"]", xloc=xloc.bar_time, textcolor=LTxtColor, style=label.style_none, size=phll_size)
label.delete(l_DLrLow[1])
pDsrHigh = plot(showDH and showHDHLR and timeframe.isintraday ? DsrHigh : na, title='Small Range - Predicted High', color=HHlvlColor, style=plot.style_circles, linewidth=1)
pDrHigh = plot(showDH and showHDHLR and timeframe.isintraday ? DrHigh : na, title='Range - Predicted High', color=HHlvlColor, style=plot.style_circles, linewidth=1)
pDLrHigh = plot(showDH and showHDHLR and timeframe.isintraday ? DLrHigh : na, title='Large Range - Predicted High', color=HHlvlColor, style=plot.style_circles, linewidth=1)
pDsrLow = plot(showDL and showHDHLR and timeframe.isintraday ? DsrLow : na, title='Small Range - Predicted Low', color=HLlvlColor, style=plot.style_circles, linewidth=1)
pDrLow = plot(showDL and showHDHLR and timeframe.isintraday ? DrLow : na, title='Range - Predicted Low', color=HLlvlColor, style=plot.style_circles, linewidth=1)
pDLrLow = plot(showDL and showHDHLR and timeframe.isintraday ? DLrLow : na, title='Large Range - Predicted Low', color=HLlvlColor, style=plot.style_circles, linewidth=1)
fill(pDsrHigh, pDsrLow, color=FillsHL ? color.new(color.white,97) : na)
fill(pDrHigh, pDrLow, color=FilllHL ? color.new(color.white,97) : na)
fill(pDLrHigh, pDLrLow, color=FillLHL ? color.new(color.white,97) : na)
//-------------- Table code Start {-------------------//
//---- Table Position & Size code start {----//
var ptable_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 ptable_text_size = text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var pt = table.new(ptable_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 ----}//
if ShowpTable and (barstate.islast) and timeframe.isintraday
table.cell(pt,1,0,'Intraday High-Low',text_color=txt_col,text_size=ptable_text_size,bgcolor=bg_col)
table.cell(pt,2,0,'Predictor using Pi',text_color=txt_col,text_size=ptable_text_size,bgcolor=bg_col)
table.cell(pt,1,1,ticker.standard(syminfo.ticker),text_color=txt_col,text_size=ptable_text_size,bgcolor=bg_col)
table.cell(pt,2,1,'Values',text_color=txt_col,text_size=ptable_text_size,bgcolor=bg_col)
table.cell(pt,1,2, "1st "+str.tostring(ORtf)+" Minutes Range",text_color=txt_col,text_size=ptable_text_size,bgcolor=bg_col)
table.cell(pt,2,2, str.tostring(ORange, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,3, 'Small range High',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,3, str.tostring(DsrHigh, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,4, 'Range High',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,4, str.tostring(DrHigh, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,5, 'Large range High',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,5, str.tostring(DLrHigh, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,6, 'Small range Low',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,6, str.tostring(DsrLow, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,7, 'Range Low',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,7, str.tostring(DrLow, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,1,8, 'Large range Low',text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
table.cell(pt,2,8, str.tostring(DLrLow, format.mintick),text_color=txt_col,text_size=ptable_text_size, bgcolor=bg_col)
//-------------- Table code end -------------------}//
//===========================๐ฆ๐๐ถ๐๐_๐
๐พ๐ฏ๐ Pi - Intraday High-Low Predictor Code End - Keanu_RiTz===========================}//
//==================================================================================================================================================================================================================// |
Statistics Table | https://www.tradingview.com/script/ElY8K73e-Statistics-Table/ | jadeja_rajdeep | https://www.tradingview.com/u/jadeja_rajdeep/ | 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/
// ยฉ jadeja_rajdeep
//@version=5
indicator("Statistics Table",overlay=true)
firstema_length=input.int(13,"First Ema Length",1,step = 1)
secondema_length=input.int(21,"Second Ema Length",1,step = 1)
thirdema_length=input.int(50,"Third Ema Length",1,step = 1)
fourthema_length=input.int(200,"Fourth Ema Length",1,step = 1)
atr_length=input.int(21,"ATR/ADR Length",1,step = 1)
vud_length=input.int(21,"Volume U/D Ratio Length",1,step = 1)
pp_length=input.int(21,"Volume Pocket Pivot Point Length",1,step = 1)
firstrs_length=input.int(21,"First RS Length",1,step = 1)
secondrs_length=input.int(42,"Second RS Length",1,step = 1)
thirdrs_length=input.int(63,"Third RS Length",1,step = 1)
fourthrs_length=input.int(126,"Fourth RS Length",1,step = 1)
firstrsi_length=input.int(14,"First RSI Length",1,step = 1,inline = 'firstrsi')
firstrsi_timeframe=input.string('60',"First RSI TimeFrame",inline = 'firstrsi',tooltip = 'The unit is represented by a single letter, with no letter used for minutes: โSโ for seconds, โDโ for days, โWโ for weeks and โMโ for months.')
secondrsi_length=input.int(14,"Second RSI Length",1,step = 1,inline = 'secondrsi')
secondrsi_timeframe=input.string('1D',"Second RSI TimeFrame",inline = 'secondrsi')
thirdrsi_length=input.int(14,"Third RSI Length",1,step = 1,inline = 'thirdrsi')
thirdrsi_timeframe=input.string('1W',"Third RSI TimeFrame",inline = 'thirdrsi')
fourthrsi_length=input.int(12,"Fourth RSI Length",1,step = 1,inline = 'fourthrsi')
fourthrsi_timeframe=input.string('1M',"Fourth RSI TimeFrame",inline = 'fourthrsi')
firstcci_length=input.int(14,"First CCI Length",1,step = 1,inline = 'firstcci')
firstcci_timeframe=input.string('60',"First CCI TimeFrame",inline = 'firstcci',tooltip = 'The unit is represented by a single letter, with no letter used for minutes: โSโ for seconds, โDโ for days, โWโ for weeks and โMโ for months.')
secondcci_length=input.int(14,"Second CCI Length",1,step = 1,inline = 'secondcci')
secondcci_timeframe=input.string('1D',"Second CCI TimeFrame",inline = 'secondcci')
thirdcci_length=input.int(14,"Third CCI Length",1,step = 1,inline = 'thirdcci')
thirdcci_timeframe=input.string('1W',"Third CCI TimeFrame",inline = 'thirdcci')
fourthcci_length=input.int(12,"Fourth CCI Length",1,step = 1,inline = 'fourthcci')
fourthcci_timeframe=input.string('1M',"Fourth CCI TimeFrame",inline = 'fourthcci')
firstadx_length=input.int(14,"First ADX Length",1,step = 1,inline = 'firstadx')
firstadx_timeframe=input.string('60',"First ADX TimeFrame",inline = 'firstadx',tooltip = 'The unit is represented by a single letter, with no letter used for minutes: โSโ for seconds, โDโ for days, โWโ for weeks and โMโ for months.')
firstadx_smoothing_length=input.int(7,"First ADX Smoothing Length",1,step = 1,inline = 'firstadx')
secondadx_length=input.int(14,"Second ADX Length",1,step = 1,inline = 'secondadx')
secondadx_timeframe=input.string('1D',"Second ADX TimeFrame",inline = 'secondadx')
secondadx_smoothing_length=input.int(7,"Second ADX Smoothing Length",1,step = 1,inline = 'secondadx')
thirdadx_length=input.int(14,"Third ADX Length",1,step = 1,inline = 'thirdadx')
thirdadx_timeframe=input.string('1W',"Third ADX TimeFrame",inline = 'thirdadx')
thirdadx_smoothing_length=input.int(7,"Third ADX Smoothing Length",1,step = 1,inline = 'thirdadx')
fourthadx_length=input.int(12,"Fourth ADX Length",1,step = 1,inline = 'fourthadx')
fourthadx_timeframe=input.string('1M',"Fourth ADX TimeFrame",inline = 'fourthadx')
fourthadx_smoothing_length=input.int(3,"Fourth ADX Smoothing Length",1,step = 1,inline = 'fourthadx')
display_diff_ema_first=input.bool(true,"Display close difference from first ema",group = "Display")
display_diff_ema_second=input.bool(true,"Display close difference from second ema",group = "Display")
display_diff_ema_third=input.bool(true,"Display close difference from third ema",group = "Display")
display_diff_ema_fourth=input.bool(true,"Display close difference from fourth ema",group = "Display")
display_diff_ema_first_second=input.bool(true,"Display difference between first and second ema",group = "Display")
display_diff_ema_second_third=input.bool(true,"Display difference between second and third ema",group = "Display")
display_diff_ema_first_third=input.bool(true,"Display difference between first and third ema",group = "Display")
display_ud_ratio=input.bool(true,"Display volume up down ratio",group = "Display")
display_atr_adr=input.bool(true,"Display ATR/ADR %",group = "Display")
display_vppc=input.bool(true,"Display volume pocket pivot count",group = "Display")
display_dcr=input.bool(true,"Display daily closing range",group = "Display")
display_wcr=input.bool(true,"Display weekly closing range",group = "Display")
display_52week_high=input.bool(true,"Display close difference from 52week high",group = "Display")
display_52week_low=input.bool(true,"Display close difference from 52week low",group = "Display")
display_ath=input.bool(true,"Display close difference from All time high",group = "Display")
display_atl=input.bool(true,"Display close difference from All time low",group = "Display")
display_rsline_above_ema_first=input.bool(true,"Display rs line above or below first rs ema",group = "Display")
display_rsline_above_ema_second=input.bool(true,"Display rs line above or below second rs ema",group = "Display")
display_rsline_above_ema_third=input.bool(true,"Display rs line above or below third rs ema",group = "Display")
display_rsline_above_ema_fourth=input.bool(true,"Display rs line above or below fourth rs ema",group = "Display")
display_rs_value_first=input.bool(true,"Display first rs value",group = "Display")
display_rs_value_second=input.bool(true,"Display second rs value",group = "Display")
display_rs_value_third=input.bool(true,"Display third rs value",group = "Display")
display_rs_value_fourth=input.bool(true,"Display fourth rs value",group = "Display")
display_diff_change_first_first=input.bool(true,"Display difference between previous first rs length days change % and current first rs length days change %",group = "Display")
display_diff_change_second_second=input.bool(true,"Display difference between previous second rs length days change % and current second rs length days change %",group = "Display")
display_diff_change_third_third=input.bool(true,"Display difference between previous third rs length days change % and current third rs length days change %",group = "Display")
display_first_rsi=input.bool(true,"Display first rsi value",group = "Display")
display_second_rsi=input.bool(true,"Display second rsi value",group = "Display")
display_third_rsi=input.bool(true,"Display third rsi value",group = "Display")
display_fourth_rsi=input.bool(true,"Display fourth rsi value",group = "Display")
display_first_cci=input.bool(true,"Display first cci value",group = "Display")
display_second_cci=input.bool(true,"Display second cci value",group = "Display")
display_third_cci=input.bool(true,"Display third cci value",group = "Display")
display_fourth_cci=input.bool(true,"Display fourth cci value",group = "Display")
display_first_adx=input.bool(true,"Display first adx value",group = "Display")
display_second_adx=input.bool(true,"Display second adx value",group = "Display")
display_third_adx=input.bool(true,"Display third adx value",group = "Display")
display_fourth_adx=input.bool(true,"Display fourth adx value",group = "Display")
color_regular_value=input.color(color.blue,'Regular Value Color',group = "Color")
color_positive_value=input.color(color.green,'Positive Value Color',group = "Color")
color_negative_value=input.color(color.red,'Negative Value Color',group = "Color")
color_label=input.color(color.gray,'Label Color',group = "Color")
font_size=input.string(size.small,"Font Size",options = [size.normal,size.small,size.tiny])
table_postion=input.string(position.top_right,"Table Position",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])
check_first_ema_diff=input.float(0,"Positive First EMA Diff",group = "Condition Check Value")
check_second_ema_diff=input.float(0,"Positive Second EMA Diff",group = "Condition Check Value")
check_third_ema_diff=input.float(0,"Positive Third EMA Diff",group = "Condition Check Value")
check_fourth_ema_diff=input.float(0,"Positive Fourth EMA Diff",group = "Condition Check Value")
check_first_second_ema_diff=input.float(0,"Positive First - Second EMA Diff",group = "Condition Check Value")
check_second_third_ema_diff=input.float(0,"Positive Second - Third EMA Diff",group = "Condition Check Value")
check_first_third_ema_diff=input.float(0,"Positive First - Third EMA Diff",group = "Condition Check Value")
check_ud_ratio=input.float(2.5,"Positive V U/D RATIO",group = "Condition Check Value")
check_pocket_pivot=input.float(1,"Positive Pocket Pivot Point",group = "Condition Check Value")
check_dcr=input.float(50,"Positive Daily Closing Range",group = "Condition Check Value")
check_wcr=input.float(50,"Positive Weekly Closing Range",group = "Condition Check Value")
check_52wkhigh=input.float(-21,"Positive From 52 Week High",group = "Condition Check Value")
check_52wklow=input.float(30,"Positive From 52 Week Low",group = "Condition Check Value")
check_allhigh=input.float(-50,"Positive From All Time High",group = "Condition Check Value")
check_alllow=input.float(50,"Positive From All Time Low",group = "Condition Check Value")
check_rsi_first=input.float(50,"Positive First RSI",group = "Condition Check Value")
check_rsi_second=input.float(50,"Positive Second RSI",group = "Condition Check Value")
check_rsi_third=input.float(50,"Positive Third RSI",group = "Condition Check Value")
check_rsi_fourth=input.float(50,"Positive Fourth RSI",group = "Condition Check Value")
check_cci_first=input.float(50,"Positive First CCI",group = "Condition Check Value")
check_cci_second=input.float(50,"Positive Second CCI",group = "Condition Check Value")
check_cci_third=input.float(50,"Positive Third CCI",group = "Condition Check Value")
check_cci_fourth=input.float(50,"Positive Fourth CCI",group = "Condition Check Value")
check_adx_first=input.float(25,"Positive First ADX",group = "Condition Check Value")
check_adx_second=input.float(25,"Positive Second ADX",group = "Condition Check Value")
check_adx_third=input.float(25,"Positive Third ADX",group = "Condition Check Value")
check_adx_fourth=input.float(25,"Positive Fourth ADX",group = "Condition Check Value")
ema13=ta.ema(close,firstema_length)
ema21=ta.ema(close,secondema_length)
ema50=ta.ema(close,thirdema_length)
ema200=ta.ema(close,fourthema_length)
whigh=request.security(syminfo.tickerid,"1W",high)
wlow=request.security(syminfo.tickerid,"1W",low)
wclose=request.security(syminfo.tickerid,"1W",close)
atr23=ta.atr(atr_length)
whigh52=request.security(syminfo.tickerid,"1W",ta.highest(high,52))
wlow52=request.security(syminfo.tickerid,"1W",ta.lowest(low,52))
ahigh=ta.highest(high,(last_bar_index + 1))
alow=ta.lowest(low,(last_bar_index + 1))
//displaying rs21 and rs50 line in table
i_nifty50 = input.symbol("NIFTY", "Symbol")
NIFTY50 = request.security(i_nifty50, 'D', close)
NIFTY50_21 = request.security(i_nifty50, 'D', close[firstrs_length - 1])
NIFTY50_42 = request.security(i_nifty50, 'D', close[secondrs_length - 1])
NIFTY50_63 = request.security(i_nifty50, 'D', close[thirdrs_length - 1])
NIFTY50_126 = request.security(i_nifty50, 'D', close[fourthrs_length - 1])
rsline=(close/NIFTY50)
rsline21=ta.ema(rsline,firstrs_length)
rsline42=ta.ema(rsline,secondrs_length)
rsline63=ta.ema(rsline,thirdrs_length)
rsline126=ta.ema(rsline,fourthrs_length)
rs21=close / close[firstrs_length - 1]
rs42=close / close[secondrs_length - 1]
rs63=close / close[thirdrs_length - 1]
rs126=close / close[fourthrs_length - 1]
rs21_index=NIFTY50 / NIFTY50_21
rs42_index=NIFTY50 / NIFTY50_42
rs63_index=NIFTY50 / NIFTY50_63
rs126_index=NIFTY50 / NIFTY50_126
rs_21=rs21/rs21_index
rs_42=rs42/rs42_index
rs_63=rs63/rs63_index
rs_126=rs126/rs126_index
//RSI CODE START
rsi1=request.security(syminfo.tickerid,firstrsi_timeframe,ta.rsi(close,firstrsi_length))
rsi2=request.security(syminfo.tickerid,secondrsi_timeframe,ta.rsi(close,secondrsi_length))
rsi3=request.security(syminfo.tickerid,thirdrsi_timeframe,ta.rsi(close,thirdrsi_length))
rsi4=request.security(syminfo.tickerid,fourthrsi_timeframe,ta.rsi(close,fourthrsi_length))
//RSI CODE END
//CCI CODE START
cci1=request.security(syminfo.tickerid,firstcci_timeframe,ta.cci(hlc3,firstcci_length))
cci2=request.security(syminfo.tickerid,secondcci_timeframe,ta.cci(hlc3,secondcci_length))
cci3=request.security(syminfo.tickerid,thirdcci_timeframe,ta.cci(hlc3,thirdcci_length))
cci4=request.security(syminfo.tickerid,fourthcci_timeframe,ta.cci(hlc3,fourthcci_length))
//CCI CODE END
//ADX CODE START
[diplus1, diminus1, adx1]=request.security(syminfo.tickerid,firstadx_timeframe,ta.dmi(firstadx_length,firstadx_smoothing_length))
[diplus2, diminus2, adx2]=request.security(syminfo.tickerid,secondadx_timeframe,ta.dmi(secondadx_length,secondadx_smoothing_length))
[diplus3, diminus3, adx3]=request.security(syminfo.tickerid,thirdadx_timeframe,ta.dmi(thirdadx_length,thirdadx_smoothing_length))
[diplus4, diminus4, adx4]=request.security(syminfo.tickerid,fourthadx_timeframe,ta.dmi(fourthadx_length,fourthadx_smoothing_length))
//CCI CODE END
if barstate.islast
ema13_close_diff=((close - ema13) * 100) / ema13
ema13_close_diff_color=(ema13_close_diff >= check_first_ema_diff ? color_positive_value : color_negative_value)
ema21_close_diff=((close - ema21) * 100) / ema21
ema21_close_diff_color=(ema21_close_diff >= check_second_ema_diff ? color_positive_value : color_negative_value)
ema50_close_diff=((close - ema50) * 100) / ema50
ema50_close_diff_color=(ema50_close_diff >= check_third_ema_diff ? color_positive_value : color_negative_value)
ema200_close_diff=((close - ema200) * 100) / ema200
ema200_close_diff_color=(ema200_close_diff >= check_fourth_ema_diff ? color_positive_value : color_negative_value)
ema_13_21=((ema13 - ema21) * 100) / ema21
ema_13_21_color=(ema_13_21 >= check_first_second_ema_diff ? color_positive_value : color_negative_value)
ema_21_50=((ema21 - ema50) * 100) / ema50
ema_21_50_color=(ema_21_50 >= check_second_third_ema_diff ? color_positive_value : color_negative_value)
ema_13_50=((ema13 - ema50) * 100) / ema50
ema_13_50_color=(ema_13_50 >= check_first_third_ema_diff ? color_positive_value : color_negative_value)
up = 0
down = 0
for i = 0 to (vud_length - 1)
if (close[i] > close[i + 1])
up := up + int(volume[i])
else
down := down + int(volume[i])
ud_ratio=up/down
ud_ratio_color=(ud_ratio >= check_ud_ratio ? color_positive_value : color_negative_value)
pocketvol=0.0
pocket_pivot_count=0
for i = 0 to (pp_length - 1)
pocketvol :=0.0
for j = 1 to 10
if (close[i + 1] < close[i + 2] and (volume[i + 1] > pocketvol or pocketvol == 0.0))
pocketvol := volume[i + 1]
if (volume[i] > pocketvol and close[i] >= open[i] and close[i] >= close[i + 1])
pocket_pivot_count := pocket_pivot_count + 1
pocket_pivot_count_colour=(pocket_pivot_count > check_pocket_pivot ? color_positive_value : color_negative_value)
adr23=(atr23 / close) * 100
dcr=((close - low) / (high - low)) * 100
dcr_color=(dcr >= check_dcr ? color_positive_value : color_negative_value)
wcr=((wclose - wlow) / (whigh - wlow)) * 100
wcr_color=(wcr >= check_wcr ? color_positive_value : color_negative_value)
from52whigh=((close - whigh52) * 100) / whigh52
from52whigh_color=(from52whigh >= check_52wkhigh ? color_positive_value : color_negative_value)
from52wlow=((close - wlow52) * 100) / wlow52
from52wlow_color=(from52wlow >= check_52wklow ? color_positive_value : color_negative_value)
fromahigh=((close - ahigh) * 100) / ahigh
fromalow=((close - alow) * 100) / alow
fromahigh_color=(fromahigh >= check_allhigh ? color_positive_value : color_negative_value)
fromalow_color=(fromalow >= check_alllow ? color_positive_value : color_negative_value)
rsline21text=(rsline >= rsline21 ? "Yes" : "No")
rsline42text=(rsline >= rsline42 ? "Yes" : "No")
rsline63text=(rsline >= rsline63 ? "Yes" : "No")
rsline126text=(rsline >= rsline126 ? "Yes" : "No")
rsline21textcolor=(rsline >= rsline21 ? color_positive_value : color_negative_value)
rsline42textcolor=(rsline >= rsline42 ? color_positive_value : color_negative_value)
rsline63textcolor=(rsline >= rsline63 ? color_positive_value : color_negative_value)
rsline126textcolor=(rsline >= rsline126 ? color_positive_value : color_negative_value)
rs21textcolor=(rs_21 >= 1 ? color_positive_value : color_negative_value)
rs42textcolor=(rs_42 >= 1 ? color_positive_value : color_negative_value)
rs63textcolor=(rs_63 >= 1 ? color_positive_value : color_negative_value)
rs126textcolor=(rs_126 >= 1 ? color_positive_value : color_negative_value)
chng_21=(((close - close[firstrs_length - 1])*100)/close[firstrs_length - 1]) - math.abs(((close[firstrs_length] - close[(firstrs_length * 2) - 1])*100)/close[(firstrs_length * 2) - 1])
chng_42=(((close - close[secondrs_length - 1])*100)/close[secondrs_length - 1]) - math.abs(((close[secondrs_length] - close[(secondrs_length * 2) - 1])*100)/close[(secondrs_length * 2) - 1])
chng_63=(((close - close[thirdrs_length - 1])*100)/close[thirdrs_length - 1]) - math.abs(((close[thirdrs_length] - close[(thirdrs_length * 2) - 1])*100)/close[(thirdrs_length * 2) - 1])
chng_21textcolor=(chng_21 > 0 ? color_positive_value : color_negative_value)
chng_42textcolor=(chng_42 > 0 ? color_positive_value : color_negative_value)
chng_63textcolor=(chng_63 > 0 ? color_positive_value : color_negative_value)
var rstable = table.new(position = table_postion ,columns = 2, rows = 39)
var table_row=0
if(display_diff_ema_first==true)
table.cell(rstable,0,table_row,"EMA"+str.tostring(firstema_length) + " %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema13_close_diff,2)),text_color=ema13_close_diff_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_second==true)
table.cell(rstable,0,table_row,"EMA"+str.tostring(secondema_length) + " %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema21_close_diff,2)),text_color=ema21_close_diff_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_third==true)
table.cell(rstable,0,table_row,"EMA"+str.tostring(thirdema_length) + " %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema50_close_diff,2)),text_color=ema50_close_diff_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_fourth==true)
table.cell(rstable,0,table_row,"EMA"+str.tostring(fourthema_length) + " %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema200_close_diff,2)),text_color=ema200_close_diff_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_first_second==true)
table.cell(rstable,0,table_row,"EMA "+str.tostring(firstema_length)+"/"+str.tostring(secondema_length)+" %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema_13_21,2)),text_color=ema_13_21_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_second_third==true)
table.cell(rstable,0,table_row,"EMA "+str.tostring(secondema_length)+"/"+str.tostring(thirdema_length)+" %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema_21_50,2)),text_color=ema_21_50_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_ema_first_third==true)
table.cell(rstable,0,table_row,"EMA "+str.tostring(firstema_length)+"/"+str.tostring(thirdema_length)+" %",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ema_13_50,2)),text_color=ema_21_50_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_ud_ratio==true)
table.cell(rstable,0,table_row,"V U/D RATIO "+str.tostring(vud_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(ud_ratio,2)),text_color=ud_ratio_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_atr_adr==true)
table.cell(rstable,0,table_row,"ADR "+str.tostring(atr_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(adr23,2)),text_color=color_regular_value,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_vppc==true)
table.cell(rstable,0,table_row,"Pocket PP "+str.tostring(pp_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(pocket_pivot_count,2)),text_color=pocket_pivot_count_colour,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_dcr==true)
table.cell(rstable,0,table_row,"DCR",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(dcr,2)),text_color=dcr_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_wcr==true)
table.cell(rstable,0,table_row,"WCR",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(wcr,2)),text_color=wcr_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_52week_high==true)
table.cell(rstable,0,table_row,"52W High",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(from52whigh,2)),text_color=from52whigh_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_52week_low==true)
table.cell(rstable,0,table_row,"52W Low",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(from52wlow,2)),text_color=from52wlow_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_ath==true)
table.cell(rstable,0,table_row,"ATH",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(fromahigh,2)),text_color=fromahigh_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_atl==true)
table.cell(rstable,0,table_row,"ATL",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(fromalow,2)),text_color=fromalow_color,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rsline_above_ema_first==true)
table.cell(rstable,0,table_row,"RsLine > EMA"+str.tostring(firstrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,rsline21text,text_color=rsline21textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rsline_above_ema_second==true)
table.cell(rstable,0,table_row,"RsLine > EMA"+str.tostring(secondrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,rsline42text,text_color=rsline42textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rsline_above_ema_third==true)
table.cell(rstable,0,table_row,"RsLine > EMA"+str.tostring(thirdrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,rsline63text,text_color=rsline63textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rsline_above_ema_fourth==true)
table.cell(rstable,0,table_row,"RsLine > EMA"+str.tostring(fourthrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,rsline126text,text_color=rsline126textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rs_value_first==true)
table.cell(rstable,0,table_row,"RS"+str.tostring(firstrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row, str.tostring(math.round(rs_21,2)) ,text_color=rs21textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rs_value_second==true)
table.cell(rstable,0,table_row,"RS"+str.tostring(secondrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rs_42,2)),text_color=rs42textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rs_value_third==true)
table.cell(rstable,0,table_row,"RS"+str.tostring(thirdrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rs_63,2)),text_color=rs63textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_rs_value_fourth==true)
table.cell(rstable,0,table_row,"RS"+str.tostring(fourthrs_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rs_126,2)),text_color=rs126textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_change_first_first==true)
table.cell(rstable,0,table_row,str.tostring(firstrs_length)+" Chng Diff",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row, str.tostring(math.round(chng_21,2)) ,text_color=chng_21textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_change_second_second==true)
table.cell(rstable,0,table_row,str.tostring(secondrs_length)+" Chng Diff",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(chng_42,2)),text_color=chng_42textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_diff_change_third_third==true)
table.cell(rstable,0,table_row,str.tostring(thirdrs_length)+" Chng Diff",text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(chng_63,2)),text_color=chng_63textcolor,text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_first_rsi==true)
table.cell(rstable,0,table_row,'RSI '+str.tostring(firstrsi_timeframe)+' '+str.tostring(firstrsi_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rsi1,2)),text_color=(rsi1 >= check_rsi_first ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_second_rsi==true)
table.cell(rstable,0,table_row,'RSI '+str.tostring(secondrsi_timeframe)+' '+str.tostring(secondrsi_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rsi2,2)),text_color=(rsi2 >= check_rsi_second ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_third_rsi==true)
table.cell(rstable,0,table_row,'RSI '+str.tostring(thirdrsi_timeframe)+' '+str.tostring(thirdrsi_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rsi3,2)),text_color=(rsi3 >= check_rsi_third ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_fourth_rsi==true)
table.cell(rstable,0,table_row,'RSI '+str.tostring(fourthrsi_timeframe)+' '+str.tostring(fourthrsi_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(rsi4,2)),text_color=(rsi4 >= check_rsi_fourth ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_first_cci==true)
table.cell(rstable,0,table_row,'CCI '+str.tostring(firstcci_timeframe)+' '+str.tostring(firstcci_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(cci1,2)),text_color=(cci1 >= check_cci_first ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_second_cci==true)
table.cell(rstable,0,table_row,'CCI '+str.tostring(secondcci_timeframe)+' '+str.tostring(secondcci_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(cci2,2)),text_color=(cci2 >= check_cci_second ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_third_cci==true)
table.cell(rstable,0,table_row,'CCI '+str.tostring(thirdcci_timeframe)+' '+str.tostring(thirdcci_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(cci3,2)),text_color=(cci3 >= check_cci_third ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_fourth_cci==true)
table.cell(rstable,0,table_row,'CCI '+str.tostring(fourthcci_timeframe)+' '+str.tostring(fourthcci_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(cci4,2)),text_color=(cci4 >= check_cci_fourth ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_first_adx==true)
table.cell(rstable,0,table_row,'ADX '+str.tostring(firstadx_timeframe)+' '+str.tostring(firstadx_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(adx1,2)),text_color=(adx1 >= check_adx_first ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_second_adx==true)
table.cell(rstable,0,table_row,'ADX '+str.tostring(secondadx_timeframe)+' '+str.tostring(secondadx_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(adx2,2)),text_color=(adx2 >= check_adx_second ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_third_adx==true)
table.cell(rstable,0,table_row,'ADX '+str.tostring(thirdadx_timeframe)+' '+str.tostring(thirdadx_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(adx3,2)),text_color=(adx3 >= check_adx_third ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
if(display_fourth_adx==true)
table.cell(rstable,0,table_row,'ADX '+str.tostring(fourthadx_timeframe)+' '+str.tostring(fourthadx_length),text_halign = text.align_right,text_size = font_size,text_color = color_label)
table.cell(rstable,1,table_row,str.tostring(math.round(adx4,2)),text_color=(adx4 >= check_adx_fourth ? color_positive_value : color_negative_value ),text_halign = text.align_left,text_size = font_size)
table_row := table_row + 1
|
Scalping Strategy (5min) | https://www.tradingview.com/script/EafghSFE-Scalping-Strategy-5min/ | AySiam | https://www.tradingview.com/u/AySiam/ | 151 | 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/
// ยฉ AySiam
//@version=5
indicator("Scalping Strategy (5min)", overlay=true)
usesma = input(true , "Slow MA")
usesmafilter= input(true , "Fast MA")
rsi1Length = input(28, "Slow RSI Length")
rsi2Length = input(7, "Fast RSI Length")
simplema = input(200, "Slow MA")
simplema2 = input(5, "Fast MA")
sma1= ta.sma(close, simplema)
sma2= ta.sma(close, simplema2)
src = input.source(close, "Source (This Affects Signals)")
smafilterbuy= (src > sma2)
smafiltersell= (src < sma2)
rsi14Value = ta.rsi(close, rsi1Length)
rsi2Value = ta.rsi(close, rsi2Length)
smaValue = ta.sma(close, simplema)
//Bollinger Bands
[bbUpper, bbMiddle, bbLower] = ta.bb(close, 20, 2)
//Buy/Sell
enterLong = (not usesmafilter or smafilterbuy) and (not usesma or (open > smaValue)) and ta.crossover(rsi2Value, rsi14Value)
enterShort = (not usesmafilter or smafiltersell) and (not usesma or (open < smaValue)) and ta.crossunder(rsi2Value, rsi14Value)
plotshape(enterLong, title="Buy", location=location.belowbar, color=color.green, style=shape.square, text="Buy",textcolor= color.green)
plotshape(enterShort, title="Sell", location=location.abovebar, color=color.red, style=shape.square, text= "Sell", textcolor= color.red)
plot(bbMiddle, color=color.blue , title="BB Upper")
plot(bbUpper, color=color.orange, title="BB Middle")
plot(bbLower, color=color.blue, title="BB Lower")
plot(sma1, color=color.white, title = "Slow MA")
plot(sma2, color=color.yellow , title = "Fast MA") |
Draw Line For High Low Custom Range Interactive | https://www.tradingview.com/script/44NQpol9-Draw-Line-For-High-Low-Custom-Range-Interactive/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 60 | 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('Draw Line For High Low Custom Range Interactive', 'DLFHLCRI', true)
//#region โโโโโโโโโโโโโโโโโโโโ 0. Inputs
G0 = 'POINTS'
int stamp1 = timestamp('2023-04')
int stamp2 = timestamp('2023-05')
int time1 = input.time(stamp1, 'Point 1', group = G0, confirm = true, tooltip = 'Point 1 must BEFORE Point 2')
int time2 = input.time(stamp2, 'Point 2', group = G0, confirm = true, tooltip = 'Point 2 must AFTER Point 1')
G1 = 'SETUP'
T0 = 'Left : Color Up\nRight : Color Down'
T1 = 'Values:\nMin : 1\nMax : 4'
i_c_Up = input.color(color.teal, 'Color', group = G1, inline = '1')
i_c_Dn = input.color(color.red, '', group = G1, inline = '1', tooltip = T0)
i_s_style = input.string( 'arrow', 'Line Style', group = G1, options = ['solid', 'dashed', 'dotted', 'arrow'])
i_i_width = input.int( 2, 'Line Width', group = G1, minval = 1, maxval = 4, tooltip = T1)
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 1. Types
// @type Used for point
// @field bar Int value for bar time
// @field price Int value for price
type point
int bar = na
float price = na
// @type Used for setting
// @field col1 Color value for col1
// @field col2 Color value for col2
// @field style String value for line style
// @field width Int value for line width
type setting
color col1 = na
color col2 = na
string style = na
int width = na
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 2. Customs Functions
// @function get price based on given time
// @param t
// @returns o, h, l, c
getPrice(int t = na)=>
var float o = na, var float h = na, var float l = na, var float c = na
if time[1] <= t and time >= t and na(c)
o := open, h := high, l := low, c := close
[o, h, l, c]
// @function compare High Low points to get correct trend
// @param price1, price2
// @returns o, h, l, c
compareHL(int t1 = na, int t2 = na) =>
[O1, H1, L1, C1] = getPrice(t1)
[O2, H2, L2, C2] = getPrice(t2)
[price1, price2] = switch C1 < C2
true => [L1, H2]
false => [H1, L2]
[price1, price2]
// @function draw line if point is correct, otherwise draw label
// @param point1, point2, setup
// @returns lineID, labelID
createDrawing(point point1 = na, point point2 = na, setting setup = na) =>
col = switch point1.price < point2.price
true => setup.col1
false => setup.col2
var line lineID = na, lineID.delete()
var label labelID = na, labelID.delete()
if point1.bar < point2.bar
lineID := line.new(point1.bar, point1.price, point2.bar, point2.price, xloc.bar_time,
color = col, width = setup.width, style = setup.style)
else
labelID := label.new(point2.bar, point2.price, 'Please move this point\nafter blue point', xloc.bar_time,
style = label.style_label_right, color = color.red)
[lineID, labelID]
// @function select line style
// @param value
// @returns style
selectLineStyle(string value = na) =>
style = switch value
'solid' => line.style_solid
'dashed' => line.style_dashed
'dotted' => line.style_dotted
'arrow' => line.style_arrow_right
style
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 3. Constructs
[price1, price2] = compareHL(time1, time2)
point1 = point.new(time1, price1)
point2 = point.new(time2, price2)
setup = setting.new(i_c_Up, i_c_Dn, selectLineStyle(i_s_style), i_i_width)
// // Point 1 on right side (False) // Point 1 on left side (Correct)
bgcolor(time1 > time2 and time == time1 ? color.new(color.blue, 90) : time1 < time2 and time == time1 ? color.new(color.blue, 90) : na, 0, false)
bgcolor(time1 > time2 and time == time2 ? color.new(color.red, 90) : time1 < time2 and time == time2 ? color.new(color.blue, 90) : na, 0, false)
if barstate.islast
[trendLine, wrongPoint2] = createDrawing(point1, point2, setup)
//#endregion |
Hui-Heubel Liquidity Ratio | https://www.tradingview.com/script/gxdpQhF0-Hui-Heubel-Liquidity-Ratio/ | potato_hedge | https://www.tradingview.com/u/potato_hedge/ | 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/
// ยฉ potato_hedge
//@version=5
indicator("LHH",precision=4)
length = input.int(title="Lookback Window", defval=10)
sma = input.int(title="SMA",defval=20)
sma2 = input.int(title="SMA2",defval=50)
// implementation of volume based liquidity metric https://www.imf.org/external/pubs/ft/wp/2002/wp02232.pdf
lhh_function(source,length) =>
pmax = ta.highest(source,length)
pmin = ta.lowest(source,length)
tdv = (high+low+close/3) * volume
dv = math.sum(tdv,length)
lhhsma = ta.sma(source,length)
sa = ta.sma(volume,length)
lhh = (((pmax - pmin)/pmin) / (dv/(sa*lhhsma)))*100
lhh = lhh_function(close,length)
lsma1 = ta.sma(lhh,sma)
lsma2 = ta.sma(lhh,sma2)
p0 = plot(lhh,color=color.white,linewidth=2)
p1 = plot(lsma1,color=lhh>lsma1?color.new(color.green,20):color.new(color.yellow,20))
p2 = plot(lsma2,color=lsma1>lsma2?color.new(color.yellow,20):color.new(color.red,20))
fill(p0,p1,color=lhh>lsma1?color.new(color.green,90):color.new(color.yellow,90))
fill(p1,p2,color=lsma1>lsma2?color.new(color.yellow,90):color.new(color.red,90)) |
Intraday Intensity Modes | https://www.tradingview.com/script/S7HGang6-Intraday-Intensity-Modes/ | allanster | https://www.tradingview.com/u/allanster/ | 590 | 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 on TradingView
//@version=5
// Original concept by David Bostian, with variations featured in "Bollinger on Bollinger Bands".
indicator("Intraday Intensity Modes", 'Intensity')
toolTipA = 'III (Individual):\nOsc Length 1\n[ ] Cumulative (Off)\n[ ] Normalized (Off)\n[ ] Inverse Volu' +
'me (Off)\n[ ] Show Levels (Off)\n\n'
toolTipB = 'II (Cumulative):\nOsc Length 1\n[โ] Cumulative (On)\n[ ] Normalized (Off)\n[ ] Inverse Volume ' +
'(Off)\n[ ] Show Levels (Off)\n\n'
toolTipC = 'II% (Oscillator):\nOsc Length 21\n[ ] Cumulative (Off)\n[โ] Normalized (On)\n[ ] Inverse Volume' +
' (Off)\n[โ] Show Levels (On)'
toolTipD = 'Enables examination of intensity per bar instead of per day, this is a departure from the original ' +
'concept. Whenever this setting is enabled the indicator should be regarded as operating in an experimental mode.'
toolTipV = '[ ] Inverse Volume (Off):\n\n (2 * close - high - low) * volume\n โโโโโโโโโโโโโโโโ\n ' +
' high - low\n\n\n[โ] Inverse Volume (On):\n\n 2 * close - high - low\n โโโโโโโโโโโ' +
'\n (high - low) * volume'
i_length = input.int (21, 'Osc Length', minval = 1, tooltip = toolTipA + toolTipB + toolTipC)
i_cumltv = input.bool (false, 'Cumulative')
i_normal = input.bool (true, 'Normalized')
i_candle = input.bool (false, 'Intrabar', tooltip = toolTipD)
i_invert = input.bool (false, 'Inverse Volume', tooltip = toolTipV)
i_colrUp = input.color(#00BCD4, 'Colors For Up', inline = 'a')
i_colrDn = input.color(#E040FB, 'Down', inline = 'a')
i_styles = input.string('Columns', 'Style & Width', options = ['Columns', 'Histogram', 'Line'], inline = 'b')
i_widths = input.int (1, '', minval = 1, inline = 'b')
i_shoLvl = input.bool (true, '', inline = 'c')
i_levelH = input.int (25, 'Show Levels Above', inline = 'c')
i_levelL = input.int (-25, 'Below', inline = 'c')
id_cum(source) => // perform cumulative sum once per day when using realtime intraday source values
var carrySum = float(na)
var dailySum = float(na)
if not timeframe.isintraday
carrySum := ta.cum(nz(source))
else
dailySum := timeframe.change('D') ? nz(carrySum) : nz(dailySum)
carrySum := nz(dailySum) + nz(source)
altSum(source, length) => normal = math.sum(nz(source), length) // treat na as 0 and return sum
var idRangeH = float(na)
var idRangeL = float(na)
var idVolume = float(na)
startDay = timeframe.change('D')
idRangeH := not timeframe.isintraday or startDay ? high : high > nz(idRangeH) ? high : idRangeH // intraday high
idRangeL := not timeframe.isintraday or startDay ? low : low < nz(idRangeL, 10e99) ? low : idRangeL // intraday low
idVolume := not timeframe.isintraday or startDay ? volume : nz(idVolume) + volume // intraday volume
idUseVol = i_invert ? 1 / idVolume : idVolume
iiiValue = nz(((2 * close - idRangeH - idRangeL) / (idRangeH - idRangeL)) * idUseVol) // intraday intensity
use_iii = i_invert ?
(2 * close - high - low) / ((high - low) * volume) :
((2 * close - high - low) / (high - low)) * volume
usePrcnt = i_normal ? 100 : 1
iiSource =
usePrcnt * altSum(i_cumltv ? i_candle ? ta.cum(nz(use_iii)) : id_cum(iiiValue) : i_candle ? nz(use_iii) : iiiValue, i_length) /
(i_normal ? altSum(i_cumltv ? i_candle ? ta.cum(volume) : id_cum(idVolume) : i_candle ? volume : idVolume, i_length) : 1)
colrSign = altSum(i_candle ? use_iii : iiiValue, i_length) / (i_normal ? i_candle ? volume : altSum(idVolume, i_length) : 1)
pltStyle = i_styles == 'Columns' ? plot.style_columns : i_styles == 'Histogram' ? plot.style_histogram : plot.style_line
plot(iiSource, 'III, II, or II%', math.sign(colrSign) != -1 ? i_colrUp : i_colrDn, i_widths, pltStyle)
plot(startDay ? 1 : 0, 'startDay', #ffff00, display = display.data_window)
plot(close, 'close', #ffff00, display = display.data_window)
plot(high, 'high', #ffff00, display = display.data_window)
plot(low, 'low', #ffff00, display = display.data_window)
plot(volume, 'volume', #ffff00, display = display.data_window)
plot(idRangeH, 'idRangeH', #ffff00, display = display.data_window)
plot(idRangeL, 'idRangeL', #ffff00, display = display.data_window)
plot(idVolume, 'idVolume', #ffff00, display = display.data_window)
plot(iiiValue, 'iiiValue', #ffff00, display = display.data_window)
plot(iiSource, 'iiSource', #ffff00, display = display.data_window)
hline(i_shoLvl ? i_levelH : na)
hline(i_shoLvl ? i_levelL : na)
// Reference Equations Used For Normal Volume
// III = (((2 * close) - high - low) / (high - low)) * volume
// II = ta.cum((((2 * close) - high - low) / ((high - low)) * volume)
// II% = 100 * math.sum((((2 * close) - high - low) / ((high - low)) * volume, 21) / math.sum(volume, 21)
// Reference Equations Used For Inverted Volume
// III = ((2 * close) - high - low) / ((high - low) * volume)
// II = ta.cum(((2 * close) - high - low) / ((high - low) * volume))
// II% = 100 * math.sum(((2 * close) - high - low) / ((high - low) * volume), 21) / math.sum(volume, 21) |
RD Opening Range/Initial Balance | https://www.tradingview.com/script/JEm7dk0W-RD-Opening-Range-Initial-Balance/ | RexDogActual | https://www.tradingview.com/u/RexDogActual/ | 145 | 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/
// ยฉ Bhangerang with help by @RexDogActual as well as permission to publish
//@version=5
indicator("RD Opening Range", "RD-OR", overlay=true, max_bars_back=5000)
// inputs
show_table = input.bool(true, "Display Data Panel", group = "options")
opening_session = input.session("0830-0930", "Opening Raing Session Time", group = "time")
timeZone = input.string("CST6CDT", title="Time Zone", group = "time")
main_color = input.color(color.gray, "Main Color", group = "line settings")
sub_color = input.color(color.new(color.gray,40), "Mid/50% Line Color", group = "line settings")
dh_color = input.color(color.red, "Data High Color", group="line settings")
dl_color = input.color(color.blue, "Data Low Color", group="line settings")
main_width = input.int(1, "Main Plot Width (top & bottom)", group = "line settings")
sub_width = input.int(1, "Mid Plot Width", group = "line settings")
label_size = input.string("Normal", title="Label Size", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="label settings")
label_text_color = input.color(color.black, "Label Text Color", group = "label settings")
// variables
opening_high = float(-1)
opening_low = float(-1)
opening_range_hour = int(str.tonumber(array.get(str.split(opening_session, "-"), 1))/100)-int(str.tonumber(array.get(str.split(opening_session, "-"), 0))/100)
opening_range_minute = int(str.tonumber(array.get(str.split(opening_session, "-"), 1))%100)-int(str.tonumber(array.get(str.split(opening_session, "-"), 0))%100)
opening_range_in_minutes = opening_range_hour*60+opening_range_minute
current_time = hour(time, timeZone)*100+minute(time, timeZone)
dt = (time-time[1])/60000
bars_till_next_opening_range = (1440-opening_range_in_minutes)/dt
var offset = 0
var int close_above_oh_20days = 0
var int close_below_ol_20days = 0
// float variables
var float rda_sum = na
var float rda_avg = na
var float higher_mid = na
var float lower_mid = na
var float high_avg = na
var float low_avg = na
var float last_week_delta = na
var float this_week_delta = na
var float test = 0
// opening high varialbes
var float h1 = na
var float h2 = na
var float h3 = na
var float h4 = na
var float h5 = na
var float h6 = na
var float h7 = na
var float h8 = na
var float h9 = na
var float h10 = na
var float oh1 = na
var float oh2 = na
var float oh3 = na
var float oh4 = na
var float oh5 = na
var float oh6 = na
var float oh7 = na
var float oh8 = na
var float oh9 = na
var float oh10 = na
var float oh11 = na
var float oh12 = na
var float oh13 = na
var float oh14 = na
var float oh15 = na
var float oh16 = na
var float oh17 = na
var float oh18 = na
var float oh19 = na
var float oh20 = na
// opening low varialbes
var float l1 = na
var float l2 = na
var float l3 = na
var float l4 = na
var float l5 = na
var float l6 = na
var float l7 = na
var float l8 = na
var float l9 = na
var float l10 = na
var float ol1 = na
var float ol2 = na
var float ol3 = na
var float ol4 = na
var float ol5 = na
var float ol6 = na
var float ol7 = na
var float ol8 = na
var float ol9 = na
var float ol10 = na
var float ol11 = na
var float ol12 = na
var float ol13 = na
var float ol14 = na
var float ol15 = na
var float ol16 = na
var float ol17 = na
var float ol18 = na
var float ol19 = na
var float ol20 = na
// close variables
var float c1 = na
var float c2 = na
var float c3 = na
var float c4 = na
var float c5 = na
var float c6 = na
var float c7 = na
var float c8 = na
var float c9 = na
var float c10 = na
var float c11 = na
var float c12 = na
var float c13 = na
var float c14 = na
var float c15 = na
var float c16 = na
var float c17 = na
var float c18 = na
var float c19 = na
var float c20 = na
// drawing variables
var label ohl = na
var label oll = na
var label midl = na
var table rda_analytics = table.new(position.bottom_left, 2, 6)
labelSize = (label_size == "Huge") ? size.huge :
(label_size == "Large") ? size.large :
(label_size == "Small") ? size.small :
(label_size == "Tiny") ? size.tiny :
(label_size == "Auto") ? size.auto : size.normal
// functions
InSession(sessionTimes) =>
not na(time(timeframe.period, sessionTimes, timeZone))
// calculating opening high
if(InSession(opening_session) and not InSession(opening_session)[1])
opening_high := high
else if(InSession(opening_session) and high > opening_high[1])
opening_high := high
else
opening_high := opening_high[1]
// calculating opening low
if(InSession(opening_session) and not InSession(opening_session)[1])
opening_low := low
else if(InSession(opening_session) and low < opening_low[1])
opening_low := low
else
opening_low := opening_low[1]
// updating
if(InSession(opening_session))
offset += 1
// Opening range
if InSession(opening_session)[1] and not InSession(opening_session)
h5 := h4
h4 := h3
h3 := h2
h2 := h1
h1 := opening_high
l5 := l4
l4 := l3
l3 := l2
l2 := l1
l1 := opening_low
this_week_delta := (h5+h4+h3+h2+h1-l5-l4-l3-l2-l1)/(dayofweek(time, timeZone)-1)
offset := 0
// Updating table stuff
if dayofweek(time, timeZone) == 1 and (hour(time, timeZone) >= 17 and hour(time, timeZone)[1] <17)
h6 := h1
h7 := h2
h8 := h3
h9 := h4
h10 := h5
l6 := l1
l7 := l2
l8 := l3
l9 := l4
l10 := l5
h1 := 0
h2 := 0
h3 := 0
h4 := 0
h5 := 0
l1 := 0
l2 := 0
l3 := 0
l4 := 0
l5 := 0
last_week_delta := (h6+h7+h8+h9+h10-(l6+l7+l8+l9+l10))/5
this_week_delta := 0
// Record close above/below OR
if (hour(time, timeZone)==15 and hour(time, timeZone)[1] < 15)
close_above_oh_20days := 0
close_below_ol_20days := 0
test := 1
oh20 := oh19
oh19 := oh18
oh18 := oh17
oh17 := oh16
oh16 := oh15
oh15 := oh14
oh14 := oh13
oh13 := oh12
oh12 := oh11
oh11 := oh10
oh10 := oh9
oh9 := oh8
oh8 := oh7
oh7 := oh6
oh6 := oh5
oh5 := oh4
oh4 := oh3
oh3 := oh2
oh2 := oh1
oh1 := opening_high
ol20 := ol19
ol19 := ol18
ol18 := ol17
ol17 := ol16
ol16 := ol15
ol15 := ol14
ol14 := ol13
ol13 := ol12
ol12 := ol11
ol11 := ol10
ol10 := ol9
ol9 := ol8
ol8 := ol7
ol7 := ol6
ol6 := ol5
ol5 := ol4
ol4 := ol3
ol3 := ol2
ol2 := ol1
ol1 := opening_low
c20 := c19
c19 := c18
c18 := c17
c17 := c16
c16 := c15
c15 := c14
c14 := c13
c13 := c12
c12 := c11
c11 := c10
c10 := c9
c9 := c8
c8 := c7
c7 := c6
c6 := c5
c5 := c4
c4 := c3
c3 := c2
c2 := c1
c1 := close
if (oh20 < c20)
close_above_oh_20days += 1
if (oh19 < c19)
close_above_oh_20days += 1
if (oh18 < c18)
close_above_oh_20days += 1
if (oh17 < c17)
close_above_oh_20days += 1
if (oh16 < c16)
close_above_oh_20days += 1
if (oh15 < c15)
close_above_oh_20days += 1
if (oh14 < c14)
close_above_oh_20days += 1
if (oh13 < c13)
close_above_oh_20days += 1
if (oh12 < c12)
close_above_oh_20days += 1
if (oh11 < c11)
close_above_oh_20days += 1
if (oh10 < c10)
close_above_oh_20days += 1
if (oh9 < c9)
close_above_oh_20days += 1
if (oh8 < c8)
close_above_oh_20days += 1
if (oh7 < c7)
close_above_oh_20days += 1
if (oh6 < c6)
close_above_oh_20days += 1
if (oh5 < c5)
close_above_oh_20days += 1
if (oh4 < c4)
close_above_oh_20days += 1
if (oh3 < c3)
close_above_oh_20days += 1
if (oh2 < c2)
close_above_oh_20days += 1
if (oh1 < c1)
close_above_oh_20days += 1
if (ol20 > c20)
close_below_ol_20days += 1
if (ol19 > c19)
close_below_ol_20days += 1
if (ol18 > c18)
close_below_ol_20days += 1
if (ol17 > c17)
close_below_ol_20days += 1
if (ol16 > c16)
close_below_ol_20days += 1
if (ol15 > c15)
close_below_ol_20days += 1
if (ol14 > c14)
close_below_ol_20days += 1
if (ol13 > c13)
close_below_ol_20days += 1
if (ol12 > c12)
close_below_ol_20days += 1
if (ol11 > c11)
close_below_ol_20days += 1
if (ol10 > c10)
close_below_ol_20days += 1
if (ol9 > c9)
close_below_ol_20days += 1
if (ol8 > c8)
close_below_ol_20days += 1
if (ol7 > c7)
close_below_ol_20days += 1
if (ol6 > c6)
close_below_ol_20days += 1
if (ol5 > c5)
close_below_ol_20days += 1
if (ol4 > c4)
close_below_ol_20days += 1
if (ol3 > c3)
close_below_ol_20days += 1
if (ol2 > c2)
close_below_ol_20days += 1
if (ol1 > c1)
close_below_ol_20days += 1
// plot
// Background coloring
bgcolor(InSession(opening_session) and timeframe.isintraday? color.new(color.gray, 80) : na)
// coloring
main_color := InSession(opening_session) and not InSession(opening_session)[1] ? na : main_color
sub_color := InSession(opening_session) and not InSession(opening_session)[1] ? na : sub_color
// Plot opening range lines
plot(opening_high, "Opening High", color = timeframe.isintraday?main_color:na, style=plot.style_line, linewidth = main_width)
plot(opening_low, "Opening Low", color = timeframe.isintraday?main_color:na, style=plot.style_line, linewidth = main_width)
plot((opening_high+opening_low)/2, "Opening Mid", color = timeframe.isintraday?sub_color:na, style=plot.style_line, linewidth = sub_width)
// Update labels
label.delete(ohl)
label.delete(oll)
label.delete(midl)
ohl := label.new(bar_index+9, opening_high, "OH: " + str.tostring(opening_high, "#.##"), style=label.style_none, textcolor = label_text_color, size = labelSize, textalign = text.align_left)
oll := label.new(bar_index+9, opening_low, "OL: " + str.tostring(opening_low, "#.##"), style=label.style_none, textcolor = label_text_color, size = labelSize, textalign = text.align_left)
midl := label.new(bar_index+9, (opening_high+opening_low)/2, "Mid: " + str.tostring((opening_high+opening_low)/2, "#.##"), style=label.style_none, textcolor = label_text_color, size = labelSize, textalign = text.align_left)
if not timeframe.isintraday
label.delete(ohl)
label.delete(oll)
label.delete(midl)
// Table
if show_table and timeframe.isintraday
table.cell(rda_analytics, 0, 0, "Data", bgcolor=color.black, text_color=color.white)
// table.cell(rda_analytics, 0, 1, "LW-Avg", bgcolor=color.black, text_color=color.white)
// table.cell(rda_analytics, 1, 1, str.tostring(last_week_delta, "#.##"), bgcolor=color.black, text_color=color.red)
table.cell(rda_analytics, 0, 2, "W-Avg", bgcolor=color.black, text_color=color.white)
table.cell(rda_analytics, 1, 2, str.tostring(this_week_delta, "#.##"), bgcolor=color.black, text_color=color.blue)
table.cell(rda_analytics, 0, 3, "20D CA-OH", bgcolor=color.black, text_color=color.white)
table.cell(rda_analytics, 1, 3, str.tostring(close_above_oh_20days), bgcolor=color.black, text_color=color.red)
table.cell(rda_analytics, 0, 4, "20D CB-OL", bgcolor=color.black, text_color=color.white)
table.cell(rda_analytics, 1, 4, str.tostring(close_below_ol_20days), bgcolor=color.black, text_color=color.blue)
table.cell(rda_analytics, 0, 5, " ", bgcolor=chart.bg_color, text_color=color.white)
table.cell(rda_analytics, 1, 5, " ", bgcolor=chart.bg_color, text_color=color.blue) |
Trend lines | https://www.tradingview.com/script/41FSzWNz-Trend-lines/ | tantisch | https://www.tradingview.com/u/tantisch/ | 238 | 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/
// ยฉ anTIMAtter_
//@version=5
indicator("Trend lines", overlay=true)
// User inputs
prd = input.int(defval=30, title=' Period for Pivot Points', minval=1, maxval=50)
max_num_of_pivots = input.int(defval=6, title=' Maximum Number of Pivots', minval=5, maxval=10)
max_lines = input.int(defval=1, title=' Maximum number of trend lines', minval=1, maxval=10)
show_lines = input.bool(defval=true, title=' Show trend lines')
show_pivots = input.bool(defval=false, title=' Show Pivot Points')
sup_line_color = input(defval = color.lime, title = "Colors", inline = "tcol")
res_line_color = input(defval = color.red, title = "", inline = "tcol")
float ph = ta.pivothigh(high, prd, prd)
float pl = ta.pivotlow(low, prd, prd)
plotshape(ph and show_pivots, style=shape.triangledown, location=location.abovebar, offset=-prd, size=size.tiny)
plotshape(pl and show_pivots, style=shape.triangleup, location=location.belowbar, offset=-prd, size=size.tiny)
// Creating array of pivots
var pivots_high = array.new_float(0)
var pivots_low = array.new_float(0)
var high_ind = array.new_int(0)
var low_ind = array.new_int(0)
if ph
array.push(pivots_high, ph)
array.push(high_ind, bar_index - prd)
if array.size(pivots_high) > max_num_of_pivots // limit the array size
array.shift(pivots_high)
array.shift(high_ind)
if pl
array.push(pivots_low, pl)
array.push(low_ind, bar_index - prd)
if array.size(pivots_low) > max_num_of_pivots // limit the array size
array.shift(pivots_low)
array.shift(low_ind)
// Create arrays to store slopes and lines
var res_lines = array.new_line()
var res_slopes = array.new_float()
len_lines = array.size(res_lines)
if (len_lines >= 1)
for ind = 0 to len_lines - 1
to_delete = array.pop(res_lines)
array.pop(res_slopes)
line.delete(to_delete)
count_slope(ph1, ph2, pos1, pos2) => (ph2 - ph1) / (pos2 - pos1)
if array.size(pivots_high) == max_num_of_pivots
index_of_biggest_slope = 0
for ind1 = 0 to max_num_of_pivots - 2
for ind2 = ind1 + 1 to max_num_of_pivots - 1
p1 = array.get(pivots_high, ind1)
p2 = array.get(pivots_high, ind2)
pos1 = array.get(high_ind, ind1)
pos2 = array.get(high_ind, ind2)
k = count_slope(p1, p2, pos1, pos2)
b = p1 - k * pos1
ok = true
if ind2 - ind1 >= 1 and ok
for ind3 = ind1 + 1 to ind2 - 1
p3 = array.get(pivots_high, ind3)
pos3 = array.get(high_ind, ind3)
if p3 > k * pos3 + b
ok := false
break
pos3 = 0
p_val = p2 + k
if ok
for ind = pos2 + 1 to bar_index
if close[bar_index - ind] > p_val
ok := false
break
pos3 := ind + 1
p_val += k
if ok
if array.size(res_slopes) < max_lines
line = line.new(pos1, p1, pos3, p_val, color=res_line_color)//, extend=extend.right)
array.push(res_lines, line)
array.push(res_slopes, k)
else
max_slope = array.max(res_slopes)
max_slope_ind = array.indexof(res_slopes, max_slope)
if max_lines == 1
max_slope_ind := 0
if k < max_slope
line_to_delete = array.get(res_lines, max_slope_ind)
line.delete(line_to_delete)
new_line = line.new(pos1, p1, pos3, p_val, color=res_line_color)//, extend=extend.right)
array.insert(res_lines, max_slope_ind, new_line)
array.insert(res_slopes, max_slope_ind, k)
array.remove(res_lines, max_slope_ind + 1)
array.remove(res_slopes, max_slope_ind + 1)
if not show_lines
len_l = array.size(res_lines)
if (len_l >= 1)
for ind = 0 to len_l - 1
to_delete = array.pop(res_lines)
array.pop(res_slopes)
line.delete(to_delete)
var sup_lines = array.new_line()
var sup_slopes = array.new_float()
len_lines1 = array.size(sup_lines)
if (len_lines1 >= 1)
for ind = 0 to len_lines1 - 1
to_delete = array.pop(sup_lines)
array.pop(sup_slopes)
line.delete(to_delete)
if array.size(pivots_low) == max_num_of_pivots
for ind1 = 0 to max_num_of_pivots - 2
for ind2 = ind1 + 1 to max_num_of_pivots - 1
p1 = array.get(pivots_low, ind1)
p2 = array.get(pivots_low, ind2)
pos1 = array.get(low_ind, ind1)
pos2 = array.get(low_ind, ind2)
k = count_slope(p1, p2, pos1, pos2)
b = p1 - k * pos1
ok = true
// check if pivot points in the middle of two points is lower
if ind2 - ind1 >= 1 and ok
for ind3 = ind1 + 1 to ind2 - 1
p3 = array.get(pivots_low, ind3)
pos3 = array.get(low_ind, ind3)
if p3 < k * pos3 + b
ok := false
break
pos3 = 0
p_val = p2 + k
if ok
for ind = pos2 + 1 to bar_index
if close[bar_index - ind] < p_val
ok := false
break
pos3 := ind + 1
p_val += k
if ok
if array.size(sup_slopes) < max_lines
line = line.new(pos1, p1, pos3, p_val, color=sup_line_color)//, extend=extend.right)
array.push(sup_lines, line)
array.push(sup_slopes, k)
else
max_slope = array.min(sup_slopes)
max_slope_ind = array.indexof(sup_slopes, max_slope)
if max_lines == 1
max_slope_ind := 0
if k > max_slope
line_to_delete = array.get(sup_lines, max_slope_ind)
line.delete(line_to_delete)
new_line = line.new(pos1, p1, pos3, p_val, color=sup_line_color)//, extend=extend.right)
array.insert(sup_lines, max_slope_ind, new_line)
array.insert(sup_slopes, max_slope_ind, k)
array.remove(sup_lines, max_slope_ind + 1)
array.remove(sup_slopes, max_slope_ind + 1)
if not show_lines
len_l = array.size(sup_lines)
if (len_l >= 1)
for ind = 0 to len_l - 1
to_delete = array.pop(sup_lines)
array.pop(sup_slopes)
line.delete(to_delete) |
4H Range | https://www.tradingview.com/script/TFxIt2P5-4H-Range/ | My3rdid | https://www.tradingview.com/u/My3rdid/ | 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/
// ยฉ My3rdid
//@version=5
indicator("Custom Range", overlay=true)
colorChoice = input(color.white, "Choose your color")
sminutes = input(true, title="Show Range")
mperiod = input.string("240", title="Select Range Period", options=["5", "15", "30", "60", "240", "D", "W", "M"])
showLabels = input.bool(true, title="Show labels", inline="labels")
labelSize = input.string("normal", options=["tiny", "small", "normal", "large"], title="Label Size")
display_value = input.bool(true, title='Show Price Values in Labels')
nbarsforward = input.int(title='Offset labels N bars to the right', defval=8)
ticksThreshold = input(10, "Number of ticks")
tickSize = syminfo.mintick
var line highLine = na
var line lowLine = na
var line midLine = na
var label highLabel = na
var label lowLabel = na
var label midLabel = na
var float prevHigh = na
var float prevLow = na
var bool firstTime = na
// New series type variables
var float highValue = na
var float lowValue = na
var float midValue = na
// Find the Last candle in minutes series selection
// This is the only candle we want to show the levels for
_minHigh = request.security(syminfo.tickerid, mperiod, high)
_minLow = request.security(syminfo.tickerid, mperiod, low)
_minClose = request.security(syminfo.tickerid, mperiod, close)
_minMid = (_minHigh + _minLow) / 2
//Calculations for Minutes levels
if (na(firstTime))
highLine := line.new(x1=bar_index, y1=_minHigh, x2=bar_index, y2=_minHigh, color=colorChoice, width = 1)
lowLine := line.new(x1=bar_index, y1=_minLow, x2=bar_index, y2=_minLow, color=colorChoice, width = 1)
midLine := line.new(x1=bar_index, y1=_minMid, x2=bar_index, y2=_minMid, color=colorChoice, width = 1)
prevHigh := _minHigh
prevLow := _minLow
firstTime := false
if (_minClose > prevHigh + ticksThreshold * tickSize or _minClose < prevLow - ticksThreshold * tickSize)
line.delete(highLine)
line.delete(lowLine)
line.delete(midLine)
label.delete(highLabel)
label.delete(lowLabel)
label.delete(midLabel)
highLine := line.new(x1=bar_index, y1=_minHigh, x2=bar_index, y2=_minHigh, color=colorChoice, width = 1)
lowLine := line.new(x1=bar_index, y1=_minLow, x2=bar_index, y2=_minLow, color=colorChoice, width = 1)
midLine := line.new(x1=bar_index, y1=_minMid, x2=bar_index, y2=_minMid, color=colorChoice, width = 1)
prevHigh := _minHigh
prevLow := _minLow
// Update series type variables
highValue := _minHigh
lowValue := _minLow
midValue := _minMid
if showLabels
highLabel := label.new(x=bar_index+nbarsforward, y=_minHigh, text=str.tostring(_minHigh, "#.00"), style=label.style_none, textcolor=colorChoice, textalign=text.align_left, size=labelSize, xloc=xloc.bar_index)
lowLabel := label.new(x=bar_index+nbarsforward, y=_minLow, text=str.tostring(_minLow, "#.00"), style=label.style_none, textcolor=colorChoice, textalign=text.align_left, size=labelSize, xloc=xloc.bar_index)
midLabel := label.new(x=bar_index+nbarsforward, y=_minMid, text=str.tostring(_minMid, "#.00"), style=label.style_none, textcolor=colorChoice, textalign=text.align_left, size=labelSize, xloc=xloc.bar_index)
// Output values for data window display
plot(highValue, "Range High", color.new(color.white,100))
plot(midValue, "Range Mid", color.new(color.white,100))
plot(lowValue, "Range Low", color.new(color.white,100))
line.set_x2(highLine, bar_index)
line.set_x2(lowLine, bar_index)
line.set_x2(midLine, bar_index)
label.set_x(highLabel, bar_index + nbarsforward)
label.set_x(lowLabel, bar_index + nbarsforward)
label.set_x(midLabel, bar_index + nbarsforward)
|
Rule of 40 | https://www.tradingview.com/script/8yEVVisv-Rule-of-40/ | barnabygraham | https://www.tradingview.com/u/barnabygraham/ | 6 | 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/
// ยฉ barnabygraham
// The rule of 40 is a popular metric for measuring the quality of SaaS companies. It is the sum of the year over year sales growth and profit margin. Companies are considered good if this sum is above 40.
//@version=5
indicator("Rule of 40")
sales = request.financial(syminfo.tickerid,'TOTAL_REVENUE','FY')
var salesGrowth = 0.
if sales != sales[1]
salesGrowth := ((sales/sales[1])-1)*100
netIncome = request.financial(syminfo.tickerid,'NET_INCOME','FY')
operatingMargin = (netIncome/sales)*100
ruleOf40 = salesGrowth + operatingMargin
plot(ruleOf40,'Rule of 40')
plot(salesGrowth,'Sales Growth',color=color.orange,display=display.none)
plot(operatingMargin,'Operating Margin',color=color.teal,display=display.none) |
[TTI] NDR 63-Day QQQ-QQEW ROC% Spread | https://www.tradingview.com/script/7rUEaj32-TTI-NDR-63-Day-QQQ-QQEW-ROC-Spread/ | TintinTrading | https://www.tradingview.com/u/TintinTrading/ | 34 | 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/
// ยฉ TintinTrading
//@version=4
study("[TTI] NDR 63-Day QQQ-QQEW ROC% Spread", shorttitle="[TTI] NDR QQQ-QQEW ROC% Spread", overlay=false)
// Define the tickers
qqq = security("NASDAQ:QQQ", "D", close)
qqew = security("NASDAQ:QQEW", "D", close)
// Calculate the 63-day Rate of Change (ROC%) for each ticker
roc_qqq = roc(qqq, 63) * 100
roc_qqew = roc(qqew, 63) * 100
// Calculate the spread
spread = roc_qqq - roc_qqew
// Plot the spread
Spread = plot(spread, title="63-Day QQQ-QQEW ROC% Spread", color=color.orange)
// Plot zero line
Zero = plot(0, "Zero Line", color=color.orange)
Warning = plot(600, "Warning line 1",style = plot.style_cross, color=color.rgb(120, 123, 134, 55))
Warning2 = plot(-600, "Warning line 1",style = plot.style_cross, color=color.rgb(120, 123, 134, 55))
fill(Spread, Zero, color.rgb(255, 153, 0)) |
RSI Divergences on price chart - Open Source Code | https://www.tradingview.com/script/QNWgRxT4-RSI-Divergences-on-price-chart-Open-Source-Code/ | Trading_Paradise | https://www.tradingview.com/u/Trading_Paradise/ | 309 | 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/
// ยฉ Trading_Paradise
//@version=5
indicator("RSI DIVERGENCES", overlay=true, max_labels_count = 500, max_lines_count = 500)
// Input
rsiLength = input.int(title="RSI Length", defval=14, minval=1)
smoothK = input.int(title="Smooth K", defval=3, minval=1)
stochLength = input.int(title="Stochastic Length", defval=14, minval=1)
bulldivcol = input.color(defval = color.green, title = 'Bullish Div Color', inline = "1")
beardivcol = input.color(defval = color.red, title = 'Bearish Div Color', inline = "1")
divwidth = input.int(defval = 1, title="Divergence Line Width", minval=1, maxval=4)
_m = input.string(title="Margin", defval="1", tooltip = "The input value determines the extent of divergence considered by the system between the RSI and price. A lower input value, approaching 0, means the system focuses on smaller, more immediate divergences. On the other hand, a higher input value, up to 2, allows the system to consider larger divergences by comparing those that are more distant in time. Essentially, the input value adjusts the breadth of the divergence examination, with lower values focusing on the short term, and higher values examining longer-term trends. 1 is a good Compromise ", options=["0", "0.236", "0.382", "0.5", "0.618", "0.786", "1", "1.272", "1.618", "1.786", "2"])
atr = ta.atr(14)
// RSI
rsi = ta.rsi(close, rsiLength)
// PLOT DIVERGENCES ON CHART
nwh = close > open ? close : na
nwl = close < open ? close : na
nwh_ = close > open ? high : close < open ? high : na
nwl_ = close > open ? low : close < open ? low : na
LB = 1
RB = 1
ph = ta.pivothigh(nwh, LB, RB)
pl = ta.pivotlow(nwl, LB, RB)
ph_ = ta.pivothigh(nwh_, LB, RB)
pl_ = ta.pivotlow(nwl_, LB, RB)
rh = ta.pivothigh(rsi, LB, RB)
rl = ta.pivotlow(rsi, LB, RB)
hh0 = ta.valuewhen(ph, nwh[1], 0)
ll0 = ta.valuewhen(pl, nwl[1], 0)
rsih0 = hh0 ? ta.valuewhen(ph, rsi[1], 0) : na
rsil0 = ll0 ? ta.valuewhen(pl, rsi[1], 0) : na
hh1 = hh0 ? ta.valuewhen(ph, nwh[1], 1) : na
hh1_ = hh0 ? ta.valuewhen(ph, nwh_[1], 1) : na
ll1 = ll0 ? ta.valuewhen(pl, nwl[1], 1) : na
ll1_ = ll0 ? ta.valuewhen(pl, nwl_[1], 1) : na
rsih1 = hh0 ? ta.valuewhen(ph, rsi[1], 1) : na
rsil1 = ll0 ? ta.valuewhen(pl, rsi[1], 1) : na
//plotshape(ll1 and pl ? ll1 : na)
hh2 = hh0 ? ta.valuewhen(ph, nwh[1], 2) : na
hh2_ = hh0 ? ta.valuewhen(ph, nwh_[1], 2) : na
ll2 = ll0 ? ta.valuewhen(pl, nwl[1], 2) : na
ll2_ = ll0 ? ta.valuewhen(pl, nwl_[1], 2) : na
rsih2 = hh0 ? ta.valuewhen(ph, rsi[1], 2) : na
rsil2 = ll0 ? ta.valuewhen(pl, rsi[1], 2) : na
hh3 = hh0 ? ta.valuewhen(ph, nwh[1], 3) : na
hh3_ = hh0 ? ta.valuewhen(ph, nwh_[1], 3) : na
ll3 = ll0 ? ta.valuewhen(pl, nwl[1], 3) : na
ll3_ = ll0 ? ta.valuewhen(pl, nwl_[1], 3) : na
rsih3 = hh0 ? ta.valuewhen(ph, rsi[1], 3) : na
rsil3 = ll0 ? ta.valuewhen(pl, rsi[1], 3) : na
hh4 = hh0 ? ta.valuewhen(ph, nwh[1], 4) : na
hh4_ = hh0 ? ta.valuewhen(ph, nwh_[1], 4) : na
ll4 = ll0 ? ta.valuewhen(pl, nwl[1], 4) : na
ll4_ = ll0 ? ta.valuewhen(pl, nwl_[1], 4) : na
rsih4 = hh0 ? ta.valuewhen(ph, rsi[1], 4) : na
rsil4 = ll0 ? ta.valuewhen(pl, rsi[1], 4) : na
hh5 = hh0 ? ta.valuewhen(ph, nwh[1], 5) : na
hh5_ = hh0 ? ta.valuewhen(ph, nwh_[1], 5) : na
ll5 = ll0 ? ta.valuewhen(pl, nwl[1], 5) : na
ll5_ = ll0 ? ta.valuewhen(pl, nwl_[1], 5) : na
rsih5 = hh0 ? ta.valuewhen(ph, rsi[1], 5) : na
rsil5 = ll0 ? ta.valuewhen(pl, rsi[1], 5) : na
hh6 = hh0 ? ta.valuewhen(ph, nwh[1], 6) : na
hh6_ = hh0 ? ta.valuewhen(ph, nwh_[1], 6) : na
ll6 = ll0 ? ta.valuewhen(pl, nwl[1], 6) : na
ll6_ = ll0 ? ta.valuewhen(pl, nwl_[1], 6) : na
rsih6 = hh0 ? ta.valuewhen(ph, rsi[1], 6) : na
rsil6 = ll0 ? ta.valuewhen(pl, rsi[1], 6) : na
hh7 = hh0 ? ta.valuewhen(ph, nwh[1], 7) : na
hh7_ = hh0 ? ta.valuewhen(ph, nwh_[1], 7) : na
ll7 = ll0 ? ta.valuewhen(pl, nwl[1], 7) : na
ll7_ = ll0 ? ta.valuewhen(pl, nwl_[1], 7) : na
rsih7 = hh0 ? ta.valuewhen(ph, rsi[1], 7) : na
rsil7 = ll0 ? ta.valuewhen(pl, rsi[1], 7) : na
hh8 = hh0 ? ta.valuewhen(ph, nwh[1], 8) : na
hh8_ = hh0 ? ta.valuewhen(ph, nwh_[1], 8) : na
ll8 = ll0 ? ta.valuewhen(pl, nwl[1], 8) : na
ll8_ = ll0 ? ta.valuewhen(pl, nwl_[1], 8) : na
rsih8 = hh0 ? ta.valuewhen(ph, rsi[1], 8) : na
rsil8 = ll0 ? ta.valuewhen(pl, rsi[1], 8) : na
m = 0.5
if _m == "0"
m := 0
else
if _m == "0.236"
m := 0.236
else
if _m == "0.382"
m := 0.382
else
if _m == "0.5"
m := 0.5
else
if _m == "0.618"
m := 0.618
else
if _m == "0.786"
m := 0.786
else
if _m == "1"
m := 1
else
if _m == "1.272"
m := 1.272
else
if _m == "1.618"
m := 1.618
else
if _m == "1.786"
m := 1.786
else
if _m == "2"
m := 2
// Bullish Divergences = close LL - RSI HL
close_LL1 = ll0 < ll1
rsi_HL1 = rsil0 > rsil1
close_LL2 = ll0 < ll2
and ll1 > ll0 and ll1 > (ll2_ - ((ll2_ - ll0) * m))
rsi_HL2 = rsil0 > rsil2
and rsil1 > rsil2
and rsil1 > (rsil2 + ((rsil0 - rsil2) / 2))
close_LL3 = ll0 < ll3
and ll1 > ll0 and ll1 > (ll3_ - ((ll3_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll3_ - ((ll3_ - ll0) * m))
rsi_HL3 = rsil0 > rsil3
and rsil1 > (rsil3 + ((rsil0 - rsil3) / 2))
and rsil2 > (rsil3 + ((rsil0 - rsil3) / 2))
close_LL4 = ll0 < ll4
and ll1 > ll0 and ll1 > (ll4_ - ((ll4_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll4_ - ((ll4_ - ll0) * m))
and ll3 > ll0 and ll3 > (ll4_ - ((ll4_ - ll0) * m))
rsi_HL4 = rsil0 > rsil4
and rsil1 > (rsil4 + ((rsil0 - rsil4) / 2))
and rsil2 > (rsil4 + ((rsil0 - rsil4) / 2))
and rsil3 > (rsil4 + ((rsil0 - rsil4) / 2))
close_LL5 = ll0 < ll5
and ll1 > ll0 and ll1 > (ll5_ - ((ll5_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll5_ - ((ll5_ - ll0) * m))
and ll3 > ll0 and ll3 > (ll5_ - ((ll5_ - ll0) * m))
and ll4 > ll0 and ll4 > (ll5_ - ((ll5_ - ll0) * m))
rsi_HL5 = rsil0 > rsil5
and rsil1 > (rsil5 + ((rsil0 - rsil5) / 2))
and rsil2 > (rsil5 + ((rsil0 - rsil5) / 2))
and rsil3 > (rsil5 + ((rsil0 - rsil5) / 2))
and rsil4 > (rsil5 + ((rsil0 - rsil5) / 2))
close_LL6 = ll0 < ll6
and ll1 > ll0 and ll1 > (ll6_ - ((ll6_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll6_ - ((ll6_ - ll0) * m))
and ll3 > ll0 and ll3 > (ll6_ - ((ll6_ - ll0) * m))
and ll4 > ll0 and ll4 > (ll6_ - ((ll6_ - ll0) * m))
and ll5 > ll0 and ll5 > (ll6_ - ((ll6_ - ll0) * m))
rsi_HL6 = rsil0 > rsil6
and rsil1 > (rsil6 + ((rsil0 - rsil6) / 2))
and rsil2 > (rsil6 + ((rsil0 - rsil6) / 2))
and rsil3 > (rsil6 + ((rsil0 - rsil6) / 2))
and rsil4 > (rsil6 + ((rsil0 - rsil6) / 2))
and rsil5 > (rsil6 + ((rsil0 - rsil6) / 2))
close_LL7 = ll0 < ll7
and ll1 > ll0 and ll1 > (ll7_ - ((ll7_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll7_ - ((ll7_ - ll0) * m))
and ll3 > ll0 and ll3 > (ll7_ - ((ll7_ - ll0) * m))
and ll4 > ll0 and ll4 > (ll7_ - ((ll7_ - ll0) * m))
and ll5 > ll0 and ll5 > (ll7_ - ((ll7_ - ll0) * m))
and ll6 > ll0 and ll6 > (ll7_ - ((ll7_ - ll0) * m))
rsi_HL7 = rsil0 > rsil7
and rsil1 > (rsil7 + ((rsil0 - rsil7) / 2))
and rsil2 > (rsil7 + ((rsil0 - rsil7) / 2))
and rsil3 > (rsil7 + ((rsil0 - rsil7) / 2))
and rsil4 > (rsil7 + ((rsil0 - rsil7) / 2))
and rsil5 > (rsil7 + ((rsil0 - rsil7) / 2))
and rsil6 > (rsil7 + ((rsil0 - rsil7) / 2))
close_LL8 = ll0 < ll8
and ll1 > ll0 and ll1 > (ll8_ - ((ll8_ - ll0) * m))
and ll2 > ll0 and ll2 > (ll8_ - ((ll8_ - ll0) * m))
and ll3 > ll0 and ll3 > (ll8_ - ((ll8_ - ll0) * m))
and ll4 > ll0 and ll4 > (ll8_ - ((ll8_ - ll0) * m))
and ll5 > ll0 and ll5 > (ll8_ - ((ll8_ - ll0) * m))
and ll6 > ll0 and ll6 > (ll8_ - ((ll8_ - ll0) * m))
and ll7 > ll0 and ll7 > (ll8_ - ((ll8_ - ll0) * m))
rsi_HL8 = rsil0 > rsil8
and rsil1 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil2 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil3 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil4 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil5 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil6 > (rsil8 + ((rsil0 - rsil8) / 2))
and rsil7 > (rsil8 + ((rsil0 - rsil8) / 2))
div_bull_1 = close_LL1 and rsi_HL1
div_bull_2 = close_LL2 and rsi_HL2
div_bull_3 = close_LL3 and rsi_HL3
div_bull_4 = close_LL4 and rsi_HL4
div_bull_5 = close_LL5 and rsi_HL5
div_bull_6 = close_LL6 and rsi_HL6
div_bull_7 = close_LL7 and rsi_HL7
div_bull_8 = close_LL8 and rsi_HL8
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Bearish Divergences = close HH - RSI LH
close_HH1 = hh0 > hh1
rsi_LH1 = rsih0 < rsih1
close_HH2 = hh0 > hh2
and hh1 < hh0 and hh1 < (hh2_ + ((hh0 - hh2_) * m))
rsi_LH2 = rsih0 < rsih2
and rsih1 < (rsih2 - ((rsih2 - rsih0) / 2))
close_HH3 = hh0 > hh3
and hh1 < hh0 and hh1 < (hh3_ + ((hh0 - hh3_) * m))
and hh2 < hh0 and hh2 < (hh3_ + ((hh0 - hh3_) * m))
rsi_LH3 = rsih0 < rsih3
and rsih1 < (rsih3 - ((rsih3 - rsih0) / 2))
and rsih2 < (rsih3 - ((rsih3 - rsih0) / 2))
close_HH4 = hh0 > hh4
and hh1 < hh0 and hh1 < (hh4_ + ((hh0 - hh4_) * m))
and hh2 < hh0 and hh2 < (hh4_ + ((hh0 - hh4_) * m))
and hh3 < hh0 and hh3 < (hh4_ + ((hh0 - hh4_) * m))
rsi_LH4 = rsih0 < rsih4
and rsih1 < (rsih4 - ((rsih4 - rsih0) / 2))
and rsih2 < (rsih4 - ((rsih4 - rsih0) / 2))
and rsih3 < (rsih4 - ((rsih4 - rsih0) / 2))
close_HH5 = hh0 > hh5
and hh1 < hh0 and hh1 < (hh5_ + ((hh0 - hh5_) * m))
and hh2 < hh0 and hh2 < (hh5_ + ((hh0 - hh5_) * m))
and hh3 < hh0 and hh3 < (hh5_ + ((hh0 - hh5_) * m))
and hh4 < hh0 and hh4 < (hh5_ + ((hh0 - hh5_) * m))
rsi_LH5 = rsih0 < rsih5
and rsih1 < (rsih5 - ((rsih5 - rsih0) / 2))
and rsih2 < (rsih5 - ((rsih5 - rsih0) / 2))
and rsih3 < (rsih5 - ((rsih5 - rsih0) / 2))
and rsih4 < (rsih5 - ((rsih5 - rsih0) / 2))
close_HH6 = hh0 > hh6
and hh1 < hh0 and hh1 < (hh6_ + ((hh0 - hh6_) * m))
and hh2 < hh0 and hh2 < (hh6_ + ((hh0 - hh6_) * m))
and hh3 < hh0 and hh3 < (hh6_ + ((hh0 - hh6_) * m))
and hh4 < hh0 and hh4 < (hh6_ + ((hh0 - hh6_) * m))
and hh5 < hh0 and hh5 < (hh6_ + ((hh0 - hh6_) * m))
rsi_LH6 = rsih0 < rsih6
and rsih1 < (rsih6 - ((rsih6 - rsih0) / 2))
and rsih2 < (rsih6 - ((rsih6 - rsih0) / 2))
and rsih3 < (rsih6 - ((rsih6 - rsih0) / 2))
and rsih4 < (rsih6 - ((rsih6 - rsih0) / 2))
and rsih5 < (rsih6 - ((rsih6 - rsih0) / 2))
close_HH7 = hh0 > hh7
and hh1 < hh0 and hh1 < (hh7_ + ((hh0 - hh7_) * m))
and hh2 < hh0 and hh2 < (hh7_ + ((hh0 - hh7_) * m))
and hh3 < hh0 and hh3 < (hh7_ + ((hh0 - hh7_) * m))
and hh4 < hh0 and hh4 < (hh7_ + ((hh0 - hh7_) * m))
and hh5 < hh0 and hh5 < (hh7_ + ((hh0 - hh7_) * m))
and hh6 < hh0 and hh6 < (hh7_ + ((hh0 - hh7_) * m))
rsi_LH7 = rsih0 < rsih7
and rsih1 < (rsih7 - ((rsih7 - rsih0) / 2))
and rsih2 < (rsih7 - ((rsih7 - rsih0) / 2))
and rsih3 < (rsih7 - ((rsih7 - rsih0) / 2))
and rsih4 < (rsih7 - ((rsih7 - rsih0) / 2))
and rsih5 < (rsih7 - ((rsih7 - rsih0) / 2))
and rsih6 < (rsih7 - ((rsih7 - rsih0) / 2))
close_HH8 = hh0 > hh8
and hh1 < hh0 and hh1 < (hh8_ + ((hh0 - hh8_) * m))
and hh2 < hh0 and hh2 < (hh8_ + ((hh0 - hh8_) * m))
and hh3 < hh0 and hh3 < (hh8_ + ((hh0 - hh8_) * m))
and hh4 < hh0 and hh4 < (hh8_ + ((hh0 - hh8_) * m))
and hh5 < hh0 and hh5 < (hh8_ + ((hh0 - hh8_) * m))
and hh6 < hh0 and hh6 < (hh8_ + ((hh0 - hh8_) * m))
and hh7 < hh0 and hh7 < (hh8_ + ((hh0 - hh8_) * m))
rsi_LH8 = rsih0 < rsih8
and rsih1 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih2 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih3 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih4 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih5 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih6 < (rsih8 - ((rsih8 - rsih0) / 2))
and rsih7 < (rsih8 - ((rsih8 - rsih0) / 2))
div_bear_1 = close_HH1 and rsi_LH1
div_bear_2 = close_HH2 and rsi_LH2
div_bear_3 = close_HH3 and rsi_LH3
div_bear_4 = close_HH4 and rsi_LH4
div_bear_5 = close_HH5 and rsi_LH5
div_bear_6 = close_HH6 and rsi_LH6
div_bear_7 = close_HH7 and rsi_LH7
div_bear_8 = close_HH8 and rsi_LH8
// Bullish Divergences = close LL - RSI HL
bl1 = 0
bl_1 = 0
bl2 = 0
bl_2 = 0
bl3 = 0
bl_3 = 0
bl4 = 0
bl_4 = 0
bl5 = 0
bl_5 = 0
bl6 = 0
bl_6 = 0
bl7 = 0
bl_7 = 0
bl8 = 0
bl_8 = 0
// Bearish Divergences = close HH - RSI LH
br1 = 0
br_1 = 0
br2 = 0
br_2 = 0
br3 = 0
br_3 = 0
br4 = 0
br_4 = 0
br5 = 0
br_5 = 0
br6 = 0
br_6 = 0
br7 = 0
br_7 = 0
br8 = 0
br_8 = 0
for i = 0 to 1
if div_bull_1 and rsi[i] == rsil0
break
bl_1 := bl_1 + 1
if div_bull_2 and rsi[i] == rsil0
break
bl_2 := bl_2 + 1
if div_bull_3 and rsi[i] == rsil0
break
bl_3 := bl_3 + 1
if div_bull_4 and rsi[i] == rsil0
break
bl_4 := bl_4 + 1
if div_bull_5 and rsi[i] == rsil0
break
bl_5 := bl_5 + 1
if div_bull_6 and rsi[i] == rsil0
break
bl_6 := bl_6 + 1
if div_bull_7 and rsi[i] == rsil0
break
bl_7 := bl_7 + 1
if div_bull_8 and rsi[i] == rsil0
break
bl_8 := bl_8 + 1
if rsi[i] == rsil0
break
for i = 0 to 1
if div_bear_1 and rsi[i] == rsih0
break
br_1 := br_1 + 1
if div_bear_2 and rsi[i] == rsih0
break
br_2 := br_2 + 1
if div_bear_3 and rsi[i] == rsih0
break
br_3 := br_3 + 1
if div_bear_4 and rsi[i] == rsih0
break
br_4 := br_4 + 1
if div_bear_5 and rsi[i] == rsih0
break
br_5 := br_5 + 1
if div_bear_6 and rsi[i] == rsih0
break
br_6 := br_6 + 1
if div_bear_7 and rsi[i] == rsih0
break
br_7 := br_7 + 1
if div_bear_8 and rsi[i] == rsih0
break
br_8 := br_8 + 1
if rsi[i] == rsih0
break
for i = 0 to 100
if div_bull_1 and rsi[i] == rsil1
break
bl1 := bl1 + 1
if rsi[i] == rsil1
break
for i = 0 to 150
if div_bull_2 and rsi[i] == rsil2
break
bl2 := bl2 + 1
if rsi[i] == rsil2
break
for i = 0 to 200
if div_bull_3 and rsi[i] == rsil3
break
bl3 := bl3 + 1
if rsi[i] == rsil3
break
for i = 0 to 200
if div_bull_4 and rsi[i] == rsil4
break
bl4 := bl4 + 1
if rsi[i] == rsil4
break
for i = 0 to 300
if div_bull_5 and rsi[i] == rsil5
break
bl5 := bl5 + 1
if rsi[i] == rsil5
break
for i = 0 to 400
if div_bull_6 and rsi[i] == rsil6
break
bl6 := bl6 + 1
if rsi[i] == rsil6
break
for i = 0 to 500
if div_bull_7 and rsi[i] == rsil7
break
bl7 := bl7 + 1
if rsi[i] == rsil7
break
for i = 0 to 500
if div_bull_8 and rsi[i] == rsil8
break
bl8 := bl8 + 1
if rsi[i] == rsil8
break
for i = 0 to 100
if div_bear_1 and rsi[i] == rsih1
break
br1 := br1 + 1
if rsi[i] == rsih1
break
for i = 0 to 150
if div_bear_2 and rsi[i] == rsih2
break
br2 := br2 + 1
if rsi[i] == rsih2
break
for i = 0 to 200
if div_bear_3 and rsi[i] == rsih3
break
br3 := br3 + 1
if rsi[i] == rsih3
break
for i = 0 to 200
if div_bear_4 and rsi[i] == rsih4
break
br4 := br4 + 1
if rsi[i] == rsih4
break
for i = 0 to 300
if div_bear_5 and rsi[i] == rsih5
break
br5 := br5 + 1
if rsi[i] == rsih5
break
for i = 0 to 400
if div_bear_6 and rsi[i] == rsih6
break
br6 := br6 + 1
if rsi[i] == rsih6
break
for i = 0 to 500
if div_bear_7 and rsi[i] == rsih7
break
br7 := br7 + 1
if rsi[i] == rsih7
break
for i = 0 to 500
if div_bear_8 and rsi[i] == rsih8
break
br8 := br8 + 1
if rsi[i] == rsih8
break
if div_bull_1 and not div_bull_2 and not div_bull_3
and not div_bull_4 and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_1], ll0, bar_index[bl1], ll1, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
//lb = label.new(bar_index[bl_4], rsi[bl_4], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=lime, size=_size)
line.delete(not pl ? ln : na)
if div_bull_2 and not div_bull_3 and not div_bull_4
and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_2], ll0, bar_index[bl2], ll2, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
if div_bull_3 and not div_bull_4 and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_3], ll0, bar_index[bl3], ll3, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
if div_bull_4 and not div_bull_5 and not div_bull_6
and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_4], ll0, bar_index[bl4], ll4, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
//lb = label.new(bar_index[bl_4], rsi[bl_4], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=lime, size=_size)
//label.delete(not pl ? lb : na)
if div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_5], ll0, bar_index[bl5], ll5, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
//lb = label.new(bar_index[bl_5], rsi[bl_5], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=lime, size=_size)
//label.delete(not pl ? lb : na)
if div_bull_6 and not div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_6], ll0, bar_index[bl6], ll6, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
//lb = label.new(bar_index[bl_6], rsi[bl_6], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=lime, size=_size)
//label.delete(not pl ? lb : na)
if div_bull_7 and not div_bull_8
ln = line.new(bar_index[bl_7], ll0, bar_index[bl7], ll7, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
//lb = label.new(bar_index[bl_7], rsi[bl_7], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=aqua, size=_size)
//label.delete(not pl ? lb : na)
if div_bull_8
ln = line.new(bar_index[bl_8], ll0, bar_index[bl8], ll8, xloc = xloc.bar_index, extend=extend.none, color=bulldivcol, width = divwidth)
line.delete(not pl ? ln : na)
//lb = label.new(bar_index[bl_8], rsi[bl_8], xloc = xloc.bar_index, yloc=yloc.price, style=_symbl, color=aqua, size=_size)
//label.delete(not pl ? lb : na)
// Bearish Divergences = close HH - RSI LH
if div_bear_1 and not div_bear_2 and not div_bear_3
and not div_bear_4 and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_1], hh0, bar_index[br1], hh1, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
if div_bear_2 and not div_bear_3 and not div_bear_4
and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_2], hh0, bar_index[br2], hh2, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
if div_bear_3 and not div_bear_4 and not div_bear_5
and not div_bear_6 and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_3], hh0, bar_index[br3], hh3, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
if div_bear_4 and not div_bear_5 and not div_bear_6
and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_4], hh0, bar_index[br4], hh4, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
//lb = label.new(bar_index[br_4], rsi[br_4], xloc = xloc.bar_index, yloc=yloc.price, style=levels_style, color=red, size=_size)
//label.delete(not ph ? lb : na)
if div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_5], hh0, bar_index[br5], hh5, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
//lb = label.new(bar_index[br_5], rsi[br_5], xloc = xloc.bar_index, yloc=yloc.price, style=levels_style, color=red, size=_size)
//label.delete(not ph ? lb : na)
if div_bear_6 and not div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_6], hh0, bar_index[br6], hh6, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
//lb = label.new(bar_index[br_6], rsi[br_6], xloc = xloc.bar_index, yloc=yloc.price, style=levels_style, color=red, size=_size)
//label.delete(not ph ? lb : na)
if div_bear_7 and not div_bear_8
ln = line.new(bar_index[br_7], hh0, bar_index[br7], hh7, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
//lb = label.new(bar_index[br_7], rsi[br_7], xloc = xloc.bar_index, yloc=yloc.price, style=levels_style, color=purple, size=_size)
//label.delete(not ph ? lb : na)
if div_bear_8
ln = line.new(bar_index[br_8], hh0, bar_index[br8], hh8, xloc = xloc.bar_index, extend=extend.none, color=beardivcol, width = divwidth)
line.delete(not ph ? ln : na)
//lb = label.new(bar_index[br_8], rsi[br_8], xloc = xloc.bar_index, yloc=yloc.price, style=levels_style, color=purple, size=_size)
//label.delete(not ph ? lb : na)
//End
//TO TEST FOR DIVERGENCES USE BOOL FIELDS: div_bull_1, div_bull_2, div_bear_1, div_bear_2, etc
//TO TEST FOR ANY DIVERGENCE UNCOMMENT THIS CODE and use bull_div or bear_div bools
bull_div = (div_bull_3 and not div_bull_3[1] and not div_bull_4 and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8)
or (div_bull_4 and not div_bull_4[1] and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8)
or (div_bull_5 and not div_bull_5[1] and not div_bull_6 and not div_bull_7 and not div_bull_8)
or (div_bull_6 and not div_bull_6[1] and not div_bull_7 and not div_bull_8)
or (div_bull_7 and not div_bull_7[1] and not div_bull_8)
or (div_bull_8 and not div_bull_8[1])
bull_divsmall = (div_bull_1 and not div_bull_1[1]and not div_bull_2 and not div_bull_3 and not div_bull_4 and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8)
or (div_bull_2 and not div_bull_2[1] and not div_bull_3 and not div_bull_4 and not div_bull_5 and not div_bull_6 and not div_bull_7 and not div_bull_8)
bear_div = (div_bear_3 and not div_bear_3[1] and not div_bear_4 and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8)
or (div_bear_4 and not div_bear_4[1] and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8)
or (div_bear_5 and not div_bear_5[1] and not div_bear_6 and not div_bear_7 and not div_bear_8)
or (div_bear_6 and not div_bear_6[1] and not div_bear_7 and not div_bear_8)
or (div_bear_7 and not div_bear_7[1] and not div_bear_8)
or (div_bear_8 and not div_bear_8[1])
bear_divsmall = (div_bear_1 and not div_bear_1[1] and not div_bear_2 and not div_bear_3 and not div_bear_4 and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8)
or (div_bear_2 and not div_bear_2[1] and not div_bear_3 and not div_bear_4 and not div_bear_5 and not div_bear_6 and not div_bear_7 and not div_bear_8)
// plot large bullish divergence
plotshape(bull_div, title = "Big Bullish Divergence", style=shape.circle, location=location.belowbar, size=size.small, color=color.green, offset = -1)
// plot small bullish divergence
plotshape(bull_divsmall, title= "Small Bullish Divergence", style=shape.circle, location=location.belowbar, size=size.tiny, color=color.green, offset = -1)
// plot large bearish divergence
plotshape(bear_div, title= "Big Bearish Divergence", style=shape.circle, location=location.abovebar, size=size.small, color=color.red, offset = -1)
// plot small bearish divergence
plotshape(bear_divsmall, title= "Small Bearish Divergence", style=shape.circle, location=location.abovebar, size=size.tiny, color=color.red, offset = -1)
alertcondition(bull_div, title="Big Bullish Divergence", message="Big Bullish Divergence detected!")
alertcondition(bull_divsmall, title="Small Bullish Divergence", message="Small Bullish Divergence detected!")
alertcondition(bear_div, title="Big Bearish Divergence", message="Big Bearish Divergence detected!")
alertcondition(bear_divsmall, title="Small Bearish Divergence", message="Small Bearish Divergence detected!") |
Color Changing MACD | https://www.tradingview.com/script/qzC8GJia/ | FX365_Thailand | https://www.tradingview.com/u/FX365_Thailand/ | 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/
// ยฉ FX365_Thailand
//@version=5
//Release note
//v24.0 Released
indicator(title="Color Changing MACD", shorttitle="Color MACD")
//User inputs
fast_length = input(title="Fast Length", defval=12,group="Common")
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="SMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="SMA", options=["SMA", "EMA"])
i_signal = input.bool(true,title="Show GC/DC Signals?")
// Plot colors
col_macd = input(#2962FF, "MACD Lineโโ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Lineโโ", group="Color Settings", inline="Signal")
col_grow_above = input(color.new(color.green,20), "Aboveโโโ
Grow", group="Histogram", inline="Above")
col_fall_above = input(color.new(color.green,80), "Fall", group="Histogram", inline="Above")
col_grow_below = input(color.new(color.red,80), "BelowโGrow", group="Histogram", inline="Below")
col_fall_below = input(color.new(color.red,20), "Fall", group="Histogram", inline="Below")
//Logic
//MACD calculation
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//Determine colors
color_macd = (macd > signal) and (hist > hist[1]) ? color.green : (macd > signal) and (hist < hist[1]) ? #9c27b0 : (macd < signal) and (hist < hist[1]) ? color.red : (macd < signal) and (hist > hist[1]) ? #9c27b0 : na
//Plot
// a=plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
color_bull = color.from_gradient(value=hist, bottom_value = 0,top_value = 0.3 , top_color = color.new(color.green,80), bottom_color = color.new(color.green,20) )
color_bear = color.from_gradient(value=hist, top_value = 0, bottom_value = -100, top_color = color.new(color.red,20), bottom_color = color.new(color.red,80) )
a=plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
b=plot(macd, title="MACD", color=color_macd,display=display.none)
c=plot(signal, title="Signal", color=color_macd,display=display.none)
//Fill
//Condition
bull = macd > signal
bear = macd < signal
color_top = (macd > signal) and (hist > hist[1]) ? color.new(#e1bee7,80) : (macd > signal) and (hist < hist[1]) ? color.new(#9c27b0,80) : (macd < signal) and (hist < hist[1]) ? color.new(color.red,80) : (macd < signal) and (hist > hist[1]) ? color.new(#e1bee7,80) : na
color_bottom = (macd > signal) and (hist > hist[1]) ? color.new(#0ef30e,0) : (macd > signal) and (hist < hist[1]) ? color.new(#9c27b0,0) : (macd < signal) and (hist < hist[1]) ? color.new(color.red,0) : (macd < signal) and (hist > hist[1]) ? color.new(#9c27b0,0) : na
fill(b,c, top_value=macd, bottom_value = signal, top_color = color_top, bottom_color = color_bottom)
//signals
gc = ta.crossover(macd, signal)
dc = ta.crossunder(macd, signal)
//Plot signals
plotshape(i_signal ? gc : na,style= shape.triangleup, color=color.new(color.green,0),title="Golden Cross",location=location.bottom,size=size.tiny)
plotshape(i_signal ? dc : na,style= shape.triangledown, color=color.new(color.red,0),title="Death Cross",location=location.top,size=size.tiny)
//alert conditions
alertcondition(gc, title="Golden Cross", message="Golden Cross Occurred")
alertcondition(dc, title="Death Cross", message="Death Cross Occurred")
|
ICT Donchian Smart Money Structure (Expo) | https://www.tradingview.com/script/rN9I61Q9-ICT-Donchian-Smart-Money-Structure-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 1,718 | 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/
// ยฉ Zeiierman
//@version=5
indicator("ICT Donchian Smart Money Structure",overlay=true,max_bars_back=5000,max_labels_count=500,max_lines_count=500)
// ~~ Tooltips {
string t1 = "Set the pivot period"
string t2 = "Set the response period. A low value returns a short-term structure and a high value returns a long-term structure. If you disable this option the pivot length above will be used."
string t3 = "Enable the Donchian Channel."
string t4 = "A high value returns the long-term structure and a low value returns the short-term structure."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
prd = input.int(20,minval=1,title="Structure Period",tooltip=t1)
s1 = input.bool(true,title="Structure Responseโโ", inline="resp")
resp = input.int(7,minval=1,title="",inline="resp",tooltip=t2)
bull = input.bool(true,"Bullish Structureโโโโโ",inline="Bullish"), bull2 = input.color(color.rgb(8, 236, 126),"",inline="Bullish"), bull3 = input.color(color.rgb(8, 236, 126),"",inline="Bullish")
bear = input.bool(true,"Bearish Structureโโโโ",inline="Bearish"), bear2 = input.color(color.rgb(255, 34, 34),"",inline="Bearish"), bear3 = input.color(color.rgb(255, 34, 34),"",inline="Bearish")
showPD = input.bool(true,"Premium & Discount",inline="pd"), prem = input.color(color.new(color.rgb(255, 34, 34),80),"",inline="pd"), disc = input.color(color.new(color.rgb(8, 236, 126),80),"",inline="pd")
don = input.bool(false,"Donchian Channel", tooltip=t3)
Candle = input.bool(true, "Structure Candles", inline="", group="Structure Candles")
length = input.int(40, minval=1,title="Structure Response", inline="", group="Structure Candles", tooltip=t4)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
b = bar_index
var Up = float(na)
var Dn = float(na)
var iUp = int(na)
var iDn = int(na)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Functions {
//Labels
CreateLabel(x,y,txt,col,z)=>
label.new(x,y,txt,textcolor=col,style=z?label.style_label_down:label.style_label_up,color=color(na))
//Lines
CreateLine(x1,x2,y,col)=>
line.new(x1,x2,b,y,color=col)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Pivots {
Up := math.max(Up[1],high)
Dn := math.min(Dn[1],low)
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
Up := pvtHi
if pvtLo
Dn := pvtLo
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Structure {
var pos = 0
if Up>Up[1]
iUp := b
centerBull = math.round(math.avg(iUp[1],b))
if pos<=0
if bull
CreateLabel(centerBull,Up[1],"CHoCH",bull3,true)
CreateLine(iUp[1],Up[1],Up[1],bull2)
pos := 1
else if pos==1 and Up>Up[1] and Up[1]==Up[s1?resp:prd]
if bull
CreateLabel(centerBull,Up[1],"SMS",bull3,true)
CreateLine(iUp[1],Up[1],Up[1],bull2)
pos := 2
else if pos>1 and Up>Up[1] and Up[1]==Up[s1?resp:prd]
if bull
CreateLabel(centerBull,Up[1],"BMS",bull3,true)
CreateLine(iUp[1],Up[1],Up[1],bull2)
pos := pos + 1
else if Up<Up[1]
iUp := b-prd
if Dn<Dn[1]
iDn := b
centerBear = math.round(math.avg(iDn[1],b))
if pos>=0
if bear
CreateLabel(centerBear,Dn[1],"CHoCH",bear3,false)
CreateLine(iDn[1],Dn[1],Dn[1],bear2)
pos := -1
else if pos==-1 and Dn<Dn[1] and Dn[1]==Dn[s1?resp:prd]
if bear
CreateLabel(centerBear,Dn[1],"SMS",bear3,false)
CreateLine(iDn[1],Dn[1],Dn[1],bear2)
pos := -2
else if pos<-1 and Dn<Dn[1] and Dn[1]==Dn[s1?resp:prd]
if bear
CreateLabel(centerBear,Dn[1],"BMS",bear3,false)
CreateLine(iDn[1],Dn[1],Dn[1],bear2)
pos := pos - 1
else if Dn>Dn[1]
iDn := b-prd
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Premium & Discount {
PremiumTop = Up-(Up-Dn)*.1
PremiumBot = Up-(Up-Dn)*.25
DiscountTop = Dn+(Up-Dn)*.25
DiscountBot = Dn+(Up-Dn)*.1
MidTop = Up-(Up-Dn)*.45
MidBot = Dn+(Up-Dn)*.45
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots {
r1 = plot(don?Up:na,"Range High",bear2)
r2 = plot(don?Dn:na,"Range Low",bull2)
p1 = plot(showPD?PremiumTop:na,"Premium",na)
p2 = plot(showPD?PremiumBot:na,"Premium",na)
d1 = plot(showPD?DiscountTop:na,"Discount",na)
d2 = plot(showPD?DiscountBot:na,"Discount",na)
m1 = plot(showPD?MidTop:na,"Equilibrium",na)
m2 = plot(showPD?MidBot:na,"Equilibrium",na)
fill(p1,p2,color=prem)
fill(d1,d2,color=disc)
fill(m1,m2,color=color.new(color.gray,75))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
DonCandles(high_, low_, close_,src_,factor_,candle_,length_)=>
initial = 0.0
Don_High = ta.highest(high_,length_)
Don_Low = ta.lowest(low_,length_)
Norm = ((close_ - Don_Low) / (Don_High - Don_Low))
initial := candle_?(Norm * close + ((1 - Norm)) * nz(initial[1], close)): (Norm * close + ((1 - Norm*2)) * nz(initial[1], close))
Factor = candle_?(1-Norm)* nz(initial[1], src_) :(factor_? (1-Norm*2):(1-Norm/2)) * nz(initial[1], src_)
output = (Norm * src_) + Factor
// Return Trend Candles
O = Candle?DonCandles(Up,Dn,close,open,true,false,length):na
H = Candle?DonCandles(Up,Dn,close,high,false,false,length):na
L = Candle?DonCandles(Up,Dn,close,low,false,false,length):na
C = Candle?DonCandles(Up,Dn,close,close,true,false,length):na
// Return Color Sign
pricewick(h_,a)=>
cond = h_>a
cond
cond_open = pricewick(H,open)
cond_high = pricewick(H,high)
cond_low = pricewick(H,low)
cond_close = pricewick(H,close)
sign = (cond_open or cond_high or cond_low or cond_close)?color.lime:color.red
// Plot Structure Candles
plotcandle(open, high,low,close, color=Candle?sign:na,bordercolor=Candle?sign:na, wickcolor=Candle?sign:na, title="Structure Candles")
|
Average Variation Bands Oscillator | https://www.tradingview.com/script/ddajUlsd-Average-Variation-Bands-Oscillator/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 175 | 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/
// ยฉ RicardoSantos
//@version=5
indicator('Average Variation Bands Oscillator', 'AVBo', false, timeframe='')
// Inputs:
float src = input.source(close, 'Source Series.')
int ma_length = input.int(100, 'Moving Average Length:')
int dev_length = input.int(100, 'Deviation Moving Average Length:')
bool use_cum_average = input.bool(false, 'Use Cumulative Average?')
float dev1 = input.float(1, 'Band Deviations:', inline='1')
float dev2 = input.float(2, '', inline='1')
float dev3 = input.float(3, '', inline='1')
color col_up = input.color(#f0643c, 'Colors: ', '', '2')
color col_lo = input.color(#3c64f0, '', '', '2')
//
float ma = ta.ema(src, ma_length)
float high_dev = math.max(0.0, high - ma)
float low_dev = ma - math.min(ma, low)
float high_range = use_cum_average ? ta.cum(high_dev) / (bar_index - 1) : ta.ema(high_dev, dev_length)
float low_range = use_cum_average ? ta.cum(low_dev ) / (bar_index - 1) : ta.ema(low_dev , dev_length)
float upper1 = ma + high_range * dev1
float upper2 = ma + high_range * dev2
float upper3 = ma + high_range * dev3
float lower1 = ma - low_range * dev1
float lower2 = ma - low_range * dev2
float lower3 = ma - low_range * dev3
perc (src, upper, lower) => math.max(0.0, math.min(1.0, (src - lower) / (upper - lower))) * 100.0
float osc1 = perc(src, upper1, lower1)
float osc2 = perc(src, upper2, lower2)
float osc3 = perc(src, upper3, lower3)
//
col (p) => color.from_gradient(p, 0.0, 100.0, col_up, col_lo)
plot(series=osc3, title='', color=col(osc3))
plot(series=osc2, title='', color=col(osc2))
plot(series=osc1, title='', color=col(osc1))
hline(100)
hline(080)
hline(050)
hline(020)
hline(000)
|
The Golden Candlestick Pattern | https://www.tradingview.com/script/eaaszMDW-The-Golden-Candlestick-Pattern/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 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/
// ยฉ Sofien-Kaabar
//@version=5
indicator("Candlestick Pattern - Golden Pattern", overlay = true)
golden_difference = 2.618 * (high[2] - low[2])
bullish_pattern = low <= open[1] and close[1] > (golden_difference + low[2]) and close[2] > open[2] and close[1] > open[1]
bearish_pattern = high >= open[1] and close[1] < (high[2] - golden_difference) and close[2] < open[2] and close[1] < open[1]
plotshape(bullish_pattern, style = shape.triangleup, color = color.green, location = location.belowbar, size = size.small)
plotshape(bearish_pattern, style = shape.triangledown, color = color.red, location = location.abovebar, size = size.small) |
Interactive trendline - Proximity Doji & 3LS | https://www.tradingview.com/script/zDUhc8Cl-Interactive-trendline-Proximity-Doji-3LS/ | Marc_Thiart | https://www.tradingview.com/u/Marc_Thiart/ | 136 | 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/
// ยฉ Blockhead305
//@version=5
indicator("Interactive trendline - Proximity Doji & 3LS", overlay = true)
atr_mul = input.int(defval=2, title="ATR muntiplte")
source = input.source(defval=close, title="canlde source in atr zone")
plot_above_below = input.string(defval="below", title="plot above or below", options=["below", "above"])
x_1 = input.time(defval = 1, title = "X 1", confirm = true)
y_1 = input.price(defval = 1, title = "Y 1", confirm = true)
x_2 = input.time(defval = 1, title = "X 2", confirm = true)
y_2 = input.price(defval = 1, title = "Y 2", confirm = true)
run_input = input.int(defval=0, title="run")
extend = input.bool(true, title="extnd trendline")
var int bar_index_x_1_table = 0
var int bar_index_x_2_table = 0
if time == x_1
bar_index_x_1_table := bar_index
if time == x_2
bar_index_x_2_table := bar_index
rise = (math.max(y_1, y_2) - math.min(y_1, y_2))
slope = rise / run_input
var float plot_line = na
var int bar_count = 0
if time == x_1 and barstate.isconfirmed
plot_line := y_1
if time > x_1
if y_2 > y_1
plot_line := plot_line + slope
else
plot_line := plot_line - slope
if time <= x_2
bar_count += 1
if time > x_2 and extend == false
plot_line := na
plot(run_input != 0 ? plot_line : na)
plot(run_input != 0 ? (y_2 < y_1 ? plot_line - ta.atr(10) * atr_mul : plot_line + ta.atr(10) * atr_mul) : na)
if barstate.isconfirmed
var table3 = table.new(position = position.top_right, columns = 30, rows = 30, bgcolor = color.yellow, border_width = 1)
table.cell(table_id = table3, column = 0, row = 1, text = "run")
table.cell(table_id = table3, column = 1, row = 1, text = str.tostring(bar_index_x_2_table - bar_index_x_1_table))
close_in_bear_atr = y_2 > y_1 and source < plot_line + ta.atr(10) * atr_mul
close_in_bull_atr = y_2 < y_1 and source > plot_line - ta.atr(10) * atr_mul
// Inputs
//
// ### 3 Line Strike
//
showBear3LS = input.bool(title='Show Bearish 3 Line Strike', defval=true, group='3 Line Strike', tooltip="The Bearish 3 Line Strike (3LS-Bear) is a candlestick pattern comprised of 3 bullish (green) candles, " +
"followed by a bearish engulfing candle (see 'Big A$$ Candles' below).\n\n" +
"This pattern tends to be best used as a signal of the end of a retracement period as part of a trend continuation strategy.\n\n" +
"Default: Checked")
showBull3LS = input.bool(title='Show Bullish 3 Line Strike', defval=true, group='3 Line Strike', tooltip="The Bullish 3 Line Strike (3LS-Bull) is a candlestick pattern comprised of 3 bearish (red) candles, " +
"followed by a bullish engulfing candle (see 'Big A$$ Candles' below).\n\n" +
"This pattern tends to be best used as a signal of the end of a retracement period as part of a trend continuation strategy.\n\n" +
"Default: Checked")
showMemeChars = input.bool(title="Plot 3 Line Strike meme symbols", defval=false, group="3 Line Strike", tooltip="If disabled (default), standard shapes will be plotted instead, which can then be further customized on the 'Styles' tab of the indicator settings.\n\n" +
"If enabled, meme icons hand-selected by Arty himself (๐ and ๐) will be plotted for 3LS signals instead of the more typical shapes.\n\n" +
"Default: Unchecked")
//
//### Engulfing Candles
//
showBearEngulfing= input.bool(title='Show Bearish Big A$$ Candles', defval=false, group='Big A$$ Candles', tooltip="Bearish 'Big A$$ Candles' are the same as Bearish Engulfing candles.")
showBullEngulfing= input.bool(title='Show Bullish Big A$$ Candles', defval=false, group='Big A$$ Candles', tooltip="Bullish 'Big A$$ Candles' are the same as Bullish Engulfing candles.")
//
//### Alerts
showDominantUpperWick= input.bool(title='Show Dominant upper wick', defval=false, group='Dominant')
showDominantLowerWick= input.bool(title='Show Dominant lower wick', defval=false, group='Dominant')
//
//
// This won't actually DO anything, just popping it to note the behavior of the "Any alert() function call" alert type
void = input.bool(title="The new 'Any alert() function call' (dynamic) alerts will be based on what signals are enabled in the indicator settings.", defval=true, tooltip="This does nothing - it's only here to clarify alert functionality.")
//
// End Inputs ###
// Function definitions...
//
// Derive candle "color". For simplicity, I originally wanted to make this a true/false and have any true doji candles (where open and close are exactly the same)
// either inherit the previous value, or invalidate the setup (which was the original behavior), but that behavior wasn't working as expected. So for now, we're
// going to do a hack and make this a numeric return instead, where...
//
// -1 -> Red/Bearish
// 0 -> Doji
// +1 -> Green/BUllish
//
getCandleColorIndex(barIndex) =>
int ret = na
if (close[barIndex] > open[barIndex])
ret := 1
else if (close[barIndex] < open[barIndex])
ret := -1
else
ret := 0
ret
//
// Check for engulfing candles
isEngulfing(checkBearish) =>
// In an effort to try and make this a bit more consistent, we're going to calculate and compare the candle body sizes
// to inform the engulfing or not decision, and only use the open vs close comparisons to identify the candle "color"
ret = false
sizePrevCandle = close[1] - open[1] // negative numbers = red, positive numbers = green, 0 = doji
sizeCurrentCandle = close - open // negative numbers = red, positive numbers = green, 0 = doji
isCurrentLagerThanPrevious = (math.abs(sizeCurrentCandle) > math.abs(sizePrevCandle)) ? true : false
// We now have the core info to evaluate engulfing candles
switch checkBearish
true =>
// Check for bearish engulfing (green candle followed by a larger red candle)
isGreenToRed = ((getCandleColorIndex(0) < 0) and (getCandleColorIndex(1) > 0)) ? true : false
ret := (isCurrentLagerThanPrevious and isGreenToRed) ? true : false
false =>
// Check for bullish engulfing (red candle followed by a larger green candle)
isRedToGreen = ((getCandleColorIndex(0) > 0) and (getCandleColorIndex(1) < 0)) ? true : false
ret := (isCurrentLagerThanPrevious and isRedToGreen) ? true : false
=> ret := false // This should be impossible to trigger...
ret
//
// Helper functions that wraps the isEngulfing above...
isBearishEngulfuing() =>
ret = isEngulfing(true)
ret
//
isBullishEngulfuing() =>
ret = isEngulfing(false)
ret
//
// Functions to check for 3 consecutive candles of one color, followed by an engulfing candle of the opposite color
//
// Bearish 3LS = 3 green candles immediately followed by a bearish engulfing candle
is3LSBear() =>
ret = false
is3LineSetup = ((getCandleColorIndex(1) > 0) and (getCandleColorIndex(2) > 0) and (getCandleColorIndex(3) > 0)) ? true : false
ret := (is3LineSetup and isBearishEngulfuing()) ? true : false
ret
//
// Bullish 3LS = 3 red candles immediately followed by a bullish engulfing candle
is3LSBull() =>
ret = false
is3LineSetup = ((getCandleColorIndex(1) < 0) and (getCandleColorIndex(2) < 0) and (getCandleColorIndex(3) < 0)) ? true : false
ret := (is3LineSetup and isBullishEngulfuing()) ? true : false
ret
// ### 3 Line Strike
is3LSBearSig = is3LSBear()
is3LSBullSig = is3LSBull()
// Meme plots for the 3LS signal
// close_in_bear_atr = y_2 < y_1 and close > plot_line - ta.atr(10) * atr_mul
// close_in_bull_atr = y_2 > y_1 and close < plot_line + ta.atr(10) * atr_mul
plotchar(close_in_bear_atr and showBull3LS and showMemeChars ? is3LSBullSig : na, char="๐", color=color.rgb(0, 255, 0, 0), location=location.belowbar, size=size.tiny, text='3LS-Bull', title='3 Line Strike Up (Meme Icon)', editable=false)
plotchar(close_in_bull_atr and showBear3LS and showMemeChars ? is3LSBearSig : na, char="๐", color=color.rgb(255, 0, 0, 0), location=location.abovebar, size=size.tiny, text='3LS-Bear', title='3 Line Strike Down (Meme Icon)', editable=false)
//
// Standard plots for the 3LS signal
plotshape(close_in_bear_atr and showBull3LS and not showMemeChars ? is3LSBullSig : na, style=shape.triangleup, color=color.rgb(0, 255, 0, 0), location=location.belowbar, size=size.small, text='3LS-Bull', title='3 Line Strike Up')
plotshape(close_in_bull_atr and showBear3LS and not showMemeChars ? is3LSBearSig : na, style=shape.triangledown, color=color.rgb(255, 0, 0, 0), location=location.abovebar, size=size.small, text='3LS-Bear', title='3 Line Strike Down')
//
// # Alerts
//
// Old-style Alert Conditions
alertcondition(close_in_bear_atr and showBull3LS and is3LSBullSig, title='Bullish 3 Line Strike', message='{{exchange}}:{{ticker}} {{interval}} - Bullish 3 Line Strike')
alertcondition(close_in_bull_atr and showBear3LS and is3LSBearSig, title='Bearish 3 Line Strike', message='{{exchange}}:{{ticker}} {{interval}} - Bearish 3 Line Strike')
//
// New-style alerts
if (close_in_bear_atr and showBull3LS and is3LSBullSig)
m = syminfo.tickerid + ' ' + timeframe.period + ' - Bullish 3 Line Strike'
alert(message=str.tostring(m), freq=alert.freq_once_per_bar_close)
if (close_in_bull_atr and showBear3LS and is3LSBearSig)
m = syminfo.tickerid + ' ' + timeframe.period + ' - Bearish 3 Line Strike'
alert(message=str.tostring(m), freq=alert.freq_once_per_bar_close)
// End ###
//### Engulfing Candles
//If current bar open is less than equal to the previous bar close AND current bar open is less than previous bar open AND current bar close is greater than previous bar open THEN True
isBullEngulfingSig = isBullishEngulfuing()
//If current bar open is greater than equal to previous bar close AND current bar open is greater than previous bar open AND current bar close is less than previous bar open THEN True
isBearEngulfingSig = isBearishEngulfuing()
//bullishEngulfing/isBearEngulfingSig return a value of 1 or 0; if 1 then plot on chart, if 0 then don't plot
plotshape(close_in_bear_atr and showBullEngulfing ? isBullEngulfingSig : na, style=shape.triangleup, location=location.belowbar, color=color.rgb(0, 255, 0, 0), size=size.tiny, title='Big A$$ Candle Up')
plotshape(close_in_bull_atr and showBearEngulfing ? isBearEngulfingSig : na, style=shape.triangledown, location=location.abovebar, color=color.rgb(255, 0, 0, 0), size=size.tiny, title='Big A$$ Candle Down')
// Alerts
//
// Old-style alert conditions...
alertcondition(close_in_bear_atr and showBullEngulfing and isBullEngulfingSig, title='Bullish Engulfing', message='{{exchange}}:{{ticker}} {{interval}} - Bullish candle engulfing previous candle')
alertcondition(close_in_bull_atr and showBearEngulfing and isBearEngulfingSig, title='Bearish Engulfing', message='{{exchange}}:{{ticker}} {{interval}} - Bearish candle engulfing previous candle')
//
// New-style alert() functions
// New-style alerts
if (close_in_bear_atr and showBullEngulfing and isBullEngulfingSig)
m = syminfo.tickerid + ' ' + timeframe.period + ' - Bullish candle engulfing previous candle'
alert(message=str.tostring(m), freq=alert.freq_once_per_bar_close)
if (close_in_bull_atr and showBearEngulfing and isBearEngulfingSig)
m = syminfo.tickerid + ' ' + timeframe.period + ' - Bearish candle engulfing previous candle'
alert(message=str.tostring(m), freq=alert.freq_once_per_bar_close)
// End ###
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////wick candle
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
dominant_wick_multiple = input.float(defval = 2.0, title = "dominant wick multiple", minval = 1.0, maxval = 10.0, step = 0.1, group = "candlestick")
recessive_wick_multiple = input.float(defval = 2.0, title = "recessive wick multiple", minval = 0.1, maxval = 10.0, step = 0.1, group = "candlestick")
body_multiple = input.float(defval = 5.0, title = "body multiple", minval = 0.1, maxval = 10.0, step = 0.1, group = "candlestick")
body = math.abs(close - open)
upper_wick = math.abs(math.max(open, close) - high)
lower_wick = math.abs(math.min(open, close) - low)
ATR_upper_wick = ta.sma(upper_wick, 200)
ATR_lower_wick = ta.sma(lower_wick, 200)
ATR_body = ta.sma(body, 200)
// close_in_bear_atr = y_2 > y_1 and source < plot_line + ta.atr(10) * atr_mul
// close_in_bull_atr = y_2 < y_1 and source > plot_line - ta.atr(10) * atr_mul
upper_wick_dominant = (upper_wick > body) and (upper_wick > (ATR_upper_wick * dominant_wick_multiple)) and (body < (ATR_body * body_multiple)) and (lower_wick < (ATR_lower_wick * recessive_wick_multiple)) and close_in_bull_atr
lower_wick_dominant = (lower_wick > body) and (lower_wick > (ATR_lower_wick * dominant_wick_multiple)) and (body < (ATR_body * body_multiple)) and (upper_wick < (ATR_upper_wick * recessive_wick_multiple)) and close_in_bear_atr
plotshape(upper_wick_dominant, title = "upper wick dominant", location = location.abovebar, text = "S", color = color.red, textcolor = color.red)
plotshape(lower_wick_dominant, title = "lower wick dominant", location = location.belowbar, text = "B", color = color.green, textcolor = color.green)
if showDominantUpperWick and barstate.isconfirmed
alert("Dominant Upper Wick", freq = alert.freq_once_per_bar_close)
if showDominantLowerWick and barstate.isconfirmed
alert("Dominant Lower Wick", freq = alert.freq_once_per_bar_close) |
Cobra's CryptoMarket Visualizer | https://www.tradingview.com/script/DqqCwK2h-Cobra-s-CryptoMarket-Visualizer/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 226 | 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/
// ยฉ EliCobra
//@version=5
indicator("Cobra's Crypto Market Visualizer", "{ษ
} - ๐๐ซ๐ฒ๐ฉ๐ญ๐จ ๐๐ข๐ฌ๐ฎ๐๐ฅ๐ข๐ณ๐๐ซ", true, scale = scale.none)
type asset
string name
float beta
float alpha
float sharpe
float sortino
float omega
float zscore
float athdd
float adr
method copyasset(asset this) =>
asset.new(this.name, this.beta, this.alpha, this.sharpe, this.sortino, this.omega, this.zscore, this.athdd, this.adr)
f_beta(src, base, lookback) =>
float daily_return = src / src[1] - 1
float daily_base_return = base / base[1] - 1
returns_array = array.new_float(0)
returns_base_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
array.push(returns_base_array, daily_base_return[i])
array.covariance(returns_array, returns_base_array) / array.variance(returns_base_array)
f_alpha(src, base, period, lookback) =>
float daily_return = src / src[1] - 1
float daily_base_return = base / base[1] - 1
returns_array = array.new_float(0)
returns_base_array = array.new_float(0)
for i = 0 to period
array.push(returns_array, daily_return[i])
array.push(returns_base_array, daily_base_return[i])
array.sum(returns_array) - array.sum(returns_base_array) * f_beta(src, base, lookback)
f_sharpe(src, lookback) =>
float daily_return = src / src[1] - 1
returns_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
standard_deviation = array.stdev(returns_array)
mean = array.avg(returns_array)
math.round(mean / standard_deviation * math.sqrt(lookback), 2)
f_sortino(src, lookback) =>
float daily_return = src / src[1] - 1
returns_array = array.new_float(0)
negative_returns_array = array.new_float(0)
for i = 0 to lookback
array.push(returns_array, daily_return[i])
if daily_return[i] <= 0.0
array.push(negative_returns_array, daily_return[i])
negative_returns_standard_deviation = array.stdev(negative_returns_array)
mean = array.avg(returns_array)
math.round(mean / negative_returns_standard_deviation * math.sqrt(lookback), 2)
f_omega(src, lookback) =>
float daily_return = src / src[1] - 1
negative_returns_array = array.new_float(0)
positive_returns_array = array.new_float(0)
for i = 0 to lookback
if daily_return[i] <= 0.0
array.push(negative_returns_array, daily_return[i])
else
array.push(positive_returns_array, daily_return[i])
postive_area = array.sum(positive_returns_array)
negative_area = array.sum(negative_returns_array) * (-1)
math.round(postive_area / negative_area, 2)
f_zscore(src, lookback) =>
(src - ta.sma(src, lookback)) / ta.stdev(src, lookback)
f_ath_dd(_src) =>
var ath = 0.0
if _src > ath
ath := _src
_src / ath - 1
f_ADR(lookback) =>
ta.sma(high / low, lookback) - 1
f_calc(coin, src, base, alphaper, adrlen, lookback) =>
asset ass = request.security("BINANCE:" + coin + "USDT.P", timeframe.period,
asset.new(coin, f_beta(src, base, lookback), f_alpha(src, base, alphaper, lookback), f_sharpe(src, lookback),
f_sortino(src, lookback), f_omega(src, lookback), f_zscore(src, lookback), f_ath_dd(src), f_ADR(adrlen)))
ass
f_col(i, y) =>
var color col_dn = #4B0082
var color col_up = #db4d19
x = switch i
2 => y < 1 ? color.from_gradient(y, 0, 1, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 1, 2, color.new(col_up, 90), col_up)
3 => y < 0 ? color.from_gradient(y, -2, 0, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 0, 2, color.new(col_up, 90), col_up)
4 => y < 1 ? color.from_gradient(y, 0, 1, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 1, 2, color.new(col_up, 90), col_up)
5 => y < 1.5 ? color.from_gradient(y, 0, 1.5, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 1.5, 2.5, color.new(col_up, 90), col_up)
6 => y < 1 ? color.from_gradient(y, 0.8, 1, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 1, 1.25, color.new(col_up, 90), col_up)
7 => y < 0 ? color.from_gradient(y, -1.5, 0, col_dn, color.new(col_dn, 90)) : color.from_gradient(y, 0, 1.5, color.new(col_up, 90), col_up)
8 => #000000
9 => #000000
x
f_pos(string position) =>
pos = switch position
"Top Left" => position.top_left
"Middle Left" => position.middle_left
"Bottom Left" => position.bottom_left
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Center" => position.top_center
"Bottom Center" => position.bottom_center
"Center" => position.middle_center
pos
set = input.int(1, "Asset Group", options = [1, 2, 3])
lookback = input.int(365, "Length")
alphaperiod = input.int(30, "Alpha Period")
adrper = input.int(14, "ADR Length")
src = input.source(hlc3, "Source Calculation")
pos_table = input.string("Bottom Right", "Table Position", options = ["Top Left", "Middle Left", "Bottom Left", "Top Right", "Middle Right", "Bottom Right", "Top Center", "Center", "Bottom Center"])
comp = input.bool(false, "Compress Table Size")
split = input.string("No", "Split Mode", options = ["No", "Top Half", "Bottom Half"])
base = request.security("BINANCE:BTCUSDT.P", timeframe.period, src)
// Assets {
var string name1 = switch set
1 => "1000SHIB"
2 => "1INCH"
3 => "AAVE"
var string name2 = switch set
1 => "ACH"
2 => "ADA"
3 => "AGIX"
var string name3 = switch set
1 => "ALGO"
2 => "ALICE"
3 => "ALPHA"
var string name4 = switch set
1 => "ANKR"
2 => "ANT"
3 => "APE"
var string name5 = switch set
1 => "API3"
2 => "APT"
3 => "ARPA"
var string name6 = switch set
1 => "AR"
2 => "ATOM"
3 => "AVAX"
var string name7 = switch set
1 => "AXS"
2 => "BAND"
3 => "BAT"
var string name8 = switch set
1 => "BCH"
2 => "BNB"
3 => "BTC"
var string name9 = switch set
1 => "CFX"
2 => "CHR"
3 => "CHZ"
var string name10 = switch set
1 => "SUI"
2 => "COMP"
3 => "COTI"
var string name11 = switch set
1 => "CRV"
2 => "DOGE"
3 => "DOT"
var string name12 = switch set
1 => "DUSK"
2 => "DYDX"
3 => "EGLD"
var string name13 = switch set
1 => "ENJ"
2 => "ENS"
3 => "ETC"
var string name14 = switch set
1 => "ETH"
2 => "FET"
3 => "FIL"
var string name15 = switch set
1 => "FLM"
2 => "FLOW"
3 => "FOOTBALL"
var string name16 = switch set
1 => "FTM"
2 => "FXS"
3 => "GALA"
var string name17 = switch set
1 => "GAL"
2 => "GMT"
3 => "GMX"
var string name18 = switch set
1 => "GRT"
2 => "HFT"
3 => "HIGH"
var string name19 = switch set
1 => "HOOK"
2 => "ICP"
3 => "IMX"
var string name20 = switch set
1 => "INJ"
2 => "JASMY"
3 => "JOE"
var string name21 = switch set
1 => "KAVA"
2 => "KLAY"
3 => "KNC"
var string name22 = switch set
1 => "KSM"
2 => "LDO"
3 => "LINA"
var string name23 = switch set
1 => "LINK"
2 => "LIT"
3 => "LQTY"
var string name24 = switch set
1 => "LRC"
2 => "LTC"
3 => "MAGIC"
var string name25 = switch set
1 => "MANA"
2 => "MASK"
3 => "MATIC"
var string name26 = switch set
1 => "MINA"
2 => "MTL"
3 => "NEAR"
var string name27 = switch set
1 => "NKN"
2 => "OCEAN"
3 => "OMG"
var string name28 = switch set
1 => "ONE"
2 => "ONT"
3 => "OP"
var string name29 = switch set
1 => "PEOPLE"
2 => "PERP"
3 => "PHB"
var string name30 = switch set
1 => "QNT"
2 => "QTUM"
3 => "RDNT"
var string name31 = switch set
1 => "REEF"
2 => "RNDR"
3 => "ROSE"
var string name32 = switch set
1 => "RSR"
2 => "RUNE"
3 => "RVN"
var string name33 = switch set
1 => "SAND"
2 => "SKL"
3 => "SNX"
var string name34 = switch set
1 => "SOL"
2 => "SSV"
3 => "STG"
var string name35 = switch set
1 => "STORJ"
2 => "STX"
3 => "SUSHI"
var string name36 = switch set
1 => "SXP"
2 => "THETA"
3 => "TLM"
var string name37 = switch set
1 => "BNT"
2 => "TRB"
3 => "TRU"
var string name38 = switch set
1 => "TRX"
2 => "UNFI"
3 => "UNI"
var string name39 = switch set
1 => "WAVES"
2 => "XLM"
3 => "XMR"
var string name40 = switch set
1 => "XRP"
2 => "XTZ"
3 => "ZEC"
// Assets End }
asset1 = f_calc(name1, src, base, alphaperiod, adrper, lookback)
asset2 = f_calc(name2, src, base, alphaperiod, adrper, lookback)
asset3 = f_calc(name3, src, base, alphaperiod, adrper, lookback)
asset4 = f_calc(name4, src, base, alphaperiod, adrper, lookback)
asset5 = f_calc(name5, src, base, alphaperiod, adrper, lookback)
asset6 = f_calc(name6, src, base, alphaperiod, adrper, lookback)
asset7 = f_calc(name7, src, base, alphaperiod, adrper, lookback)
asset8 = f_calc(name8, src, base, alphaperiod, adrper, lookback)
asset9 = f_calc(name9, src, base, alphaperiod, adrper, lookback)
asset10 = f_calc(name10, src, base, alphaperiod, adrper, lookback)
asset11 = f_calc(name11, src, base, alphaperiod, adrper, lookback)
asset12 = f_calc(name12, src, base, alphaperiod, adrper, lookback)
asset13 = f_calc(name13, src, base, alphaperiod, adrper, lookback)
asset14 = f_calc(name14, src, base, alphaperiod, adrper, lookback)
asset15 = f_calc(name15, src, base, alphaperiod, adrper, lookback)
asset16 = f_calc(name16, src, base, alphaperiod, adrper, lookback)
asset17 = f_calc(name17, src, base, alphaperiod, adrper, lookback)
asset18 = f_calc(name18, src, base, alphaperiod, adrper, lookback)
asset19 = f_calc(name19, src, base, alphaperiod, adrper, lookback)
asset20 = f_calc(name20, src, base, alphaperiod, adrper, lookback)
asset21 = f_calc(name21, src, base, alphaperiod, adrper, lookback)
asset22 = f_calc(name22, src, base, alphaperiod, adrper, lookback)
asset23 = f_calc(name23, src, base, alphaperiod, adrper, lookback)
asset24 = f_calc(name24, src, base, alphaperiod, adrper, lookback)
asset25 = f_calc(name25, src, base, alphaperiod, adrper, lookback)
asset26 = f_calc(name26, src, base, alphaperiod, adrper, lookback)
asset27 = f_calc(name27, src, base, alphaperiod, adrper, lookback)
asset28 = f_calc(name28, src, base, alphaperiod, adrper, lookback)
asset29 = f_calc(name29, src, base, alphaperiod, adrper, lookback)
asset30 = f_calc(name30, src, base, alphaperiod, adrper, lookback)
asset31 = f_calc(name31, src, base, alphaperiod, adrper, lookback)
asset32 = f_calc(name32, src, base, alphaperiod, adrper, lookback)
asset33 = f_calc(name33, src, base, alphaperiod, adrper, lookback)
asset34 = f_calc(name34, src, base, alphaperiod, adrper, lookback)
asset35 = f_calc(name35, src, base, alphaperiod, adrper, lookback)
asset36 = f_calc(name36, src, base, alphaperiod, adrper, lookback)
asset37 = f_calc(name37, src, base, alphaperiod, adrper, lookback)
asset38 = f_calc(name38, src, base, alphaperiod, adrper, lookback)
asset39 = f_calc(name39, src, base, alphaperiod, adrper, lookback)
var metric = array.from("", "Asset", "Beta", "Alpha", "Sharpe", "Sortino", "Omega", "Z-Score", "ATH-DD", "ADR")
var tips = array.from("", "", "Beta: Measures how an asset's price moves compared to the overall market.", "Alpha: Measures an investment's excess return compared to its expected return, given its risk.",
"Sharpe Ratio: Evaluates an investment's risk-adjusted return, considering the return per unit of risk taken.", "Sortino Ratio: Evaluates an investment's risk-adjusted return, focusing on downside risk.",
"Omega Ratio: Measures the ratio of average positive returns to average negative returns, assessing reward-to-risk.", "Z-Score: Measures the distance of a data point from the mean in terms of standard deviations.",
"ATH -DD: Current Drawdown from all time high", "Average Daily Range: Represents the average price range an asset moves within during a trading day.")
var table Main = table.new(f_pos(pos_table), 40, 10, border_color = #ffffff80, border_width = 1, frame_color = #ffffff80, frame_width = 1)
table.merge_cells(Main, split == "Bottom Half" ? 18 : 0, 0, split == "Top Half" ? 20 : 39, 0)
if barstate.islast
table.cell(Main, split == "Bottom Half" ? 18 : 0, 0, "๐ ๐พ๐ค๐๐ง๐'๐จ ๐พ๐ง๐ฎ๐ฅ๐ฉ๐ค ๐๐๐ง๐ ๐๐ฉ ๐๐๐จ๐ช๐๐ก๐๐ฏ๐๐ง ๐", text_color = #ffffff, bgcolor = #000000)
for k = 1 to 9
table.cell(Main, split == "Bottom Half" ? 18 : 0, k, array.get(metric, k), text_color = #ffffff, bgcolor = #000000, text_size = size.small, tooltip = array.get(tips, k))
for i = split == "Bottom Half" ? 19 : 1 to split == "Top Half" ? 20 : 39
asset assetbuff = switch i
1 => asset1.copyasset()
2 => asset2.copyasset()
3 => asset3.copyasset()
4 => asset4.copyasset()
5 => asset5.copyasset()
6 => asset6.copyasset()
7 => asset7.copyasset()
8 => asset8.copyasset()
9 => asset9.copyasset()
10 => asset10.copyasset()
11 => asset11.copyasset()
12 => asset12.copyasset()
13 => asset13.copyasset()
14 => asset14.copyasset()
15 => asset15.copyasset()
16 => asset16.copyasset()
17 => asset17.copyasset()
18 => asset18.copyasset()
19 => asset19.copyasset()
20 => asset20.copyasset()
21 => asset21.copyasset()
22 => asset22.copyasset()
23 => asset23.copyasset()
24 => asset24.copyasset()
25 => asset25.copyasset()
26 => asset26.copyasset()
27 => asset27.copyasset()
28 => asset28.copyasset()
29 => asset29.copyasset()
30 => asset30.copyasset()
31 => asset31.copyasset()
32 => asset32.copyasset()
33 => asset33.copyasset()
34 => asset34.copyasset()
35 => asset35.copyasset()
36 => asset36.copyasset()
37 => asset37.copyasset()
38 => asset38.copyasset()
39 => asset39.copyasset()
for j = 1 to 9
name = switch j
1 => assetbuff.name
val = switch j
2 => assetbuff.beta
3 => assetbuff.alpha
4 => assetbuff.sharpe
5 => assetbuff.sortino
6 => assetbuff.omega
7 => assetbuff.zscore
8 => assetbuff.athdd
9 => assetbuff.adr
table.cell(Main, i, j, j == 1 ? name : j > 7 ? str.tostring(math.round(val * 100, j == 8 ? 0 : 2)) + '%' : str.tostring(math.round(val, 2)),
text_color = #ffffff, bgcolor = j > 1 ? f_col(j, val) : #000000, text_size = comp ? size.tiny : size.small)
|
Volatility Speedometer | https://www.tradingview.com/script/WIM5KvCp-Volatility-Speedometer/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 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/
// ยฉ LeafAlgo
//@version=5
indicator("Volatility Speedometer", overlay=false)
lookbackPeriod = input(14, "Lookback Period")
volatilityMeasure = ta.atr(14) // Example: Using Average True Range (ATR) as the volatility measure
// Calculate the rate of change of volatility
volatilityChange = (volatilityMeasure - volatilityMeasure[lookbackPeriod]) / volatilityMeasure[lookbackPeriod] * 100
// Calculate the SMA of the Volatility Change
vcsma = ta.sma(volatilityChange, lookbackPeriod)
// Plotting the Volatility Speedometer histogram and the SMA
plot(volatilityChange, "Volatility Speed", color=color.blue, style=plot.style_histogram, linewidth = 4)
plot(vcsma, 'Volatility Speed Average Line', color=color.maroon, linewidth=4)
// Customizing the color zones based on volatility speed levels
threshold1 = input(1.5, "Threshold 1")
threshold2 = input(3, "Threshold 2")
// Additional color stuff
bgcolor(volatilityChange >= threshold2 ? color.lime : volatilityChange >= threshold1 ? color.yellow : color.fuchsia, transp=80)
barcolor(volatilityChange >= threshold2 ? color.lime : volatilityChange >= threshold1 ? color.yellow : color.fuchsia)
|
Wick Percentages | https://www.tradingview.com/script/hlw4SSBT-Wick-Percentages/ | ozzy_livin | https://www.tradingview.com/u/ozzy_livin/ | 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/
// ยฉ BOTrades
//@version=5
indicator("Wick Percentages", overlay = true)
// Global variable
var position = "Buy"
target = input(50, "Only Show Wick % Greater than")
// Define variables to calculate percentages of the upper wick and the lower wick
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
// Calculate percentages of the upper wick and the lower wick
upperWickPercentage = (upperWick / (high - low)) * 100
lowerWickPercentage = (lowerWick / (high - low)) * 100
// ROund values down to remove decimal
upperWickPercentage1 = math.floor(upperWickPercentage)
lowerWickPercentage1 = math.floor(lowerWickPercentage)
// Print percent of wick โโabove and below each candle
if (upperWickPercentage1 > target or lowerWickPercentage1 > target)
if (upperWickPercentage1 > lowerWickPercentage1)
if (position != "Sell")
label.new(bar_index, high, str.tostring(upperWickPercentage1)+"%", color = color.red, yloc = yloc.abovebar, textcolor = color.white, style=label.style_arrowdown)
position := "Sell"
else
if (position != "Buy")
label.new(bar_index, low, str.tostring(lowerWickPercentage1)+"%", color = color.green, yloc = yloc.belowbar, textcolor = color.white, style=label.style_arrowup)
position := "Buy"
|
Normalized Elastic Volume Oscillator (MTF) | https://www.tradingview.com/script/ws1KUVQW-Normalized-Elastic-Volume-Oscillator-MTF/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 18 | 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/
// ยฉ LeafAlgo
//@version=5
indicator('Normalized Elastic Volume Oscillator (MTF)', shorttitle='MTF N-EVO')
// Input parameters
emaLength = input(14, title='EMA Length')
scalingFactor = input(2.0, title='Scaling Factor')
volumeWeighting = input(true, title='Volume Weighting')
higherTF = input("240", title="Higher Timeframe")
// Calculate volume oscillator
volumeEMA = ta.ema(volume, emaLength)
volumeDeviation = volume - volumeEMA
// Calculate volume oscillator on higher timeframe
higherTFVolumeEMA = request.security(syminfo.tickerid, higherTF, ta.ema(volume, emaLength))
higherTFVolumeDeviation = request.security(syminfo.tickerid, higherTF, volume) - higherTFVolumeEMA
// Dynamic scaling and weighting
scaledVolumeDeviation = volumeDeviation * scalingFactor
weightedVolumeDeviation = volumeWeighting ? scaledVolumeDeviation : volumeDeviation
// Dynamic scaling and weighting on higher timeframe
scaledHigherTFVolumeDeviation = higherTFVolumeDeviation * scalingFactor
weightedHigherTFVolumeDeviation = volumeWeighting ? scaledHigherTFVolumeDeviation : higherTFVolumeDeviation
wvd_h = ta.max(weightedVolumeDeviation)
wvd_l = ta.min(weightedVolumeDeviation)
wvd_n = ((weightedVolumeDeviation - wvd_l) / (wvd_h - wvd_l)) - 0.25
whtf_h = ta.max(weightedHigherTFVolumeDeviation)
whtf_l = ta.min(weightedHigherTFVolumeDeviation)
whtf_n = ((weightedHigherTFVolumeDeviation - whtf_l) / (whtf_h - whtf_l)) - 0.25
// Color line based on positive and negative values
bColor = weightedVolumeDeviation >= 0 ? color.new(color.green, 70) : color.new(color.red, 70)
// Plotting
plot(wvd_n, title='Elastic Volume Oscillator', color=color.fuchsia, linewidth=2)
plot(whtf_n, title="Higher Timeframe Elastic Volume Oscillator", color=color.orange, linewidth=2)
bgcolor(bColor)
|
Open Interest Suite [Aggregated] - By Leviathan | https://www.tradingview.com/script/GKhS3dlt-Open-Interest-Suite-Aggregated-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 1,975 | 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/
// ยฉ LeviathanCapital
//@version=5
indicator("Open Interest Suite [Aggregated] - By Leviathan", format = format.volume)
g1 = 'General'
g2 = 'Thresholds'
g3 = 'Additional Settings'
g5 = 'Screener'
g4 = 'Distribution profile '
g6 = 'Data Sources and Aggregation'
// User inputs - Data Source Settings
maindisp = input.string('Open Interest', 'Display', options = ['Open Interest', 'Open Interest Delta', 'OIฮ x rVOL', 'Open Interest RSI'])
quotecur = input.string('USD', 'Quoted in', options = ['USD', 'COIN'])
upcol = input.color(#d1d4dc, 'Color โโโโโโโโโโโโโโโโฒ', inline = 'udcol')
downcol = input.color(#9598a1f6, 'โผ', inline = 'udcol')
// User inputs - Data Sources
binance = input.bool(true, 'Binance USDT.P_OI', inline = 'src', group = g6)
binance2 = input.bool(true, 'Binance USD.P_OI', inline = 'src', group = g6)
binance3 = input.bool(true, 'Binance BUSD.P_OI', inline = 'src2', group = g6)
bitmex = input.bool(true, 'BitMEX USD.P_OI', inline = 'src2', group = g6)
bitmex2 = input.bool(true, 'BitMEX USDT.P_OIโ', inline = 'src3', group = g6)
kraken = input.bool(true, 'Kraken USD.P_OI', inline = 'src3', group = g6)
// User Inputs - Thresholds
d_mult = input.float(5, 'Threshold Multiplier', step = 0.1, group = g2)
show_loi = input.bool(false, 'Highlight Large OI Increaseโ', inline = 'loi', group = g2)
show_lod = input.bool(false, 'Highlight Large OI Decrease', inline = 'lod', group = g2)
upoicol = input.color(#a5d6a7, '', inline = 'loi', group = g2)
dwoicol = input.color(#fe5f6d, '', inline = 'lod', group = g2)
col_cha = input.bool(false, 'Color Chart Bars', group = g2)
col_bg = input.bool(false, 'Color Background', group = g2)
show_thresh = input.bool(false, 'Show Thresholds', group = g2)
// User Inputs - Additional Settings
show_ema = input.bool(false, 'OI EMA', group = g3, inline = 'ema')
ema_len = input.int(50, '', group = g3, inline = 'ema')
ema_col = input.color(color.gray, '', group = g3, inline = 'ema')
rsi_len = input.int(20, 'OI RSIโโโโโโ', group = g3, inline = 'rsi')
rsi_col = input.color(color.gray, '', inline = 'rsi', group = g3)
// User Inputs - Screener
lookback = input.int(200, 'Lookback (bars)', group = g5)
show_screener = input.bool(false, 'Show Screener', group = g5)
show_OI = input.bool(true, ' โ Open Interest', group = g5)
show_rekt = input.bool(true, ' โ Rekt Longs & Shorts', group = g5)
show_agg = input.bool(true, ' โ Aggressive Longs & Shorts', group = g5)
// User inputs - Profile settings
prof = input.bool (false, 'Generate a profile', group=g4)
vapct = input.float (70, 'Value Area %', minval = 5, maxval = 95, group = g4)
profSize = input.int (2, 'Node Size', minval = 1, group = g4)
rows = input.int (40, 'Rows', minval = 6, maxval = 500, step = 25, group = g4) - 1
vancol = input.color (color.new(color.blue, 75), 'Node Colorsโโโโโโโโโ', group = g4, inline = 'nc')
nvancol = input.color (color.new(color.gray, 75), 'โ', group = g4, inline = 'nc')
poc = input.bool (false, 'POC', group = g4, inline = 'POC'),
poccol = input.color (color.new(color.red, 50), 'โโโโโโโโโโโโ', group = g4, inline = "POC")
val = input.bool (false, 'VA', group = g4, inline = "VA")
vafill = input.color (color.new(color.blue, 95), 'โโโโโโโโโโโโโ', group = g4, inline = 'VA')
//
pc = maindisp=='Open Interest'
pd = maindisp=='Open Interest Delta'
prdv = maindisp=='OIฮ x rVOL'
poir = maindisp=='Open Interest RSI'
ori = 'Left'
// Getting OI data
mex = syminfo.basecurrency=='BTC' ? 'XBT' : string(syminfo.basecurrency)
[oid1, oic1, oio1, oih1, oil1] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USDT.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
[oid2, oic2, oio2, oih2, oil2] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
[oid3, oic3, oio3, oih3, oil3] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'BUSD.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
[oid4, oic4, oio4, oih4, oil4] = request.security('BITMEX' + ":" + mex + 'USD.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
[oid5, oic5, oio5, oih5, oil5] = request.security('BITMEX' + ":" + mex + 'USDT.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
[oid6, oic6, oio6, oih6, oil6] = request.security('KRAKEN' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, [close-close[1], close, open, high, low], ignore_invalid_symbol = true)
deltaOI = (binance ? nz(oid1,0) : 0) + (binance2 ? nz(oid2,0)/close : 0) + (binance3 ? nz(oid3,0) : 0) + (bitmex ? nz(oid4,0)/close : 0) + (bitmex2 ? nz(oid5,0)/close : 0) + (kraken ? nz(oid6,0)/close : 0)
// Thresholds, conditions
p_delta_thresh = ta.sma(deltaOI>0 ? deltaOI : 0, 300) * d_mult
n_delta_thresh = ta.sma(deltaOI<0 ? deltaOI : 0, 300) * d_mult
large_oi_up = deltaOI > p_delta_thresh
large_oi_dw = deltaOI < n_delta_thresh
// OHLC values for plotting candles
O = (binance ? nz(oio1, 0) : 0) + (binance2 ? nz(oio2/close, 0) : 0) + (binance3 ? nz(oio3, 0) : 0) + (bitmex ? nz(oio4/close, 0) : 0) + (bitmex2 ? nz(oio5/close, 0) : 0) + (kraken ? nz(oio6/close, 0) : 0)
H = (binance ? nz(oih1, 0) : 0) + (binance2 ? nz(oih2/close, 0) : 0) + (binance3 ? nz(oih3, 0) : 0) + (bitmex ? nz(oih4/close, 0) : 0) + (bitmex2 ? nz(oih5/close, 0) : 0) + (kraken ? nz(oih6/close, 0) : 0)
L = (binance ? nz(oil1, 0) : 0) + (binance2 ? nz(oil2/close, 0) : 0) + (binance3 ? nz(oil3, 0) : 0) + (bitmex ? nz(oil4/close, 0) : 0) + (bitmex2 ? nz(oil5/close, 0) : 0) + (kraken ? nz(oil6/close, 0) : 0)
C = (binance ? nz(oic1, 0) : 0) + (binance2 ? nz(oic2/close, 0) : 0) + (binance3 ? nz(oic3, 0) : 0) + (bitmex ? nz(oic4/close, 0) : 0) + (bitmex2 ? nz(oic5/close, 0) : 0) + (kraken ? nz(oic6/close, 0) : 0)
O_ = (quotecur=='COIN' ? O : O * close)
H_ = (quotecur=='COIN' ? H : H * close)
L_ = (quotecur=='COIN' ? L : L * close)
C_ = (quotecur=='COIN' ? C : C * close)
// Conditions for coloring
rvol = volume/ta.sma(volume, 20)
if prdv
deltaOI := deltaOI * rvol
pd := true
pccol = C_>O_ ? upcol : downcol
pdcol = deltaOI > 0 ? upcol : downcol
if show_loi and large_oi_up
pccol := upoicol
pdcol := upoicol
if show_lod and large_oi_dw
pccol := dwoicol
pdcol := dwoicol
// Plotting data
plotcandle(pc ? C_[1] : na, pc ? H_ : na, pc ? L_ : na, pc ? C_ : na, color = pccol, wickcolor = pccol, bordercolor = pccol, title = 'Open Interest Candles', editable = false)
plot (pd ? deltaOI : na, style = plot.style_columns, color = pdcol, title = 'Open Interest Delta')
plot (show_ema and pc ? ta.ema(C_, ema_len) : na, color = ema_col, editable = false)
plot (poir ? ta.rsi(C, rsi_len) : na, color = rsi_col, editable = false)
hline (poir ? 30 : na, editable = false)
hline (poir ? 70 : na, editable = false)
hline (poir ? 50 : na, editable = false)
bgcolor (col_bg and show_loi and large_oi_up ? color.new(pdcol, 85) : na, editable = false)
bgcolor (col_bg and show_lod and large_oi_dw ? color.new(pdcol, 85) : na, editable = false)
barcolor (col_cha and show_loi and large_oi_up ? color.new(pdcol, 0) : na, editable = false)
barcolor (col_cha and show_lod and large_oi_dw ? color.new(pdcol, 0) : na, editable = false)
plot (show_thresh ? p_delta_thresh : na, color = color.gray, editable = false)
plot (show_thresh ? n_delta_thresh : na, color = color.gray, editable = false)
// Generating a profile - Code from @KioseffTrading's "Profile Any Indicator" script (used with their permission)
srcp = C_
var int [] timeArray = array.new_int()
var float [] dist = array.new_float()
var int [] x2 = array.new_int(rows + 1, 5)
var vh = matrix.new<float>(1, 1)
array.unshift(timeArray, math.round(time))
if prof and (poir or pc) and time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
matrix.add_col(vh)
matrix.set(vh, 0, matrix.columns(vh) - 1, srcp)
if prof and (poir or pc) and barstate.islast
[pos, n] = switch ori
"Left" => [chart.left_visible_bar_time , array.indexof(timeArray, chart.left_visible_bar_time)]
=> [chart.right_visible_bar_time, array.indexof(timeArray, chart.right_visible_bar_time)]
calc = (matrix.max(vh) - matrix.min(vh)) / (rows + 1)
for i = 0 to rows
array.push(dist, matrix.min(vh) + (i * calc))
for i = 1 to matrix.columns(vh) - 1
for x = 0 to array.size(dist) - 1
if matrix.get(vh, 0, i) >= matrix.get(vh, 0, i - 1)
if array.get(dist, x) >= matrix.get(vh, 0, i - 1) and array.get(dist, x) <= matrix.get(vh, 0, i)
array.set(x2, x, array.get(x2, x) + profSize)
else
if array.get(dist, x) >= matrix.get(vh, 0, i) and array.get(dist, x) <= matrix.get(vh, 0, i - 1)
array.set(x2, x, array.get(x2, x) + profSize)
boc = array.new_box()
for i = 1 to rows
right = array.get(timeArray, n + array.get(x2, i))
if ori == "Left"
switch math.sign(n - array.get(x2, i))
-1 => right := chart.right_visible_bar_time
=> right := array.get(timeArray, n - array.get(x2, i))
array.push(boc, box.new(pos, array.get(dist, i - 1),
right, array.get(dist, i), xloc = xloc.bar_time, border_color =
nvancol, bgcolor = nvancol
))
if i == rows
array.push(boc, box.new(pos, array.get(dist, array.size(dist) - 1),
right, array.get(dist, array.size(dist) - 1) + calc, xloc = xloc.bar_time, border_color =
nvancol, bgcolor = nvancol
))
array.shift(x2), nx = array.indexof(x2, array.max(x2))
nz = nx - 1, nz2 = 0, nz3 = 0, nz4 = 0
for i = 0 to array.size(x2) - 1
if nz > -1 and nx <= array.size(x2) - 1
switch array.get(x2, nx) >= array.get(x2, nz)
true => nz2 += array.get(x2, nx), nx += 1
=> nz2 += array.get(x2, nz), nz -= 1
else if nz <= -1
nz2 += array.get(x2, nx), nx += 1
else if nx >= array.size(x2)
nz2 += array.get(x2, nz), nz -= 1
if nz2 >= array.sum(x2) * (vapct / 100)
nz3 := nx <= array.size(x2) - 1 ? nx : array.size(x2) - 1, nz4 := nz <= -1 ? 0 : nz
break
for i = nz3 to nz4
box.set_border_color(array.get(boc, i), vancol)
box.set_bgcolor(array.get(boc, i), vancol)
if poc
var pocL = line(na)
y = math.avg(box.get_top(array.get(boc, array.indexof(x2, array.max(x2)))), box.get_bottom(array.get(boc, array.indexof(x2, array.max(x2)))))
if na(pocL)
pocL := line.new(chart.left_visible_bar_time, y, chart.right_visible_bar_time, y, xloc = xloc.bar_time, color = poccol, width = 1)
else
line.set_xy1(pocL, chart.left_visible_bar_time, y)
line.set_xy2(pocL, chart.right_visible_bar_time, y)
if val
var vaup = line(na), var vadn = line(na)
ydn = box.get_bottom(array.get(boc, nz3)), yup = box.get_top(array.get(boc, nz4))
if na(vaup)
vadn := line.new(chart.left_visible_bar_time, ydn, chart.right_visible_bar_time, ydn, xloc = xloc.bar_time, color = vancol, width = 1)
vaup := line.new(chart.left_visible_bar_time, yup, chart.right_visible_bar_time, yup, xloc = xloc.bar_time, color = vancol, width = 1)
else
line.set_xy1(vadn, chart.left_visible_bar_time, ydn), line.set_xy2(vadn, chart.right_visible_bar_time, ydn)
line.set_xy1(vaup, chart.left_visible_bar_time, yup), line.set_xy2(vaup, chart.right_visible_bar_time, yup)
linefill.new(vadn, vaup, vafill)
// Screener
if show_screener
table = table.new(position.top_right, 2, 6, color.rgb(120, 123, 134, 82))
float rekt_longs = 0
float rekt_shorts = 0
float aggressive_longs = 0
float aggressive_shorts = 0
for i = 0 to lookback - 1
if large_oi_dw[i] and close[i]<open[i]
rekt_longs := rekt_longs + math.abs(deltaOI[i] * close[i])
if large_oi_dw[i] and close[i]>open[i]
rekt_shorts := rekt_shorts + math.abs(deltaOI[i] * close[i])
if large_oi_up[i] and close[i]>open[i]
aggressive_longs := aggressive_longs + math.abs(deltaOI[i] * close[i])
if large_oi_up[i] and close[i]<open[i]
aggressive_shorts := aggressive_shorts + math.abs(deltaOI[i] * close[i])
if show_OI
table.cell(table, 0, 0, 'Open Interest:', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 1, 0, (quotecur=='COIN' ? (str.tostring(C, format.volume) + ' BTC') : '$' + str.tostring(C*close, format.volume)) + ' ', text_halign = text.align_left, text_color = chart.fg_color)
if show_rekt
table.cell(table, 0, 2, 'Rekt Longs:', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 0, 3, 'Rekt Shorts:', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 1, 2, '$' + str.tostring(rekt_longs, format.volume) + ' ', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 1, 3, '$' + str.tostring(rekt_shorts, format.volume) + ' ', text_halign = text.align_left, text_color = chart.fg_color)
if show_agg
table.cell(table, 0, 4, 'Aggressive Longs:', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 0, 5, 'Aggressive Shorts:', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 1, 4, '$' + str.tostring(aggressive_longs, format.volume) + ' ', text_halign = text.align_left, text_color = chart.fg_color)
table.cell(table, 1, 5, '$' + str.tostring(aggressive_shorts, format.volume) + ' ', text_halign = text.align_left, text_color = chart.fg_color) |
ICT Commitment of Tradersยฐ by toodegrees | https://www.tradingview.com/script/Lj34Vxpq-ICT-Commitment-of-Traders-by-toodegrees/ | toodegrees | https://www.tradingview.com/u/toodegrees/ | 1,561 | 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/
// ยฉ toodegrees
import TradingView/LibraryCOT/2 as cot
//@version=5
indicator("ICT Commitment of Traders"
, "COTยฐ"
, format=format.volume
, max_bars_back=5000
, max_boxes_count=10
, max_lines_count=10)
if timeframe.in_seconds(timeframe.period) < timeframe.in_seconds("D")
runtime.error("Go to the Daily Timeframe or higher to see COT Data!")
//#region[Global]
noColor = color.new(color.white, 100)
_month = month(time, "America/New_York")
_year = year(time, "America/New_York")
_day = dayofmonth(time, "America/New_York")
start3M = timestamp(_month < 4? _year-1 : _year, _month <= 3 ? 9+_month : _month-3, _day, hour, minute, second)
start6M = timestamp(_month < 7? _year-1 : _year, _month <= 6 ? 6+_month : _month-6, _day, hour, minute, second)
start1Y = timestamp(_year-1 , _month , _day, hour, minute, second)
start2Y = timestamp(_year-2 , _month , _day, hour, minute, second)
start3Y = timestamp(_year-3 , _month , _day, hour, minute, second)
boxLoc(string _loc) =>
loc = switch _loc
"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
loc
size(string _size) =>
size = switch _size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
size
//#endregion
//#region[User Inputs]
// COT Data
lookBack_Title_UI = "COT Hedge Program โ โ โ โ โ โ โ โ โ โ โ โ โ"
lookBack = input.string("6 Months" , title=lookBack_Title_UI , group="COT Data", options=['3 Months', '6 Months', '12 Months', '2 Years', '3 Years', 'Custom'], inline='cot')
optionData = input.bool(false , title="Include Options Data?", group="COT Data", inline='cot')
_userStart = input.time(timestamp('01-01-2100'), title='Custom COT Look Back' , group="COT Data")
// COT Data (style)
showCOT = input.bool(true , title="Show COT Data?" , group="COT Data (style)")
colorCS = input.color(color.new(#c82f3b, 0) , title="Comm. Spec. Net Position", group="COT Data (style)")
zeroMC = input.color(color.new(#787B86, 0) , title="Main Zero Line" , group="COT Data (style)")
zeroHC = input.color(color.new(#000000, 0) , title="Hedge Zero Line" , group="COT Data (style)")
shortHC = input.color(color.new(#880e4f, 90), title="Hedge Sell Area" , group="COT Data (style)")
longHC = input.color(color.new(#4caf50, 90), title="Hedge Buy Area" , group="COT Data (style)")
// COT Table Info
showTable = input.bool(true , title="Show Info Table?" , group="COT Table Info")
showMult = input.bool(true , title="Show Multi-Market Data?", group="COT Table Info", tooltip='Follow the instructions in the code to enable this feature!')
colorBuy = input.color(#000000 , title="Buy Text Color" , group="COT Table Info")
colorSell = input.color(#000000 , title="Sell Text Color" , group="COT Table Info")
highlight = input.color(color.new(#b2b5be, 0), title="Highlight Color" , group="COT Table Info")
// COT Table Info (style)
_y_Title_UI = " โ โ โ โ โ โ โ โLocation โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ"
_x_Title_UI = " โ โ โ โ"
tableSize_Title_UI = " โ โ โ โ โ โ โTable Size"
bgcolorTI_Title_UI = " โ โ โ โ โ โBackground"
txcolorTI_Title_UI = " โ โ โ โ โ โ โ โ โ โ โ โText"
_y = input.string("Middle" , title=_y_Title_UI , group="COT Table Info (style)", options=["Top","Middle","Bottom"], inline='xy')
_x = input.string("Right" , title=_x_Title_UI , group="COT Table Info (style)", options=["Left","Center","Right"], inline='xy')
tableSize = size(input.string("Small" , title=tableSize_Title_UI, group="COT Table Info (style)", options=['Tiny', 'Small', 'Normal', 'Large', 'Huge']))
bgcolorTI = input.color(color.new(#d1d4dc, 0), title=bgcolorTI_Title_UI, group="COT Table Info (style)")
txcolorTI = input.color(color.new(#000000, 0), title=txcolorTI_Title_UI, group="COT Table Info (style)")
//#endregion
//#region[Commitment Of Traders Data]
// Current Symbol
c_cftcCode = cot.convertRootToCOTCode("Auto")
c_CommSpec = request.security(cot.COTTickerid("Legacy", c_cftcCode, optionData, "Commercial Positions", "Long" , "All"), "D", close, ignore_invalid_symbol=true) -
request.security(cot.COTTickerid("Legacy", c_cftcCode, optionData, "Commercial Positions", "Short", "All"), "D", close, ignore_invalid_symbol=true)
label = syminfo.root != syminfo.ticker and cot.rootToCFTCCode(syminfo.root) != "" ? syminfo.root :
(cot.currencyToCFTCCode(syminfo.basecurrency) != "" ? syminfo.basecurrency :
(cot.currencyToCFTCCode(syminfo.currency) != "" ? syminfo.currency : ""))
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\ How do I display multiple markets' COT Data? //\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\ Use the Find tool (ctrl+F / cmmd+F) and replace "//| " with "" (omit the "") //\\
//\\ After you have done that, choose and add the appropriate function to Lines 121, 127, and 133 //\\
//\\ See box below to learn which function is best to use //\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\ What function do I choose? //\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\ FUTURES CONTRACT: cot.rootToCFTCCode("") ~ I.E. rootToCFTCCode("NQ") for Nasdaq E-Mini Futures //\\
//\\ FOREX OR DXY: cot.currencyToCFTCCode("") ~ I.E. rootToCFTCCode("EUR") for EURUSD Forex Pair //\\
//\\ //\\
//\\ For DXY you must use "USD": cot.currencyToCFTCCode("USD") //\\
//\\----------------------------------------------------------------------------------------------------//\\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// Symbol 1
//| s1_root = "NQ"
//| s1_cftcCode = (s1_root) //cot.rootToCFTCCode(s1_root)
//| s1_CommSpec = request.security(cot.COTTickerid("Legacy", s1_cftcCode, optionData, "Commercial Positions", "Long" , "All"), "D", close, ignore_invalid_symbol=true) -
//| request.security(cot.COTTickerid("Legacy", s1_cftcCode, optionData, "Commercial Positions", "Short", "All"), "D", close, ignore_invalid_symbol=true)
// Symbol 2
//| s2_root = "YM"
//| s2_cftcCode = (s2_root) //cot.rootToCFTCCode(s2_root)
//| s2_CommSpec = request.security(cot.COTTickerid("Legacy", s2_cftcCode, optionData, "Commercial Positions", "Long" , "All"), "D", close, ignore_invalid_symbol=true) -
//| request.security(cot.COTTickerid("Legacy", s2_cftcCode, optionData, "Commercial Positions", "Short", "All"), "D", close, ignore_invalid_symbol=true)
// Symbol 3
//| s3_root = "USD"
//| s3_cftcCode = (s3_root) //cot.currencyToCFTCCode(s3_root)
//| s3_CommSpec = request.security(cot.COTTickerid("Legacy", s3_cftcCode, optionData, "Commercial Positions", "Long" , "All"), "D", close, ignore_invalid_symbol=true) -
//| request.security(cot.COTTickerid("Legacy", s3_cftcCode, optionData, "Commercial Positions", "Short", "All"), "D", close, ignore_invalid_symbol=true)
if barstate.islastconfirmedhistory
if na(c_CommSpec)
runtime.error("Could not find relevant COT data for: " + syminfo.root)
//| else if (na(s1_CommSpec) or na(s2_CommSpec)or na(s3_CommSpec))
//| runtime.error("Could not find relevant COT data for: " + (na(s1_CommSpec) ? s1_root : (na(s2_CommSpec) ? s2_root : s3_root)))
//#endregion
//#region[Functions]
ict_COT(float COT, int init, bool show=false) =>
float _high = na
float _low = na
for i=0 to bar_index
if time[i] < init
break
else
if COT[i] > _high or na(_high)
_high := COT[i]
if COT[i] < _low or na(_low)
_low := COT[i]
_z = math.avg(_high,_low)
var line z = na, var box prem = na, var box disc = na
line.delete(z), box.delete(prem), box.delete(disc)
if show and showCOT
z := line.new(init, _z , time, _z , xloc=xloc.bar_time, color=zeroHC)
prem := box.new(init, _high, time, _z , xloc=xloc.bar_time, border_color=noColor, bgcolor=longHC)
disc := box.new(init, _z , time, _low, xloc=xloc.bar_time, border_color=noColor, bgcolor=shortHC)
_z
ict_COT_Market(float COT, int init, bool show) =>
three_months = ict_COT(COT, start3M)
six_months = ict_COT(COT, start6M)
twelve_months = ict_COT(COT, start1Y)
two_years = ict_COT(COT, start2Y)
three_years = ict_COT(COT, start3Y)
user_input = ict_COT(COT, init, show)
[three_months, six_months, twelve_months, two_years, three_years, user_input]
tableInit(table tbl) =>
table.cell(tbl, 0, 0, 'Marketยฐ' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=bgcolorTI , text_font_family=font.family_monospace)
table.cell(tbl, 1, 0, 'Main-Program', 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=bgcolorTI , text_font_family=font.family_monospace)
table.cell(tbl, 2, 0, '3-Month' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='3 Months' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 3, 0, '6-Month' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='6 Months' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 4, 0, '12-Month' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='12 Months'?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 5, 0, '2-Year' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='2 Years' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 6, 0, '3-Year' , 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='3 Years' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
if lookBack=='Custom'
table.cell(tbl, 7, 0, 'Custom-Range', 0, 0, txcolorTI, "center", text_size=tableSize, bgcolor=lookBack=='Custom'?highlight:bgcolorTI, text_font_family=font.family_monospace)
tableEntry(table tbl, string mrkt, int row, float COT, float v1, float v2, float v3, float v4, float v5, float v6, int init) =>
table.cell(tbl, 0, row, mrkt , 0, 0, txcolorTI , "center", text_size=tableSize, bgcolor=bgcolorTI , text_font_family=font.family_monospace)
table.cell(tbl, 1, row, COT>0?'BUY':'SELL' , 0, 0, COT>0?colorBuy:colorSell , "center", text_size=tableSize, bgcolor=bgcolorTI , text_font_family=font.family_monospace)
table.cell(tbl, 2, row, COT>v1?'BUY':'SELL', 0, 0, COT>v1?colorBuy:colorSell, "center", text_size=tableSize, bgcolor=lookBack=='3 Months' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 3, row, COT>v2?'BUY':'SELL', 0, 0, COT>v2?colorBuy:colorSell, "center", text_size=tableSize, bgcolor=lookBack=='6 Months' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 4, row, COT>v3?'BUY':'SELL', 0, 0, COT>v3?colorBuy:colorSell, "center", text_size=tableSize, bgcolor=lookBack=='12 Months'?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 5, row, COT>v4?'BUY':'SELL', 0, 0, COT>v4?colorBuy:colorSell, "center", text_size=tableSize, bgcolor=lookBack=='2 Years' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
table.cell(tbl, 6, row, COT>v5?'BUY':'SELL', 0, 0, COT>v5?colorBuy:colorSell, "center", text_size=tableSize, bgcolor=lookBack=='3 Years' ?highlight:bgcolorTI, text_font_family=font.family_monospace)
if lookBack=='Custom'
txt = COT>v6?'BUY':'SELL'
col = COT>v6?colorBuy:colorSell
table.cell(tbl, 7, row, na(init)?txt:(init>time?"NA":txt), 0, 0, na(init)?col:(init>time?txcolorTI:col), "center", text_size=tableSize, bgcolor=lookBack=='Custom'?highlight:bgcolorTI, text_font_family=font.family_monospace)
//#endregion
//#region[Logic]
// ICT Commitment Of Traders
start = switch lookBack
'3 Months' => start3M
'6 Months' => start6M
'12 Months' => start1Y
'2 Years' => start2Y
'3 Years' => start3Y
'Custom' => _userStart
[c_3M , c_6M , c_1Y , c_2Y , c_3Y , c_UI ] = ict_COT_Market(c_CommSpec , start, true)
//| [s1_3M, s1_6M, s1_1Y, s1_2Y, s1_3Y, s1_UI] = ict_COT_Market(s1_CommSpec, start, false)
//| [s2_3M, s2_6M, s2_1Y, s2_2Y, s2_3Y, s2_UI] = ict_COT_Market(s2_CommSpec, start, false)
//| [s3_3M, s3_6M, s3_1Y, s3_2Y, s3_3Y, s3_UI] = ict_COT_Market(s3_CommSpec, start, false)
//#endregion
//#region[Plot]
// Graph
if showCOT
var zero = line.new(time, 0, time+1, 0, xloc=xloc.bar_time, extend=extend.both, color=zeroMC)
var line _start = na
line.delete(_start)
_start := line.new(start, c_CommSpec-1, start, c_CommSpec+1, xloc=xloc.bar_time, extend=extend.both, color=zeroMC)
data = plot(showCOT ? c_CommSpec : na, title="Comm. Spec. Net Position", color=colorCS)
// Table
loc = boxLoc(_y+"-"+_x)
if barstate.islast and showTable
algo_program = table.new(loc, 8, 20, frame_color=txcolorTI, frame_width=1)
tableInit(algo_program)
// Current Symbol
tableEntry(algo_program, label, 1, c_CommSpec, c_3M, c_6M, c_1Y, c_2Y, c_3Y, c_UI, start)
// Other Markets' Data
//| if showMult
//| tableEntry(algo_program, s1_root, 2, s1_CommSpec, s1_3M, s1_6M, s1_1Y, s1_2Y, s1_3Y, s1_UI, start)
//| tableEntry(algo_program, s2_root, 3, s2_CommSpec, s2_3M, s2_6M, s2_1Y, s2_2Y, s2_3Y, s2_UI, start)
//| tableEntry(algo_program, s3_root, 4, s3_CommSpec, s3_3M, s3_6M, s3_1Y, s3_2Y, s3_3Y, s3_UI, start)
//#endregion |
Directional Volume EStimate from Price Action (RedK D_VESPA) | https://www.tradingview.com/script/HOvl6jPH-Directional-Volume-EStimate-from-Price-Action-RedK-D-VESPA/ | RedKTrader | https://www.tradingview.com/u/RedKTrader/ | 369 | 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/
// ยฉ RedKTrader - May 2023
//@version=5
indicator(title='Directional Volume Estimate from Pirce Action v1.0', shorttitle='RedK D_VESPA v1.0',
format=format.volume, timeframe='', timeframe_gaps=false, explicit_plot_zorder = true)
// Originally this was based on V.Viewer - it estimates and plots average supply & demand volume based on price action
// it uses the shape of a price bar to estimate the supply vs demand split of the traded volume
// & plots a moving average of both, and an estimated Average "Net Volume"
// This provides an insightful way to look at the traded volume compared to the classic volume histogram view
// ---------------------------------
//
// - Supply/Demand calc now includes 2-bar gaps (improved algo)
// - Add option for MA type for calculation
// - Add option to show Net Volume as 3-color bars
// - Visual simplification and improvements to be less distracting & more actionable
// - options to display/hide main visuals while maintaining the status line consistency (Avg Supply, Avg Demand, Avg Net)
// - add alerts for NetVol moving into Buy (crosses 0 up) or Sell (crosses 0 down) modes
// - implement a "sentiment" timeframe - options 1W, 1D, 1H
// using request.scurity() calls to bring in the data from the HTF and pass to the Calc_VESPA function
// ==============================================================================================
GetAverage(_data, _len, MAOption) =>
value = switch MAOption
'SMA' => ta.sma(_data, _len)
'EMA' => ta.ema(_data, _len)
'RMA' => ta.rma(_data, _len)
=>
ta.wma(_data, _len)
// &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Calc_VESPA(bool VolumeOn, bool GapsOn) =>
// *********************************************************************************************************************
// Extrapolate avg estimated Buy & Sell volume per bar
// How the updated buy/sell average estimated volume algo works:
// buy volume is assoicated with price up-moves, sell volume is associated with price down-moves
// so each of the bulls and bears will get the equivalent of the top & bottom wicks,
// for up bars, bulls get the value of the "body", else the bears get the "body"
// open gaps are allocated to bulls or bears depending on the gap direction (if the option is selected)
// if there's no volume, then this will just reflect the price action split between buyers/sellers
// *********************************************************************************************************************
o = open
c = close
h = high
l = low
v = na(volume) or not VolumeOn ? 1 : volume
gap = o - c[1]
bull_gap = math.max(gap, 0)
bear_gap = math.abs(math.min(gap, 0))
body = math.abs(c - o)
BarRange = h - l
wick = BarRange - body
up_bar = c > o
bull = wick + (up_bar ? body : 0) + (GapsOn ? bull_gap : 0)
bear = wick + (up_bar ? 0 : body) + (GapsOn ? bear_gap : 0)
ViRange = bull + bear
// Rare cases with very low TF's (mainly FOREX) where no price movement occurs, ViRange (including gaps) = 0
BScore = ViRange > 0 ? bull / ViRange : 0.5
BuyVol = BScore * v
SellVol = v - BuyVol
// Return Estimated Buy & Sell Volume values
[BuyVol, SellVol]
// *********************************************************************************************************************
// inputs
// *********************************************************************************************************************
length = input.int(title='Volume Length', defval=16, minval=1)
AvgType = input.string("WMA", "Average type", options = ['SMA', 'EMA', 'RMA', 'WMA'])
smooth = input.int(title='Smoothing', defval=8, minval=1)
VolumeWeighted = input.bool(true, "Volume Weighted (Keep on)")
GapImpact = input.bool(true, "2-bar Gap Impact (Keep on)")
ShowNetVolBars = input.bool(true, "Show NetVol Bars")
ShowNetVolHisto = input.bool(true, "Show NetVol Histogram")
// *********************************************************************************************************************
// variables
// *********************************************************************************************************************
// Calculate estimated Buy & Sell colume
[B_BuyVol, B_SellVol] = Calc_VESPA(VolumeWeighted, GapImpact)
// Calc average Buy & Sell vol and NetVol from estimate
demand = ta.wma(GetAverage(B_BuyVol, length, AvgType), smooth)
supply = ta.wma(GetAverage(B_SellVol, length, AvgType), smooth)
NetVol = demand - supply
// *********************************************************************************************************************
// Plots -- classic volume bars have been removed
// *********************************************************************************************************************
col_red = color.new(#ff0000, 00)
col_green = color.new(#00ff00, 00)
col_hist_red = color.new(#ef5350, 25)
col_hist_green = color.new(#089981, 25)
col_gold = color.new(#ffeb3b, 20)
//plot(v, title='Volume', style=plot.style_columns, color=up_bar ? col_green : col_red, display=display.none)
// ======================================================================================================================
// NetVol Bars Plot
// ======================================================================================================================
nvo = fixnan(supply) // fixes NaN values - observed mainly on Renko
nvc = fixnan(demand)
nvh = math.max(nvo, nvc)
nvl = math.min(nvo, nvc)
rising = ta.change(NetVol) > 0
c_barup = color.new(#11ff20, 60)
c_bardn = color.new(#ff1111, 60)
c_bardj = color.new(#ffffff, 50)
c_barupb = color.new(#1b5e20, 50)
c_bardnb = color.new(#981919, 50)
c_bardjb = color.new(#9598a1, 50)
barcolor = nvc > nvo and rising ? c_barup : nvc < nvo and not rising ? c_bardn : c_bardj
borcolor = nvc > nvo and rising ? c_barupb : nvc < nvo and not rising ? c_bardnb : c_bardjb
plotcandle(nvo, nvh, nvl, nvc, 'NetVol Bars', barcolor, barcolor, bordercolor = borcolor,
display = ShowNetVolBars ? display.pane : display.none)
hline(0, title='zero line', linestyle=hline.style_dotted, color=col_gold,
display = ShowNetVolHisto ? display.all : display.none) //hides with histogram
plot(supply, title='Supply', color=col_red, linewidth=2)
plot(demand, title='Demand', color=col_green, linewidth=2)
// ======================================================================================================================
// Net Volume Histogram Plot
// ======================================================================================================================
c_NetVol = NetVol >= 0 ? col_hist_green : col_hist_red
plot(NetVol, title='NetVol Histogram', style=plot.style_columns, color = c_NetVol, linewidth = 4,
display = ShowNetVolHisto ? display.all : display.status_line + display.data_window)
// ======================================================================================================================
// Secondary TF Average Net Volume Plot
// ======================================================================================================================
S_gp = "Secondary TF"
ShowS_NetVol = input.bool(false, 'Show Secondary', group = S_gp, inline = "Senti_TF") // STF plot hidden by default
i_STF = input.string("Chart", 'TF', options = ['Chart', '1Wk', '1Day' , '1Hr'], group = S_gp, inline = "Senti_TF")
S_length = input.int(12, "Length", minval = 1, group = S_gp, inline = "Senti_L")
S_smooth = input.int(4, "Smooth", minval = 1, group = S_gp, inline = "Senti_L")
STF = switch i_STF
'1Wk' => 'W'
'1Day' => 'D'
'1Hr' => '60'
=>
timeframe.period
// Error trap here if selected secondary TF is lower than chart
float chartTF_Mins = timeframe.in_seconds() / 60
float i_STF_Mins = timeframe.in_seconds(STF) / 60
if chartTF_Mins > i_STF_Mins and ShowS_NetVol
runtime.error("Secondary timeframe must be equal to, or higher than, the chart's timeframe.")
[S_BuyVol, S_SellVol] = request.security(syminfo.tickerid, STF, Calc_VESPA(VolumeWeighted, GapImpact) )
S_demand = request.security(syminfo.tickerid, STF, ta.wma(GetAverage(S_BuyVol, S_length, AvgType), S_smooth))
S_supply = request.security(syminfo.tickerid, STF, ta.wma(GetAverage(S_SellVol, S_length, AvgType), S_smooth))
S_NetVol = S_demand - S_supply
c_S_NetVol = S_NetVol >= 0 ? color.aqua : color.orange
plot(S_NetVol, title='Secondary TF NetVol', color = c_S_NetVol, linewidth = 2,
display = ShowS_NetVol ? display.all : display.data_window)
// plot(S_supply, color = color.red)
// plot(S_demand, color = color.green)
// ======================================================================================================================
// Alerts
// ======================================================================================================================
// Primary TF Alerts
Al_NetVol_up = ta.crossover(NetVol, 0)
Al_NetVol_dn = ta.crossunder(NetVol, 0)
Al_NetVol_swing = Al_NetVol_up or Al_NetVol_dn
alertcondition(Al_NetVol_up, "A1. Avg NetVol Crossing 0 Up", "Avg NetVol Positive - Bullish Mode Detected!")
alertcondition(Al_NetVol_dn, "A2. Avg NetVol Crossing 0 Down", "Avg NetVol Negative - Bearish Mode Detected!")
alertcondition(Al_NetVol_swing, "A3. Avg NetVol Crossing 0", "Avg NetVol Swing - Possible Mode Reversal Detected!")
// Secondary TF Alerts
Al_SNetVol_up = ta.crossover(S_NetVol, 0)
Al_SNetVol_dn = ta.crossunder(S_NetVol, 0)
Al_SNetVol_swing = Al_SNetVol_up or Al_SNetVol_dn
alertcondition(Al_SNetVol_up, "B1. STF Avg NetVol Crossing 0 Up", "Secondary TF Avg NetVol Positive - Bullish Mode Detected!")
alertcondition(Al_SNetVol_dn, "B2. STF Avg NetVol Crossing 0 Down", "Secondary TF Avg NetVol Negative - Bearish Mode Detected!")
alertcondition(Al_SNetVol_swing, "B3. STF Avg NetVol Crossing 0", "Secondary TF Avg NetVol Swing - Possible Mode Reversal Detected!") |
Master Supertrend [Trendoscope] | https://www.tradingview.com/script/vHpsE0Ft-Master-Supertrend-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 617 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ Trendoscope Pty Ltd
// โโ
// โโโ โโ
// โโโโโ โโ
// โโโโโโโโ โ โโ
// โโโโโโ โ โโ
// โโโโ โ โโโโโโโโโโโ
// โโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโ
// โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโ โโ
// โโโโโ โโโโโโโ
// โโโโโโโโโ
// โโโโโ โโโโโ
// โโโโโ โโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ
// โโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโ
// โโโโโ โโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโ โโโโโโ
// โโโโโ โโโโโ โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ
// โโ โ
//
//@version=5
indicator("Master Supertrend [Trendoscope]", "MST [Trendoscope]", overlay = true)
import HeWhoMustNotBeNamed/ta/1 as eta
import HeWhoMustNotBeNamed/arrayutils/22 as pa
supertrendType = input.string('Plus/Minus Range', 'Range Type', ['Plus/Minus Range', 'Ladder TR', 'True Range', 'Standard Deviation'], 'Type of range used for supertrend calculation')
rangeType = input.string('high', 'Applied Calculation', ['sma', 'ema', 'hma', 'rma', 'wma', 'high', 'median', 'medianHigh', 'medianLow'], 'Applied calculation method on the range before using them for calculation of supertrend stops')
length = input.int(20, 'Length', 10, 1000, 10, tooltip = 'Supertrend range calculation length')
multiplier = input.int(4, 'Multiplier', 2, 100, 1, tooltip='Supertrend range multiplier')
useClosePrices = input.bool(true, 'Use Close Price', tooltip = 'Use close price as reference instad of high/low for calculation of stop')
waitForClose = input.bool(true, 'Wait for Close', tooltip = 'Wait for close before changing the direction and change direction only if close price has breached the stop line')
useDiminishingRange = input.bool(true, 'Diminishing Stop Distance', tooltip = 'When selected stop distance from reference price can only decrease and not increase')
float ladderPositiveAtr = na
float ladderNegativeAtr = na
if(supertrendType == 'Ladder TR')
var plusLadderAtr = array.new<float>()
var minusLadderAtr = array.new<float>()
if(open < close)
pa.push(plusLadderAtr, ta.tr, length)
else
pa.push(minusLadderAtr, ta.tr, length)
ladderPositiveAtr := pa.ma(plusLadderAtr, rangeType, length)
ladderNegativeAtr := pa.ma(minusLadderAtr, rangeType, length)
plusRange = supertrendType == 'Plus/Minus Range' ? math.max(high-open, high-close[1]) : supertrendType == 'Ladder TR'? ladderPositiveAtr : supertrendType == 'True Range' ? ta.tr : ta.stdev(close, length, true)
minusRange = supertrendType == 'Plus/Minus Range' ? math.max(open-low, close[1]-low) : supertrendType == 'Ladder TR'? ladderNegativeAtr : supertrendType == 'True Range' ? ta.tr : ta.stdev(close, length, true)
appliedPlusRange = supertrendType == 'Ladder TR'? plusRange : eta.ma(plusRange, rangeType, length)
appliedMinusRange = supertrendType == 'Ladder TR'? minusRange: eta.ma(minusRange, rangeType, length)
var direction = 1
var derivedPlusRange = appliedPlusRange*multiplier
var derivedMinusRange = appliedMinusRange*multiplier
currentDerivedPlusRange = appliedPlusRange*multiplier
derivedPlusRange := direction < 0 and useDiminishingRange? math.min(nz(derivedPlusRange,currentDerivedPlusRange), currentDerivedPlusRange) : currentDerivedPlusRange
currentDerivedMinusRange = appliedMinusRange*multiplier
derivedMinusRange := direction > 0 and useDiminishingRange? math.min(nz(derivedMinusRange,currentDerivedMinusRange), currentDerivedMinusRange) : currentDerivedMinusRange
buyStopCurrent = (useClosePrices? close : low) - derivedMinusRange
var buyStop = buyStopCurrent
sellStopCurrent = (useClosePrices? close : high) + derivedPlusRange
var sellStop = sellStopCurrent
buyStop:= direction > 0? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent) : buyStopCurrent
sellStop:=direction < 0? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent) : sellStopCurrent
direction := direction > 0 and (waitForClose?close:low) < buyStop? -1 :
direction < 0 and (waitForClose?close:high) > sellStop? 1 : direction
supertrend = direction[1] > 0? buyStop : sellStop
plot(supertrend, 'Supertrend', direction[1]>0? color.red:color.green)
alertcondition(ta.crossover(direction, 0), 'Supertrend Bullish Breakout')
alertcondition(ta.crossunder(direction, 0), 'Supertrend Bearish Breakout') |
Cumulative TICK Trend[Pt] | https://www.tradingview.com/script/fgUogo7g-Cumulative-TICK-Trend-Pt/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 220 | 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
//@version=5
indicator(title='Cumulative TICK Trend[Pt]', shorttitle='CumTICK-trend[Pt]', overlay=true)
group_atr = 'ATR EMA Band'
group_display = 'Display'
tick_src = input.string("USI:TICK", "TICK Source", options = ["USI:TICK", "USI:TICKQ", "USI:TICKI", "USI:TICKA"])
candle_src = input.string('Close', 'TICK Data', options = ['Close', 'Open', 'hl2', 'ohlc4', 'hlc3'])
show_ma = input.bool(false, "Apply SMA | length", inline = 'ma')
ma_len = input.int(5, '', inline = 'ma')
show_atr = input.bool(false, 'Show ATR Bands', group = group_atr)
atrPeriod = input.int(10, 'ATR Period', minval=1, group = group_atr)
emaPeriod = input.int(10, 'EMA Period', minval=1, group = group_atr)
atr_src = input(close, 'Source', group = group_atr)
atrMultiplier = input.float(3, 'ATR Multiplier', group = group_atr)
bull_col = input.color(color.green, 'Trend Colors', inline = 'col', group = group_display)
bear_col = input.color(color.red, '', inline = 'col', group = group_display)
smooth_line = input.bool(true, 'Smooth Line', inline = 'smooth', group = group_display)
smooth_ma_len = input.int(5, '| Length', inline = 'smooth', group = group_display)
t1 = time(timeframe.period, "0930-1600:23456", "America/New_York")
//get TICK data
[tickO, tickC, tickHL2, tickOHLC4, tickHLC3] = request.security(tick_src, timeframe.period, [open, close, hl2, ohlc4, hlc3])
cumTICK_src = switch candle_src
'Close' => tickC
'Open' => tickO
'hl2' => tickHL2
'ohlc4' => tickOHLC4
'hlc3' => tickHLC3
// Calculation - Cumulative TICK ----------------------------------
var cumTICK = 0.0
if t1
cumTICK += cumTICK_src
if not t1 or session.islastbar_regular
cumTICK := 0
cumTICK_ma = show_ma ? ta.sma(cumTICK, ma_len) : cumTICK
bull_trend = cumTICK_ma >= 0
bear_trend = cumTICK_ma < 0
// ATR Band ------------------------------------------------------
atr = ta.atr(atrPeriod)
up_ma = ta.ema(atr_src + atr * atrMultiplier,emaPeriod)
down_ma = ta.ema(atr_src - atr * atrMultiplier, emaPeriod)
if smooth_line
up_ma := ta.sma(up_ma, smooth_ma_len)
down_ma := ta.sma(down_ma, smooth_ma_len)
// Plotting
plot(up_ma, 'Upper ATR', color= show_atr ? color.new(bear_col, 70) : na, style = plot.style_linebr)
plot(down_ma, 'Lower ATR', color= show_atr ? color.new(bull_col, 70) : na, style = plot.style_linebr)
plot(up_ma, 'Bear Trend', color= t1 and bear_trend and cumTICK_ma <= cumTICK_ma[1] ? bear_col : na, style = plot.style_linebr, linewidth = 4)
plot(up_ma, 'Bear Trend', color= t1 and bear_trend and cumTICK_ma > cumTICK_ma[1] ? color.new(bear_col,50) : na, style = plot.style_linebr, linewidth = 1)
plot(down_ma, 'Bull Trend', color= t1 and bull_trend and cumTICK_ma >= cumTICK_ma[1] ? bull_col : na, style = plot.style_linebr, linewidth = 4)
plot(down_ma, 'Bull Trend', color= t1 and bull_trend and cumTICK_ma < cumTICK_ma[1] ? color.new(bull_col,50) : na, style = plot.style_linebr, linewidth = 1)
|
Pro Trading Art - Head And Shoulders | https://www.tradingview.com/script/opQmMjpo-Pro-Trading-Art-Head-And-Shoulders/ | protradingart | https://www.tradingview.com/u/protradingart/ | 344 | 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/
// ยฉ protradingart
//@version=5
indicator("Pro Trading Art - Head And Shoulders", "PTA - Head And Shoulders", overlay = true,
max_lines_count=500, max_labels_count=500)
pivotLeg = input.int(10, "Pivot Leg")
isBullish = input.bool(true, "Bullish")
isBearish = input.bool(true, "Bearish")
ph = ta.pivothigh(high, pivotLeg, pivotLeg)
pl = ta.pivotlow(low, pivotLeg, pivotLeg)
var allPH = array.new_float(3)
var allPL = array.new_float(3)
var allPHIndex = array.new_int(3)
var allPLIndex = array.new_int(3)
if not na(ph)
allPH.push(ph)
allPHIndex.push(bar_index[pivotLeg])
allPHIndex.shift()
allPH.shift()
if not na(pl)
allPL.push(pl)
allPLIndex.push(bar_index[pivotLeg])
allPL.shift()
allPLIndex.shift()
drawLine(X1, Y1, X2, Y2, COLOR=color.lime)=>
line.new(X1, Y1, X2, Y2, color=COLOR, width = 2)
drawLabel(X, Y, TEXT, STYLE="UP", COLOR=color.lime)=>
label.new(X, Y, TEXT, color=COLOR,
style=STYLE == "UP" ? label.style_label_up : label.style_label_down,
textcolor = COLOR == color.lime ? color.black : color.white)
//#region ///////////////////// H & S ////////////////////////////////////////////
isRight = allPH.last() > allPL.last() and allPH.last() < allPH.get(1)
isLeft = allPH.first() > allPL.first() and allPH.first() > allPL.get(1)
isHead = allPH.get(1) > allPH.first() and allPH.get(1) > allPH.last()
var line leftA = na
var line leftB = na
var line headA = na
var line headB = na
var line rightA = na
var label leftLabel = na
var label headLabel = na
var label rightLabel = na
isHS = isLeft and
isHead and
isRight and
allPH.last() < allPH.get(1) and
allPH.last() > allPL.last() and
allPHIndex.last() > allPLIndex.last() and
allPH.get(1) > allPH.first() and
allPHIndex.get(1) > allPLIndex.get(1) and
allPH.first() > allPL.first() and
allPHIndex.first() > allPLIndex.first() and
allPHIndex.first() < allPLIndex.get(1) and
allPLIndex.last() > allPHIndex.get(1) and
allPL.last() > allPL.first()
var isHSCreated = false
var neckIndex = 0
var neckPrice = 0.0
var rsIndex = 0
var rsPrice = 0.0
var headPrice = 0.0
if isBearish and isHS and not isHS[1]
isHSCreated := true
neckIndex := allPLIndex.last()
neckPrice := allPL.last()
rsIndex := allPHIndex.last()
rsPrice := allPH.last()
headPrice := allPH.get(1)
leftA := drawLine(allPLIndex.first(), allPL.first(), allPHIndex.first(), allPH.first(), color.red)
leftB := drawLine(allPHIndex.first(), allPH.first(), allPLIndex.get(1), allPL.get(1), color.red)
headA := drawLine(allPLIndex.get(1), allPL.get(1), allPHIndex.get(1), allPH.get(1), color.red)
headB := drawLine(allPHIndex.get(1), allPH.get(1), allPLIndex.get(2), allPL.get(2), color.red)
rightA := drawLine(allPLIndex.get(2), allPL.get(2), allPHIndex.get(2), allPH.get(2), color.red)
leftLabel := drawLabel(allPHIndex.first(), allPH.first(), "Left Shoulder", "DOWN", color.red)
headLabel := drawLabel(allPHIndex.get(1), allPH.get(1), "Head", "DOWN", color.red)
rightLabel := drawLabel(allPHIndex.last(), allPH.last(), "Right Shoulder", "DOWN", color.red)
shortCondition = ta.crossunder(close, neckPrice) and isHSCreated and isBearish
var line HSNeckLineA = na
var line HSNeckLineB = na
plotshape(shortCondition ? high : na, style=shape.labeldown, text="Sell", color=color.red, textcolor = color.white,
size=size.large, location=location.absolute)
if shortCondition
alert("Confirm H & S Sell in : " + syminfo.ticker, alert.freq_once_per_bar_close)
if shortCondition
HSNeckLineA := drawLine(neckIndex, neckPrice, bar_index, neckPrice, color.red)
HSNeckLineA.set_style(line.style_dotted)
HSNeckLineB := drawLine(rsIndex, rsPrice, bar_index, neckPrice, color.red)
HSNeckLineB.set_style(line.style_dotted)
if shortCondition[1] or ta.crossover(close, headPrice)
isHSCreated := false
//#endregion
//#region ///////////////////// Inverted H & S ////////////////////////////////////////////
isIVRight = allPL.last() > allPL.get(1) and allPL.last() < allPH.last()
isIVLeft = allPL.first() < allPH.get(1) and allPL.first() < allPH.first()
isIVHead = allPL.first() > allPL.get(1) and allPL.get(1) < allPL.last()
var line ivLeftA = na
var line ivLeftB = na
var line ivHeadA = na
var line ivHeadB = na
var line ivRightA = na
var line ivRightB = na
var label ivLeftLabel = na
var label ivHeadLabel = na
var label ivRightLabel = na
isIVHS = isIVLeft and
isIVHead and
isIVRight and
(allPH.get(2) > allPL.first()) and
(allPH.last() > allPH.get(1)) and
(allPH.last() < allPH.first()) and
(allPHIndex.first() < allPLIndex.first()) and
(allPLIndex.first() < allPHIndex.get(1)) and
(allPHIndex.get(1) < allPLIndex.get(1)) and
(allPLIndex.last() > allPHIndex.last()) and
(allPHIndex.last() > allPLIndex.get(1)) and
(allPL.last() < allPH.get(1))
var isIVHSCreated = false
var ivRSNeckIndex = 0
var ivRSNeckPrice = 0.0
var ivRSIndex = 0
var ivRSPrice = 0.0
var ivHeadPrice = 0.0
if isBullish and isIVHS and not isIVHS[1]
isIVHSCreated := true
ivRSNeckIndex := allPHIndex.last()
ivRSNeckPrice := allPH.last()
ivRSIndex := allPLIndex.last()
ivRSPrice := allPL.last()
ivHeadPrice := allPL.get(1)
ivLeftA := drawLine(allPHIndex.first(), allPH.first(), allPLIndex.first(), allPL.first())
ivLeftB := drawLine(allPLIndex.first(), allPL.first(), allPHIndex.get(1), allPH.get(1))
ivHeadA := drawLine(allPHIndex.get(1), allPH.get(1), allPLIndex.get(1), allPL.get(1))
ivHeadB := drawLine(allPLIndex.get(1), allPL.get(1), allPHIndex.get(2), allPH.get(2))
ivRightA := drawLine(allPHIndex.get(2), allPH.get(2), allPLIndex.get(2), allPL.get(2))
ivLeftLabel := drawLabel(allPLIndex.first(), allPL.first(), "Left Shoulder")
ivHeadLabel := drawLabel(allPLIndex.get(1), allPL.get(1), "Head")
ivRightLabel := drawLabel(allPLIndex.last(), allPL.last(), "Right Shoulder")
longCondition = ta.crossover(close, ivRSNeckPrice) and isIVHSCreated and isBullish
var line ivHSNeckLineA = na
var line ivHSNeckLineB = na
plotshape(longCondition ? low : na, style=shape.labelup, text="Buy", color=color.lime, textcolor = color.black,
size=size.large, location=location.absolute)
if longCondition
alert("Confirm H & S Buy in : " + syminfo.ticker, alert.freq_once_per_bar_close)
if longCondition
ivHSNeckLineA := drawLine(ivRSNeckIndex, ivRSNeckPrice, bar_index, ivRSNeckPrice)
ivHSNeckLineA.set_style(line.style_dotted)
ivHSNeckLineB := drawLine(ivRSIndex, ivRSPrice, bar_index, ivRSNeckPrice)
ivHSNeckLineB.set_style(line.style_dotted)
if longCondition or ta.crossunder(close, ivHeadPrice)
isIVHSCreated := false
//#endregion
|
High Liquidity Zones and Threshold Volume | https://www.tradingview.com/script/slCXI7fU-High-Liquidity-Zones-and-Threshold-Volume/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 87 | 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/
// ยฉ LeafAlgo
//@version=5
indicator("High Liquidity Zones", overlay=false)
lookbackPeriod = input(20, "Lookback Period")
thresholdPercentage = input(100, "Threshold Percentage")
// Calculate average volume over the lookback period
averageVolume = ta.sma(volume, lookbackPeriod)
// Calculate the threshold volume level
thresholdVolume = averageVolume * (thresholdPercentage / 100)
// Calculate the threshold volume SMA
tvsma = ta.sma(thresholdVolume, lookbackPeriod)
// Identify high liquidity zones
isHighLiquidity = volume > thresholdVolume
hlcolor = isHighLiquidity ? color.lime : color.fuchsia
// Plotting high liquidity zones and threshold volume
plotshape(isHighLiquidity, "High Liquidity", shape.square, location.belowbar, color=color.lime, size=size.small)
plot(thresholdVolume, 'Threshold Volume Histogram', color=hlcolor, style=plot.style_histogram, linewidth=4)
plot(thresholdVolume, 'Threshold Volume Outline', color=color.yellow, linewidth=3)
plot(tvsma, 'Threshold Volume SMA', color=color.maroon, linewidth=3)
// Plotting barcolor
barcolor(hlcolor)
|
MOJO Opening Range Box | https://www.tradingview.com/script/VEyExCFY-MOJO-Opening-Range-Box/ | yoursimplechoice | https://www.tradingview.com/u/yoursimplechoice/ | 30 | 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/
// ยฉ yoursimplechoice
//@version=5
indicator("MOJO Opening Range Box", overlay=true)
InSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTime, sessionTimeZone))
// Define custom session trading times with inputs
sessionTime = input.session("0900-0955", title="Session time")
sessionZone = input.string("GMT-5", title="Session time zone")
// Other inputs for the boxes' visual appearance
boxBorderSize = input.int(2, title="Box border size", minval=0)
upBoxColor = input.color(color.new(color.green, 100), title="Up box")
upBorderColor = input.color(color.green, title="Up border")
downBoxColor = input.color(color.new(color.red, 100), title="Down box")
downBorderColor = input.color(color.red, title="Down border")
// Create variables
var sessionHighPrice = 0.0
var sessionLowPrice = 0.0
var sessionOpenPrice = 0.0
var box sessionBox = na
// See if the session is currently active and just started
inSession = InSession(sessionTime, sessionZone) and timeframe.isintraday
sessionStart = inSession and not inSession[1]
// When a new session starts, set the session high and low to the data
// of the bar in the session.
if sessionStart
sessionHighPrice := high
sessionLowPrice := low
sessionOpenPrice := open
// Else, during the session, track the highest high and lowest low
else if inSession
sessionHighPrice := math.max(sessionHighPrice, high)
sessionLowPrice := math.min(sessionLowPrice, low)
// When a session begins, make a new box for that session
if sessionStart
sessionBox := box.new(left=bar_index, top=na, right=na, bottom=na,
border_width=boxBorderSize)
// During the session, update that session's existing box
if inSession
box.set_top(sessionBox, sessionHighPrice)
box.set_bottom(sessionBox, sessionLowPrice)
box.set_right(sessionBox, bar_index + 1)
// See if bar closed higher than session open. When it did, make
// box green (and use red otherwise).
if close > sessionOpenPrice
box.set_bgcolor(sessionBox, upBoxColor)
box.set_border_color(sessionBox, upBorderColor)
else
box.set_bgcolor(sessionBox, downBoxColor)
box.set_border_color(sessionBox, downBorderColor)
//end range box |
Session Open Price | https://www.tradingview.com/script/A67nVhQA-Session-Open-Price/ | Lilzubski | https://www.tradingview.com/u/Lilzubski/ | 87 | 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/
// ยฉ zubzero
//@version=5
indicator("Session Open Price", "Session Open Price", true, max_lines_count=500)
// New York Open
iMTimey = input.session ('0830-0831:1234567', "Session", group="New York Open")
iMStyley = input.string ("Dashed", "Line Style", options=["Solid", "Dotted", "Dashed"], group="New York Open")
iMColory = input.color (color.new(#ff9800,0), "Color", group="New York Open")
iMLabely = input.bool (true, "Show Label", group="New York Open")
tMidnighty = time ("1", iMTimey)
_MStyley = iMStyley == "Solid" ? line.style_solid : iMStyley == "Dotted" ? line.style_dotted : line.style_dashed
var line lney = na
var openMidnighty = 0.0
if tMidnighty
if not tMidnighty[1]
openMidnighty := open
else
openMidnighty := math.max(open, openMidnighty)
if openMidnighty != openMidnighty[1]
if barstate.isconfirmed
line.set_x2(lney, tMidnighty)
lney := line.new(tMidnighty, openMidnighty, last_bar_time + 14400000/2, openMidnighty, xloc.bar_time, extend.none, iMColory, _MStyley, 1)
// London Open
iMTimel = input.session ('0300-0301:1234567', "Session", group="London Open")
iMStylel = input.string ("Dashed", "Line Style", options=["Solid", "Dotted", "Dashed"], group="London Open")
iMColorl = input.color (color.new(#2196f3,0), "Color", group="London Open")
iMLabell = input.bool (true, "Show Label", group="London Open")
tMidnightl = time ("1", iMTimel)
_MStylel = iMStylel == "Solid" ? line.style_solid : iMStylel == "Dotted" ? line.style_dotted : line.style_dashed
var line lnel = na
var openMidnightl = 0.0
if tMidnightl
if not tMidnightl[1]
openMidnightl := open
else
openMidnightl := math.max(open, openMidnightl)
if openMidnightl != openMidnightl[1]
if barstate.isconfirmed
line.set_x2(lnel, tMidnightl)
lnel := line.new(tMidnightl, openMidnightl, last_bar_time + 14400000/2, openMidnightl, xloc.bar_time, extend.none, iMColorl, _MStylel, 1)
// Frankfurt Open
iMTimef = input.session ('0200-0201:1234567', "Session", group="Frankfurt Open")
iMStylef = input.string ("Dashed", "Line Style", options=["Solid", "Dotted", "Dashed"], group="Frankfurt Open")
iMColorf = input.color (color.new(#25ff00,0), "Color", group="Frankfurt Open")
iMLabelf = input.bool (true, "Show Label", group="Frankfurt Open")
tMidnightf = time ("1", iMTimef)
_MStylef = iMStylef == "Solid" ? line.style_solid : iMStylef == "Dotted" ? line.style_dotted : line.style_dashed
var line lnef = na
var openMidnightf = 0.0
if tMidnightf
if not tMidnightf[1]
openMidnightf := open
else
openMidnightf := math.max(open, openMidnightf)
if openMidnightf != openMidnightf[1]
if barstate.isconfirmed
line.set_x2(lnef, tMidnightf)
lnef := line.new(tMidnightf, openMidnightf, last_bar_time + 14400000/2, openMidnightf, xloc.bar_time, extend.none, iMColorf, _MStylef, 1)
// New York Midnight Open
iMTime = input.session ('0000-0001:1234567', "Session", group="New York Midnight Open")
iMStyle = input.string ("Dashed", "Line Style", options=["Solid", "Dotted", "Dashed"], group="New York Midnight Open")
iMColor = input.color (color.new(#e91e63,0), "Color", group="New York Midnight Open")
iMLabel = input.bool (true, "Show Label", group="New York Midnight Open")
tMidnight = time ("1", iMTime)
_MStyle = iMStyle == "Solid" ? line.style_solid : iMStyle == "Dotted" ? line.style_dotted : line.style_dashed
var line lne = na
var openMidnight = 0.0
if tMidnight
if not tMidnight[1]
openMidnight := open
else
openMidnight := math.max(open, openMidnight)
if openMidnight != openMidnight[1]
if barstate.isconfirmed
line.set_x2(lne, tMidnight)
lne := line.new(tMidnight, openMidnight, last_bar_time + 14400000/2, openMidnight, xloc.bar_time, extend.none, iMColor, _MStyle, 1)
|
CommonTypesDrawing | https://www.tradingview.com/script/JIRKVGo5-CommonTypesDrawing/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 17 | library | 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/
// ยฉ RicardoSantos
//@version=5
// @description Provides a common library source for common types of used graphical drawing structures.
// Includes: `Triangle, Quad, Polygon`
library("CommonTypesDrawing")
//#region ~~~ Drawings interface:
// @type Representation of a triangle using lines and linefill.
// @field ab Edge of point a to b.
// @field bc Edge of point b to c.
// @field ca Edge of point c to a.
// @field fill Fill of the object.
// @field solid Check if polygon should have a fill.
export type Triangle
line ab
line bc
line ca
linefill fill
// option properties:
bool solid = true
// @type Representation of a quadrilateral using lines and linefill.
// @field ab Edge of point a to b.
// @field bc Edge of point b to c.
// @field cd Edge of point c to d.
// @field da Edge of point d to a.
// @field fill Fill of the object.
// @field solid Check if polygon should have a fill.
export type Quad
line ab
line bc
line cd
line da
linefill fill
// option properties:
bool solid = true
// @type Representation of a polygon using lines and linefill.
// @field edges List of edges in the polygon.
// @field fills Fills of the object.
// @field closed Check if polygon line should connect last vertice to first.
// @field solid Check if polygon should have a fill.
export type Polygon
array<line> edges
array<linefill> fills
// graphical properties:
bool closed = true
bool solid = true
//#endregion |
Time Series Model Indicator | https://www.tradingview.com/script/SFQUikqU-Time-Series-Model-Indicator/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 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/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// ยฉ Steversteves
//@version=5
indicator("Time Series Model", overlay=true)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Groups ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Groups
inp = "Inputs"
tab = "Tables"
cors = "Correlation Assessments"
fil = "Fills"
anom = "Outliers"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// User Inputs ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
len = input.int(50, title="Length of Assessment", group = inp)
allowinput = input.bool(false, title="Allow manual calculcations", group=inp)
userinput = input.float(14, title="User input hours in advance", group = inp)
showtable = input.bool(false, title="Show Data Table", group=tab)
timeframe = input.timeframe("", "Timeframe", group=inp)
trendtable = input.bool(false, title="Show Trend Table", group=tab)
displayfills = input.bool(true, title="Display outer band fills?", group=fil)
showoutlier = input.bool(false, title="Show Outlier", group=anom)
showcor = input.bool(false, title="Show Variable Correlations", group=cors)
showinfill = input.bool(true, title="Show Time Series Fill", group=fil)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Slope Calculations ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Get the price data
price = close
// Define the time variable
timea = time
// Compute the slope and intercept of the regression line
n = len
sum_x = ta.sma(timea, n)
sum_y = ta.sma(price, n)
sum_xy = ta.sma(timea * price, n)
sum_x2 = ta.sma(timea * timea, n)
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x)
intercept = (sum_y - slope * sum_x) / n
cor = ta.correlation(time, close, len)
// Compute the regression line
reg_line = slope * timea + intercept
// Compute the residuals
residuals = price - reg_line
// Compute the standard error of the regression
sum_sq_residuals = ta.sma(residuals * residuals, n)
std_error = math.sqrt(sum_sq_residuals / (n - 2))
// Compute the upper and lower bounds of the standard error region
std_error_upper = reg_line + std_error
std_error_lower = reg_line - std_error
divse = std_error / 4
// Extend by SD
sd = ta.stdev(reg_line, 500)
sd1 = reg_line + 1.5 * sd
sd2 = sd1 - (divse * 2)
sd3 = sd2 - (divse * 4)
sd4 = sd3 - (divse * 6)
sd5 = sd4 - (divse * 8)
sd6 = reg_line - 1.5 * sd
sd7 = sd6 + (divse * 2)
sd8 = sd7 + (divse * 4)
sd9 = sd8 + (divse * 6)
sd10 = sd9 + (divse * 8)
er1 = 1.5 * sd
dif = sd1 - sd2
difmax = ta.highest(dif, len)
difmin = ta.lowest(dif, len)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Colours ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
color green = color.new(color.green, 50)
color red = color.new(color.red, 65)
color orange = color.new(color.orange, 85)
color gray = color.new(color.gray, 50)
aquaNavy1 = color.new(color.rgb(0, 128, 128), 75)
aquaNavy2 = color.new(color.rgb(0, 139, 139), 75)
aquaNavy3 = color.new(color.rgb(0, 128, 129), 75)
aquaNavy4 = color.new(color.rgb(0, 130, 140), 75)
aquaNavy5 = color.new(color.rgb(0, 120, 130), 75)
aquaNavy6 = color.new(color.rgb(0, 124, 134), 75)
aquaNavy7 = color.new(color.rgb(0, 125, 136), 75)
aquaNavy8 = color.new(color.rgb(0, 122, 132), 75)
aquaNavy9 = color.new(color.rgb(0, 118, 128), 75)
aquaNavy10 = color.new(color.rgb(0, 116, 126), 75)
aquaNavytable1 = color.new(color.rgb(0, 120, 130), 55)
aquaNavytable2 = color.new(color.rgb(0, 124, 134), 55)
aquaNavytable3 = color.new(color.rgb(0, 125, 136), 55)
shade1 = color.new(color.rgb(200, 220, 255), 85) // Light shade
shade2 = color.new(color.rgb(150, 180, 240), 85) // Medium shade
shade3 = color.new(color.rgb(100, 140, 220), 85) // Dark shade
shade4 = color.rgb(50, 100, 200) // Dark shade
shade5 = color.rgb(20, 60, 160) // Darkest shade
shade6 = color.new(color.rgb(82, 142, 204), 85)
shade7 = color.new(color.rgb(61, 107, 153), 85)
shade8 = color.new(color.rgb(41, 71, 102), 85)
shade9 = color.new(color.rgb(20, 35, 51), 85)
shade10 = color.new(color.rgb(10, 17, 25), 85)
shade11 = color.new(color.rgb(5, 9, 12), 85)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Outliers ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Z for outlier detection
sma = ta.sma(close, len)
zsd = ta.stdev(close, len)
z = (close - sma) / zsd
bool extreme_positive_outlier = z >= 3.0
bool extreme_negative_outlier = z <= -3.0
bgcolor(extreme_positive_outlier ? red : na, display = showoutlier ? display.all : display.none)
bgcolor(extreme_negative_outlier ? red : na, display = showoutlier ? display.all : display.none)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Assessments ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Assessments
bool uptrend = cor >= 0.5 and cor[5] >= 0.5
bool downtrend = cor <= -0.5 and cor[5] <= -0.5
falling = ta.falling(reg_line, 3)
rising = ta.rising(reg_line, 3)
color sent = uptrend ? green : downtrend ? red : gray
color reg_line_col = rising ? color.green : falling ? color.red : color.gray
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Outerband Plots ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
plot(reg_line, color=reg_line_col, title="Regression Line", linewidth=4)
aa = plot(std_error_upper, color=sent)
bb = plot(std_error_lower, color=sent)
cc = plot(sd1, color=aquaNavy1)
dd = plot(sd2, color=aquaNavy2)
ee = plot(sd3, color=aquaNavy3)
ff = plot(sd4, color=aquaNavy4)
gg = plot(sd5 - divse, color=aquaNavy5)
hh = plot(sd7, color=aquaNavy6)
ii = plot(sd8, color=aquaNavy7)
jj = plot(sd9, color=aquaNavy8)
kk = plot(sd10, color=aquaNavy9)
ll = plot(sd6, color=aquaNavy10)
fill(ll, hh, color = displayfills ? aquaNavy6 : na)
fill(hh, ii, color= displayfills ? aquaNavy7 : na)
fill(ii, jj, color= displayfills ? aquaNavy8 : na)
fill(jj, kk, color= displayfills ? aquaNavy9 : na)
fill(hh, bb, color= displayfills ? aquaNavy10 : na)
fill(cc, dd, color= displayfills ? aquaNavy1 : na)
fill(dd, ee, color= displayfills ? aquaNavy2 : na)
fill(ee, ff, color= displayfills ? aquaNavy3 : na)
fill(ff, gg, color= displayfills ? aquaNavy4 : na)
fill(gg, aa, color= displayfills ? aquaNavy5 : na)
fill(aa, bb, color=sent)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Trend Assessment ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool strongup = cor >= 0.9
bool modup = cor >= 0.6 and cor < 0.9
bool weakup = cor >= 0.5 and cor < 0.6
bool strongdown = cor <= -0.9
bool moddown = cor <= -0.6 and cor > -0.9
bool weakdown = cor <= -0.5
bool notrend = cor < 0.5 and cor > -0.5
fallingcor = ta.falling(cor, 2)
risingcor = ta.rising(cor, 2)
corchange = ta.change(cor, 3)
bool weakeningup = cor >= 0.5 and fallingcor
bool weakeningdown = cor <= -0.5 and risingcor
bool strenghteningup = cor >= 0.5 and risingcor
bool strengtheningdown = cor <= -0.5 and fallingcor
bool notrendup = cor < 0.5 and cor > -0.5 and risingcor
bool notrenddown = cor < 0.5 and cor > -0.5 and fallingcor
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Linear Regression Time Data ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cl_reg_array = array.new_float()
cl_sq_array = array.new_float()
time_array = array.new_float()
time_sq_array = array.new_float()
cl_cl_array = array.new_float()
hi_reg_array = array.new_float()
hi_sq_array = array.new_float()
hi_time_array = array.new_float()
lo_reg_array = array.new_float()
lo_sq_array = array.new_float()
lo_time_array = array.new_float()
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Security Requests ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cl = request.security(syminfo.ticker, timeframe, close)
cl_lag = request.security(syminfo.ticker, timeframe, close[1])
hi = request.security(syminfo.ticker, timeframe, high)
hi_lag = request.security(syminfo.ticker, timeframe, high[1])
lo = request.security(syminfo.ticker, timeframe, low)
op = request.security(syminfo.ticker, timeframe, open)
for i = 0 to len
array.push(cl_reg_array, cl[i])
array.push(cl_sq_array, cl[i] * cl[i])
array.push(time_array, time[i])
array.push(time_sq_array, time[i] * time[i])
array.push(cl_cl_array, cl[i] * time[i])
array.push(hi_reg_array, hi[i])
array.push(hi_sq_array, hi[i] * hi[i])
array.push(hi_time_array, hi[i] * time[i])
array.push(lo_reg_array, lo[i])
array.push(lo_sq_array, lo[i] * lo[i])
array.push(lo_time_array, lo[i] * time[i])
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Define LinReg Variables ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var float y = 0.0 // intercept
var float y2 = 0.0
x = array.sum(time_array)
x2 = array.sum(time_sq_array)
var float xy = 0.0
var float b1 = 0.0
var float bbb2 = 0.0
var float abc = 0.0
var float abc1 = 0.0
var float r1 = 0.0
var float r2 = 0.0
// Linreg for Close
y := array.sum(cl_reg_array)
y2 := array.sum(cl_sq_array)
xy := array.sum(cl_cl_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
cl_slope = (b1 / bbb2)
abc := y - (cl_slope * x)
abc1 := abc / len
pcl = (time * cl_slope) + abc1
pcl_sm = ta.sma(pcl, 14)
pcl_sd = ta.stdev(pcl_sm, 14)
se_residuals = array.new_float()
for i = 0 to len
array.push(se_residuals, (pcl[i] - cl[i]) * (pcl[i] - cl[i]))
se_add = array.sum(se_residuals)
r1 := se_add / (len - 2)
r2 := math.sqrt(r1)
pcl_ucl = pcl + r2
pcl_lcl = pcl - r2
// Close Correlation
cl_time_co = array.covariance(cl_reg_array, time_array)
cl_sd = array.stdev(cl_reg_array)
time_sd = array.stdev(time_array)
cl_cor = cl_time_co / (cl_sd * time_sd)
// LinReg for High
y := array.sum(hi_reg_array)
y2 := array.sum(hi_sq_array)
xy := array.sum(hi_time_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
hi_slope = (b1 / bbb2)
abc := y - (hi_slope * x)
abc1 := abc / len
phi = (time * hi_slope) + abc1
se_residuals_hi = array.new_float()
for i = 0 to len
array.push(se_residuals_hi, (phi[i] - hi[i]) * (phi[i] - hi[i]))
se_add_hi = array.sum(se_residuals_hi)
r1 := se_add_hi / (len - 2)
r2 := math.sqrt(r1)
phi_ucl = phi + r2
phi_lcl = phi - r2
hif1 = plot(phi, color = shade6)
hif2 = plot(phi - r2, color = shade7)
hif3 = plot(phi + r2, color = shade8)
fill(hif1, hif2, color= showinfill ? shade6 : na)
fill(hif1, hif3, color= showinfill ? shade8 : na)
// High Correlation
hi_cov = array.covariance(hi_reg_array, time_array)
hi_sd = array.stdev(hi_reg_array)
hi_cor = hi_cov / (hi_sd * time_sd)
// Linreg for Low
y := array.sum(lo_reg_array)
y2 := array.sum(lo_sq_array)
xy := array.sum(lo_time_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
lo_slope = (b1 / bbb2)
abc := y - (lo_slope * x)
abc1 := abc / len
plo = (time * lo_slope) + abc1
se_residuals_lo = array.new_float()
for i = 0 to len
array.push(se_residuals_lo, (phi[i] - hi[i]) * (phi[i] - hi[i]))
se_add_lo = array.sum(se_residuals_lo)
r1 := se_add_lo / (len - 2)
r2 := math.sqrt(r1)
fill1 = plot(plo, color = showinfill ? shade9 : na)
fill2 = plot(plo - r2, color= showinfill ? shade10 : na)
fill3 = plot(plo + r2, color= showinfill ? shade11 : na)
fill(fill1, fill2, color= showinfill ? shade9 : na)
fill(fill1, fill3, color= showinfill ? shade11 : na)
plo_ucl = plo + r2
plo_lcl = plo - r2
bo = plot(pcl, color=shade2)
ba = plot(pcl + r2, color=shade1)
be = plot(pcl-r2, color=shade3)
fill(bo, ba, color= showinfill ? shade1 : na)
fill(ba, be, color= showinfill ? shade3 : na)
// Low Correlation
lo_cov = array.covariance(lo_reg_array, time_array)
lo_sd = array.stdev(lo_reg_array)
lo_cor = lo_cov / (lo_sd * time_sd)
userinputprice = ((time + (userinput * 3600)) * slope) + intercept
userinputprice2 = userinputprice + er1
userinputprice3 = userinputprice - er1
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Model Fit ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
maxoutside = math.max(plo_ucl, pcl_ucl, phi_ucl, pcl, phi, plo)
minoutside = math.min(plo_lcl, pcl_lcl, phi_lcl, plo, pcl, phi)
bool outside = close > maxoutside or close < minoutside
bool inside = close <= maxoutside and close >= minoutside
bool outsidereg = close > sd1 or close < sd6
bool insidereg = close <= std_error_upper and close >= std_error_lower
var float outside_count = 0
var float inside_count = 0
var float outside_count_reg = 0
var float inside_count_reg = 0
for i = 0 to len
if outside[i]
outside_count := outside_count + 1
if inside[i]
inside_count := inside_count + 1
if outsidereg[i]
outside_count_reg := outside_count_reg + 1
if insidereg[i]
inside_count_reg := inside_count_reg + 1
cumulative_count = outside_count + inside_count
outside_perc = (outside_count / cumulative_count) * 100
inside_perc = (inside_count / cumulative_count) * 100
cumulative_reg_count = outside_count_reg + inside_count_reg
outside_reg_perc = (outside_count_reg / cumulative_reg_count) * 100
inside_reg_perc = (inside_count_reg / cumulative_reg_count) * 100
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Manual Calculation Parameters ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if allowinput
pcl := ((time + (userinput * 3600)) * cl_slope) + abc1
pcl_ucl := pcl + r2
pcl_lcl := pcl - r2
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Correlation Change Assessment for Data Tables ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cl_cor_change = ta.change(cl_cor, len)
hi_cor_change = ta.change(hi_cor, len)
lo_cor_change = ta.change(lo_cor, len)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Data Tables ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
trendtablePosInput = input.string(title="Position", defval="Bottom Right", options=["Bottom Left", "Bottom Right", "Top Left", "Top Right", "Bottom Centre"], tooltip="Select where you want the table to draw.")
var trendtablePos = trendtablePosInput == "Bottom Centre" ? position.bottom_center : trendtablePosInput == "Bottom Left" ? position.bottom_left : trendtablePosInput == "Bottom Right" ? position.bottom_right : trendtablePosInput == "Top Left" ? position.top_left : trendtablePosInput == "Top Right" ? position.top_right : na
var trendtabledata = table.new(trendtablePos, 4, 6, bgcolor = color.black, frame_color = color.white, frame_width = 2, border_color = color.black)
tablePosInput = input.string(title="Position", defval="Top Right", options=["Bottom Left", "Bottom Right", "Top Left", "Top Right"], tooltip="Select where you want the table to draw.")
var tablePos = tablePosInput == "Bottom Left" ? position.bottom_left : tablePosInput == "Bottom Right" ? position.bottom_right : tablePosInput == "Top Left" ? position.top_left : tablePosInput == "Top Right" ? position.top_right : na
var regtable = table.new(tablePos, columns = 4, rows = 20, border_color = aquaNavytable2, border_width = 0)
if showtable
table.cell(regtable, 1, 1, text = "Regression Slope", bgcolor = aquaNavy1, text_color = color.white)
table.cell(regtable, 1, 2, text = "Y = " + str.tostring(slope) + "x +" + str.tostring(intercept), bgcolor = aquaNavytable2, text_color = color.white)
table.cell(regtable, 1, 3, text = "Standard Error:" + str.tostring(math.round(std_error,2)), bgcolor = aquaNavytable3, text_color = color.white)
table.cell(regtable, 1, 4, text = "# of Closes Outside Range: " + str.tostring(outside_count_reg) + " or " + str.tostring(math.round(outside_reg_perc, 2)) + "% of closes.", bgcolor = aquaNavytable2, text_color = color.white)
table.cell(regtable, 1, 5, text = "# of Closes Inside Range: " + str.tostring(inside_count_reg) + " or " + str.tostring(math.round(inside_reg_perc, 2)) + "% of closes.", bgcolor = aquaNavytable2, text_color = color.white)
if allowinput
table.cell(regtable, 1, 6, text = "Predicted Price at:" + str.tostring(userinput) + " hours in the future should fall between " + str.tostring(math.round(userinputprice2, 2)) + " and" + str.tostring(math.round(userinputprice3,2)), bgcolor = aquaNavytable3, text_color = color.white)
table.cell(regtable, 1, 7, text = "Linear Regression Over Time", bgcolor = aquaNavy5, text_color = color.white)
table.cell(regtable, 1, 8, text = "Y = " + str.tostring(cl_slope) + "x + " + str.tostring(abc1), bgcolor = aquaNavy6, text_color = color.white)
table.cell(regtable, 1, 9, text = "Standard Error: " + str.tostring(math.round(r2, 2)), bgcolor = aquaNavy7, text_color = color.white)
table.cell(regtable, 1, 10, text = "# of Closes Outside Range: " + str.tostring(outside_count) + " or " + str.tostring(math.round(outside_perc, 2)) + "% of closes", bgcolor = aquaNavy8, text_color = color.white)
table.cell(regtable, 1, 11, text = "# of Closes Inside Range: " + str.tostring(inside_count) + " or " + str.tostring(math.round(inside_perc,2)) + "% of closes", bgcolor = aquaNavy8, text_color = color.white)
if allowinput
table.cell(regtable, 1, 12, text = "Predicted Price at: " + str.tostring(userinput) + " hours in the future should fall between " + str.tostring(math.round(pcl_ucl, 2)) + " and" + str.tostring(math.round(pcl_lcl,2)) , bgcolor = aquaNavy9, text_color = color.white)
if trendtable
table.cell(trendtabledata, 1, 1, text = "Correlation: " + str.tostring(math.round(cor, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 2, 1, text = strongup ? "Strong Uptrend" : modup ? "Moderate Uptrend" : weakup ? "Weak Uptrend" : strongdown ? "Strong Downtrend" : moddown ? "Moderate Downtrend" : weakdown ? "Weak Downtrend" : notrend ? "No Trend" : na, bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 1, 2, text = weakeningup ? "Uptrend is Weakening" : weakeningdown ? "Downtrend is Weakening" : strenghteningup ? "Uptrend is Strengthening" : strengtheningdown ? "Downtrend is Stregthening" : notrendup ? "No Trend, uptrend forming" : notrenddown ? "No Trend, downtrend forming" : na, bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 2, 2, text = str.tostring(math.round(corchange, 2)), bgcolor = color.black, text_color = color.white)
if showcor
table.cell(trendtabledata, 1, 3, text = "Close Correlation to Time: " + str.tostring(math.round(cl_cor, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 1, 4, text = "High Correlation to Time: " + str.tostring(math.round(hi_cor, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 1, 5, text = "Low Correlation to Time: " + str.tostring(math.round(lo_cor, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 2, 3, text = str.tostring(math.round(cl_cor_change, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 2, 4, text = str.tostring(math.round(hi_cor_change, 2)), bgcolor = color.black, text_color = color.white)
table.cell(trendtabledata, 2, 5, text = str.tostring(math.round(lo_cor_change, 2)), bgcolor = color.black, text_color = color.white)
|
Multi-Timeframe FVG [TFO] | https://www.tradingview.com/script/ipyHUfOO-Multi-Timeframe-FVG-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,575 | 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/
// ยฉ tradeforopp
//@version=5
indicator("Multi-Timeframe FVG [TFO]", "MFVG [TFO]", true)
// ------------------------------ Inputs ------------------------------
var g_TF = "Timeframes"
use_tf1 = input.bool(true, "Timeframe 1", inline = "TF1", group = g_TF)
tf1 = input.timeframe("5", "", inline = "TF1", group = g_TF)
tf1_color = input.color(color.new(#089981, 70), "", inline = "TF1", group = g_TF)
use_tf2 = input.bool(true, "Timeframe 2", inline = "TF2", group = g_TF)
tf2 = input.timeframe("15", "", inline = "TF2", group = g_TF)
tf2_color = input.color(color.new(#00bcd4, 70), "", inline = "TF2", group = g_TF)
use_tf3 = input.bool(true, "Timeframe 3", inline = "TF3", group = g_TF)
tf3 = input.timeframe("60", "", inline = "TF3", group = g_TF)
tf3_color = input.color(color.new(#673ab7, 70), "", inline = "TF3", group = g_TF)
var g_OPT = "Options"
mitigation = input.string('Wick', "Mitigation Type", options = ['Wick','Close'], tooltip = "Close will only delete FVGs if price closes through the area, whereas Wick will delete FVGs once they are fully traded through at all (not necessarily closing through)", group = g_OPT)
disp_x = input.int(3, "Displacement", 0, 10, tooltip = "Larger values will require larger displacement in order to draw FVGs, filtering out smaller moves", group = g_OPT)
tf_align = input.int(3, "Timerfame Alignment", 1, 3, tooltip = "The number of timeframes that must be aligned in order to draw a FVG. A value of 1 will draw any/all FVGs, 2 will draw FVGs that overlap on 2+ timeframes, and 3 will draw FVGs that overlap on all 3 timeframes", group = g_OPT)
max_arr_size = input.int(10, "Max FVG Storage", 0, 30, tooltip = "The maximum FVG objects to be stored at one time, per timeframe. Larger values will significantly increase load times", group = g_OPT)
delete_after = input.int(500, "Delete After X Bars", 0, tooltip = "If not mitigated, FVGs will be deleted after this many bars have passed", group = g_OPT)
// ------------------------------ Inputs ------------------------------
// ------------------------------ Constants & Variables ------------------------------
long_atr = ta.atr(200) / 4
transparent = #ffffff00
mg_wick = mitigation == 'Wick'
[o1, h1, l1, c1] = request.security(syminfo.tickerid, tf1, [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[o2, h2, l2, c2] = request.security(syminfo.tickerid, tf2, [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[o3, h3, l3, c3] = request.security(syminfo.tickerid, tf3, [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
var tf1_o = array.new_float()
var tf1_h = array.new_float()
var tf1_l = array.new_float()
var tf1_c = array.new_float()
var tf1_fvg_bull = array.new_box()
var tf1_fvg_bear = array.new_box()
var tf2_o = array.new_float()
var tf2_h = array.new_float()
var tf2_l = array.new_float()
var tf2_c = array.new_float()
var tf2_fvg_bull = array.new_box()
var tf2_fvg_bear = array.new_box()
var tf3_o = array.new_float()
var tf3_h = array.new_float()
var tf3_l = array.new_float()
var tf3_c = array.new_float()
var tf3_fvg_bull = array.new_box()
var tf3_fvg_bear = array.new_box()
// ------------------------------ Constants & Variables ------------------------------
// ------------------------------ Functions ------------------------------
check_disp(o, c) =>
result = false
if math.abs(o.get(1) - c.get(1)) > long_atr * disp_x
result := true
result
overlap(top1, bot1, top2, bot2) =>
result = false
// Overlap formula: w1 + w2 <= max - min
if math.abs(top1 - bot1) + math.abs(top2 - bot2) > math.max(top1, top2) - math.min(bot1, bot2)
result := true
result
update_price(o_price, h_price, l_price, c_price, o_arr, h_arr, l_arr, c_arr) =>
if o_price != o_price[1]
o_arr.unshift(o_price[1])
h_arr.unshift(h_price[1])
l_arr.unshift(l_price[1])
c_arr.unshift(c_price[1])
if o_arr.size() > max_arr_size
o_arr.pop()
h_arr.pop()
l_arr.pop()
c_arr.pop()
check_fvg(o, h, l, c, fvg_bull, fvg_bear, color) =>
if fvg_bull.size() > 0
for i = fvg_bull.size() - 1 to 0
if (mg_wick ? low : close[1]) <= fvg_bull.get(i).get_bottom() or bar_index - fvg_bull.get(i).get_left() > delete_after
box.delete(fvg_bull.get(i))
fvg_bull.remove(i)
if fvg_bear.size() > 0
for i = fvg_bear.size() - 1 to 0
if (mg_wick ? high : close[1]) >= fvg_bear.get(i).get_top() or bar_index - fvg_bear.get(i).get_left() > delete_after
box.delete(fvg_bear.get(i))
fvg_bear.remove(i)
proceed = false
if o.size() > 2
if fvg_bull.size() == 0
proceed := true
else
if l.get(0) != fvg_bull.get(0).get_top()
proceed := true
if proceed and l.get(0) > h.get(2) and c.get(1) > o.get(1) and check_disp(o, c)
fvg_bull.unshift(box.new(bar_index, l.get(0), bar_index, h.get(2), extend = extend.right, bgcolor = transparent, border_color = na))
if fvg_bull.size() > max_arr_size
fvg_bull.get(fvg_bull.size() - 1).delete()
fvg_bull.pop()
proceed := false
if o.size() > 2
if fvg_bear.size() == 0
proceed := true
else
if l.get(2) != fvg_bear.get(0).get_top()
proceed := true
if proceed and l.get(2) > h.get(0) and c.get(1) < o.get(1) and check_disp(o, c)
fvg_bear.unshift(box.new(bar_index, l.get(2), bar_index, h.get(0), extend = extend.right, bgcolor = transparent, border_color = na))
if fvg_bear.size() > max_arr_size
fvg_bear.get(fvg_bear.size() - 1).delete()
fvg_bear.pop()
check_overlap(tf1_fvg, tf2_fvg, tf3_fvg) =>
if (use_tf1 ? tf1_fvg.size() > 0 : true) and (use_tf2 ? tf2_fvg.size() > 0 : true) and (use_tf3 ? tf3_fvg.size() > 0 : true)
for i = 0 to tf1_fvg.size() - 1
for j = 0 to tf2_fvg.size() - 1
for k = 0 to tf3_fvg.size() - 1
fvg1 = use_tf1 ? tf1_fvg.get(i) : na
fvg2 = use_tf2 ? tf2_fvg.get(j) : na
fvg3 = use_tf3 ? tf3_fvg.get(k) : na
top1 = use_tf1 ? fvg1.get_top() : na
bot1 = use_tf1 ? fvg1.get_bottom() : na
top2 = use_tf2 ? fvg2.get_top() : na
bot2 = use_tf2 ? fvg2.get_bottom() : na
top3 = use_tf3 ? fvg3.get_top() : na
bot3 = use_tf3 ? fvg3.get_bottom() : na
if tf_align == 1
if use_tf1
fvg1.set_bgcolor(tf1_color)
if use_tf2
fvg2.set_bgcolor(tf2_color)
if use_tf3
fvg3.set_bgcolor(tf3_color)
else if tf_align == 2
if use_tf1 and use_tf2
if overlap(top1, bot1, top2, bot2)
fvg1.set_bgcolor(tf1_color)
fvg2.set_bgcolor(tf2_color)
if use_tf1 and use_tf3
if overlap(top1, bot1, top3, bot3)
fvg1.set_bgcolor(tf1_color)
fvg3.set_bgcolor(tf3_color)
if use_tf3 and use_tf2
if overlap(top3, bot3, top2, bot2)
fvg3.set_bgcolor(tf3_color)
fvg2.set_bgcolor(tf2_color)
else if tf_align == 3
if use_tf1 and use_tf2 and use_tf3
if overlap(top1, bot1, top2, bot2) and overlap(top1, bot1, top3, bot3) and overlap(top2, bot2, top3, bot3)
fvg1.set_bgcolor(tf1_color)
fvg2.set_bgcolor(tf2_color)
fvg3.set_bgcolor(tf3_color)
// ------------------------------ Functions ------------------------------
// ------------------------------ Logic ------------------------------
if use_tf1
update_price(o1, h1, l1, c1, tf1_o, tf1_h, tf1_l, tf1_c)
check_fvg(tf1_o, tf1_h, tf1_l, tf1_c, tf1_fvg_bull, tf1_fvg_bear, tf1_color)
if use_tf2
update_price(o2, h2, l2, c2, tf2_o, tf2_h, tf2_l, tf2_c)
check_fvg(tf2_o, tf2_h, tf2_l, tf2_c, tf2_fvg_bull, tf2_fvg_bear, tf2_color)
if use_tf3
update_price(o3, h3, l3, c3, tf3_o, tf3_h, tf3_l, tf3_c)
check_fvg(tf3_o, tf3_h, tf3_l, tf3_c, tf3_fvg_bull, tf3_fvg_bear, tf3_color)
check_overlap(tf1_fvg_bear, tf2_fvg_bear, tf3_fvg_bear)
check_overlap(tf1_fvg_bull, tf2_fvg_bull, tf3_fvg_bull)
// ------------------------------ Logic ------------------------------ |
L&S Volatility Index | https://www.tradingview.com/script/ib17l4it-L-S-Volatility-Index/ | gabasco | https://www.tradingview.com/u/gabasco/ | 89 | 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/
// ยฉ gabasco
//@version=5
indicator(title="L&S Volatility Index", shorttitle="LSVI", format=format.percent, precision=2, timeframe="", timeframe_gaps=true)
// Input
lengthInput = input.int(21, "Length", minval=2, tooltip="How many candles to lookback", group="LSVI Settings")
hviAnnualInput = input.int(252, "Days", minval=1, tooltip="Trading days in 1 year. Used for annualizing historical volatility.", group="LSVI Settings")
// Average Historical Volatility Index
hvi = ta.stdev(math.log(close / close[1]), lengthInput, false) * math.sqrt(hviAnnualInput) * 100
avgHvi = ta.sma(hvi, lengthInput)
// L&S Volatility Index
sma = ta.sma(close, lengthInput)
priceDeviation = math.abs(close - sma) / sma * 100
lsVolatility = priceDeviation / avgHvi * 100
// Drawings
threshold = hline(30, title="Threshold", color=color.new(#787B86, 0), linestyle=hline.style_dashed)
zero = hline(0, title="Zero", color=color.new(#787B86, 0), linestyle=hline.style_dashed, display=display.none)
lsvi = plot(lsVolatility, "LSVI", color.new(#7E57C2, 0))
fill(zero, threshold, color = color.rgb(126, 87, 194, 90), title="Background Fill") |
Dual Dynamic Fibonacci Retracement โ Long and Short Duration | https://www.tradingview.com/script/qvfsO64L-Dual-Dynamic-Fibonacci-Retracement-Long-and-Short-Duration/ | StockJustice | https://www.tradingview.com/u/StockJustice/ | 364 | 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/
// ยฉ StockJustice
//@version=5
indicator("Dual Dynamic Fibonacci Retracement Levels", shorttitle="Fib Levels", overlay=true)
// User-defined input for the lookback period
lookbackPeriod = input.int(title="Lookback Period", defval=50, minval=1)
// Calculate pivot high and pivot low
pivotHigh = ta.highest(high, lookbackPeriod)
pivotLow = ta.lowest(low, lookbackPeriod)
// Calculate the mid point
midPoint = (pivotHigh + pivotLow) / 2
// Determine trading position: above or below mid point
aboveMid = close > midPoint
belowMid = close < midPoint
// Calculate Fibonacci retracement levels based on trading position
level_236 = aboveMid ? pivotHigh - 0.236 * (pivotHigh - pivotLow) : pivotLow + 0.236 * (pivotHigh - pivotLow)
level_382 = aboveMid ? pivotHigh - 0.382 * (pivotHigh - pivotLow) : pivotLow + 0.382 * (pivotHigh - pivotLow)
level_50 = aboveMid ? pivotHigh - 0.5 * (pivotHigh - pivotLow) : pivotLow + 0.5 * (pivotHigh - pivotLow)
level_618 = aboveMid ? pivotHigh - 0.618 * (pivotHigh - pivotLow) : pivotLow + 0.618 * (pivotHigh - pivotLow)
level_786 = aboveMid ? pivotHigh - 0.786 * (pivotHigh - pivotLow) : pivotLow + 0.786 * (pivotHigh - pivotLow)
level_100 = aboveMid ? pivotLow : pivotHigh
// Find the last bar where a new pivot high or low was found
var int pivotBar = na
if high == pivotHigh or low == pivotLow
pivotBar := bar_index
// Only plot the lines at the last pivot bar
var line l_236 = na
var line l_382 = na
var line l_50 = na
var line l_618 = na
var line l_786 = na
var line l_100 = na
// Define shift as a function of the lookback period
shift = input(0, title = "Left Line: Shift Left (Negative) or Right (Positive)")
extend = input(0, title = "Right Line: Shift Left (Negative) or Right (Positive)")
if not na(pivotBar)
if na(l_236)
l_236 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_236, x2=bar_index + extend, y2=level_236, color=color.red, width=1)
else
line.delete(l_236)
l_236 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_236, x2=bar_index + extend, y2=level_236, color=color.red, width=1)
if na(l_382)
l_382 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_382, x2=bar_index + extend, y2=level_382, color=color.orange, width=1)
else
line.delete(l_382)
l_382 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_382, x2=bar_index + extend, y2=level_382, color=color.orange, width=1)
if na(l_50)
l_50 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_50, x2=bar_index + extend, y2=level_50, color=color.yellow, width=1)
else
line.delete(l_50)
l_50 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_50, x2=bar_index + extend, y2=level_50, color=color.yellow, width=1)
if na(l_618)
l_618 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_618, x2=bar_index + extend, y2=level_618, color=color.green, width=1)
else
line.delete(l_618)
l_618 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_618, x2=bar_index + extend, y2=level_618, color=color.green, width=1)
if na(l_786)
l_786 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_786, x2=bar_index + extend, y2=level_786, color=color.blue, width=1)
else
line.delete(l_786)
l_786 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_786, x2=bar_index + extend, y2=level_786, color=color.blue, width=1)
if na(l_100)
l_100 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_100, x2=bar_index + extend, y2=level_100, color=color.purple, width=1)
else
line.delete(l_100)
l_100 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_100, x2=bar_index + extend, y2=level_100, color=color.purple, width=1)
// Variable for the "0" level line
var line l_0 = na
// Inside the if bar_index == pivotBar block
if not na(pivotBar)
// Add these lines to plot the "0" level
if na(l_0)
l_0 := line.new(x1=bar_index - lookbackPeriod + shift, y1=aboveMid ? pivotHigh : pivotLow, x2=bar_index + extend, y2=aboveMid ? pivotHigh : pivotLow, color=color.white, width=1)
else
line.delete(l_0)
l_0 := line.new(x1=bar_index - lookbackPeriod + shift, y1=aboveMid ? pivotHigh : pivotLow, x2=bar_index + extend, y2=aboveMid ? pivotHigh : pivotLow, color=color.white, width=1)
// User input to toggle the plotting of 0.114 and 0.886 levels
plotExtraLevels = input.bool(title="Plot 0.114 and 0.886 levels?", defval=false)
// Calculate additional Fibonacci retracement levels
level_114 = aboveMid ? pivotHigh - 0.114 * (pivotHigh - pivotLow) : pivotLow + 0.114 * (pivotHigh - pivotLow)
level_886 = aboveMid ? pivotHigh - 0.886 * (pivotHigh - pivotLow) : pivotLow + 0.886 * (pivotHigh - pivotLow)
// Initialize lines for the new levels
var line l_114 = na
var line l_886 = na
if not na(pivotBar) and plotExtraLevels
// Add lines for the new levels
if na(l_114)
l_114 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_114, x2=bar_index + extend, y2=level_114, color=color.fuchsia, width=1)
else
line.delete(l_114)
l_114 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_114, x2=bar_index + extend, y2=level_114, color=color.fuchsia, width=1)
if na(l_886)
l_886 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_886, x2=bar_index + extend, y2=level_886, color=color.fuchsia, width=1)
else
line.delete(l_886)
l_886 := line.new(x1=bar_index - lookbackPeriod + shift, y1=level_886, x2=bar_index + extend, y2=level_886, color=color.fuchsia, width=1)
// User input to toggle the plotting of the second set of levels
plotSecondSet = input.bool(false, title="Plot second set of levels?")
// User-defined input for the second lookback period
lookbackPeriod2 = input.int(title="Lookback Period 2", defval=14, minval=1)
// Define shift as a function of the lookback period
shift2 = input(0, title = "Second Left Line: Shift Left (Negative) or Right (Positive)")
extend2 = input(30, title = "Second Right Line: Shift Left (Negative) or Right (Positive)")
var float pivotHigh2 = na
var float pivotLow2 = na
// Calculate pivot high and pivot low for second set
if plotSecondSet
pivotHigh2 := ta.highest(high, lookbackPeriod2)
pivotLow2 := ta.lowest(low, lookbackPeriod2)
// Calculate the mid point for second set
midPoint2 = (pivotHigh2 + pivotLow2) / 2
// Determine trading position: above or below mid point for second set
aboveMid2 = close > midPoint2
belowMid2 = close < midPoint2
// Calculate Fibonacci retracement levels based on trading position for second set
level_236_2 = aboveMid2 ? pivotHigh2 - 0.236 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.236 * (pivotHigh2 - pivotLow2)
level_382_2 = aboveMid2 ? pivotHigh2 - 0.382 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.382 * (pivotHigh2 - pivotLow2)
level_50_2 = aboveMid2 ? pivotHigh2 - 0.5 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.5 * (pivotHigh2 - pivotLow2)
level_618_2 = aboveMid2 ? pivotHigh2 - 0.618 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.618 * (pivotHigh2 - pivotLow2)
level_786_2 = aboveMid2 ? pivotHigh2 - 0.786 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.786 * (pivotHigh2 - pivotLow2)
level_100_2 = aboveMid2 ? pivotLow2 : pivotHigh2
// Find the last bar where a new pivot high or low was found for second set
var int pivotBar2 = na
if high == pivotHigh2 or low == pivotLow2
pivotBar2 := bar_index
// Initialize lines for second set
var line l_236_2 = na
var line l_382_2 = na
var line l_50_2 = na
var line l_618_2 = na
var line l_786_2 = na
var line l_100_2 = na
// Plotting lines for second set
if not na(pivotBar2)
if na(l_236_2)
l_236_2 := line.new(x1=bar_index + shift2, y1=level_236_2, x2=bar_index + extend2, y2=level_236_2, color=color.red, width=1)
else
line.delete(l_236_2)
l_236_2 := line.new(x1=bar_index + shift2, y1=level_236_2, x2=bar_index + extend2, y2=level_236_2, color=color.red, width=1)
if na(l_382_2)
l_382_2 := line.new(x1=bar_index + shift2, y1=level_382_2, x2=bar_index + extend2, y2=level_382_2, color=color.orange, width=1)
else
line.delete(l_382_2)
l_382_2 := line.new(x1=bar_index + shift2, y1=level_382_2, x2=bar_index + extend2, y2=level_382_2, color=color.orange, width=1)
if na(l_50_2)
l_50_2 := line.new(x1=bar_index + shift2, y1=level_50_2, x2=bar_index + extend2, y2=level_50_2, color=color.yellow, width=1)
else
line.delete(l_50_2)
l_50_2 := line.new(x1=bar_index + shift2, y1=level_50_2, x2=bar_index + extend2, y2=level_50_2, color=color.yellow, width=1)
if na(l_618_2)
l_618_2 := line.new(x1=bar_index + shift2, y1=level_618_2, x2=bar_index + extend2, y2=level_618_2, color=color.green, width=1)
else
line.delete(l_618_2)
l_618_2 := line.new(x1=bar_index + shift2, y1=level_618_2, x2=bar_index + extend2, y2=level_618_2, color=color.green, width=1)
if na(l_786_2)
l_786_2 := line.new(x1=bar_index + shift2, y1=level_786_2, x2=bar_index + extend2, y2=level_786_2, color=color.blue, width=1)
else
line.delete(l_786_2)
l_786_2 := line.new(x1=bar_index + shift2, y1=level_786_2, x2=bar_index + extend2, y2=level_786_2, color=color.blue, width=1)
if na(l_100_2)
l_100_2 := line.new(x1=bar_index + shift2, y1=level_100_2, x2=bar_index + extend2, y2=level_100_2, color=color.purple, width=1)
else
line.delete(l_100_2)
l_100_2 := line.new(x1=bar_index + shift2, y1=level_100_2, x2=bar_index + extend2, y2=level_100_2, color=color.purple, width=1)
// Variable for the "0" level line for the second set
var line l_0_2 = na
// Inside the if bar_index == pivotBar2 block
if not na(pivotBar2)
// Add these lines to plot the "0" level for the second set
if na(l_0_2)
l_0_2 := line.new(x1=bar_index + shift2, y1=aboveMid2 ? pivotHigh2 : pivotLow2, x2=bar_index + extend2, y2=aboveMid2 ? pivotHigh2 : pivotLow2, color=color.white, width=1)
else
line.delete(l_0_2)
l_0_2 := line.new(x1=bar_index + shift2, y1=aboveMid2 ? pivotHigh2 : pivotLow2, x2=bar_index + extend2, y2=aboveMid2 ? pivotHigh2 : pivotLow2, color=color.white, width=1)
// User input to toggle the plotting of 0.114 and 0.886 levels for second set
plotExtraLevels2 = input(false, title="Plot 0.114 and 0.886 levels for second set?")
// Calculate additional Fibonacci retracement levels for second set
level_114_2 = aboveMid2 ? pivotHigh2 - 0.114 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.114 * (pivotHigh2 - pivotLow2)
level_886_2 = aboveMid2 ? pivotHigh2 - 0.886 * (pivotHigh2 - pivotLow2) : pivotLow2 + 0.886 * (pivotHigh2 - pivotLow2)
// Initialize lines for the new levels for second set
var line l_114_2 = na
var line l_886_2 = na
if not na(pivotBar2) and plotExtraLevels2
if na(l_114_2)
l_114_2 := line.new(x1=bar_index + shift2, y1=level_114_2, x2=bar_index + extend2, y2=level_114_2, color=color.fuchsia, width=1)
else
line.delete(l_114_2)
l_114_2 := line.new(x1=bar_index + shift2, y1=level_114_2, x2=bar_index + extend2, y2=level_114_2, color=color.fuchsia, width=1)
if na(l_886_2)
l_886_2 := line.new(x1=bar_index + shift2, y1=level_886_2, x2=bar_index + extend2, y2=level_886_2, color=color.fuchsia, width=1)
else
line.delete(l_886_2)
l_886_2 := line.new(x1=bar_index + shift2, y1=level_886_2, x2=bar_index + extend2, y2=level_886_2, color=color.fuchsia, width=1)
|
MTF Stationary Extreme Indicator | https://www.tradingview.com/script/OPuTySwS-MTF-Stationary-Extreme-Indicator/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 33 | 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/
// ยฉ LeafAlgo
//@version=5
indicator('Multiple Timeframe Stationary Extreme Indicator', shorttitle='MTF SEI')
// Input parameters
periodsBack = input(5, title='Periods Back')
higherTF = input('240', title='Higher Timeframe', tooltip = 'Higher Timeframe defaulted to 240 minutes.')
// Calculate stationary extreme indicator on current timeframe
highDiff = (high - high[periodsBack]) * 100
lowDiff = (low - low[periodsBack]) * 100
// Calculate stationary extreme indicator on higher timeframe
higherTFHighDiff = request.security(syminfo.tickerid, higherTF, high - high[periodsBack]) * 100
higherTFLowDiff = request.security(syminfo.tickerid, higherTF, low - low[periodsBack]) * 100
// Plotting
plot(highDiff, title='High Difference', color=color.new(color.green, 0), linewidth=3)
plot(lowDiff, title='Low Difference', color=color.new(color.red, 0), linewidth=3)
hline(0)
h1 = hline(1)
h11 = hline(-1)
h2 = hline(2)
h22 = hline(-2)
h3 = hline(3)
h33 = hline(-3)
h5 = hline(5)
h55 = hline(-5)
fill(h1, h2, color=color.new(color.lime, 90))
fill(h2, h3, color=color.new(color.lime, 70))
fill(h3, h5, color=color.new(color.lime, 50))
fill(h11, h22, color=color.new(color.fuchsia, 90))
fill(h22, h33, color=color.new(color.fuchsia, 70))
fill(h33, h55, color=color.new(color.fuchsia, 50))
// Plotting higher timeframe stationary extreme indicator
plot(higherTFHighDiff, title='Higher Timeframe High Difference', color=color.new(color.blue, 0), linewidth=2, offset=-periodsBack)
plot(higherTFLowDiff, title='Higher Timeframe Low Difference', color=color.new(color.orange, 0), linewidth=2, offset=-periodsBack)
|
Ravi teja sreevatsav's consecutive candle | https://www.tradingview.com/script/wl1luXsv-Ravi-teja-sreevatsav-s-consecutive-candle/ | Ravitejasreevatsav | https://www.tradingview.com/u/Ravitejasreevatsav/ | 25 | 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/
// ยฉ RTS_Tview
//@version=4
study(title="Ravi teja's consecutive candle", overlay=true)
candleColor = close > open ? color.green : close < open ? color.red : na
// Mark low for the first two consecutive green candles
greenCandleLow = low
greenCandleLow := candleColor == color.green and candleColor[1] == color.green and candleColor[2] != color.green ? low : na
// Mark high for the first two consecutive red candles
redCandleHigh = high
redCandleHigh := candleColor == color.red and candleColor[1] == color.red and candleColor[2] != color.red ? high : na
plotshape(greenCandleLow, style=shape.triangleup, color=color.green, title="Green Candle Low", location=location.belowbar, size=size.tiny)
plotshape(redCandleHigh, style=shape.triangledown, color=color.red, title="Red Candle High", location=location.abovebar, size=size.tiny)
|
Autoregressive Cloud | https://www.tradingview.com/script/HX4ptxz7-Autoregressive-Cloud/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 51 | 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("Autoregressive Cloud", overlay=true)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// User Inputs ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
smalen = input.int(3, "SMA Length", tooltip = "Smoothes the Autoregression Range. Reccomended value 3.")
timeframe = input.timeframe("", "Timeframe Period", tooltip = "Sets the trading range for the desired timeframe.")
len = input.int(50, "Lookback Length", tooltip = "Lookback length for the autoregressive function.")
transp = input.int(85, "Transparency", tooltip = "Sets the transparency of the clouds.")
showtable = input.bool(true, "Show Correlation Table", tooltip = "Show the Correlation Results Table.")
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Arrays ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cl_reg_array = array.new_float()
cl_sq_array = array.new_float()
cl_lag_array = array.new_float()
cl_lag_sq_array = array.new_float()
cl_cl_array = array.new_float()
hi_reg_array = array.new_float()
hi_sq_array = array.new_float()
hi_lag_array = array.new_float()
hi_lag_sq_array = array.new_float()
hi_hi_array = array.new_float()
lo_reg_array = array.new_float()
lo_sq_array = array.new_float()
lo_lag_array = array.new_float()
lo_lag_sq_array = array.new_float()
lo_lo_array = array.new_float()
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Security Requests ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
cl = request.security(syminfo.ticker, timeframe, close, lookahead=barmerge.lookahead_on)
cl_lag = request.security(syminfo.ticker, timeframe, close[1], lookahead=barmerge.lookahead_on)
hi = request.security(syminfo.ticker, timeframe, high, lookahead=barmerge.lookahead_on)
hi_lag = request.security(syminfo.ticker, timeframe, high[1], lookahead=barmerge.lookahead_on)
lo = request.security(syminfo.ticker, timeframe, low, lookahead=barmerge.lookahead_on)
lo_lag = request.security(syminfo.ticker, timeframe, low[1], lookahead=barmerge.lookahead_on)
op = request.security(syminfo.ticker, timeframe, open, lookahead=barmerge.lookahead_on)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Loop security prices ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for i = 0 to len
array.push(cl_reg_array, cl[i])
array.push(cl_sq_array, cl[i] * cl[i])
array.push(cl_lag_array, cl_lag[i])
array.push(cl_lag_sq_array, cl_lag[i] * cl_lag[i])
array.push(cl_cl_array, cl[i] * cl_lag[i])
array.push(hi_reg_array, hi[i])
array.push(hi_sq_array, hi[i] * hi[i])
array.push(hi_lag_array, hi_lag[i])
array.push(hi_lag_sq_array, hi_lag[i] * hi_lag[i])
array.push(hi_hi_array, hi[i] * hi_lag[i])
array.push(lo_reg_array, lo[i])
array.push(lo_sq_array, lo[i] * lo[i])
array.push(lo_lag_array, lo_lag[i])
array.push(lo_lag_sq_array, lo_lag[i] * lo_lag[i])
array.push(lo_lo_array, lo[i] * lo_lag[i])
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Colours ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// White Base Scheme
whiteBaseColor1 = color.new(color.rgb(51 * 1.5, 255 * 0.6, 255 * 0.6), transp)
whiteBaseColor2 = color.new(color.rgb(51 * 1.8, 255 * 0.8, 255 * 0.8), transp)
whiteBaseColor3 = color.new(color.rgb(51 * 2, 255 * 1, 255 * 1), transp)
// Teal Base Scheme
tealBaseColor1 = color.new(color.rgb(51 * 2.2, 255 * 1.2, 255 * 1.2), transp)
tealBaseColor2 = color.new(color.rgb(51 * 2.4, 255 * 1.4, 255 * 1.4), transp)
tealBaseColor3 = color.new(color.rgb(51 * 2.6, 255 * 1.6, 255 * 1.6), transp)
// Dark Navy Base Scheme
darkNavyBaseColor1 = color.new(color.rgb(51 * 2.8, 255 * 1.8, 255 * 1.8), transp)
darkNavyBaseColor2 = color.new(color.rgb(51 * 3, 255 * 2, 255 * 2), transp)
darkNavyBaseColor3 = color.new(color.rgb(51 * 3.2, 255 * 2.2, 255 * 2.25), transp)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Define Regression Variables ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var float y = 0.0 // intercept
var float y2 = 0.0
var float x = 0.0 // autoregressive dependent
var float x2 = 0.0
var float xy = 0.0
var float b1 = 0.0
var float bbb2 = 0.0
var float abc = 0.0
var float abc1 = 0.0
var float se_add = 0.0
var float r1 = 0.0
var float r2 = 0.0
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Autoregressive Functions ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Autoregresion for Close
y := array.sum(cl_reg_array)
y2 := array.sum(cl_sq_array)
x := array.sum(cl_lag_array)
x2 := array.sum(cl_lag_sq_array)
xy := array.sum(cl_cl_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
cl_slope = (b1 / bbb2)
abc := y - (cl_slope * x)
abc1 := abc / len
pcl = (cl_lag * cl_slope) + abc1
se_residuals = array.new_float()
for i = 0 to len
array.push(se_residuals, (pcl[i] - cl[i]) * (pcl[i] - cl[i]))
se_add := array.sum(se_residuals)
r1 := se_add / (len - 2)
r2 := math.sqrt(r1)
a = plot(ta.sma(pcl, smalen), color=whiteBaseColor1)
b = plot(ta.sma(pcl + r2, smalen), color=whiteBaseColor2)
c = plot(ta.sma(pcl - r2, smalen), color=whiteBaseColor3)
fill(a, b, color=whiteBaseColor1)
fill(a, c, color=whiteBaseColor3)
// Correlation for Close
cl_cov = array.covariance(cl_reg_array, cl_lag_array)
cl_sd = array.stdev(cl_reg_array)
cl_lag_sd = array.stdev(cl_lag_array)
cl_cor = cl_cov / (cl_sd * cl_lag_sd)
// Autoregresion for High
y := array.sum(hi_reg_array)
y2 := array.sum(hi_sq_array)
x := array.sum(hi_lag_array)
x2 := array.sum(hi_lag_sq_array)
xy := array.sum(hi_hi_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
hi_slope = (b1 / bbb2)
abc := y - (hi_slope * x)
abc1 := abc / len
phi = (hi_lag * hi_slope) + abc1
se_residuals_high = array.new_float()
for i = 0 to len
array.push(se_residuals_high, (phi[i] - hi[i]) * (phi[i] - hi[i]))
se_add_high = array.sum(se_residuals_high)
r1 := se_add_high / (len - 2)
r2 := math.sqrt(r1)
aa = plot(ta.sma(phi, smalen), color=tealBaseColor1)
bb = plot(ta.sma(phi + r2, smalen), color=tealBaseColor2)
cc = plot(ta.sma(phi - r2, smalen), color=tealBaseColor3)
fill(aa, bb, color=tealBaseColor1)
fill(aa, cc, color=tealBaseColor3)
// Correlation for High
hi_cov = array.covariance(hi_reg_array, hi_lag_array)
hi_sd = array.stdev(hi_reg_array)
hi_lag_sd = array.stdev(hi_lag_array)
hi_cor = hi_cov / (hi_sd * hi_lag_sd)
// Autoregresion for Low
y := array.sum(lo_reg_array)
y2 := array.sum(lo_sq_array)
x := array.sum(lo_lag_array)
x2 := array.sum(lo_lag_sq_array)
xy := array.sum(lo_lo_array)
b1 := xy - (x * y) / len
bbb2 := x2 - (math.pow(x, 2) / len)
lo_slope = (b1 / bbb2)
abc := y - (lo_slope * x)
abc1 := abc / len
plo = (lo_lag * lo_slope) + abc1
se_residuals_low = array.new_float()
for i = 0 to len
array.push(se_residuals_low, (plo[i] - lo[i]) * (plo[i] - lo[i]))
se_add := array.sum(se_residuals_low)
r1 := se_add / (len - 2)
r2 := math.sqrt(r1)
aaa = plot(ta.sma(plo, smalen), color=darkNavyBaseColor1)
bbb = plot(ta.sma(plo + r2, smalen), color=darkNavyBaseColor2)
ccc = plot(ta.sma(plo - r2, smalen), color=darkNavyBaseColor3)
fill(aaa, bbb, color=darkNavyBaseColor1)
fill(aaa, ccc, color=darkNavyBaseColor3)
lo_cov = array.covariance(lo_reg_array, lo_lag_array)
lo_sd = array.stdev(lo_reg_array)
lo_lag_sd = array.stdev(lo_lag_array)
lo_cor = lo_cov / (lo_sd * lo_lag_sd)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Data Table ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
tablePosInput = input.string(title="Position", defval="Top Right", options=["Bottom Left", "Bottom Right", "Top Left", "Top Right"], tooltip="Select where you want the table to draw.")
var tablePos = tablePosInput == "Bottom Left" ? position.bottom_left : tablePosInput == "Bottom Right" ? position.bottom_right : tablePosInput == "Top Left" ? position.top_left : tablePosInput == "Top Right" ? position.top_right : na
var cor_table = table.new(tablePos, columns = 3, rows = 5, border_color = whiteBaseColor1, border_width = 2)
if showtable
table.cell(cor_table, 1, 1, text = "Correlation table", bgcolor = whiteBaseColor1, text_color = color.white)
table.cell(cor_table, 1, 2, text = "Close Lag Correlation: " + str.tostring(math.round(cl_cor, 2)), bgcolor = whiteBaseColor1, text_color = color.white)
table.cell(cor_table, 1, 3, text = "High Lag Correlation: " + str.tostring(math.round(hi_cor, 2)), bgcolor = whiteBaseColor2, text_color = color.white)
table.cell(cor_table, 1, 4, text = "Low Lag Correlation: " + str.tostring(math.round(lo_cor, 2)), bgcolor = whiteBaseColor3, text_color = color.white) |
Open Interest Profile [Fixed Range] - By Leviathan | https://www.tradingview.com/script/ox607m21-Open-Interest-Profile-Fixed-Range-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 1,677 | 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/
// ยฉ LeviathanCapital
//@version=5
indicator("Open Interest Profile [Fixed Range] - By Leviathan", shorttitle='OI Profile [Fixed Range] - By Leviathan', overlay=true, max_boxes_count=500, max_bars_back = 500, max_lines_count = 500, max_labels_count = 500)
// Tooltips
nstip = 'Node Size inputs controls the scaling of volume profile nodes in relation to the range size. Example: The value of 100 will proportionally extend the nodes to right max of the range.'
rstip = 'Resolution refers to the amount of rows in the profile. Increasing the resolution input will make the profile more granular but will also limit the script from generating profiles on longer ranges. Play around and find the higest resolution value that works on your selected range.'
ndtytip = 'Type 1 means that each node consists of both OI Increase and OI Decrease data. Type 2 means that the nodes of OI Increase will be on the right side of y axis and OI Decrease nodes will be on the left side of y axis.'
prfdirtip = 'Choose whether the nodes of the profile are facing left or right when Type 1 is selected.'
prfpostip = 'Choose whether the profile is positioned on the left side of the range or on the right side of the range.'
volndtip = 'OI+ & OI- shows the proportion of OI+ data and OI- data in a node. Total shows the net value of OI+ data. Delta shows the net difference between OI+ Data and OI- data.'
// User Input Groups
g1 = 'General Settings'
g2 = 'Levels'
g4 = 'Additional Settings'
g3 = 'Data Sources'
g5 = 'Time Parameters'
// User Inputs - General Settings
bullCol = input.color(color.green, 'OI โฒ', group=g1)
bearCol = input.color(color.red, 'OI โผ', group=g1)
res = input.int(30, 'Resolution', minval=5, tooltip=rstip, group=g1)
volnodes = input.string('Delta', 'Node Type', options = ['OI+ & OI-', 'Total', 'Delta'], group=g1, tooltip = volndtip)
profiletype = input.string('Type 2', 'Profile Type', options=['Type 1', 'Type 2'], group=g1, tooltip = ndtytip)
nodesize = input.float(50, 'Node Size (%)', minval=1, maxval = 600, step = 5, group=g1, tooltip = nstip)
volval = input.bool(true, 'Profile Values', group = g1, inline = 'volval')
volvalcols = input.string('Color: Max BG Contrast', '', options = ['Color: Max BG Contrast', 'Color: Custom'], group = g1, inline = 'volval')
volvalcol = input.color(color.black, '', group = g1, inline = 'volval')
sr = input.bool(false, '+Delta Levels', group=g1, inline = '+d')
srtyp = input.string('Line', '', options = ['Box', 'Line'], group = g1, inline = '+d')
pdlcol = input.color(color.rgb(33, 149, 243, 74),'', group=g1, inline = '+d')
profilelbl = input.bool(true, 'Profile Label', group = g1)
// User Inputs - Levels
showPoc = input.bool(false, 'POC โโโโโโโโโโโ', group=g2, inline='poc')
pocCol = input.color(color.maroon, '', inline='poc', group=g2)
pocStyle = input.string('โโโโ', '', options=['โโโโ', '--------', 'โโโโ'], inline='poc', group = g2)
showHL = input.bool(false, 'Range High/Lowโ', inline='rm', group = g2)
hlCol = input.color(color.silver, '', inline='rm', group = g2)
rangemaxStyle = input.string('โโโโ', '', options=['โโโโ', '--------', 'โโโโ'], inline='rm', group = g2)
lvl05 = input.bool(false, 'Range Halfโโโโโโ', inline='2', group = g2)
lvl05Col = input.color(color.rgb(178, 181, 190, 20), '', inline='2', group = g2)
lvl05Style = input.string('โโโโ', '', options=['โโโโ', '--------', 'โโโโ'], inline='2', group = g2)
quarters = input.bool(false, 'Range Quartersโโโโ', inline='4', group = g2)
quartersCol = input.color(color.rgb(178, 181, 190, 70), '', inline='4', group = g2)
quartersStyle = input.string('โโโโ', '', options=['โโโโ', '--------', 'โโโโ'], inline='4', group = g2)
showvwap = input.bool(false, 'OIWAP โโโโโโโโโ', group = g2, inline='vwap')
vwapCol = input.color(color.silver, '', group = g2, inline='vwap')
vwapStyle = input.string('โขโขโขโขโขโขโขโขโข', '', options=['โขโขโขโขโขโขโขโขโข', 'โโโโ'], inline='vwap', group = g2)
labels = input.bool(true, 'Show Labels', group = g2, inline='opt')
extendb = false
extnmb = 50
extend = false
// User Inputs - Additional Settings
hvolhm = input.bool(false, 'Heatmapโ', group = g4, inline = 'hhm')
hhmcol1 = input.color(color.rgb(33, 149, 243, 100), '', group=g4, inline='hhm')
hhmcol2 = input.color(color.rgb(20, 94, 255, 63), '', group=g4, inline='hhm')
profilepos = input.string('Left', 'Profile Position', options=['Left', 'Right'], group=g4, tooltip = prfpostip)
profiledir = input.string('Right', 'Profile Direction', options=['Left', 'Right'], group=g4, tooltip = prfdirtip)
offs = input.int(0, 'Profile Offset', step = 10, group= g4)
profbuff = input.int(10, 'Profile Node Buffer',minval = 3,maxval = 12, group= g4)
hmbuff = input.int(1, 'Heatmap Node Buffer', minval = 1,maxval = 10, group= g4)
ndsize = input.string('Auto', 'Node Text Style โโโโ', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], group= g4, inline = 'nds')
ndpos = input.string('Center', '', options = ['Outer', 'Innter', 'Center'], group= 'Additional Settings', inline = 'nds')
lblsize = input.string('Small', 'Label Text Style โโโโ', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], group= g4, inline = 'lbls')
lblpos = input.string('Right', '', options=['Right', 'Left'], group= g4, inline = 'lbls')
netcol1 = input.color(color.blue, 'Total Volume', group=g4, inline='ttv')
netcol2 = input.color(color.red, '', group=g4, inline='ttv')
showRB = input.bool(false, 'Range Box', inline='rb', group= g4)
rangebCol = input.color(color.rgb(178, 181, 190, 98), '', inline='rb', group= g4)
// User Inputs - OI Data Sources
binance = input.bool(true, 'Binance USDT.P', inline = 'src')
binance2 = input.bool(true, 'Binance USD.P', inline = 'src')
binance3 = input.bool(true, 'Binance BUSD.P', inline = 'src2')
bitmex = input.bool(true, 'BitMEX USD.P', inline = 'src2')
bitmex2 = input.bool(true, 'BitMEX USDT.Pโ', inline = 'src3')
kraken = input.bool(true, 'Kraken USD.P', inline = 'src3')
// Time parameters
startTime = input.time(defval=0, title='Start Time', confirm=true, group=g5)
endTime = input.time(defval=0, title='End Time', confirm=true, group=g5)
endTime2 = endTime==chart.right_visible_bar_time ? chart.right_visible_bar_time : endTime
// Variables, parameters, etc
bool inZone = time >= startTime and time <= endTime2
bool newSession = inZone and not inZone[1]
bool endSession = not inZone and inZone[1]
var int barsInSession = 0, var int zoneStartIndex = 0
var int zoneEndIndex = 0, var int zoneStart = 0
barsInSession := inZone ? barsInSession + 1 : barsInSession
profHigh = ta.highest(high, barsInSession+1)[1]
profLow = ta.lowest(low, barsInSession+1)[1]
resolution = res
if newSession
zoneStartIndex := bar_index
if endSession
zoneEndIndex := bar_index
int lookback = bar_index - zoneStart
var activeZone = false
var vpGreen = array.new_float(resolution, 0)
var vpRed = array.new_float(resolution, 0)
var zoneBounds = array.new_float(resolution, 0)
var float[] ltfOpen = array.new_float(0)
var float[] ltfClose = array.new_float(0)
var float[] ltfHigh = array.new_float(0)
var float[] ltfLow = array.new_float(0)
var float[] ltfVolume = array.new_float(0)
// Getting Aggregated OI Data
mex = syminfo.basecurrency=='BTC' ? 'XBT' : string(syminfo.basecurrency)
[oid1, oi1] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USDT.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
[oid2, oi2] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
[oid3, oi3] = request.security('BINANCE' + ":" + string(syminfo.basecurrency) + 'BUSD.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
[oid4, oi4] = request.security('BITMEX' + ":" + mex + 'USD.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
[oid5, oi5] = request.security('BITMEX' + ":" + mex + 'USDT.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
[oid6, oi6] = request.security('KRAKEN' + ":" + string(syminfo.basecurrency) + 'USD.P_OI', timeframe.period, [close-close[1], close], ignore_invalid_symbol = true)
deltaOI = (binance ? nz(oid1,0) : 0) + (binance2 ? nz(oid2,0)/close : 0) + (binance3 ? nz(oid3,0) : 0) + (bitmex ? nz(oid4,0)/close : 0) + (bitmex2 ? nz(oid5,0)/close : 0) + (kraken ? nz(oid6,0)/close : 0)
OI = (binance ? nz(oi1,0) : 0) + (binance2 ? nz(oi2,0)/close : 0) + (binance3 ? nz(oi3,0) : 0) + (bitmex ? nz(oi4,0)/close : 0) + (bitmex2 ? nz(oi5,0)/close : 0) + (kraken ? nz(oi6,0)/close : 0)
// Data source
vol() =>
out = deltaOI
// Bar Data
float dO = open
float dC = close
float dH = high
float dL = low
float dV = vol()
// Appearance Functions
switchLineStyle(x) =>
switch x
'โโโโ' => line.style_solid
'--------' => line.style_dashed
'โโโโ' => line.style_dotted
switchPos(x) =>
switch x
'Left' => text.align_left
'Right' => text.align_right
'Center' => text.align_center
switchPlotStyle(x) =>
switch x
'โขโขโขโขโขโขโขโขโข' => plot.style_circles
'โโโโ' => plot.style_linebr
switchsize(x) =>
switch x
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Auto' => size.auto
// Reset Function
resetProfile(enable) =>
if enable
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
array.clear(ltfOpen)
array.clear(ltfHigh)
array.clear(ltfLow)
array.clear(ltfClose)
array.clear(ltfVolume)
// Calculating & Adding Profile Data
get_vol(y11, y12, y21, y22, height, vol) =>
nz(math.max(math.min(math.max(y11, y12), math.max(y21, y22)) - math.max(math.min(y11, y12), math.min(y21, y22)), 0) * vol / height)
profileAdd(o, h, l, c, v, g, w) =>
for i = 0 to array.size(vpGreen) - 1
zoneTop = array.get(zoneBounds, i)
zoneBot = zoneTop - g
body_top = math.max(c, o)
body_bot = math.min(c, o)
itsgreen = c >= o
topwick = h - body_top
bottomwick = body_bot - l
body = body_top - body_bot
bodyvol = body * v / (2 * topwick + 2 * bottomwick + body)
topwickvol = 2 * topwick * v / (2 * topwick + 2 * bottomwick + body)
bottomwickvol = 2 * bottomwick * v / (2 * topwick + 2 * bottomwick + body)
if v > 0
array.set(vpGreen, i, array.get(vpGreen, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
if v < 0
array.set(vpRed, i, array.get(vpRed, i) + get_vol(zoneBot, zoneTop, body_bot, body_top, body, -v))// + get_vol(zoneBot, zoneTop, body_top, h, topwick, topwickvol) / 2 + get_vol(zoneBot, zoneTop, body_bot, l, bottomwick, bottomwickvol) / 2)
calcSession(update) =>
array.fill(vpGreen, 0)
array.fill(vpRed, 0)
if bar_index > lookback and update
gap = (profHigh - profLow) / resolution
for i = 0 to resolution - 1
array.set(zoneBounds, i, profHigh - gap * i)
if array.size(ltfOpen) > 0
for j = 0 to array.size(ltfOpen) - 1
profileAdd(array.get(ltfOpen, j), array.get(ltfHigh, j), array.get(ltfLow, j), array.get(ltfClose, j), array.get(ltfVolume, j), gap, 1)
// Calculating POC Level
pocLevel() =>
float maxOI = 0
int levelInd = 0
for i = 0 to array.size(vpRed) - 1
delta = array.get(vpGreen, i) - array.get(vpRed, i)
sum = array.get(vpRed, i) + array.get(vpGreen, i)
if (volnodes=='Delta' ? (na(maxOI) or delta > maxOI) : (sum > maxOI))
maxOI := volnodes=='Delta' ? delta : sum
levelInd := i
float outLevel = na
if levelInd != array.size(vpRed) - 1
outLevel := array.get(zoneBounds, levelInd) - (array.get(zoneBounds, levelInd) - array.get(zoneBounds, levelInd+1)) / 2
outLevel
// Levels
half = (profHigh+profLow) / 2
l75 = (half + profHigh) / 2
l25 = (half + profLow) / 2
var pocx = 0
// Functions for drawing lines, boxes, etc
f_newLine(condition,x, y, c, w, s) =>
condition ? line.new(x, y, extendb ? bar_index+extnmb : bar_index, y, color=c, width=w, style=switchLineStyle(s), extend = extend ? extend.right : extend.none) : na
f_newLabel(condition, x, y, txt, txtcl) =>
condition ? label.new(extend ? x : (lblpos=='Right' ? (extendb ? bar_index+extnmb+1 : bar_index+1) : x), y, text=txt, color=color.rgb(255, 255, 255, 100), textcolor = txtcl, style = extend or lblpos=='Left' ? label.style_label_right : label.style_label_left, size=switchsize(lblsize)) : na
f_newNode(condition, x, top, right, bott, col, txt) =>
condition ? box.new(x, top, right, bott, bgcolor=col, border_width=0, text= volval ? txt : na,xloc=xloc.bar_index, text_size = switchsize(ndsize), text_color = volvalcols=='Color: Custom' ? volvalcol : chart.fg_color, text_halign = switchPos(ndpos)) : na
f_newHeatmap(condition, x, top, right, bott, col, txt) =>
condition ? box.new(x, top, right, bott, bgcolor=col, border_width=0, xloc=xloc.bar_index) : na
// Profile Generation
drawNewZone(update) =>
var box [] profileBoxesArray = array.new_box(0)
var line [] levelsLinesArray = array.new_line(0)
var box [] boxes = array.new_box(0)
var line [] RangeLinesArray = array.new_line(0)
var label[] levelLabels = array.new_label(0)
float maxGreenVol = array.max(vpGreen)
float maxRedVol = array.max(vpRed)
float leftMax = zoneStartIndex
float rightMax = (((barstate.islast and inZone) ? bar_index : zoneEndIndex) - zoneStartIndex) * ((volnodes=='Delta' ? nodesize+20 : nodesize)/100) + zoneStartIndex
if update and array.sum(vpGreen) + array.sum(vpRed) > 0
gap = (profHigh - profLow) / resolution
gap2 = (profHigh - profLow) / 10
float rightMaxVol = array.max(vpGreen)+array.max(vpRed)
float buffer = gap / profbuff
float buffer2 = gap / hmbuff
size = array.size(profileBoxesArray)
if size > 0
for j = 0 to size - 1
box.delete(array.get(profileBoxesArray, size - 1 - j))
array.remove(profileBoxesArray, size - 1 - j)
for i = 0 to array.size(vpRed) - 1
vpct = array.percentrank(vpGreen, i)/100
netcol = color.from_gradient(vpct, 0, 1, netcol1, netcol2)
hmcol = color.from_gradient(vpct, 0, 1, hhmcol1, hhmcol2)
gleft = profilepos=='Left' ? leftMax : bar_index[0]
greenEnd = int(leftMax + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + offs
greenEndD = int(gleft - (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + offs
greenEnd2 = int(bar_index[0] + (rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + offs
redEnd = int(greenEnd + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
redEndD = int(greenEndD - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
redEnd2 = int(greenEnd2 + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
redEnd3 = int(int(leftMax) - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
redEnd4 = int(bar_index[0] - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
total = int(leftMax + ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
totalD = int(gleft - ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) - (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
total2 = int(bar_index[0] + ((rightMax - leftMax) * (array.get(vpGreen, i) / rightMaxVol)) + (rightMax - leftMax) * (array.get(vpRed, i) / rightMaxVol)) + offs
delta = array.get(vpGreen, i)-array.get(vpRed, i)
deltap = (int(gleft + (rightMax - leftMax) * (math.abs(array.get(vpGreen, i)-array.get(vpRed, i)) / rightMaxVol))) + offs
deltap2 = (int(gleft - (rightMax - leftMax) * (math.abs(array.get(vpGreen, i)-array.get(vpRed, i)) / rightMaxVol))) + offs
totvol = str.tostring(array.get(vpGreen, i), format.volume)
hmvoloi = str.tostring(array.get(vpGreen, i) - array.get(vpRed, i) , format.volume)
gvol = str.tostring(array.get(vpGreen, i), format.volume)
rvol = str.tostring(array.get(vpRed, i), format.volume)
dvol = str.tostring(delta, format.volume)
if profilepos=='Left'
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-', int(leftMax) + offs, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? greenEnd : greenEndD, array.get(zoneBounds, i) - gap + buffer, bullCol, gvol))
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-' and profiletype=='Type 1', profiledir=='Right' ? greenEnd : greenEndD, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? redEnd : redEndD, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-' and profiletype=='Type 2', int(leftMax) + offs, array.get(zoneBounds, i) - buffer, redEnd3, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Total', int(leftMax) + offs, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? total : totalD, array.get(zoneBounds, i) - gap + buffer, netcol, totvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 1', int(leftMax) + offs, array.get(zoneBounds, i) - buffer, deltap, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 2', int(leftMax) + offs, array.get(zoneBounds, i) - buffer, delta>0 ? deltap : deltap2, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
if profilelbl
label.new(int(leftMax) + offs, profHigh + gap, 'ฮ OI: ' + str.tostring(array.sum(vpGreen) - array.sum(vpRed), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
label.new(int(leftMax) + offs, profHigh + 2 * gap, '+ OI: ' + str.tostring(array.sum(vpGreen), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
label.new(int(leftMax) + offs, profHigh + 3 * gap, '- OI: ' + str.tostring(array.sum(vpRed), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
if profilepos=='Right'
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-', bar_index[0] + offs, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? greenEnd2 : greenEndD, array.get(zoneBounds, i) - gap + buffer, bullCol, gvol))
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-' and profiletype=='Type 1', profiledir=='Right' ? greenEnd2 : greenEndD , array.get(zoneBounds, i) - buffer, profiledir=='Right' ? redEnd2 : redEndD, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='OI+ & OI-' and profiletype=='Type 2', bar_index[0] + offs, array.get(zoneBounds, i) - buffer, redEnd4, array.get(zoneBounds, i) - gap + buffer, bearCol, rvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Total', bar_index[0] + offs, array.get(zoneBounds, i) - buffer, profiledir=='Right' ? total2 : totalD, array.get(zoneBounds, i) - gap + buffer, netcol, totvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 1', int(gleft) + offs, array.get(zoneBounds, i) - buffer, deltap, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
array.push(profileBoxesArray, f_newNode(volnodes=='Delta' and profiletype=='Type 2', int(gleft) + offs, array.get(zoneBounds, i) - buffer, delta>0 ? deltap : deltap2, array.get(zoneBounds, i) - gap + buffer, delta>0 ? bullCol : bearCol, dvol))
if profilelbl
label.new(bar_index[0] + offs, profHigh, 'ฮ OI: ' + str.tostring(array.sum(vpGreen) - array.sum(vpRed), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
label.new(bar_index[0] + offs, profHigh + gap, '+ OI: ' + str.tostring(array.sum(vpGreen), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
label.new(bar_index[0] + offs, profHigh + 2 * gap, '- OI: ' + str.tostring(array.sum(vpRed), format.volume), color= color.rgb(255, 255, 255, 100), textcolor = color.gray, style=label.style_label_down, size = switchsize(lblsize))
if hvolhm
array.push(profileBoxesArray, f_newHeatmap(true, int(leftMax), array.get(zoneBounds, i) - buffer2, bar_index, array.get(zoneBounds, i) - gap + buffer2, hmcol, hmvoloi))
if sr
pdlvl = ((array.get(zoneBounds, i) - buffer) + (array.get(zoneBounds, i) - gap + buffer)) / 2
array.push(profileBoxesArray, f_newNode(delta>0 and srtyp=='Box', int(leftMax) , array.get(zoneBounds, i) - buffer, bar_index, array.get(zoneBounds, i) - gap + buffer,pdlcol, txt=''))
array.push(levelsLinesArray, delta>0 and srtyp=='Line' ? line.new(int(leftMax), pdlvl, bar_index, pdlvl, color = pdlcol) : na)
if showHL
line.new(int(leftMax), profHigh, extendb ? bar_index+extnmb : bar_index, profHigh, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none)
line.new(int(leftMax), profLow, extendb ? bar_index+extnmb : bar_index, profLow, color=hlCol, width=1, style=line.style_solid, extend = extend ? extend.right : extend.none)
if lvl05 or quarters
f_newLine(true,int(leftMax), half, lvl05Col, 1, lvl05Style)
if quarters
f_newLine(true,int(leftMax), l75, quartersCol, 1, quartersStyle)
f_newLine(true,int(leftMax), l25, quartersCol, 1, quartersStyle)
if labels
f_newLabel(lvl05, int(leftMax), half, '0.5', hlCol)
f_newLabel(showHL, int(leftMax), profHigh, '1', hlCol)
f_newLabel(showHL, int(leftMax), profLow, '0', hlCol)
f_newLabel(quarters, int(leftMax), l75, '0.75', hlCol)
f_newLabel(quarters, int(leftMax), l25, '0.25', hlCol)
poc = pocLevel()
if showPoc
sizel = array.size(levelsLinesArray)
if sizel > 0
for j = 0 to sizel - 1
line.delete(array.get(levelsLinesArray, sizel - 1 - j))
array.remove(levelsLinesArray, sizel - 1 - j)
if showPoc
array.push(levelsLinesArray, line.new(int(leftMax), poc, extendb ? bar_index+extnmb : bar_index, poc, color=pocCol, width=1, xloc=xloc.bar_index, extend = extend ? extend.right : extend.none, style = switchLineStyle(pocStyle)))
// Updating data
combArray(arr1, arr2) =>
out = array.copy(arr1)
if array.size(arr2) > 0
for i = 0 to array.size(arr2) - 1
array.push(out, array.get(arr2, i))
out
updateIntra(o, h, l, c, v) =>
array.push(ltfOpen, o)
array.push(ltfHigh, h)
array.push(ltfLow, l)
array.push(ltfClose, c)
array.push(ltfVolume, v)
calcSession(endSession or (barstate.islast and inZone))
drawNewZone(endSession or (barstate.islast and inZone))
resetProfile(newSession)
if inZone
updateIntra(dO, dH, dL, dC, dV)
if endSession
activeZone := false
if newSession
zoneStart := bar_index
activeZone := true
// Generating and plotting OIWAP
startCalculationDate = startTime
posoi = deltaOI > 0 ? deltaOI : 0
vwap_calc() =>
var srcVolArray = array.new_float(na)
var volArray = array.new_float(na)
if startCalculationDate <= time
array.push(srcVolArray, hlc3*posoi)
array.push(volArray, posoi)
else
array.clear(srcVolArray), array.clear(volArray)
array.sum(srcVolArray)/array.sum(volArray)
anchoredVwap = vwap_calc()
plot((extend ? true : inZone) and showvwap ? anchoredVwap : na, "VWAP", linewidth=1, color=vwapCol, style = switchPlotStyle(vwapStyle), editable=false)
|
Inside candle (Inside Bar) Strategy- by smartanu | https://www.tradingview.com/script/KpC644Qx-Inside-candle-Inside-Bar-Strategy-by-smartanu/ | anukul786 | https://www.tradingview.com/u/anukul786/ | 29 | 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/
// ยฉ beingtrader4life
//@version=4
study('BUY SELL signals by smartanu', overlay=true)
bullishBar = 1
bearishBar = -1
isInside() =>
previousBar = 1
bodyStatus = (close >= open) ? 1 : -1
isInsidePattern = high < high[previousBar] and low > low[previousBar]
isInsidePattern ? bodyStatus : 0
barcolor(isInside() == bullishBar ? color.green : na)
barcolor(isInside() == bearishBar ? color.red : na)
// When is bullish bar paint green
plotshape(isInside() == bullishBar, style=shape.triangleup,
location=location.abovebar, color=color.green)
// When is bearish bar paint red
plotshape(isInside() == bearishBar, style=shape.triangledown,
location=location.belowbar, color=color.red)
isInsideBarMade = isInside() == bullishBar or isInside() == bearishBar
alertcondition(isInsideBarMade, title='Inside Bar', message='Inside Bar came up!') |
Supply and Demand | https://www.tradingview.com/script/k4tbraqw-Supply-and-Demand/ | StockJustice | https://www.tradingview.com/u/StockJustice/ | 283 | 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/
// ยฉ StockJustice
//@version=5
indicator("Supply and Demand (Responsive)", shorttitle="S&D", overlay=true)
// Get high and low for the last 10 bars
pivotHigh_1 = ta.highest(high, 10)
pivotLow_1 = ta.lowest(low, 10)
// Get high and low for the 10th to 19th last bars
pivotHigh_2 = ta.highest(high[10], 10)
pivotLow_2 = ta.lowest(low[10], 10)
// Get high and low for the 20th to 29th last bars
pivotHigh_3 = ta.highest(high[20], 10)
pivotLow_3 = ta.lowest(low[20], 10)
// Get high and low for the 30th to 39th last bars
pivotHigh_4 = ta.highest(high[30], 10)
pivotLow_4 = ta.lowest(low[30], 10)
// Get high and low for the 40th to 49th last bars
pivotHigh_5 = ta.highest(high[40], 10)
pivotLow_5 = ta.lowest(low[40], 10)
// Get high and low for the 50th to 59th last bars
pivotHigh_6 = ta.highest(high[50], 10)
pivotLow_6 = ta.lowest(low[50], 10)
// Get high and low for the 60th to 69th last bars
pivotHigh_7 = ta.highest(high[60], 10)
pivotLow_7 = ta.lowest(low[60], 10)
// Get high and low for the 70th to 79th last bars
pivotHigh_8 = ta.highest(high[70], 10)
pivotLow_8 = ta.lowest(low[70], 10)
// Get high and low for the 80th to 89th last bars
pivotHigh_9 = ta.highest(high[80], 10)
pivotLow_9 = ta.lowest(low[80], 10)
// Get high and low for the 90th to 99th last bars
pivotHigh_10 = ta.highest(high[90], 10)
pivotLow_10 = ta.lowest(low[90], 10)
// Create an input for the toggle
toggle = input(false, "Limit to specific timeframes? (15m, 30m, 1hr, 4hr, 1d)")
plotCircles = input(true, title="Plot Circles?")
plotLines = input(true, title="Plot Lines?")
is_1h = (timeframe.period == "15" or timeframe.period == "30" or timeframe.period == "60" or timeframe.period == "240" or timeframe.period == "D")
// Get user input
ranges_to_plot = input(6, title="Number of Ranges to Plot (1-10)")
candlesToPlot = input(5, title="Number of Last Ranges to Show for Circles(1-?)")
// Plot pivot points
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 1 ? pivotHigh_1 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 0-9")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 1 ? pivotLow_1 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 0-9")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 2 ? pivotHigh_2: na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 10-19")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 2 ? pivotLow_2: na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 10-19")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 3 ? pivotHigh_3 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 20-29")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 3 ? pivotLow_3: na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 20-29")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 4 ? pivotHigh_4 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 30-39")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 4 ? pivotLow_4 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 30-39")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 5 ? pivotHigh_5 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 40-49")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 5 ? pivotLow_5 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 40-49")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 6 ? pivotHigh_6 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 50-59")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 6 ? pivotLow_6 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 50-59")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 7 ? pivotHigh_7 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 60-69")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 7 ? pivotLow_7 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 60-69")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 8 ? pivotHigh_8 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 70-79")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 8 ? pivotLow_8 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 70-79")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 9 ? pivotHigh_9 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 80-89")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 9 ? pivotLow_9 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 80-89")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 10 ? pivotHigh_10 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.red, 55), linewidth=2, title="Pivot High 90-99")
plot((toggle and is_1h or not toggle) and plotCircles and ranges_to_plot >= 10 ? pivotLow_10 : na, show_last = candlesToPlot, style=plot.style_circles, color=color.new(color.green, 55), linewidth=2, title="Pivot Low 90-99")
//
var line line_pivotHigh_1 = na
var line line_pivotLow_1 = na
var line line_pivotHigh_2 = na
var line line_pivotLow_2 = na
var line line_pivotHigh_3 = na
var line line_pivotLow_3 = na
var line line_pivotHigh_4 = na
var line line_pivotLow_4 = na
var line line_pivotHigh_5 = na
var line line_pivotLow_5 = na
var line line_pivotHigh_6 = na
var line line_pivotLow_6 = na
var line line_pivotHigh_7 = na
var line line_pivotLow_7 = na
var line line_pivotHigh_8 = na
var line line_pivotLow_8 = na
var line line_pivotHigh_9 = na
var line line_pivotLow_9 = na
var line line_pivotHigh_10 = na
var line line_pivotLow_10 = na
if barstate.islast and (toggle and is_1h or not toggle)
if ranges_to_plot >= 1 and plotLines
line.delete(line_pivotHigh_1)
line_pivotHigh_1 := line.new(x1=bar_index[9], y1=pivotHigh_1, x2=bar_index, y2=pivotHigh_1, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_1)
line_pivotLow_1 := line.new(x1=bar_index[9], y1=pivotLow_1, x2=bar_index, y2=pivotLow_1, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 2 and plotLines
line.delete(line_pivotHigh_2)
line_pivotHigh_2 := line.new(x1=bar_index[19], y1=pivotHigh_2, x2=bar_index, y2=pivotHigh_2, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_2)
line_pivotLow_2 := line.new(x1=bar_index[19], y1=pivotLow_2, x2=bar_index, y2=pivotLow_2, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 3 and plotLines
line.delete(line_pivotHigh_3)
line_pivotHigh_3 := line.new(x1=bar_index[29], y1=pivotHigh_3, x2=bar_index, y2=pivotHigh_3, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_3)
line_pivotLow_3 := line.new(x1=bar_index[29], y1=pivotLow_3, x2=bar_index, y2=pivotLow_3, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 4 and plotLines
line.delete(line_pivotHigh_4)
line_pivotHigh_4 := line.new(x1=bar_index[39], y1=pivotHigh_4, x2=bar_index, y2=pivotHigh_4, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_4)
line_pivotLow_4 := line.new(x1=bar_index[39], y1=pivotLow_4, x2=bar_index, y2=pivotLow_4, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 5 and plotLines
line.delete(line_pivotHigh_5)
line_pivotHigh_5 := line.new(x1=bar_index[49], y1=pivotHigh_5, x2=bar_index, y2=pivotHigh_5, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_5)
line_pivotLow_5 := line.new(x1=bar_index[49], y1=pivotLow_5, x2=bar_index, y2=pivotLow_5, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 6 and plotLines
line.delete(line_pivotHigh_6)
line_pivotHigh_6 := line.new(x1=bar_index[59], y1=pivotHigh_6, x2=bar_index, y2=pivotHigh_6, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_6)
line_pivotLow_6 := line.new(x1=bar_index[59], y1=pivotLow_6, x2=bar_index, y2=pivotLow_6, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 7 and plotLines
line.delete(line_pivotHigh_7)
line_pivotHigh_7 := line.new(x1=bar_index[69], y1=pivotHigh_7, x2=bar_index, y2=pivotHigh_7, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_7)
line_pivotLow_7 := line.new(x1=bar_index[69], y1=pivotLow_7, x2=bar_index, y2=pivotLow_7, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 8 and plotLines
line.delete(line_pivotHigh_8)
line_pivotHigh_8 := line.new(x1=bar_index[79], y1=pivotHigh_8, x2=bar_index, y2=pivotHigh_8, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_8)
line_pivotLow_8 := line.new(x1=bar_index[79], y1=pivotLow_8, x2=bar_index, y2=pivotLow_8, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 9 and plotLines
line.delete(line_pivotHigh_9)
line_pivotHigh_9 := line.new(x1=bar_index[89], y1=pivotHigh_9, x2=bar_index, y2=pivotHigh_9, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_9)
line_pivotLow_9 := line.new(x1=bar_index[89], y1=pivotLow_9, x2=bar_index, y2=pivotLow_9, color=color.new(color.green, 55), width=1)
if ranges_to_plot >= 10 and plotLines
line.delete(line_pivotHigh_10)
line_pivotHigh_10 := line.new(x1=bar_index[99], y1=pivotHigh_10, x2=bar_index, y2=pivotHigh_10, color=color.new(color.red, 55), width=1)
line.delete(line_pivotLow_10)
line_pivotLow_10 := line.new(x1=bar_index[99], y1=pivotLow_10, x2=bar_index, y2=pivotLow_10, color=color.new(color.green, 55), width=1)
// Check if the current timeframe is 1 minute
// is_1m = timeframe.period == "1" or timeframe.period == "5"
// Get high and low for the last 10 bars on hourly timeframe
// pivotHigh_1_hourly = request.security(syminfo.tickerid, "60", ta.highest(high, 10))
// pivotLow_1_hourly = request.security(syminfo.tickerid, "60", ta.lowest(low, 10))
// Plot pivot points if the timeframe is 1 minute
// plot(is_1m ? pivotHigh_1_hourly : na, show_last = 1, style=plot.style_circles, color=color.red, linewidth=2, title="Pivot High 0-9 Hourly")
// plot(is_1m ? pivotLow_1_hourly : na, show_last = 1, style=plot.style_circles, color=color.green, linewidth=2, title="Pivot Low 0-9 Hourly")
//
// plot(is_1m ? pivotHigh_2_hourly : na, show_last = 1, color=color.red)
// plot(is_1m ? pivotLow_2_hourly : na, show_last = 1, color=color.blue)
// //
//
// //
// // |
Intraday Mean Reversion Main | https://www.tradingview.com/script/EzDT1Dzf-Intraday-Mean-Reversion-Main/ | RandomWalker | https://www.tradingview.com/u/RandomWalker/ | 24 | 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/
// ยฉ RandomWalker
// The Intraday Mean Reversion Indicator works well on certain stocks. It should be used for day trading stocks but IMPORTANT! must be applied to the Day to Day timeframe.
// The logic behind the indicator is that stocks that opens substantially lower than yesterdays close, very often bounces back during the day and closes higher than the open price, thus the name Intraday Mean reversdal. The stock so to speak, reverses against the mean.
// The indicator shows 7 levels to choose from:
// 0.5 * standard deviation
// 0.6 * standard deviation
// 0.7 * standard deviation
// 0.8 * standard deviation
// 0.9 * standard deviation
// 1.0 * standard deviation
// 1.1 * standard deviation
// The script can easily be modified to test other levels as well.
//
//The info box shows the performance of one of these levels.
// The Multiplier shows which multiplier is chosen, the sum shows the profit following the strategy if ONE stock is bought on every buy signal. The Ratio shows the ratio between winning and losing trades if we followed the strategy historically.
// We want to find stocks that have a high ratio. That is More Ups than downs. A ration ovcer 0.5 is good, but of course we want a margin of safety so, 0,75 is a better choice.
// If we find a stock that meets our criteria then the strategy will be to buy as early as possible on the open, and sell as close as possible on the close!
// The yellow bars in the graph are days where the indicator gives a buy signal according to the chosen multiplier.
//
// To help study which stocks it performs well against there is also an indicator called Intraday Mean Reversal Money Performance which indicates the performance of the strategy to different levels of open levels.
//@version=5
indicator("Intraday Mean Reversion Main", overlay=false)
multiplier = input.float(title="Multiplier", defval=1.0)
var histcol=color.red
var float summa=0
var float percentage=1.00000
float profit=0
var int plus=0
var int minus=0
var float ratio=0
var table infoTable = table.new(position.top_center, 2, 2, bgcolor=color.white)
out1=0.5*ta.stdev(close,90)
out2=0.6*ta.stdev(close,90)
out3=0.7*ta.stdev(close,90)
out4=0.8*ta.stdev(close,90)
out5=0.9*ta.stdev(close,90)
out6=1.0*ta.stdev(close,90)
out7=1.1*ta.stdev(close,90)
diff=close[1]-open
if (diff>=out1 and bar_index>90)
profit:=close-open
percentage:=percentage*(1+(profit/open))
if(profit>0)
plus:=plus+1
else if(profit<0)
minus:=minus+1
ratio:=plus/(plus+minus)
histcol:=color.yellow
else
profit:=0
histcol:=color.red
summa:=summa+profit
plot(request.security(syminfo.tickerid,'D',out1), color=color.rgb(0,0,255), title="Stdev 0.5")
plot(request.security(syminfo.tickerid,'D',out2), color=color.rgb(20,0,235), title="Stdev 0.6")
plot(request.security(syminfo.tickerid,'D',out3), color=color.rgb(40,0,215), title="Stdev 0.7")
plot(request.security(syminfo.tickerid,'D',out4), color=color.rgb(60,0,195), title="Stdev 0.8")
plot(request.security(syminfo.tickerid,'D',out5), color=color.rgb(80,0,175), title="Stdev 0.9")
plot(request.security(syminfo.tickerid,'D',out6), color=color.rgb(100,0,155), title="Stdev 1.0")
plot(request.security(syminfo.tickerid,'D',out7), color=color.rgb(120,0,135), title="Stdev 1.1")
plot(diff,color=histcol,style=plot.style_histogram, linewidth=2, title="Diff")
if barstate.islast
table.cell(infoTable, 0, 0, "Multiplier: "+str.tostring(multiplier), text_color=color.green)
table.cell(infoTable, 1, 0, "Sum: "+str.tostring(summa), text_color=color.green)
table.cell(infoTable,0, 1, "Ratio: "+str.tostring(ratio), text_color=color.green)
table.cell(infoTable,1,1, "Ups: "+str.tostring(plus)+" Downs: "+str.tostring(minus), text_color=color.green)
|
MA Correlation Coefficient | https://www.tradingview.com/script/e6Okk7CA-MA-Correlation-Coefficient/ | nonamealgo | https://www.tradingview.com/u/nonamealgo/ | 3 | 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/
// ยฉ nonamealgo
//@version=5
indicator(title = 'MA Correlation Coefficient', shorttitle = 'MA Correlation', overlay = false)
import PineCoders/VisibleChart/4
// Inputs //
src = input(defval = close, title = 'Source')
corr_len = input.int(14, title = 'Correlation Window', minval = 1)
modeSwitch = input.string(defval = 'SMA', title = 'Average Type', options = ['SMA','EMA','HMA','VWMA'])
ma1_len = input.int(7, title = 'MA1', minval = 1, group = 'Lookback')
ma2_len = input.int(14, title = 'MA2', minval = 1, group = 'Lookback')
ma3_len = input.int(30, title = 'MA3', minval = 1, group = 'Lookback')
ma4_len = input.int(91, title = 'MA4', minval = 1, group = 'Lookback')
grad_bottom_color = input.color(defval = color.rgb(5, 48, 97), title = 'Bottom Color', group = 'Gradient ')
grad_centre_color = input.color(defval = color.rgb(247, 247, 247), title = 'Centre Color', group = 'Gradient ')
grad_top_color = input.color(defval = color.rgb(103, 0, 31), title = 'Top Color', group = 'Gradient ')
// Functions //
// Switch
Mode(modeSwitch, src, len) => modeSwitch == 'SMA' ?
ta.sma(source = src, length = len) : modeSwitch == 'EMA' ?
ta.ema(source = src, length = len) : modeSwitch == 'VWMA' ?
ta.vwma(source = src, length = len) : modeSwitch == 'HMA' ? ta.hma(source = src, length = len) : na
// Color picker
ColorPicker(src, bColor, cColor, tColor) => color.from_gradient(value = src, bottom_value = src <= 0 ? -1 : 0, top_value = src <= 0 ? 0 : 1, bottom_color = src <= 0 ? bColor : cColor, top_color = src <= 0 ? cColor : tColor)
// Moving Averages //
ma1 = Mode(modeSwitch, src, ma1_len)
ma2 = Mode(modeSwitch, src, ma2_len)
ma3 = Mode(modeSwitch, src, ma3_len)
ma4 = Mode(modeSwitch, src, ma4_len)
// Calculate Correlation Coefficients //
cma1 = ta.correlation(source1 = src, source2 = ma1, length = corr_len)
cma2 = ta.correlation(source1 = src, source2 = ma2, length = corr_len)
cma3 = ta.correlation(source1 = src, source2 = ma3, length = corr_len)
cma4 = ta.correlation(source1 = src, source2 = ma4, length = corr_len)
// Correlation Colors //
color1 = ColorPicker(cma1, grad_bottom_color, grad_centre_color, grad_top_color)
color2 = ColorPicker(cma2, grad_bottom_color, grad_centre_color, grad_top_color)
color3 = ColorPicker(cma3, grad_bottom_color, grad_centre_color, grad_top_color)
color4 = ColorPicker(cma4, grad_bottom_color, grad_centre_color, grad_top_color)
// Plot Columns //
plot(series = 4, style = plot.style_area, color = color4, title = 'MA4 Correlation')
plot(series = 3, style = plot.style_area, color = color3, title = 'MA3 Correlation')
plot(series = 2, style = plot.style_area, color = color2, title = 'MA2 Correlation')
plot(series = 1, style = plot.style_area, color = color1, title = 'MA1 Correlation') |
Volume Indicator (MA) | https://www.tradingview.com/script/oaTyuXoW-Volume-Indicator-MA/ | CryptoCoBean | https://www.tradingview.com/u/CryptoCoBean/ | 13 | 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/
// ยฉ CryptoCoBean
//@version=5
indicator("Volume Indicator (MA)", overlay=true)
vol_ma = ta.sma(volume, 14)
color volume_candlecolor = na
if volume > vol_ma and (close > open)
volume_candlecolor := color.aqua
if volume > vol_ma and (open > close)
volume_candlecolor := color.red
barcolor(volume_candlecolor)
|
Intraday Mean Reversion Money Performance indicator | https://www.tradingview.com/script/rOtSBTZl-Intraday-Mean-Reversion-Money-Performance-indicator/ | RandomWalker | https://www.tradingview.com/u/RandomWalker/ | 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/
// ยฉ RandomWalker
// The diagram shows Money Performance when buying stocks for 10.000 at every nuy signal
// The rules is: Buy on Open price if the Mean reversion indicator gives a buy signal. Sell on the daily close price.
// According to my knowledge it is not possible to create a strategy based on these rules. Therefore this indicator can be used to analyze Money performance of this strategy
// The lines show the performance of the intraday mean reversion strategy, based on the different levels in the strategy (from 0.5 Standard deviation to 1.1 standard deviation)
//@version=5
indicator("Intraday Mean Reversal Money Performance", overlay=false, precision=2)
showProfit = input.bool(title="Show Profit", defval=true)
showPercentage = input.bool(title="Show Percentage", defval=true)
var int nrOfBars = 0
var float[] multArray = array.from(0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1)
var int[] antalArray = array.from(0,0,0,0,0,0,0) // Nr of trades
var int[] antalPlusArray = array.from(0,0,0,0,0,0,0)
var int[] antalMinusArray = array.from(0,0,0,0,0,0,0)
var float[] totalMoneyArray =array.from(0.0,0.0,0.0,0.0,0.0,0.0,0.0)
var table infoTable = table.new(position.bottom_left, 5, 8, bgcolor=color.rgb(255,0,255,70))
var table tradesTable = table.new(position.bottom_center, 2,3, bgcolor=color.rgb(255,255,0,70))
var chartStartTime = time
// Make one label to show the chart's date range
var rangeLabel = label.new(x=na, y=na, style=label.style_label_left, color=color.black, textcolor=color.white, size=size.normal)
var float mp1=0.0
var float mp2=0.0
var float mp3=0.0
var float mp4=0.0
var float mp5=0.0
var float mp6=0.0
var float mp7=0.0
nrOfBars:=nrOfBars+1
float std=ta.stdev(close,90)
for i=0 to array.size(multArray)-1
out=array.get(multArray,i)*std
diff=close[1]-open
if (diff>=out and bar_index>90)
cProfit=close-open
if(cProfit>0)
cAP=array.get(antalPlusArray,i)
cAP:=cAP+1
array.set(antalPlusArray,i,cAP)
else
cAM=array.get(antalMinusArray,i)
cAM:=cAM+1
array.set(antalMinusArray,i,cAM)
cA=array.get(antalArray,i)
cA:=cA+1
array.set(antalArray,i,cA)
moneyProfit=10000*cProfit/open
cMP=array.get(totalMoneyArray,i)
array.set(totalMoneyArray,i,cMP+moneyProfit)
mp1:=array.get(totalMoneyArray,0)
mp2:=array.get(totalMoneyArray,1)
mp3:=array.get(totalMoneyArray,2)
mp4:=array.get(totalMoneyArray,3)
mp5:=array.get(totalMoneyArray,4)
mp6:=array.get(totalMoneyArray,5)
mp7:=array.get(totalMoneyArray,6)
plot(mp1,color=color.rgb(255,0,255), title="Money Profit 0.5", style=plot.style_stepline_diamond)
plot(mp2,color=color.rgb(215,0,185), title="Money Profit 0.6", style=plot.style_stepline_diamond)
plot(mp3,color=color.rgb(185,0,150), title="Money Profit 0.7", style=plot.style_stepline_diamond)
plot(mp4,color=color.rgb(155,0,115), title="Money Profit 0.8", style=plot.style_stepline_diamond)
plot(mp5,color=color.rgb(125,0,80), title="Money Profit 0.9", style=plot.style_stepline_diamond)
plot(mp6,color=color.rgb(95,0,45), title="Money Profit 1.0", style=plot.style_stepline_diamond)
plot(mp7,color=color.rgb(95,0,45), title="Money Profit 1.1", style=plot.style_stepline_diamond)
if barstate.islast
// We only populate the table on the last bar.
table.cell(infoTable, 0, 0, "Type", text_color=color.white)
table.cell(infoTable, 0, 1, "0.5: ", text_color=color.green)
table.cell(infoTable, 0, 2, "0.6: ", text_color=color.green)
table.cell(infoTable, 0, 3, "0.7: ", text_color=color.green)
table.cell(infoTable, 0, 4, "0.8: ", text_color=color.green)
table.cell(infoTable, 0, 5, "0.9: ", text_color=color.green)
table.cell(infoTable, 0, 6, "1.0: ", text_color=color.green)
table.cell(infoTable, 0, 7, "1.1: ", text_color=color.green)
table.cell(infoTable, 1, 0, "Plus", text_color=color.white)
table.cell(infoTable, 1, 1, str.tostring(array.get(antalPlusArray,0)), text_color=color.green)
table.cell(infoTable, 1, 2, str.tostring(array.get(antalPlusArray,1)), text_color=color.green)
table.cell(infoTable, 1, 3, str.tostring(array.get(antalPlusArray,2)), text_color=color.green)
table.cell(infoTable, 1, 4, str.tostring(array.get(antalPlusArray,3)), text_color=color.green)
table.cell(infoTable, 1, 5, str.tostring(array.get(antalPlusArray,4)), text_color=color.green)
table.cell(infoTable, 1, 6, str.tostring(array.get(antalPlusArray,5)), text_color=color.green)
table.cell(infoTable, 1, 7, str.tostring(array.get(antalPlusArray,6)), text_color=color.green)
table.cell(infoTable, 2, 0, "Minus", text_color=color.white)
table.cell(infoTable, 2, 1, str.tostring(array.get(antalMinusArray,0)), text_color=color.green)
table.cell(infoTable, 2, 2, str.tostring(array.get(antalMinusArray,1)), text_color=color.green)
table.cell(infoTable, 2, 3, str.tostring(array.get(antalMinusArray,2)), text_color=color.green)
table.cell(infoTable, 2, 4, str.tostring(array.get(antalMinusArray,3)), text_color=color.green)
table.cell(infoTable, 2, 5, str.tostring(array.get(antalMinusArray,4)), text_color=color.green)
table.cell(infoTable, 2, 6, str.tostring(array.get(antalMinusArray,5)), text_color=color.green)
table.cell(infoTable, 2, 7, str.tostring(array.get(antalMinusArray,6)), text_color=color.green)
table.cell(infoTable, 3, 0, "Total", text_color=color.white)
table.cell(infoTable, 3, 1, str.tostring(array.get(antalArray,0)), text_color=color.green)
table.cell(infoTable, 3, 2, str.tostring(array.get(antalArray,1)), text_color=color.green)
table.cell(infoTable, 3, 3, str.tostring(array.get(antalArray,2)), text_color=color.green)
table.cell(infoTable, 3, 4, str.tostring(array.get(antalArray,3)), text_color=color.green)
table.cell(infoTable, 3, 5, str.tostring(array.get(antalArray,4)), text_color=color.green)
table.cell(infoTable, 3, 6, str.tostring(array.get(antalArray,5)), text_color=color.green)
table.cell(infoTable, 3, 7, str.tostring(array.get(antalArray,6)), text_color=color.green)
table.cell(infoTable, 4, 0, "Ratio", text_color=color.white)
table.cell(infoTable, 4, 1, str.tostring(array.get(antalPlusArray,0)/array.get(antalArray,0),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 2, str.tostring(array.get(antalPlusArray,1)/array.get(antalArray,1),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 3, str.tostring(array.get(antalPlusArray,2)/array.get(antalArray,2),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 4, str.tostring(array.get(antalPlusArray,3)/array.get(antalArray,3),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 5, str.tostring(array.get(antalPlusArray,4)/array.get(antalArray,4),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 6, str.tostring(array.get(antalPlusArray,5)/array.get(antalArray,5),'#.##'), text_color=color.green)
table.cell(infoTable, 4, 7, str.tostring(array.get(antalPlusArray,6)/array.get(antalArray,6),'#.##'), text_color=color.green)
labelText = "Ticker: " + syminfo.ticker +"\n" +
"Start: "+str.format("{0,date,YYYY-MM-dd}", chartStartTime)+"\n" +
"End: " + str.format("{0,date,YYYY-MM-dd}", time) + "\n" +
"Nr of bars: " + str.tostring(nrOfBars)
label.set_textalign(rangeLabel, text.align_left)
label.set_xy(id=rangeLabel, x=bar_index + 1, y=array.max(totalMoneyArray))
label.set_text(id=rangeLabel, text=labelText)
|
Volume Profile Regression Channel [LuxAlgo] | https://www.tradingview.com/script/pkxnfdYZ-Volume-Profile-Regression-Channel-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,897 | 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("Volume Profile Regression Channel [LuxAlgo]", "LuxAlgo - Volume Profile Regression Channel", overlay = true, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
sections = input.int(100 , minval = 2)
width = input.float(25, 'Width %' , minval = 0, maxval = 100) / 100
vaPer = input.float(50, 'Volume Area %', minval = 0, maxval = 100) / 100
//Style
bull = input(color.teal, 'Bullish' , group = 'Style')
bear = input(color.red, 'Bearish' , group = 'Style')
showLoc = input(true, 'Show Loc' , inline = 'loc' , group = 'Style')
locCss = input(#ffeb3b, '' , inline = 'loc' , group = 'Style')
showDloc = input(true, 'Show Developing Loc', inline = 'dloc', group = 'Style')
dlocCss = input(#2157f3, '' , inline = 'dloc', group = 'Style')
vaTransp = input.int(50, 'VA Transparency' , minval = 0, maxval = 100, group = 'Style')
outVaTransp = input.int(80, 'Outside VA Transparency', minval = 0, maxval = 100, group = 'Style')
//Coordinates
userX1 = input.time(0, confirm = true, inline = '1', group = 'Coordinates')
userX2 = input.time(0, confirm = true, inline = '2', group = 'Coordinates')
//-----------------------------------------------------------------------------}
//Main
//-----------------------------------------------------------------------------{
var x1 = 0
var x2 = 0
var float mean = na
var float wmean = na
var den = 0
//Initial LOC line
var loc_ext = line.new(na,na,na,na
, style = line.style_dashed
, color = locCss
, extend = extend.right)
//Initial profile bins array
var lines = array.new<line>(0)
if barstate.isfirst
for i = 0 to sections-1 //Populate array
lines.push(line.new(na,na,na,na))
//-----------------------------------------------------------------------------}
//Get anchor coordinates and calculate trailing weighted/sum
//-----------------------------------------------------------------------------{
n = bar_index
if time == userX1
x1 := n
den := 1
mean := close
wmean := close
else
den += 1
mean += close
wmean += close * den
//-----------------------------------------------------------------------------}
//Set regression profile
//-----------------------------------------------------------------------------{
var vol = array.new<float>(sections, 0)
//Set volume profile
if time == userX2
x2 := n
dist = 0.
//Get linreg coordinates & slope
mean := mean / den
wmean := wmean / (den * (den+1) / 2)
lreg_y1 = 4 * mean - 3 * wmean
lreg_y2 = 3 * wmean - 2 * mean
slope = (lreg_y2 - lreg_y1)/(x2 - x1)
css = slope > 0 ? bull : bear //Get color based on slope sign
//Get channel width
max = 0., max_dist = 0.
min = 0., min_dist = 0.
for i = 0 to (x2 - x1)
y2 = lreg_y2 + slope * -i
max := math.max(high[i] - y2, max, 0)
min := math.min(low[i] - y2, min, 0)
lreg_y1 += min
lreg_y2 += min
dist := math.abs(max + -min)
//Display profile bins/loc/developing loc
dloc = 0.
float prev_dloc = na
max_vol = 0.
//Loop over the user set interval
for i = 0 to (x2 - x1)
h = high[(x2 - x1) - i]
l = low[(x2 - x1) - i]
v = volume[(x2 - x1) - i]
y2 = lreg_y1 + slope * i
d = 0.
lvl = y2
prev = y2
//Loop over the channel areas
for j = 0 to sections-1
lvl += dist / sections
d += dist / sections
//If within area accumulate volume
if h > math.min(lvl, prev) and l < math.max(lvl, prev)
vol.set(j, vol.get(j) + v)
//Get developing loc
get_vol = vol.get(j)
max_vol := math.max(get_vol, max_vol)
dloc := get_vol == max_vol ? lvl : dloc
prev := lvl
//Get bin length
idx = int(get_vol / max_vol * width * (x2 - x1))
//Set bins
get_l = lines.get(j)
get_l.set_xy1(x1, lreg_y1 + d)
get_l.set_xy2(x1 + idx, lreg_y1 + slope * idx + d)
//Highlight and set loc extension
if vol.get(j) == max_vol and showLoc
get_l.set_color(color.yellow)
loc_ext.set_xy1(x1 + idx, lreg_y1 + slope * idx + d)
loc_ext.set_xy2(x1 + idx + 1, lreg_y1 + slope * (idx + 1) + d)
else
get_l.set_color(color.new(css, outVaTransp))
//Set developing point
if showDloc
line.new(x1 + i - 1, prev_dloc, x1 + i, dloc)
prev_dloc := dloc
va_idx = 0
vol_sum = vol.sum()
loc_idx = vol.indexof(max_vol)
//Set value area
for i = 0 to sections-1
va_idx += 1
gotop = loc_idx + va_idx <= sections-1
gobtm = loc_idx - va_idx >= 0
//Loop above LOC
if gotop
max_vol += vol.get(loc_idx + va_idx)
lines.get(loc_idx + va_idx).set_color(color.new(css, vaTransp))
//Loop below LOC
if gobtm
max_vol += vol.get(loc_idx - va_idx)
lines.get(loc_idx - va_idx).set_color(color.new(css, vaTransp))
if max_vol / vol_sum > vaPer
break
//Set Lines
l1 = line.new(userX1, lreg_y1, userX2, lreg_y2, xloc.bar_time, color = css)
l2 = line.new(userX1, lreg_y1 + dist, userX2, lreg_y2 + dist, xloc.bar_time, color = color(na))
//Set fill
linefill.new(l1, l2, color.new(color.gray, 90))
//-----------------------------------------------------------------------------} |
All-In-One Auto Anchored VWAPs | https://www.tradingview.com/script/HrnQhdjc-All-In-One-Auto-Anchored-VWAPs/ | Texmoonbeam | https://www.tradingview.com/u/Texmoonbeam/ | 250 | 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/
// ยฉ Texmoonbeam
//@version=5
indicator("All-In-One Auto Anchored VWAPs", overlay = true, max_bars_back = 5000, max_labels_count = 500)
//Settings
s = "Settings"
zone = input.string('GMT+1', title='Timezone', options=['GMT-11', 'GMT-10', 'GMT-9', 'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', 'GMT-4', 'GMT-3', 'GMT-2', 'GMT-1', 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+330', 'GMT+4', 'GMT+430', 'GMT+5', 'GMT+530', 'GMT+6', 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12'], group = s)
vwap_source = input.source(close, "VWAP Source", group = s)
std_dev = input.float(defval = 0.5, minval = 0, maxval = 10, title = "Std Deviation Multiplier", group = s)
width = input.int(1, 'Line Width', minval=0, group = s)
leftbars = input.int(defval = 30, title = "Left Bars for Pivots", minval = 0, group = s)
//rightbars = input.int(defval = 10, title = "Right Bars for Pivots", minval = 0, group = s)
OSession = input.session("0800-1800:1234567", "Session Time", group=s)
// Anchors
g = "AVWAPs"
t = "NOTE: Pivots can only be used with High/Low anchors, Sessions can only be used with Open anchors"
show_hist = input.bool(defval = true, title = "Show Historical Periods?", group = g, tooltip = "Ticked will show all historical anchor changes based on the period, unticked will just show the most recent period. Does not affect pivots or sessions.")
vwap1_reset = input.string(defval = "Monthly", title = "VWAP 1 Period", options = ["Daily", "Weekly", "Monthly", "Quarterly", "Yearly","All Time", "Pivot", "Session"], group = g, inline = "1", tooltip = t)
vwap_col1 = input.color(defval=color.new(color.maroon,25), title='Colour', inline = "1", group = g)
show_vwap1_Open = input.bool(defval = true, title = "Open Anchorโโโโโโโ", group = g, inline="1a")
show_vwap1_Open_sd = input.bool(defval = true, title = "With Std Deviation Band", group = g, inline="1a")
show_vwap1_High = input.bool(defval = false, title = "High Anchorโโโโโโโโ", group = g, inline="1b")
show_vwap1_High_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="1b")
show_vwap1_Low = input.bool(defval = false, title = "Low Anchorโโโโโโโโ", group = g, inline="1c")
show_vwap1_Low_sd = input.bool(defval = false, title = "With Std Deviation Band\n", group = g, inline="1c")
vwap2_reset = input.string(defval = "Yearly", title = "VWAP 2 Period", options =["Daily", "Weekly", "Monthly", "Quarterly", "Yearly","All Time", "Pivot", "Session"], group = g, inline = "2", tooltip = t)
vwap_col2 = input.color(defval=color.new(color.maroon,25), title='Colour', inline = "2", group = g)
show_vwap2_Open = input.bool(defval = false, title = "Open Anchorโโโโโโโ", group = g, inline="2a")
show_vwap2_Open_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="2a")
show_vwap2_High = input.bool(defval = false, title = "High Anchorโโโโโโโโ", group = g, inline="2b")
show_vwap2_High_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="2b")
show_vwap2_Low = input.bool(defval = false, title = "Low Anchorโโโโโโโโ", group = g, inline="2c")
show_vwap2_Low_sd = input.bool(defval = false, title = "With Std Deviation Band\n", group = g, inline="2c")
vwap3_reset = input.string(defval = "All Time", title = "VWAP 3 Period", options =["Daily", "Weekly", "Monthly", "Quarterly", "Yearly","All Time", "Pivot", "Session"], group = g, inline = "3", tooltip = t)
vwap_col3 = input.color(defval=color.new(color.maroon,25), title='Colour', inline = "3", group = g)
show_vwap3_Open = input.bool(defval = false, title = "Open Anchorโโโโโโโ", group = g, inline="3a")
show_vwap3_Open_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="3a")
show_vwap3_High = input.bool(defval = false, title = "High Anchorโโโโโโโโ", group = g, inline="3b")
show_vwap3_High_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="3b")
show_vwap3_Low = input.bool(defval = false, title = "Low Anchorโโโโโโโโ", group = g, inline="3c")
show_vwap3_Low_sd = input.bool(defval = false, title = "With Std Deviation Band\n", group = g, inline="3c")
// vwap4_reset = input.string(defval = "Monthly", title = "VWAP 4 Period", options =["Daily", "Weekly", "Monthly", "Quarterly", "Yearly","All Time", "Pivot", "Session"], group = g, inline = "2")
// show_vwap4_Open = input.bool(defval = false, title = "Open Anchorโโโโโโโ", group = g, inline="2a")
// show_vwap4_Open_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="2a")
// show_vwap4_High = input.bool(defval = false, title = "High Anchorโโโโโโโโ", group = g, inline="2b")
// show_vwap4_High_sd = input.bool(defval = false, title = "With Std Deviation Band", group = g, inline="2b")
// show_vwap4_Low = input.bool(defval = false, title = "Low Anchorโโโโโโโโ", group = g, inline="2c")
// show_vwap4_Low_sd = input.bool(defval = false, title = "With Std Deviation Band\n", group = g, inline="2c")
// List Of Anchors
// Daily Open
// Weekly Open
// Monthly Open
// Yearly Open
// Daily High
// Daily Low
// Weekly High
// Weekly Low
// Monthly High
// Monthly Low
// Yearly High
// Yearly Low
// All time high
// All time low
// All time open
// Customn Pivot Highs
// Custom Pivot Lows
// Session Open
//Functions
ResolutionToSec(res)=>
mins = res == "1" ? 1 :
res == "3" ? 3 :
res == "5" ? 5 :
res == "10" ? 10 :
res == "15" ? 15 :
res == "30" ? 30 :
res == "45" ? 45 :
res == "60" ? 60 :
res == "120" ? 120 :
res == "180" ? 180 :
res == "240" ? 240 :
res == "D" or res == "1D" ? 1440 :
res == "W" or res == "1W" ? 10080 :
res == "M" or res == "1M" ? 43200 :
res == "" ? int(str.tonumber(timeframe.period)) :
str.substring(timeframe.period, 2, 3) == "S" ? int(str.tonumber(str.substring(timeframe.period, 0, 2)))/60 : int(str.tonumber(res))
ms = mins * 60 * 1000
GetChartHighest(dataSeries = high) =>
var chartHighest = dataSeries
if dataSeries > nz(chartHighest, -1e10)
chartHighest := dataSeries
chartHighest
GetAllTimeHigh(dataSeries = high) =>
highestHTF = request.security(syminfo.tickerid, "D", GetChartHighest(dataSeries)[1], lookahead=barmerge.lookahead_on)
highestChartTF = GetChartHighest(dataSeries)
math.max(highestHTF, highestChartTF)
GetChartLowest(dataSeries = low) =>
var chartLowest = dataSeries
if dataSeries < nz(chartLowest, 1e10)
chartLowest := dataSeries
chartLowest
GetAllTimeLow(dataSeries = low) =>
lowestHTF = request.security(syminfo.tickerid, "D",
GetChartLowest(dataSeries)[1], lookahead=barmerge.lookahead_on)
lowestChartTF = GetChartLowest(dataSeries)
math.min(lowestHTF, lowestChartTF)
f_get_started (_session) => na(_session[1]) and _session
//Variables & Change Detection
int sess1 = time(timeframe.period, OSession, zone)
var dh = 0.0
var dl = 0.0
var wh = 0.0
var wl = 0.0
var mh = 0.0
var ml = 0.0
var qh = 0.0
var ql = 0.0
var yh = 0.0
var yl = 0.0
bar = ResolutionToSec(timeframe.period)
vis_bars = ((chart.right_visible_bar_time - chart.left_visible_bar_time) / bar)
year_change = show_hist ? year(time, zone) != year(time[1], zone) : year(time, zone) != year(time[1], zone) and time > (timenow - (86400000 * 366))
quarterly_change = show_hist ? ((month(time, zone) == 4 and month(time[1], zone) == 3) or (month(time, zone) == 7 and month(time[1], zone) == 6) or (month(time, zone) == 10 and month(time[1], zone) == 9) or (month(time, zone) == 1 and month(time[1], zone) == 12)) : ((month(time, zone) == 4 and month(time[1], zone) == 3) or (month(time, zone) == 7 and month(time[1], zone) == 6) or (month(time, zone) == 10 and month(time[1], zone) == 9) or (month(time, zone) == 1 and month(time[1], zone) == 12)) and time > (timenow - (86400000 * 94))
month_change = show_hist ? month(time, zone) != month(time[1], zone) : month(time, zone) != month(time[1], zone) and time > (timenow - (86400000 * 32))
week_change = show_hist ? dayofweek(time, zone) == 2 and dayofweek(time[1], zone) == 1 : dayofweek(time, zone) == 2 and dayofweek(time[1], zone) == 1 and time > (timenow - (86400000 * 8))
day_change = show_hist ? dayofweek(time, zone) != dayofweek(time[1], zone) : dayofweek(time, zone) != dayofweek(time[1], zone) and time > (timenow - (86460000 ))
if not(year_change)
if high > yh
yh := high
if low < yl
yl := low
else
yh := high
yl := low
if not(quarterly_change)
if high > qh
qh := high
if low < ql
ql := low
else
qh := high
ql := low
if not(month_change)
if high > mh
mh := high
if low < ml
ml := low
else
mh := high
ml := low
if not(week_change)
if high > wh
wh := high
if low < wl
wl := low
else
wh := high
wl := low
if not(day_change)
if high > dh
dh := high
if low < dl
dl := low
else
dh := high
dl := low
yh_change = show_hist ? yh > yh[1] or year_change : (yh > yh[1] or year_change) and time > (timenow - (86400000 * 366))
qh_change = show_hist ? qh > qh[1] or quarterly_change : (qh > qh[1] or quarterly_change) and time > (timenow - (86400000 * 94))
mh_change = show_hist ? mh > mh[1] or month_change : (mh > mh[1] or month_change ) and time > (timenow - (86400000 * 32))
wh_change = show_hist ? wh > wh[1] or week_change : (wh > wh[1] or week_change ) and time > (timenow - (86400000 * 8))
dh_change = show_hist ? dh > dh[1] or day_change : (dh > dh[1] or day_change) and time > (timenow - (86460000 ))
yl_change = show_hist ? yl < yl[1] or year_change :(yl < yl[1] or year_change) and time > (timenow - (86400000 * 366))
ql_change = show_hist ? ql < ql[1] or quarterly_change : (ql < ql[1] or quarterly_change) and time > (timenow - (86400000 * 94))
ml_change = show_hist ? ml < ml[1] or month_change : (ml < ml[1] or month_change ) and time > (timenow - (86400000 * 32))
wl_change = show_hist ? wl < wl[1] or week_change : (wl < wl[1] or week_change ) and time > (timenow - (86400000 * 8))
dl_change = show_hist ? dl < dl[1] or day_change : (dl < dl[1] or day_change) and time > (timenow - (86460000 ))
ath = GetAllTimeHigh(high)
ath_change = ath > ath[1]
atl = GetAllTimeLow(high)
atl_change = atl < atl[1]
ph = ta.pivothigh(leftbars, 0)
pl = ta.pivotlow(leftbars, 0)
ph_change = not na(ph)
pl_change = not na(pl)
sess_start = f_get_started(sess1)
vwap1_open_change = vwap1_reset == "Daily" ? day_change : vwap1_reset == "Weekly" ? week_change : vwap1_reset == "Monthly" ? month_change : vwap1_reset == "Quarterly" ? quarterly_change : vwap1_reset == "Yearly" ? year_change : vwap1_reset == "All Time" ? barstate.isfirst : vwap1_reset == "Session" ? sess_start : na
vwap1_high_change = vwap1_reset == "Daily" ? dh_change : vwap1_reset == "Weekly" ? wh_change : vwap1_reset == "Monthly" ? mh_change : vwap1_reset == "Quarterly" ? qh_change : vwap1_reset == "Yearly" ? yh_change : vwap1_reset == "All Time" ? ath_change : vwap1_reset == "Pivot" ? ph_change : na
vwap1_low_change = vwap1_reset == "Daily" ? dl_change : vwap1_reset == "Weekly" ? wl_change : vwap1_reset == "Monthly" ? ml_change : vwap1_reset == "Quarterly" ? ql_change : vwap1_reset == "Yearly" ? yl_change : vwap1_reset == "All Time" ? atl_change : vwap1_reset == "Pivot" ? pl_change : na
vwap2_open_change = vwap2_reset == "Daily" ? day_change : vwap2_reset == "Weekly" ? week_change : vwap2_reset == "Monthly" ? month_change : vwap2_reset == "Quarterly" ? quarterly_change : vwap2_reset == "Yearly" ? year_change : vwap2_reset == "All Time" ? barstate.isfirst : vwap2_reset == "Session" ? sess_start : na
vwap2_high_change = vwap2_reset == "Daily" ? dh_change : vwap2_reset == "Weekly" ? wh_change : vwap2_reset == "Monthly" ? mh_change : vwap2_reset == "Quarterly" ? qh_change : vwap2_reset == "Yearly" ? yh_change : vwap2_reset == "All Time" ? ath_change : vwap2_reset == "Pivot" ? ph_change : na
vwap2_low_change = vwap2_reset == "Daily" ? dl_change : vwap2_reset == "Weekly" ? wl_change : vwap2_reset == "Monthly" ? ml_change : vwap2_reset == "Quarterly" ? ql_change : vwap2_reset == "Yearly" ? yl_change : vwap2_reset == "All Time" ? atl_change : vwap2_reset == "Pivot" ? pl_change : na
vwap3_open_change = vwap3_reset == "Daily" ? day_change : vwap3_reset == "Weekly" ? week_change : vwap3_reset == "Monthly" ? month_change : vwap3_reset == "Quarterly" ? quarterly_change : vwap3_reset == "Yearly" ? year_change : vwap3_reset == "All Time" ? barstate.isfirst : vwap3_reset == "Session" ? sess_start : na
vwap3_high_change = vwap3_reset == "Daily" ? dh_change : vwap3_reset == "Weekly" ? wh_change : vwap3_reset == "Monthly" ? mh_change : vwap3_reset == "Quarterly" ? qh_change : vwap3_reset == "Yearly" ? yh_change : vwap3_reset == "All Time" ? ath_change : vwap3_reset == "Pivot" ? ph_change : na
vwap3_low_change = vwap3_reset == "Daily" ? dl_change : vwap3_reset == "Weekly" ? wl_change : vwap3_reset == "Monthly" ? ml_change : vwap3_reset == "Quarterly" ? ql_change : vwap3_reset == "Yearly" ? yl_change : vwap3_reset == "All Time" ? atl_change : vwap3_reset == "Pivot" ? pl_change : na
//debug
// if wh_change
// label.new(bar_index, high, text = "h")
// Plot all the vwaps!
[vwap1_open_vwap, upper_vwap1_open_vwap, lower_vwap1_open_vwap] = ta.vwap(show_vwap1_Open ? vwap_source : na, vwap1_open_change, std_dev)
[vwap1_high_vwap, upper_vwap1_high_vwap, lower_vwap1_high_vwap] = ta.vwap(show_vwap1_High ? vwap_source : na, vwap1_high_change, std_dev)
[vwap1_low_vwap, upper_vwap1_low_vwap, lower_vwap1_low_vwap] = ta.vwap(show_vwap1_Low ? vwap_source : na, vwap1_low_change, std_dev)
[vwap2_open_vwap, upper_vwap2_open_vwap, lower_vwap2_open_vwap] = ta.vwap(show_vwap2_Open ? vwap_source : na, vwap2_open_change, std_dev)
[vwap2_high_vwap, upper_vwap2_high_vwap, lower_vwap2_high_vwap] = ta.vwap(show_vwap2_High ? vwap_source : na, vwap2_high_change, std_dev)
[vwap2_low_vwap, upper_vwap2_low_vwap, lower_vwap2_low_vwap] = ta.vwap(show_vwap2_Low ? vwap_source : na, vwap2_low_change, std_dev)
[vwap3_open_vwap, upper_vwap3_open_vwap, lower_vwap3_open_vwap] = ta.vwap(show_vwap3_Open ? vwap_source : na, vwap3_open_change, std_dev)
[vwap3_high_vwap, upper_vwap3_high_vwap, lower_vwap3_high_vwap] = ta.vwap(show_vwap3_High ? vwap_source : na, vwap3_high_change, std_dev)
[vwap3_low_vwap, upper_vwap3_low_vwap, lower_vwap3_low_vwap] = ta.vwap(show_vwap3_Low ? vwap_source : na, vwap3_low_change, std_dev)
plot(show_vwap1_Open_sd ? upper_vwap1_open_vwap : na, "VWAP 1 Open Upper", vwap_col1, width, style = plot.style_line)
plot(vwap1_open_vwap, "VWAP 1 Open", vwap_col1, width, style = plot.style_line)
plot(show_vwap1_Open_sd ? lower_vwap1_open_vwap : na, "VWAP 1 Open Lower", vwap_col1, width, style = plot.style_line)
plot(show_vwap1_High_sd ? upper_vwap1_high_vwap : na, "VWAP 1 High Upper", vwap_col1, width, style = plot.style_line)
plot(vwap1_high_vwap, "VWAP 1 High", vwap_col1, width, style = plot.style_line)
plot(show_vwap1_High_sd ? lower_vwap1_high_vwap : na, "VWAP 1 High Lower", vwap_col1, width, style = plot.style_line)
plot(show_vwap1_Low_sd ? upper_vwap1_low_vwap : na, "VWAP 1 Low Upper", vwap_col1, width, style = plot.style_line)
plot(vwap1_low_vwap, "VWAP 1 Low", vwap_col1, width, style = plot.style_line)
plot(show_vwap1_Low_sd ? lower_vwap1_low_vwap : na, "VWAP 1 Low Lower", vwap_col1, width, style = plot.style_line)
plot(show_vwap2_Open_sd ? upper_vwap2_open_vwap : na, "VWAP 2 Open Upper", vwap_col2, width, style = plot.style_line)
plot(vwap2_open_vwap, "VWAP 2 Open", vwap_col2, width, style = plot.style_line)
plot(show_vwap2_Open_sd ? lower_vwap2_open_vwap : na, "VWAP 2 Open Lower", vwap_col2, width, style = plot.style_line)
plot(show_vwap2_High_sd ? upper_vwap2_high_vwap : na, "VWAP 2 High Upper", vwap_col2, width, style = plot.style_line)
plot(vwap2_high_vwap, "VWAP 2 High", vwap_col2, width, style = plot.style_line)
plot(show_vwap2_High_sd ? lower_vwap2_high_vwap : na, "VWAP 2 High Lower", vwap_col2, width, style = plot.style_line)
plot(show_vwap2_Low_sd ? upper_vwap2_low_vwap : na, "VWAP 2 Low Upper", vwap_col2, width, style = plot.style_line)
plot(vwap2_low_vwap, "VWAP 2 Low", vwap_col2, width, style = plot.style_line)
plot(show_vwap2_Low_sd ? lower_vwap2_low_vwap : na, "VWAP 2 Low Lower", vwap_col2, width, style = plot.style_line)
plot(show_vwap3_Open_sd ? upper_vwap3_open_vwap : na, "VWAP 3 Open Upper", vwap_col3, width, style = plot.style_line)
plot(vwap3_open_vwap, "VWAP 3 Open", vwap_col3, width, style = plot.style_line)
plot(show_vwap3_Open_sd ? lower_vwap3_open_vwap : na, "VWAP 3 Open Lower", vwap_col3, width, style = plot.style_line)
plot(show_vwap3_High_sd ? upper_vwap3_high_vwap : na, "VWAP 3 High Upper", vwap_col3, width, style = plot.style_line)
plot(vwap3_high_vwap, "VWAP 3 High", vwap_col3, width, style = plot.style_line)
plot(show_vwap3_High_sd ? lower_vwap3_high_vwap : na, "VWAP 3 High Lower", vwap_col3, width, style = plot.style_line)
plot(show_vwap3_Low_sd ? upper_vwap3_low_vwap : na, "VWAP 3 Low Upper", vwap_col3, width, style = plot.style_line)
plot(vwap3_low_vwap, "VWAP 3 Low", vwap_col3, width, style = plot.style_line)
plot(show_vwap3_Low_sd ? lower_vwap3_low_vwap : na, "VWAP 3 Low Lower", vwap_col3, width, style = plot.style_line)
// //debug
// if barstate.islast and (timenow - time) >= (timenow - ph_time)
// label.new(bar_index, high, "x") |
Purple Cloud | https://www.tradingview.com/script/CcsssyQv/ | muratm82 | https://www.tradingview.com/u/muratm82/ | 374 | 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/
// ยฉ muratm82
//@version=5
indicator("Purple Cloud [MMD]",overlay=true, timeframe="", timeframe_gaps=true)
atrPeriod = input(10, "Supertrend ATR Length")
factor = input.float(3.0, "Supertrend Factor", step = 0.01)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
x1 = input(23, "Period")
alpha = input.float(0.9, "Alpha", step = 0.1)
x2 = ta.atr(x1) * alpha
xh = close + x2
xl = close - x2
a1=ta.vwma(hl2*volume,math.ceil(x1/4))/ta.vwma(volume,math.ceil(x1/4))
a2=ta.vwma(hl2*volume,math.ceil(x1/2))/ta.vwma(volume,math.ceil(x1/2))
a3=2*a1-a2
a4=ta.vwma(a3,x1)
b1 = 0.0
b1 := na(b1[1]) ? ta.sma(close, x1) : (b1[1] * (x1 - 1) + close) / x1
buy = a4<=xl and close>b1
sell = a4>=xh and close<b1
xs = 0
xs := buy ? 1 : sell ? -1 : xs[1]
barcolor( color = xs==1 ? color.green :xs==-1? color.red:na)
plotshape(buy and xs != xs[1] , title = "BUY", text = 'B', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, size = size.tiny)
plotshape(sell and xs != xs[1] , title = "SELL", text = 'S', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, size = size.tiny)
plotshape(buy and xs != xs[1] and direction < 0 , title = "Strong BUY", text = '๐', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, size = size.tiny)
plotshape(sell and xs != xs[1] and direction > 0 , title = "Strong SELL", text = 'โ๏ธ', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, size = size.tiny)
ema200=input(false,"Ema 200")
ema50=input(false,"Ema 50")
ema20=input(false,"Ema 20")
plot(ta.ema(close,200),color=ema200?color.black:na,title="Ema 200",linewidth = 4)
plot(ta.ema(close,50),color=ema50?color.blue:na,title="EMA 50",linewidth = 3)
plot(ta.ema(close,20),color=ema20?color.orange:na,title="EMA 20",linewidth = 2)
alertcondition(buy and xs != xs[1], "PC Long", "PC Long")
alertcondition(sell and xs != xs[1], "PC Short", "PC Short") |
Crypto Correlation Matrix | https://www.tradingview.com/script/GmNlgIGx-Crypto-Correlation-Matrix/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 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/
// ยฉ EliCobra
//@version=5
indicator("Crypto Correlation Matrix", overlay = true, scale = scale.none)
swap_asset(input) =>
string asset = switch input
'Current' => syminfo.ticker
'BTC' => 'BINANCE:BTCUSDT'
'BNB' => 'BINANCE:BNBUSDT'
'ETH' => 'BINANCE:ETHUSDT'
'SOL' => 'BINANCE:SOLUSDT'
'LINK' => 'BINANCE:LINKUSDT'
'DOT' => 'BINANCE:DOTUSDT'
'MATIC' => 'BINANCE:MATICUSDT'
'LUNA' => 'BINANCE:LUNAUSDT'
'AVAX' => 'BINANCE:AVAXUSDT'
'ATOM' => 'BINANCE:ATOMUSDT'
'LTC' => 'BINANCE:LTCUSDT'
'NEAR' => 'BINANCE:NEARUSDT'
'FIL' => 'BINANCE:FILUSDT'
'1INCH' => 'BINANCE:1INCHUSDT'
'AXS' => 'BINANCE:AXSUSDT'
'ENJ' => 'BINANCE:ENJUSDT'
'ADA' => 'BINANCE:ADAUSDT'
'ONE' => 'BINANCE:ONEUSDT'
'HNT' => 'BINANCE:HNTUSDT'
'XDB' => 'KUCOIN:XDBUSDT'
'UOS' => 'KUCOIN:UOSUSDT'
'USDT' => 'COINBASE:USDTUSD'
'ALGO' => 'BINANCE:ALGOUSDT'
'ONT' => 'BINANCE:ONTUSDT'
'VET' => 'BINANCE:VETUSDT'
'XTZ' => 'BINANCE:XTZUSDT'
'XRP' => 'BINANCE:XRPUSDT'
'MANA' => 'BINANCE:MANAUSDT'
'THETA' => 'BINANCE:THETAUSDT'
'DOGE' => 'BINANCE:DOGEUSDT'
'TRX' => 'BINANCE:TRXUSDT'
'EOS' => 'BINANCE:EOSUSDT'
'DENT' => 'BINANCE:DENTUSDT'
'ANKR' => 'BINANCE:ANKRUSDT'
'ROSN' => 'KUCOIN:ROSNUSDT'
'DAG' => 'KUCOIN:DAGUSDT'
'GALA' => 'BINANCE:GALAUSDT'
'OCEAN' => 'BINANCE:OCEANUSDT'
'FTM' => 'BINANCE:FTMUSDT'
'MASK' => 'BINANCE:MASKUSDT'
'FLUX' => 'BINANCE:FLUXUSDT'
'SAND' => 'BINANCE:SANDUSDT'
'VRA' => 'KUCOIN:VRAUSDT'
'YGG' => 'BINANCE:YGGUSDT'
'RUNE' => 'BINANCE:RUNEUSDT'
'ALICE' => 'BINANCE:ALICEUSDT'
'KDA' => 'KUCOIN:KDAUSDT'
'NEO' => 'BINANCE:NEOUSDT'
'FXS' => 'BINANCE:FXSUSDT'
'YFI' => 'BINANCE:YFIUSDT'
'TIME' => 'KUCOIN:TIMEUSDT'
'KP3R' => 'BINANCE:KP3RUSDT'
'WAVES' => 'BINANCE:WAVESUSDT'
'UNIU' => 'BINANCE:UNIUSDT'
'SHIB' => 'BINANCE:SHIBUSDT'
'QTUM' => 'BINANCE:QTUMUSDT'
'PRE' => 'KUCOIN:PREUSDT'
'PRQ' => 'KUCOIN:PRQUSDT'
'AIOZ' => 'KUCOIN:AIOZUSDT'
'PYR' => 'BINANCE:PYRUSDT'
'THG' => 'COINEX:THGUSDT'
'UFO' => 'KUCOIN:UFOUSDT'
'FLUX' => 'KUCOIN:FLUXUSDT'
'BNB' => 'BINANCE:BNBUSDT'
'XEM' => 'BINANCE:XEMUSDT'
=> ""
asset
//}//// SWAP ASSET FUNC
rp_security(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isconfirmed ? 0 : 1])
col_up = #005f0a
col_dn = #690a0a
f_col(float x) =>
col = x > 0 ? color.from_gradient(x, 0, 1, color.rgb(255, 255, 255, 100), col_up) : color.from_gradient(x, -1, 0, col_dn, color.rgb(255, 255, 255, 100))
col
f_cell(float x) =>
string y = ""
switch
x < -0.8 => y := "\n\n\n\nโโโโ\n\n\n\n\nโโโโโโโ"
x >= -0.8 and x < -0.6 => y := "\n\n\n\nโโโโ\n\n\n\nโโโโโโโ\n"
x >= -0.6 and x < -0.4 => y := "\n\n\n\nโโโโ\n\n\nโโโโโโโ\n\n"
x >= -0.4 and x < -0.2 => y := "\n\n\n\nโโโโ\n\nโโโโโโโ\n\n\n"
x >= -0.2 and x < 0 => y := "\n\n\n\nโโโโโโโ\n\n\n\n\n"
x >= 0 and x < 0.2 => y := "\n\n\n\nโโโโโโโ\n\n\n\n\n"
x >= 0.2 and x < 0.4 => y := "\n\n\nโโโโโโโ\nโโโโ\n\n\n\n\n"
x >= 0.4 and x < 0.6 => y := "\n\nโโโโโโโ\n\nโโโโ\n\n\n\n\n"
x >= 0.6 and x < 0.8 => y := "\nโโโโโโโ\n\n\nโโโโ\n\n\n\n\n"
x >= 0.8 => y := "โโโโโโโ\n\n\n\nโโโโ\n\n\n\n\n"
y
checksymbol(string x) =>
y = switch x
"BTC" => "โฟ"
"ETH" => "โ "
"LTC" => "ล"
"USDT" => "โฎ"
"ADA" => "โณ"
"BNB" => "โ"
"XRP" => "โ"
=> x
y
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
f_pos(string position) =>
pos = switch position
"Top Left" => position.top_left
"Middle Left" => position.middle_left
"Bottom Left" => position.bottom_left
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Bottom Right" => position.bottom_right
"Top Center" => position.top_center
"Bottom Center" => position.bottom_center
"Center" => position.middle_center
pos
pos_table = input.string("Top Right", "Table Position", options = ["Top Left", "Middle Left", "Bottom Left", "Top Right", "Middle Right", "Bottom Right", "Top Center", "Center", "Bottom Center"])
src = input.source(hlc3, "Source")
length = input.string("30D", "Length", options = ["7D", "30D", "1Y"])
input_base_1 = input.string ("BTC", options = ["Current","BTC","ETH","ADA","ALGO","ALICE","ANKR","ATOM","AIOZ","AVAX","AXS","BNB","DAG","DENT","DOGE","DOT","ENJ","EOS","KP3R","FIL","FLUX","FTM","FXS","GALA","HNT","KDA","LINK","LUNA","LTC","MANA","MASK","MATIC","MBS","NEAR","NEO","OCEAN","ONE","ONT","PRE","PRQ","PYR","QTUM","ROSN","RUNE","SAND","SHIB","SOL","THETA","THG","TIME","TRX","USDT","UFO","UNI","UOS","VET","VRA", "WAVES","XDB","XEM","XRP","XTZ","YFI","YGG","1INCH"],title="Asset 1")
input_base_2 = input.string ("ETH", options = ["Current","BTC","ETH","ADA","ALGO","ALICE","ANKR","ATOM","AIOZ","AVAX","AXS","BNB","DAG","DENT","DOGE","DOT","ENJ","EOS","KP3R","FIL","FLUX","FTM","FXS","GALA","HNT","KDA","LINK","LUNA","LTC","MANA","MASK","MATIC","MBS","NEAR","NEO","OCEAN","ONE","ONT","PRE","PRQ","PYR","QTUM","ROSN","RUNE","SAND","SHIB","SOL","THETA","THG","TIME","TRX","USDT","UFO","UNI","UOS","VET","VRA", "WAVES","XDB","XEM","XRP","XTZ","YFI","YGG","1INCH"],title="Asset 2")
input_base_3 = input.string ("BNB", options = ["Current","BTC","ETH","ADA","ALGO","ALICE","ANKR","ATOM","AIOZ","AVAX","AXS","BNB","DAG","DENT","DOGE","DOT","ENJ","EOS","KP3R","FIL","FLUX","FTM","FXS","GALA","HNT","KDA","LINK","LUNA","LTC","MANA","MASK","MATIC","MBS","NEAR","NEO","OCEAN","ONE","ONT","PRE","PRQ","PYR","QTUM","ROSN","RUNE","SAND","SHIB","SOL","THETA","THG","TIME","TRX","USDT","UFO","UNI","UOS","VET","VRA", "WAVES","XDB","XEM","XRP","XTZ","YFI","YGG","1INCH"],title="Asset 3")
input_base_4 = input.string ("XRP", options = ["Current","BTC","ETH","ADA","ALGO","ALICE","ANKR","ATOM","AIOZ","AVAX","AXS","BNB","DAG","DENT","DOGE","DOT","ENJ","EOS","KP3R","FIL","FLUX","FTM","FXS","GALA","HNT","KDA","LINK","LUNA","LTC","MANA","MASK","MATIC","MBS","NEAR","NEO","OCEAN","ONE","ONT","PRE","PRQ","PYR","QTUM","ROSN","RUNE","SAND","SHIB","SOL","THETA","THG","TIME","TRX","USDT","UFO","UNI","UOS","VET","VRA", "WAVES","XDB","XEM","XRP","XTZ","YFI","YGG","1INCH"],title="Asset 4")
input_base_5 = input.string ("ADA", options = ["Current","BTC","ETH","ADA","ALGO","ALICE","ANKR","ATOM","AIOZ","AVAX","AXS","BNB","DAG","DENT","DOGE","DOT","ENJ","EOS","KP3R","FIL","FLUX","FTM","FXS","GALA","HNT","KDA","LINK","LUNA","LTC","MANA","MASK","MATIC","MBS","NEAR","NEO","OCEAN","ONE","ONT","PRE","PRQ","PYR","QTUM","ROSN","RUNE","SAND","SHIB","SOL","THETA","THG","TIME","TRX","USDT","UFO","UNI","UOS","VET","VRA", "WAVES","XDB","XEM","XRP","XTZ","YFI","YGG","1INCH"],title="Asset 5")
var drkmode = input.bool(true, "Dark Mode")
var txtcol = switch drkmode
true => #ffffff
false => #000000
var bordercol = switch drkmode
true => #ffffff80
false => #000000
len = switch length
"7D" => 7
"30D" => 30
"1Y" => 365
=> 7
var float corr = 0
data_asset_1 = ta.sma(rp_security(swap_asset(input_base_1), timeframe.period, src), 1)
data_asset_2 = ta.sma(rp_security(swap_asset(input_base_2), timeframe.period, src), 1)
data_asset_3 = ta.sma(rp_security(swap_asset(input_base_3), timeframe.period, src), 1)
data_asset_4 = ta.sma(rp_security(swap_asset(input_base_4), timeframe.period, src), 1)
data_asset_5 = ta.sma(rp_security(swap_asset(input_base_5), timeframe.period, src), 1)
corr1 = truncate(ta.correlation(data_asset_1, data_asset_2, len), 2), corr2 = truncate(ta.correlation(data_asset_1, data_asset_3, len), 2)
corr3 = truncate(ta.correlation(data_asset_1, data_asset_4, len), 2), corr4 = truncate(ta.correlation(data_asset_1, data_asset_5, len), 2)
corr5 = truncate(ta.correlation(data_asset_2, data_asset_3, len), 2), corr6 = truncate(ta.correlation(data_asset_2, data_asset_4, len), 2)
corr7 = truncate(ta.correlation(data_asset_2, data_asset_5, len), 2), corr8 = truncate(ta.correlation(data_asset_3, data_asset_4, len), 2)
corr9 = truncate(ta.correlation(data_asset_3, data_asset_5, len), 2), corr10 = truncate(ta.correlation(data_asset_4, data_asset_5, len), 2)
var table Main = table.new(f_pos(pos_table), 6, 7, border_width = 1, border_color = bordercol, frame_color = bordercol, frame_width = 1)
string stralert = na
for j = 0 to 5
name = switch j
0 => ""
1 => input_base_1
2 => input_base_2
3 => input_base_3
4 => input_base_4
5 => input_base_5
table.cell(Main, j, 0, " \n " + name + " \n ", text_color = txtcol, bgcolor = color.new(#000000, 100))
for i = 1 to 5
name2 = switch i
1 => input_base_1
2 => input_base_2
3 => input_base_3
4 => input_base_4
5 => input_base_5
corr := switch i * j
2 => corr1
3 => corr2
4 => corr3
5 => corr4
6 => corr5
8 => corr6
12 => corr7
10 => corr8
15 => corr9
20 => corr10
switch
j == 0 => table.cell(Main, 0, i, " \n " + name2 + " \n ", text_color = txtcol, bgcolor = color.new(#000000, 100))
i > j and j != 0 => table.cell(Main, j, i, str.tostring(corr), text_color = txtcol, bgcolor = f_col(corr))
i < j and j != 0 => table.cell(Main, j, i, f_cell(corr), text_color = txtcol, bgcolor = f_col(corr), text_size = size.tiny)
i == j and j != 0 => table.cell(Main, j, i, checksymbol(name), text_color = txtcol, bgcolor = color.new(#000000, 100), text_size = size.large)
table.merge_cells(Main, 0, 6, 5, 6)
table.cell(Main, 0, 6, "๏ผฃ๏ฝ๏ฝ๏ฝ๏ฝ
๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ ๏ผญ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ", text_color = txtcol, bgcolor = color.new(#000000, 100), text_size = size.normal), table.cell(Main, 0, 0, '๐', text_size = size.large)
for i = 1 to 10
str = switch i
1 => str.tostring(corr1)
2 => str.tostring(corr2)
3 => str.tostring(corr3)
4 => str.tostring(corr4)
5 => str.tostring(corr5)
6 => str.tostring(corr6)
7 => str.tostring(corr7)
8 => str.tostring(corr8)
9 => str.tostring(corr9)
10 => str.tostring(corr10)
stralert += i < 10 ? str + ", " : str
if close
alert(stralert) |
custom Bollinger bands with filters - indicator (AS) | https://www.tradingview.com/script/rdpaOJMX/ | Adam-Szafranski | https://www.tradingview.com/u/Adam-Szafranski/ | 13 | 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/
// ยฉ Adam-Szafranski
//@version=5
indicator("custom Bollinger bands with filters - indicator (AS)",'CBB-IND-(AS)',overlay = true, timeframe="", timeframe_gaps=true)
//strategy("custom Bollinger bands with filters - strategy (AS)",'CBB-STRAT-(AS)', overlay = true,initial_capital = 10000,default_qty_type=strategy.percent_of_equity,default_qty_value=100) //,use_bar_magnifier = true,process_orders_on_close = true,calc_on_every_tick = true,calc_on_order_fills = true,margin_short = 100,margin_long = 100,commission_type=strategy.commission.cash_per_contract,commission_value=0.000)
is_session(sess) =>
not na(time('D', sess))
SS(FF_SRC, LEN) =>
lam = math.pi * math.sqrt(2.0) / LEN
a1 = math.exp(-lam)
cf2 = 2.0 * a1 * math.cos(lam)
cf3 = -math.pow(a1, 2.0)
cf1 = 1.0 - cf2 - cf3
f1 = 0.0
f1 := cf1 * (FF_SRC + nz(FF_SRC[1])) * 0.5 + cf2 * nz(f1[1]) + cf3 * nz(f1[2])
f1
MA(FF_SRC, LEN, typeMA) =>
switch typeMA
'EMA' => ta.ema (FF_SRC, LEN)
'HMA' => ta.hma (FF_SRC, LEN)
'RMA' => ta.rma (FF_SRC, LEN)
'SMA' => ta.sma (FF_SRC, LEN)
'WMA' => ta.wma (FF_SRC, LEN)
'SS' => SS (FF_SRC,LEN)
StdDev(FF_SRC, LEN, typeMA) =>
MEAN = 0.0
SUMSQRT = 0.0
VAR = 0.0
if LEN > 0
MEAN := MA(FF_SRC,LEN,typeMA)
SUMSQRT := 0
for counter = 0 to LEN - 1
SUMSQRT := SUMSQRT + math.pow(FF_SRC[counter] - MEAN, 2 )
VAR := SUMSQRT / LEN
STD = math.sqrt( VAR )
else
STD = -1
//////////////////TOOLTIPS/////////////////////////////////////TOOLTIPS///////////////////////////////////TOOLTIPS//////////////////
TT_TIME = 'use custom date range?/ Enable session filter?' ,TT_STRD = 'Starting Date - if custom'
TT_ENDD = 'Ending date - if custom' ,TT_OPEN = 'Allow Long/Short trades'
TT_PLOT = 'Plot BB/DC/ATR?' ,TT_USEE = 'Use BB/DC/ATR?'
TT_SMTH = 'Smooth BB/ATR?' ,TT_STDV = 'on/off - STDV from price/STDV from BBMA'
TT_BAND = 'Len/type of middle MA/Len of DC' ,TT_COLR = 'fill bollinger bands?/Plot others for debuging(overlay=false)'
TT_BBDV = 'Len/type/multiplier for standard dev' ,TT_BBSM = 'Len/type of smoothing for BB/Perc treshold for width filter'
TT_ATR1 = 'type/len of ATR filter' ,TT_ATR2 = 'Treshold and smoothing of ATR filter'
/////////////////INPUTS//////////////////////////////////INPUTS//////////////////////////////////INPUTS/////////////////
GR_MA = '----------------------START settings------------------------'
BB_USE = input.bool (true ,'BB-USE', inline ='M1',group=GR_MA)
DC_USE = input.bool (true ,'DC-USE', inline ='M1',group=GR_MA)
TR_USE = input.bool (true ,'TR-USE', inline ='M1',group=GR_MA, tooltip =TT_USEE)
BB_PLT = input.bool (true ,'BB-PLT', inline ='M2',group=GR_MA)
DC_PLT = input.bool (true ,'DC-PLT', inline ='M2',group=GR_MA)
TR_PLT = input.bool (true ,'TR-PLT', inline ='M2',group=GR_MA, tooltip =TT_PLOT)
SM_BBU = input.bool (false ,'SM-BB?', inline ='M3',group=GR_MA)
TR_SMU = input.bool (true ,'SM-TR?', inline ='M3',group=GR_MA, tooltip =TT_SMTH)
BB_STD = input.bool (true ,'BB-STD', inline ='M6',group=GR_MA, tooltip =TT_STDV)
CC_FIL = input.bool (true ,'BG-COL', inline ='M4',group=GR_MA)
CC_REP = input.bool (false ,'OV-NOT', inline ='M4',group=GR_MA, tooltip =TT_COLR)
OP_BUY = input.bool (true ,'OP-BUY', inline ='M5',group=GR_MA) //if strategy
OP_SEL = input.bool (true ,'OP-SEL', inline ='M5',group=GR_MA, tooltip =TT_OPEN) //if strategy
GR_BB = 'Bollinger Bands and Donchian settings'
BB_LEN = input.int (55 ,'BB-LEN', inline ='B1',group=GR_BB)
BB_TYP = input.string ('SMA' ,'TYP' , inline ='B1',group=GR_BB, options=['SS','EMA','HMA','RMA','SMA','WMA'])
DC_LEN = input.int (81 ,'DC-LEN', inline ='B1',group=GR_BB, tooltip =TT_BAND)
BB_DVL = input.int (55 ,'DV-LEN', inline ='B2',group=GR_BB)
DV_TYP = input.string ('SMA' ,'TYP' , inline ='B2',group=GR_BB, options=['SS','EMA','HMA','RMA','SMA','WMA'])
BB_XDV = input.float (2.0 ,'DV-MUX', inline ='B2',group=GR_BB, tooltip =TT_BBDV, step = 0.1)
SM_LEN = input.int (55 ,'SM-LEN', inline ='B3',group=GR_BB)
SM_TYP = input.string ('RMA' ,'TYP' , inline ='B3',group=GR_BB, options=['SS','EMA','HMA','RMA','SMA','WMA'])
BB_PER = input.float (0.2 ,'BB-PER', inline ='B3',group=GR_BB, tooltip =TT_BBSM, step = 0.1)
GR_TR = 'Average true range filter settings'
TR_TYP = input.string ('SMA' ,'TR-TYP', inline ='A1',group=GR_TR, options=['SS','EMA','HMA','RMA','SMA','WMA'])
TR_LEN = input.int (12 ,'TR-LEN', inline ='A1',group=GR_TR, tooltip =TT_ATR1)
TR_XXX = input.float (0.0004,'TR-PER', inline ='A2',group=GR_TR, step = 0.00005)
TR_SMO = input.int (14 ,'TR-SMO', inline ='A2',group=GR_TR, tooltip =TT_ATR2)
GR_DT = 'Date and session settings'
FI_SEU = input.bool (false ,'DT-SES', inline ='D1',group=GR_DT)
FI_TIM = input.bool (false ,'DT-TIM', inline ='D1',group=GR_DT, tooltip =TT_TIME)
FI_SES = input.session ('0300-1400' , inline ='D4',group=GR_DT, title= 'SESSION TIME')
DT_STY = input.int (2000 , '' , inline ='D2',group=GR_DT, minval = 1900, maxval = 2100)
DT_STM = input.int (1 , '' , inline ='D2',group=GR_DT, options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
DT_STD = input.int (1 , '' , inline ='D2',group=GR_DT, tooltip =TT_STRD,options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
DT_ENY = input.int (2024 , '' , inline ='D3',group=GR_DT, minval = 1900, maxval = 2100)
DT_ENM = input.int (1 , '' , inline ='D3',group=GR_DT, options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
DT_END = input.int (1 , '' , inline ='D3',group=GR_DT, tooltip =TT_ENDD ,options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
TIMEOK = time >= timestamp(syminfo.timezone, DT_STY, DT_STM, DT_STD, 0, 0) and time < timestamp(syminfo.timezone, DT_ENY, DT_ENM, DT_END, 0, 0)
////////////////////////CALC///////////////////////////////////////////////CALC///////////////////////////////////////////////CALC////////////////////////
SESS = is_session(FI_SES)
BBMA = MA(close,BB_LEN,BB_TYP)
BBDV = BB_STD?(StdDev(close,BB_DVL,DV_TYP)*BB_XDV):(StdDev(BBMA,BB_DVL,DV_TYP)*BB_XDV)
BBUP = BBMA+BBDV
BBDN = BBMA-BBDV
BBMA := SM_BBU?MA(BBMA,SM_LEN,SM_TYP):BBMA
BBUP := SM_BBU?MA(BBUP,SM_LEN,SM_TYP):BBUP
BBDN := SM_BBU?MA(BBDN,SM_LEN,SM_TYP):BBDN
BBDW = (BBUP-BBDN)/BBMA*100
DCDN = ta.lowest (BBDN, DC_LEN)
DCUP = ta.highest (BBUP, DC_LEN)
ATRF = MA(ta.tr,TR_LEN,TR_TYP)
ATRS = TR_SMU?SS(ATRF,TR_SMO):ATRF
///////////////////////CONDITIONS/FILTERS/////////////////////////////////////////////////////CONDITIONS/FILTERS/////////////////////////////
TROK = ((ATRS>TR_XXX) and TR_USE) , BBOK = ((BBDW>BB_PER) and BB_USE)
DCOK = ((DCDN==BBDN or DCUP==BBUP) and DC_USE) //, REST = barstate.isconfirmed and strategy.position_size==0 //if strategy
UPOK = ((DCUP==BBUP) and DC_USE) , TIME = not FI_TIM or TIMEOK
DNOK = ((DCDN==BBDN) and DC_USE) , SSOK = not FI_SEU or SESS
//////////////////////ENTRY/EXITS//////////////////////////////////////////////////ENTRY/EXITS//////////////////////////////////////////////////
//GoSHORT = false
//GoLONGG = false
//if OP_BUY
// if TROK and not BBOK
// GoLONGG:=true
// else if BBOK and UPOK
// GoLONGG:=true
// else
// GoLONGG:=false
//if OP_SEL //for strategy
// if TROK and not BBOK
// GoSHORT:=true
// else if BBOK and DNOK
// GoSHORT:=true
// else
// GoSHORT:=false
//Open_LONG = (close>BBUP and GoLONGG and TIME and SSOK and REST) ,ExLong = DCUP[1]==BBUP[1] and DCUP!=BBUP
//Open_SHRT = (close<BBDN and GoSHORT and TIME and SSOK and REST) ,ExShrt = DCDN[1]==BBDN[1] and DCDN!=BBDN
//if strategy.position_size==0 and Open_LONG
// strategy.entry('L',strategy.long,comment = 'L')
//if strategy.position_size==0 and Open_SHRT
// strategy.entry('S', strategy.short,comment = 'S')
//if strategy.position_size>0 and ExLong
// strategy.close('L',comment = 'ExL')
//if strategy.position_size<0 and ExShrt
// strategy.close('S',comment = 'ExS')
/////////////////////PLOTS/FILLS/BGCOLOR/ETC/////////////////////////////////////PLOTS/FILLS/BGCOLOR/ETC//////////////////
BMA = plot(BB_PLT ? BBMA :na,'BBMA',color.rgb(36, 124, 238) ,linewidth = 1)
BDN = plot(BB_PLT ? BBDN :na,'BBDN',color.rgb(217, 0, 255) ,linewidth = 2)
BUP = plot(BB_PLT ? BBUP :na,'BBUP',color.rgb(217, 0, 255) ,linewidth = 2)
DDN = plot(DC_PLT ? DCDN :na,'DCDN',DCDN==BBDN?na:color.red)
DUP = plot(DC_PLT ? DCUP :na,'DCUP',DCUP==BBUP?na:color.red)
TR1 = plot(CC_REP ? ATRF :na,'ATRF',color.navy) //Overlay = false
TR2 = plot(CC_REP ? ATRS :na,'ATRS',color.blue) //Overlay = false
BBW = plot(CC_REP ? BBDW :na,'BBDW',color.lime) //Overlay = false
BBT = plot(CC_REP ? BB_PER :na,'BBW%',color.gray) //Overlay = false
TRT = plot(CC_REP ? TR_XXX :na,'ATR%',color.teal) //Overlay = false
fill(BUP,BDN, color = CC_FIL?((DCOK and BBOK)? color.rgb(105, 233, 107, 86):TROK and TR_PLT and not BBOK?color.rgb(85, 83, 228, 52):na):na)
bgcolor(SESS and FI_SEU?color.new(#51d755, 91):na)
//fill(BUP,BDN, color = (FILL=='DC'?(UPOK and not DNOK?color.rgb(97, 223, 158, 64):DNOK and not UPOK?color.rgb(232, 85, 66, 48):DCOK?color.rgb(106, 201, 214, 62):na):na))
//fill(BUP,BDN, color = (FILL=='BB'?(BBOK?color.rgb(74, 190, 95, 60):na):na))
//fill(BUP,BDN, color = (FILL=='TR'?(TROK?color.rgb(67, 181, 231, 68):na):na))
//fill(BUP,BDN, color = (FILL=='AL'?(BBOK and DCOK ?color.rgb(88, 221, 93, 63):TROK and not BBOK?color.rgb(108, 87, 200, 53):na):na))
//////////////////SETTINGS//////////////////////////////////////SETTINGS/////////////////////////////////////SETTINGS/////////////////////
/////////5MIN-EURUSD-10%
/////MA - 55,SMA
/////DEV - 55SMA,2
/////SM - 81,RMA
/////BB WIDTH-0,2
/////DC -81
/////tr - 8, 0.00045
/////tr - SMA,14
/////
/////
|
Subsets and Splits