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
|
---|---|---|---|---|---|---|---|---|
Price Filter [AstrideUnicorn] | https://www.tradingview.com/script/FKP3e10S-Price-Filter-AstrideUnicorn/ | AstrideUnicorn | https://www.tradingview.com/u/AstrideUnicorn/ | 269 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AstrideUnicorn
//@version=5
indicator("Price Filter [AstrideUnicorn]")
// Advanced fast price filter
// Adapted from "High-Frequency Trading with MSCI World ETF" by Markus Schmidberger (2018)
// Define inputs
length = input.int(200, minval=1, tooltip = "Length for long-term average")
threshold = input.float(0.5, minval=0, maxval=1, tooltip = "Treshold value to detect trend direction")
use_treshold = input.bool(false, title="Use treshold", tooltip = "Use treshold for the confirmation")
// Calculate price filter
pf = (close - ta.sma(close, length)) / ta.stdev(close, length)
pf_color = pf > pf[1] ? color.green : color.red
// Initialize plot
f_zero = plot(0)
f_filter = plot(pf, linewidth=2, color = pf_color)
plot(threshold, style = plot.style_circles )
plot(-threshold, style = plot.style_circles )
color_fill = pf > 0 ? color.green : color.red
if use_treshold
color_fill := pf > threshold ? color.green : pf < -threshold ? color.red : color.blue
fill(f_zero, f_filter, color_fill) |
Range Bound - Rev NR - 12-25-22 | https://www.tradingview.com/script/aLjTI0qt-Range-Bound-Rev-NR-12-25-22/ | hockeydude84 | https://www.tradingview.com/u/hockeydude84/ | 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/
// © hockeydude84
//@version=5
indicator("Range Bound - Rev NR - 12-25-22", overlay=true, precision = 2)
//Range Bound Code was created by @HockeyDude84
//Range Bound Rev NR - Released on 12-25-2022
//RangeBound - Code tracks price action within a user specified range (lookback), and tracks/charts overall high/lows, open high/lows, and close high/lows
//Code resets certain parameters based on break of range to assist with determine price action - Can be useful to determine resistances to movement regardless of S&R levels
//Code also uses the previous 5X Close High/Lows ranges as will chart as support and resitance to assist with determine resistance to price action
//Note if using "redraw" shorter lookcback periods will take additional time to compile due to multiple "redraws/deletes of previous lines" Uncheck redraw to reduce compile time
//The first code I have decided to publish
////////////////////////////
//Range Bounding ///////////
////////////////////////////
//User inputs
var RB = "Range Bound Inputs"
lookback = input.int(100, title='Lookback Length for Range (Default=100)', minval=1, group=RB)
//Variable Set Up
rangeHigh = ta.highest(high, lookback)
rangeLow = ta.lowest(low, lookback)
rangeOpenHigh = ta.highest(open, lookback)
rangeOpenLow = ta.lowest(open, lookback)
rangeCloseHigh = ta.highest(close, lookback)
rangeCloseLow = ta.lowest(close, lookback)
//Plot Highs and Lows - These are the outer brackets
plot(rangeHigh, color=color.aqua)
plot(rangeLow, color=color.aqua)
//Range Breaks - Look to determine when a range break occurs
rangeHighChange = rangeHigh <=rangeHigh[1] ? 1 : 0
rangeLowChange = rangeLow >=rangeLow[1] ? 1 : 0
rangeOpenHighChange = rangeOpenHigh <=rangeOpenHigh[1] ? 1 : 0
rangeOpenLowChange = rangeOpenLow >=rangeOpenLow[1] ? 1 : 0
rangeCloseHighChange = rangeCloseHigh <=rangeCloseHigh[1] ? 1 : 0
rangeCloseLowChange = rangeCloseLow >=rangeCloseLow[1] ? 1 : 0
//Determine and draw the ranges
//High
var rangeHighCounter = 1
rangeHighCounter := rangeLowChange ==0 ? 1: rangeHighCounter+1
rangeHighFinalLength = rangeHighCounter < lookback ? rangeHighCounter : lookback
rangeHighFinal = ta.highest(high, rangeHighFinalLength)
plot(rangeHighFinal, color=color.lime, linewidth=3)
//Low
var rangeLowCounter = 1
rangeLowCounter := rangeHighChange ==0 ? 1: rangeLowCounter+1
rangeLowFinalLength = rangeLowCounter < lookback ? rangeLowCounter : lookback
rangeLowFinal = ta.lowest(low, rangeLowFinalLength)
plot(rangeLowFinal, color=color.red, linewidth=3)
//Open High
var rangeOpenHighCounter = 1
rangeOpenHighCounter := rangeOpenHighChange ==0 ? 1: rangeOpenHighCounter+1
rangeOpenHighFinalLength = rangeOpenHighCounter < lookback ? rangeOpenHighCounter : lookback
rangeOpenHighFinal = ta.highest(open, rangeOpenHighFinalLength)
plot(rangeOpenHighFinal, color=color.green, linewidth=2)
//Open low
var rangeOpenLowCounter = 1
rangeOpenLowCounter := rangeOpenLowChange ==0 ? 1: rangeOpenLowCounter+1
rangeOpenLowFinalLength = rangeOpenLowCounter < lookback ? rangeOpenLowCounter : lookback
rangeOpenLowFinal = ta.lowest(open, rangeOpenLowFinalLength)
plot(rangeOpenLowFinal, color=color.fuchsia, linewidth=2)
//Close High
var rangeCloseHighCounter = 1
rangeCloseHighCounter := rangeCloseHighChange ==0 ? 1: rangeCloseHighCounter+1
rangeCloseHighFinalLength = rangeCloseHighCounter < lookback ? rangeCloseHighCounter : lookback
rangeCloseHighFinal = ta.highest(close, rangeCloseHighFinalLength)
plot(rangeCloseHighFinal, color=color.olive, linewidth=1)
//Close Low
var rangeCloseLowCounter = 1
rangeCloseLowCounter := rangeCloseLowChange ==0 ? 1: rangeCloseLowCounter+1
rangeCloseLowFinalLength = rangeCloseLowCounter < lookback ? rangeCloseLowCounter : lookback
rangeCloseLowFinal = ta.lowest(close, rangeCloseLowFinalLength)
plot(rangeCloseLowFinal, color=color.orange, linewidth=1)
////////////////////////////
//Support and Resistances //
////////////////////////////
//Use the previously determine ranges for Close High/Low to chart support and resistances
//User Inputs
var S_and_R = "Support and Resistance"
UseChart = input(true, title='Chart Support and Resistance)', group=S_and_R)
UseChartRedraw = input(true, title='Redraw S&R at Each Rangebreak - Reduces Chart Clutter (Default = Yes)', group=S_and_R)
UseLines = (UseChart==true and UseChartRedraw==true) ? 1 : 0
UsePlots = (UseChart==true and UseChartRedraw==false) ? 1 : 0
float preCloseHigh1 = 0
float preCloseHigh2 = 0
float preCloseHigh3 = 0
float preCloseHigh4 = 0
float preCloseHigh5 = 0
HighTrigger = rangeCloseHighChange==0 and rangeCloseHighFinal[1]==rangeCloseHighFinal[14] ? 1 : 0
preCloseHigh1 := HighTrigger==1 ? rangeCloseHighFinal[1] :preCloseHigh1[1]
preCloseHigh2 := HighTrigger==1 ? preCloseHigh1[1] :preCloseHigh2[1]
preCloseHigh3 := HighTrigger==1 ? preCloseHigh2[1] :preCloseHigh3[1]
preCloseHigh4 := HighTrigger==1 ? preCloseHigh3[1] :preCloseHigh4[1]
preCloseHigh5 := HighTrigger==1 ? preCloseHigh4[1] :preCloseHigh5[1]
if(HighTrigger==1 and UseLines==1)
var line h1 = na
var line h2 = na
var line h3 = na
var line h4 = na
var line h5 = na
line.delete(h1)
line.delete(h2)
line.delete(h3)
line.delete(h4)
line.delete(h5)
h1 := line.new(bar_index, preCloseHigh1, bar_index-14, preCloseHigh1, color=color.black, extend=extend.left, style=line.style_dashed)
h2 := line.new(bar_index, preCloseHigh2, bar_index-14, preCloseHigh2, color=color.black, extend=extend.left, style=line.style_dashed)
h3 := line.new(bar_index, preCloseHigh3, bar_index-14, preCloseHigh3, color=color.black, extend=extend.left, style=line.style_dashed)
h4 := line.new(bar_index, preCloseHigh4, bar_index-14, preCloseHigh4, color=color.black, extend=extend.left, style=line.style_dashed)
h5 := line.new(bar_index, preCloseHigh5, bar_index-14, preCloseHigh5, color=color.black, extend=extend.left, style=line.style_dashed)
plot(UsePlots==1 ? preCloseHigh1 : na, color=color.black)
plot(UsePlots==1 ? preCloseHigh2 : na, color=color.black)
plot(UsePlots==1 ? preCloseHigh3 : na, color=color.black)
plot(UsePlots==1 ? preCloseHigh4 : na, color=color.black)
plot(UsePlots==1 ? preCloseHigh5 : na, color=color.black)
//////
//Lows
float preCloseLow1 = 0
float preCloseLow2 = 0
float preCloseLow3 = 0
float preCloseLow4 = 0
float preCloseLow5 = 0
LowTrigger = rangeCloseLowChange==0 and rangeCloseLowFinal[1]==rangeCloseLowFinal[14] ? 1 : 0
preCloseLow1 := LowTrigger==1 ? rangeCloseLowFinal[1] :preCloseLow1[1]
preCloseLow2 := LowTrigger==1 ? preCloseLow1[1] :preCloseLow2[1]
preCloseLow3 := LowTrigger==1 ? preCloseLow2[1] :preCloseLow3[1]
preCloseLow4 := LowTrigger==1 ? preCloseLow3[1] :preCloseLow4[1]
preCloseLow5 := LowTrigger==1 ? preCloseLow4[1] :preCloseLow5[1]
if(LowTrigger==1 and UseLines==1)
var line l1 = na
var line l2 = na
var line l3 = na
var line l4 = na
var line l5 = na
line.delete(l1)
line.delete(l2)
line.delete(l3)
line.delete(l4)
line.delete(l5)
l1 := line.new(bar_index, preCloseLow1, bar_index-14, preCloseLow1, color=color.gray, extend=extend.left, style=line.style_dashed)
l2 := line.new(bar_index, preCloseLow2, bar_index-14, preCloseLow2, color=color.gray, extend=extend.left, style=line.style_dashed)
l3 := line.new(bar_index, preCloseLow3, bar_index-14, preCloseLow3, color=color.gray, extend=extend.left, style=line.style_dashed)
l4 := line.new(bar_index, preCloseLow4, bar_index-14, preCloseLow4, color=color.gray, extend=extend.left, style=line.style_dashed)
l5 := line.new(bar_index, preCloseLow5, bar_index-14, preCloseLow5, color=color.gray, extend=extend.left, style=line.style_dashed)
plot(UsePlots==1 ? preCloseLow1 : na, color=color.gray)
plot(UsePlots==1 ? preCloseLow2 : na, color=color.gray)
plot(UsePlots==1 ? preCloseLow3 : na, color=color.gray)
plot(UsePlots==1 ? preCloseLow4 : na, color=color.gray)
plot(UsePlots==1 ? preCloseLow5 : na, color=color.gray) |
TradingView Party | https://www.tradingview.com/script/SD9dR6TO-TradingView-Party/ | barnabygraham | https://www.tradingview.com/u/barnabygraham/ | 17 | 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
// © HeWhoMustNotBeNamed
// © RicardoSantos
//@version=5
indicator("TradingView Party",max_boxes_count = 500,max_lines_count = 500,max_labels_count = 500,overlay=true)
i_preset = input.string('Custom', title='Background', options=['Light', 'Dark', 'Light+Dark', 'Custom'])
i_h_min = input.int(0, minval=0, maxval=127, title='H', group='HSLT', inline='H')
i_h_max = input.int(255, minval=128, maxval=255, title='', group='HSLT', inline='H')
i_s_min = input.int(50, minval=0, maxval=50, title='S', group='HSLT', inline='S')
i_s_max = input.int(100, minval=51, maxval=100, title='', group='HSLT', inline='S')
i_l_min = input.int(20, minval=0, maxval=51, title='L', group='HSLT', inline='L')
i_l_max = input.int(100, minval=51, maxval=100, title='', group='HSLT', inline='L')
i_transparency = input.int(0, minval=0, maxval=100, title='T', group='HSLT', inline='T')
// ************** This part of the code is taken from // © RicardoSantos
// https://www.tradingview.com/script/4jdGt6Xo-Function-HSL-color/
f_color_hsl(_hue, _saturation, _lightness, _transparency) => //{
// @function: returns HSL color.
// @reference: https://stackoverflow.com/questions/36721830/convert-hsl-to-rgb-and-hex
float _l1 = _lightness / 100.0
float _a = _saturation * math.min(_l1, 1.0 - _l1) / 100.0
float _rk = (0.0 + _hue / 30.0) % 12.0
float _r = 255.0 * (_l1 - _a * math.max(math.min(_rk - 3.0, 9.0 - _rk, 1.0), -1.0))
float _gk = (8.0 + _hue / 30.0) % 12.0
float _g = 255.0 * (_l1 - _a * math.max(math.min(_gk - 3.0, 9.0 - _gk, 1.0), -1.0))
float _bk = (4.0 + _hue / 30.0) % 12.0
float _b = 255.0 * (_l1 - _a * math.max(math.min(_bk - 3.0, 9.0 - _bk, 1.0), -1.0))
color.rgb(_r, _g, _b, _transparency) //
//}
// ************** End of borrowed code
// This part of the code was taken from © HeWhoMustNotBeNamed's random color generator
avoidLight = i_preset == 'Light' or i_preset == 'Light+Dark'
avoidDark = i_preset == 'Dark' or i_preset == 'Light+Dark'
custom = i_preset == 'Custom'
l_min = custom ? i_l_min : avoidDark ? 30 : 0
l_max = custom ? i_l_max : avoidLight ? 70 : 100
h_min = custom ? i_h_min : 0
h_max = custom ? i_h_max : 255
s_min = custom ? i_s_min : 0
s_max = custom ? i_s_max : 100
f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, transparency) =>
f_color_hsl(math.random(h_min, h_max), math.random(s_min, s_max), math.random(l_min, l_max), transparency)
// End of borrowed code
n = bar_index
lineStyle(x) =>
output = x == 1 ? line.style_solid :
x == 2 ? line.style_dotted :
x == 3 ? line.style_dashed :
x == 4 ? line.style_arrow_left :
x == 5 ? line.style_arrow_right : line.style_arrow_both
boxStyle(x) =>
output = x == 1 ? line.style_solid :
x == 2 ? line.style_dotted : line.style_dashed
textSize(x) =>
output = x == 1 ? size.auto :
x == 2 ? size.tiny :
x == 3 ? size.small :
x == 4 ? size.normal :
x == 5 ? size.large : size.huge
line1 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line2 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line3 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line4 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line5 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line6 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line7 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line8 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line9 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line10 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line11 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line12 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line13 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line14 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line15 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line16 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line17 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line18 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line19 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line20 = line.new(n-int(math.random(0,100)),close,n-int(math.round(math.random(0,100),0)),close[int(math.round(math.random(0,100),0))],extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),style=lineStyle(int(math.random(1,6))),width=int(math.random(0,10)))
line.delete(line1[1])
line.delete(line2[1])
line.delete(line3[1])
line.delete(line4[1])
line.delete(line5[1])
line.delete(line6[1])
line.delete(line7[1])
line.delete(line8[1])
line.delete(line9[1])
line.delete(line10[1])
line.delete(line11[1])
line.delete(line12[1])
line.delete(line13[1])
line.delete(line14[1])
line.delete(line15[1])
line.delete(line16[1])
line.delete(line17[1])
line.delete(line18[1])
line.delete(line19[1])
line.delete(line20[1])
box1loc = n+int(math.random(-100,200))
box2loc = n+int(math.random(-200,100))
box3loc = n+int(math.random(-300,0))
box4loc = n+int(math.random(-400,-100))
box5loc = n+int(math.random(-500,-200))
box6loc = n+int(math.random(-600,-300))
box7loc = n+int(math.random(-700,-400))
box8loc = n+int(math.random(-800,-500))
box9loc = n+int(math.random(-900,-600))
box10loc = n+int(math.random(-1000,-700))
box1 = box.new(box1loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box2 = box.new(box2loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box3 = box.new(box3loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box4 = box.new(box4loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box5 = box.new(box5loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box6 = box.new(box6loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box7 = box.new(box7loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box8 = box.new(box8loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box9 = box.new(box9loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box10 = box.new(box10loc-int(math.random(math.random(0,10),math.random(0,100))),close*math.random(1,1.01),box1loc+int(math.random(1,100)),close*math.random(0.99,1),f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),int(math.random(0,10)),boxStyle(int(math.random(1,3))),extend.none,bgcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency+90+math.random(0,10)))
box.delete(box1[1])
box.delete(box2[1])
box.delete(box3[1])
box.delete(box4[1])
box.delete(box5[1])
box.delete(box6[1])
box.delete(box7[1])
box.delete(box8[1])
box.delete(box9[1])
box.delete(box10[1])
verticalLine1 = line.new(n+int(math.round(math.random(-100,100,2),0)),low,n+int(math.round(math.random(-100,100,2),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine2 = line.new(n+int(math.round(math.random(-100,100,3),0)),low,n+int(math.round(math.random(-100,100,3),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine3 = line.new(n+int(math.round(math.random(-100,100,4),0)),low,n+int(math.round(math.random(-100,100,4),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine4 = line.new(n+int(math.round(math.random(-100,100,5),0)),low,n+int(math.round(math.random(-100,100,5),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine5 = line.new(n+int(math.round(math.random(-100,100,6),0)),low,n+int(math.round(math.random(-100,100,6),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine6 = line.new(n+int(math.round(math.random(-100,100,7),0)),low,n+int(math.round(math.random(-100,100,7),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine7 = line.new(n+int(math.round(math.random(-100,100,8),0)),low,n+int(math.round(math.random(-100,100,8),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine8 = line.new(n+int(math.round(math.random(-100,100,9),0)),low,n+int(math.round(math.random(-100,100,9),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine9 = line.new(n+int(math.round(math.random(-100,100,10),0)),low,n+int(math.round(math.random(-100,100,10),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
verticalLine10 = line.new(n+int(math.round(math.random(-100,100,11),0)),low,n+int(math.round(math.random(-100,100,11),0)),high,extend=extend.both,color=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),width=int(math.random(0,30)))
line.delete(verticalLine1[1])
line.delete(verticalLine2[1])
line.delete(verticalLine3[1])
line.delete(verticalLine4[1])
line.delete(verticalLine5[1])
line.delete(verticalLine6[1])
line.delete(verticalLine7[1])
line.delete(verticalLine8[1])
line.delete(verticalLine9[1])
line.delete(verticalLine10[1])
labelText(x) =>
output = x == 1 ? 'Party!' :
x == 2 ? 'Yeah!' :
x == 3 ? 'Woohoo!' :
x == 4 ? 'Alright!' :
x == 5 ? 'Yippee!' :
x == 6 ? 'Incredible!' :
x == 7 ? 'Wow!' :
x == 8 ? 'Really neato!' :
x == 9 ? '☜(⌒▽⌒)☞' :
x == 10 ? '◖♪_♪|◗' :
x == 11 ? '\(^。^ )' :
x == 12 ? '((ヽ(๑╹◡╹๑)ノ))♬' :
x == 13 ? '(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)' :
x == 14 ? '👉😎👉' :
x == 15 ? '(☞ ͡° ͜ʖ ͡°)☞' :
x == 16 ? '🥳🙌🎂 🍰🎈🎉 🎁' :
x == 17 ? '(((o(*゚▽゚*)o)))' : 'ヾ(⌐■_■)ノ♪'
label1 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label2 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label3 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label4 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label5 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label6 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label7 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label8 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label9 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label10 = label.new(n+int(math.random(-100,100)),close[int(math.random(0,50))],labelText(int(math.random(1,18))),style=label.style_flag,textcolor=f_random_color(h_min, h_max, s_min, s_max, l_min, l_max, i_transparency),color=color.new(color.white,100),size=textSize(int(math.random(1,6))))
label.delete(label1[1])
label.delete(label2[1])
label.delete(label3[1])
label.delete(label4[1])
label.delete(label5[1])
label.delete(label6[1])
label.delete(label7[1])
label.delete(label8[1])
label.delete(label9[1])
label.delete(label10[1])
|
RSI on Chart Window | https://www.tradingview.com/script/DxQhOhEJ-RSI-on-Chart-Window/ | KhaiGuru | https://www.tradingview.com/u/KhaiGuru/ | 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/
// © KhaiGuru
//@version=5
indicator("RSI on Chart Window", overlay = true)
rsi_group = "RSI Setting"
rsi_length = input.int(defval = 14, minval = 1, title = "Length", group = rsi_group, inline = "1")
rsi = ta.rsi(close, rsi_length)
//Adjustment factor for the ratio of RSI to match the ratio of the current chart frame, it will be different for each currency pair
tool_tip_rsi = "Adjustment factor for the ratio of RSI to match the ratio of the current chart frame, depending on the currency pair will be different. With Forex factor = about 10, with Oil factor = about 3, with Gold, BTC factor = about 100"
factor_rsi = input.int(defval = 10, title = "Factor", tooltip = tool_tip_rsi, minval = 1, step = 1)
//=======overbought
rsi_overbought1 = input.int(defval = 70, title = "RSI Upper Band", minval = 50, maxval = 100, step = 1, group = rsi_group)
overbought1= plot(close + (rsi_overbought1-50)*factor_rsi*syminfo.mintick, title = "RSI Upper Band", color = color.rgb(175, 125, 125), display = display.none)
label_1 = label.new(bar_index+6, close + (rsi_overbought1-50)*factor_rsi*syminfo.mintick, textcolor= color.rgb(255, 1, 1), style = label.style_none)
label.delete(label_1[1])
//======oversold
rsi_oversold1 = input.int(defval = 30, title = "RSI Lower Band", minval = 1, maxval = 50, step = 1, group = rsi_group)
oversold1= plot(close - (50-rsi_oversold1)*factor_rsi*syminfo.mintick, title = "RSI Lower Band", color = color.rgb(63, 119, 65), display = display.none)
label_3 = label.new(bar_index+6, close - (50-rsi_oversold1)*factor_rsi*syminfo.mintick, textcolor= color.rgb(92, 133, 109) , style = label.style_none)
label.delete(label_3[1])
//==========RSI now
rsi_show_last = input.int(defval = 1000, minval = 5, title = "Show Last", step = 5, group = rsi_group)
rsi_color = (rsi >= rsi_overbought1)? color.red : (rsi <= rsi_oversold1) ? color.green : color.rgb(143, 139, 109)
rsi_now = plot(close + (rsi - 50)*factor_rsi*syminfo.mintick, title = "RSI color", show_last = rsi_show_last, color = rsi_color, display = display.pane)
label_rsi = label.new(bar_index + 4, close + (rsi - 50)*factor_rsi*syminfo.mintick, textcolor = rsi_color, text = "RSI = " + str.tostring(math.round(rsi, 2)), style = label.style_none, textalign = text.align_right)
label.delete((label_rsi[1]))
//===========display Overbought & Oversold candles
plotshape( (rsi >= rsi_overbought1), location = location.abovebar, color = color.red, style = shape.triangledown, display = display.pane)
plotshape( (rsi <= rsi_oversold1), location = location.belowbar, color = color.green, style = shape.triangleup, display = display.pane)
|
Elder Impulse Visualised | https://www.tradingview.com/script/IjviDpMe-Elder-Impulse-Visualised/ | muaaz2603 | https://www.tradingview.com/u/muaaz2603/ | 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/
// © muaaz2603
//@version=5
indicator("MK Elder impulse", overlay = true)
source = close
// MACD Options
macd_length_fast = input.int(title="MACD Fast Length", defval=12, minval=1)
macd_length_slow = input.int(defval=26, minval=1, title="MACD Slow Length")
macd_length_signal = input.int(defval=9, minval=1, title="MACD Signal Length")
// Calculate MACD
macd_ma_fast = ta.ema(source, macd_length_fast)
macd_ma_slow = ta.ema(source, macd_length_slow)
macd = macd_ma_fast - macd_ma_slow
macd_signal = ta.ema(macd, macd_length_signal)
macd_histogram = macd - macd_signal
// EMA Option
ema_length = input.int(defval=13, minval=1, title="EMA Length")
// Calculate EMA
ema = ta.ema(source, ema_length)
// Calculate Elder Impulse
elder_bulls = (ema[0] > ema[1]) and (macd_histogram[0] > macd_histogram[1])
elder_bears = (ema[0] < ema[1]) and (macd_histogram[0] < macd_histogram[1])
elder_color = elder_bulls
? color.green // If Bulls Control Trend and Momentum
: elder_bears
? color.red // If Bears Control Trend and Mementum
: color.blue // If Neither Bulls or Bears Control the Market
barcolor(elder_color)
// Create label on the first bar.
print(txt) =>
var lbl = label.new(bar_index, na, txt, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left)
// On next bars, update the label's x and y position, and the text it displays.
label.set_xy(lbl, bar_index, ta.highest(10)[1])
label.set_text(lbl, str.tostring(txt))
// k = float(2)/13+1
// prev_ema = ta.ema(close[1], 13)
// needed_close = (prev_ema - prev_ema*(1-k))/k
get_required_close_ema(src, len) =>
k = float(2)/len+1
prev_ema = ta.ema(src[1], len)
needed_close = (prev_ema - prev_ema*(1-k))/k
get_required_close_macdh(flen, slen, siglen) =>
kf = float(2)/(flen+1)
ks = float(2)/(slen+1)
ksig = float(2)/(siglen+1)
prev_ema_f = ta.ema(close[1], flen)
prev_ema_s = ta.ema(close[1], slen)
prev_ema_sig = macd_signal[1]
//print(str.tostring(macd_signal[1]))
close_price = (macd_histogram[1] - (prev_ema_f*(1-kf)-prev_ema_s*(1-ks))*(1-ksig) + prev_ema_sig*(1-ksig))/((kf-ks)*(1-ksig))
// close_f = get_required_close_ema(close, 12)
// close_s = get_required_close_ema(close, 26)
// close_macd = get_required_close_ema(macd, 13)
close_needed = get_required_close_ema(close, 13)
macd_close = get_required_close_macdh(12, 26, 13)
max_close = math.max(close_needed, macd_close)
min_close = math.min(close_needed, macd_close)
hit_price = float(0)
float hit_price2 = na
hit_color = color.white
if elder_bulls
hit_price := min_close
hit_color := color.lime
else if elder_bears
hit_price := max_close
hit_color := color.maroon
else
hit_price := min_close
hit_price2 := max_close
plot(max_close, title="Price_needed_green", linewidth = 2, color = color.green)
print(str.tostring(hit_price))
plot(min_close, title="Price_needed_red", linewidth = 1, color = color.red)
//plotshape(needed_close, title = "mjh", style = shape.cross, show_last = 2, locatio)
// mk=0
// if elder_bulls
// mk:=2
|
Manage trade | https://www.tradingview.com/script/spkwL1lg/ | Acneto | https://www.tradingview.com/u/Acneto/ | 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/
// © Acneto
//@version=5
indicator( "Manage trade", "", true )
// --------------------------------------- INPUTS ------------------------------------------- //
// Primeiro preço de entrada
currentPrice = input.float( 0.0, "Current price.........", inline = "entry" ) // First entry price
// Total inicial de moedas
coins = input.float( 0, "Coins", inline = "entry" ) // Initial total coins
// Simular preço segunda entrada
simulateEntry = input.float( 0.0, "Simulate entry.......", inline = "simulateEntry" ) // Simulate second entry price
// Simular nova quantidade de moedas
simulateCoins = input.float( 0, "Coins", inline = "simulateEntry" ) // Simulate new amount of coins
// Simular preço parcial
simulatePartial = input.float( 5.0, "Simulate partial %", inline = "simulatePartial" ) // Simulate partial price
// Simular quantidade parcial de moedas
partialCoins = input.float( 0, "Coins", inline = "simulatePartial" ) // Simulate partial amount of coins
// Montante, dinheiro ou moedas
valueConversion = input.float( 0.0, "Value $", inline = "conversion", group = "currency conversion $ ⮕ ₿" ) // Amount, money or coins
// Preço estimado
targetPrice = input.float( 0.0, "Target price", inline = "conversion", group = "currency conversion $ ⮕ ₿" ) // Estimated price
// Colors
colorCurrPrice = input.color( color.new(#e92907, 37), "Current price", inline = "colors" )
colorNewEntry = input.color( color.new(#00bcd4, 40), "New entry", inline = "colors" )
colorAverage = input.color( color.new(#ff9800, 40), "New avg price", inline = "colors" )
colorPartial = input.color( color.new(#ffeb3b, 40), "Partial price", inline = "colors" )
colorText = input.color( color.rgb(247, 240, 240), "Text", inline = "colors" )
//
iniLine = bar_index+10
endLine = iniLine+10
simbol = syminfo.ticker
// ------------------------------------ CALCULATIONS ---------------------------------------- //
// Conversão de dinheiro para moeda, retorna total de moedas
amountForCoins = valueConversion > 0 ? str.tonumber( str.format( "{0,number,#.#####}", (valueConversion/targetPrice) )) : 0 // Money to currency conversion, return total coins
// Total investido, retorna valor investido
initialAmount = coins*currentPrice // Get total invested, returns invested amount
// Total investimento simulado, retorna valor necessário para investir
simulatedAmount = simulateCoins*simulateEntry // Get total invested simulated, returns amount needed to invest
// Soma total do valor investido+simulado
sumOfAmount = initialAmount+simulatedAmount // Sum invested amount and simulated amount
// Soma total de moedas
sumOfCoins = coins+simulateCoins // Sum invested coins and simulated coins
// Cálculo ganho ou perda sobre o preço médio atual
profitLoss = str.format( "{0,number,#.###}", (coins*(close-currentPrice)) ) // Investment variation
// Atualiza o montante com lucro ou perda
updatedValue = str.format( "{0,number,#.###}", (str.tonumber(profitLoss)+initialAmount) ) // Update amount with profit or loss
// ------------------------------------- FUNCTIONS ------------------------------------------ //
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
plotTable( _partialProfit ) =>
var table _tbl = table.new(position.bottom_right, 7, 2, border_width = 1)
_colorText = (str.tonumber(profitLoss) < 0) ? color.rgb(204, 20, 20) : color.rgb(30, 128, 17)
table.cell_set_text_font_family( _tbl, 2, 1, font.family_monospace )
if (barstate.islast)
table.cell( _tbl, 0, 0, "Simbol", bgcolor = color.new(#d4c78c, 20), width = 6, height = 4 )
table.cell( _tbl, 1, 0, "Current price", bgcolor = color.new(#d4c78c, 20), width = 6, height = 4 )
table.cell( _tbl, 2, 0, "Coins", bgcolor = color.new(#d4c78c, 20), width = 4, height = 4 )
table.cell( _tbl, 3, 0, "Profit / Loss", bgcolor = color.new(#d4c78c, 20), width = 5, height = 4 )
table.cell( _tbl, 4, 0, "Updated value", bgcolor = color.new(#d4c78c, 20), width = 6, height = 4 )
table.cell( _tbl, 5, 0, "Partial profit", bgcolor = color.new(#eeb76f, 20), width = 5, height = 4 )
table.cell( _tbl, 6, 0, "$ ⮕ ₿", bgcolor = color.new(#81ebe2, 20), width = 5, height = 4 )
table.cell( _tbl, 0, 1, str.tostring(simbol), bgcolor = colorCurrPrice, width = 5, height = 4 , text_color = color.white )
table.cell( _tbl, 1, 1, str.tostring(currentPrice), bgcolor = colorCurrPrice, width = 5, height = 4 , text_color = color.white )
table.cell( _tbl, 2, 1, str.tostring(coins), bgcolor = #d6d6d6, width = 5, height = 4 )
table.cell( _tbl, 3, 1, str.tostring(profitLoss), bgcolor = #d6d6d6, width = 5, height = 4, text_color = _colorText )
table.cell( _tbl, 4, 1, str.tostring(updatedValue), bgcolor = #d6d6d6, width = 5, height = 4 )
table.cell( _tbl, 5, 1, str.tostring(_partialProfit), bgcolor = colorPartial, width = 5, height = 4 )
table.cell( _tbl, 6, 1, str.tostring(amountForCoins), bgcolor = #22b5da, width = 5, height = 4 )
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
plotLabel( string _style, string _text, color _color, color _colorText, float _price ) =>
var label _lb = na
label.delete(_lb)
_lb := label.new( endLine, _price, _text )
label.set_text_font_family( _lb, font.family_monospace )
label.set_textalign( _lb, text.align_left )
label.set_color( _lb, _color )
label.set_textcolor( _lb, _colorText )
label.set_style( _lb, _style )
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
plotLines( _price, _color ) =>
var line _ln = na
line.delete(_ln)
_ln := line.new( endLine, _price, iniLine, _price )
line.set_color( _ln, _color )
line.set_style( _ln, line.style_solid )
line.set_width( _ln, 2 )
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
startPlots( _strPrice, _price, _color, _colorText ) =>
plotLines( _price, _color )
plotLabel( label.style_label_left, _strPrice, _color, _colorText, _price )
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
averagePrice( _financial, _coins ) =>
_value = _financial/_coins
_avg = str.tonumber( str.format( "{0,number,#.#########}", _value ) )
// ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
// ----------------------------------------- PLOTS ------------------------------------------ //
// Novo preço médio
averagePrice = averagePrice( sumOfAmount, sumOfCoins ) // New average price
// Simular preço parcial
partialPrice = averagePrice+((simulatePartial*averagePrice)/100) // After new entry, simulate partial
// Lucro parcial
partialProfit = str.format( "{0,number,#.##}", nz( partialCoins*(partialPrice-averagePrice) )) // Calculate partial profit
if simulateCoins > 0
startPlots( "AVG PRICE: "+str.tostring(averagePrice), averagePrice, colorAverage, colorText )
startPlots( "NEW ENTRY: "+str.tostring(simulateEntry), simulateEntry, colorNewEntry, colorText )
if partialCoins > 0
startPlots( "PARTIAL: "+str.tostring(partialPrice), partialPrice, colorPartial, colorText )
if coins > 0 or valueConversion > 0
startPlots( "CURRENT PRICE: "+str.tostring(currentPrice), currentPrice, colorCurrPrice, colorText )
plotTable( partialProfit )
|
VIX Rule of 16 | https://www.tradingview.com/script/ksRDBQAy-VIX-Rule-of-16/ | sevencampbell | https://www.tradingview.com/u/sevencampbell/ | 73 | 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/
// © sevencampbell
//@version=5
indicator('VIX Rule of 16', overlay=true)
vixIndex = input.symbol(title='INDEX', defval='VIX')
tlineCol = input.color(defval=color.red, title="Top Line Color", group='Lines')
blineCol = input.color(defval=color.red, title="Bottom Line Color", group='Lines')
tlineExt = input.int(defval=25, title='Top Line Extension (In Bars/Candles)', group='Lines')
blineExt = input.int(defval=25, title='Bottom Line Extension (In Bars/Candles)', group='Lines')
lWidth = input.int(defval=2, title='Lines Width', group='Lines')
vix = request.security(vixIndex, timeframe.period, open)
InSession(sessionTimes, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTimes, sessionTimeZone))
timeZone = "GMT-5"
sess = "0930-1600"
sess2 = "0930-0931"
daysInput = input.string("123456", title="Trading Days", group="Session",
tooltip="Specifies on which day of\nthe week the session is active. " +
"\nThe session has to be active\non at least one day." +
"\n\nPossible values and days are:\n1 - Sunday\n2 - Monday" +
"\n3 - Tuesday\n4 - Wednesday\n5 - Thursday\n6 - Friday\n7 - Saturday")
tradingSession = sess + ":" + daysInput
tradingSession2 = sess2 + ":" + daysInput
IsSessionOver(sessionTime, sessionTimeZone=syminfo.timezone) =>
inSess = not na(time(timeframe.period, sessionTime, sessionTimeZone))
not inSess and inSess
isFirstAfterSession = IsSessionOver(tradingSession2, timeZone)
is_newbar(res, tradingSession) =>
t = time(res, tradingSession)
na(t[1]) or t[1] < t //and not na(t) //
newbar = InSession(tradingSession2, timeZone) and is_newbar("D", tradingSession)
float s1 = na
s1 := newbar ? open : na
float vixopen = na
vixopen := newbar ? vix : na
vixperc = vixopen / 15.87
highLevel = open + (s1 * (vixperc/100))
lowLevel = open - (s1 * (vixperc/100))
if highLevel
l = line.new(x1=bar_index, y1=highLevel, x2=bar_index+(tlineExt), y2=highLevel, color=tlineCol, width = lWidth, extend=extend.none)
l
if lowLevel
l2 = line.new(x1=bar_index, y1=lowLevel, x2=bar_index+(blineExt), y2=lowLevel, color=blineCol, width = lWidth, extend=extend.none)
l2
|
[Pt] TICK + Heikin Ashi RSI Indicator | https://www.tradingview.com/script/ik6TtcZ7-Pt-TICK-Heikin-Ashi-RSI-Indicator/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 275 | 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("[Pt] TICK + Heikin Ashi RSI Indicator", shorttitle="[Pt] TICK + HARSI", overlay=false)
t1 = time(timeframe.period, "0930-1600:23456", "America/New_York")
tableLocation = input.string(defval='Bottom', options=['Top', 'Bottom'], title='Info Table Location', tooltip='Place information table on the top of the pane or the bottom of the pane. Put on bottom if you like the headers for your indicators visible as they will overlap otherwise.')
// ***************************************************** TICK Indictor *****************************************************
tick_symbol = input.string("USI:TICK", "Symbol", options=['USI:TICK', 'USI:TICKQ', 'USI:TICKA'], group = "TICK")
tickMA_len = input.int(7, title = "TICK EMA length", group = "TICK")
tick_col = input.color(color.new(color.white,0), "TICK Color", group = "TICK", inline = 'tick')
show_tick = input.bool(true,"Show", inline = 'tick', group = "TICK")
tickEMA_col = input.color(color.rgb(161, 255, 250,0), "TICK EMA Color", group = "TICK", inline = 'tickema')
show_tickema = input.bool(true,"Show", inline = 'tickema', group = "TICK")
neutralH = input.int(200, title="Neutral zone +/- from 0", minval = 0, step=10, group = "TICK")
neutralL = -neutralH
BullishH = input.int(800, title="Trend zone +/- from 0", minval = 0, step=10, group = "TICK")
BearishL = -BullishH
OverH = input.int(1000, title="OB/OS extremes +/- from 0", minval = 0, step=10, group = "TICK")
OverL = -OverH
tickC = request.security(tick_symbol, timeframe.period, close)
tickEMA = ta.ema(tickC, tickMA_len)
//----------------------------------------------- TICK Divergence -------------------------------
lbR = input(title='Pivot Lookback Right', defval=2, group = "TICK Divergence")
lbL = input(title='Pivot Lookback Left', defval=2, group = "TICK Divergence")
rangeUpper = input(title='Max of Lookback Range', defval=60, group = "TICK Divergence")
rangeLower = input(title='Min of Lookback Range', defval=5, group = "TICK Divergence")
plotBull = input(title='Plot Bullish', defval=true, group = "TICK Divergence")
plotHiddenBull = input(title='Plot Hidden Bullish', defval=true, group = "TICK Divergence")
plotBear = input(title='Plot Bearish', defval=true, group = "TICK Divergence")
plotHiddenBear = input(title='Plot Hidden Bearish', defval=true, group = "TICK Divergence")
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
plFound = na(ta.pivotlow(tickC, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(tickC, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
// Regular Bullish
// Osc: Higher low
oscHL = tickC[lbR] > ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1])
// Price: Lower low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond ? bullColor : noneColor)
plotshape(bullCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish Label', text=' Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower low
oscLL = tickC[lbR] < ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1])
// Price: Higher low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower high
oscLH = tickC[lbR] < ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1])
// Price: Higher high
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish', linewidth=2, color=bearCond ? bearColor : noneColor)
plotshape(bearCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish Label', text=' Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher high
oscHH = tickC[lbR] > ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1])
// Price: Lower high
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish', linewidth=2, color=hiddenBearCond ? hiddenBearColor : noneColor)
plotshape(hiddenBearCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text=' H Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0))
// **************************************************** HARSI *************************************************
rsi_source = close
rsi_len = input.int(7, "RSI length", group="RSI")
rsi_smoothing = input.int(1, "RSI smoothing", group="RSI")
rsi_col = input.color(color.new(color.yellow,0),"RSI color", group = "RSI", inline ='rsi')
show_rsi = input.bool(true, "Show", inline ='rsi', group = "RSI")
show_harsi = input.bool(true, "Show HARSI", group="HARSI")
HARSI_len = input.int(14, "HARSI length", group="HARSI")
HARSI_smoothing = input.int(1, "HARSI smoothing", group="HARSI")
// RSI Heikin-Ashi generation function
f_rsiHeikinAshi( _length ) =>
float _closeRSI = ta.rsi( close, _length )
float _openRSI = nz( _closeRSI[1], _closeRSI )
float _highRSI_raw = ta.rsi( high, _length )
float _lowRSI_raw = ta.rsi( low, _length )
float _highRSI = math.max( _highRSI_raw, _lowRSI_raw )
float _lowRSI = math.min( _highRSI_raw, _lowRSI_raw )
float _close = ( _openRSI + _highRSI + _lowRSI + _closeRSI ) / 4
var float _open = na
_open := na( _open[ HARSI_smoothing ] ) ? ( _openRSI + _closeRSI ) / 2 :
( ( _open[1] * HARSI_smoothing ) + _close[1] ) / (HARSI_smoothing + 1 )
float _high = math.max( _highRSI, math.max( _open, _close ) )
float _low = math.min( _lowRSI, math.min( _open, _close ) )
[ _open, _high, _low, _close ]
RSI = ta.sma(ta.rsi(rsi_source, rsi_len),rsi_smoothing)
[ O, H, L, C ] = f_rsiHeikinAshi( HARSI_len )
RSI_scaled = RSI*40 - 2000
O_scaled = O*40 - 2000
H_scaled = H*40 - 2000
L_scaled = L*40 - 2000
C_scaled = C*40 - 2000
//****************************************** Trend / Signal Conditions **********************************************
var trend = 0
bulltick = (tickC > neutralH and tickC < 1000) or (trend[1] == 1 and tickC[1] > neutralL and tickC > neutralL)
beartick = (tickC < neutralL and tickC > -1000) or (trend[1] == -1 and tickC[1] < neutralH and tickC < neutralH)
bulltickMA = (tickEMA > 0 and tickEMA < 1000)
beartickMA = (tickEMA < 0 and tickEMA > -1000)
// Green or red HARSI candle
TICKHA_bull_0 = C > O and C >= C[1]
TICKHA_bear_0 = C < O and C <= C[1]
// Inside bar HARSI candle
TICKHA_bull_1 = C[1] < O[1] and C > C[1]
TICKHA_bear_1 = C[1] > O[1] and C < C[1]
// trend continuation based on TICK, regardless of HARSI
TICKHA_bull_2 = trend[1] == 1 and tickC > neutralL
TICKHA_bear_2 = trend[1] == -1 and tickC < neutralH
// trend continuation before RSI and HARSI crossover
TICKHA_bull_3 = trend[1] == 1 and RSI > H
TICKHA_bear_3 = trend[1] == -1 and RSI < L
rsi_bull = RSI > 50 or RSI < 30
rsi_bear = RSI < 50 or RSI > 70
sub_bull = TICKHA_bull_0 or TICKHA_bull_1 or TICKHA_bull_2 or TICKHA_bull_3
sub_bear = TICKHA_bear_0 or TICKHA_bear_1 or TICKHA_bear_2 or TICKHA_bear_3
TICKHA_bull = sub_bull and rsi_bull and bulltick and bulltickMA
TICKHA_bear = sub_bear and rsi_bear and beartick and beartickMA
trend := not(t1) ? 0 : TICKHA_bull and not(TICKHA_bear) ? 1 : TICKHA_bear and not(TICKHA_bull) ? -1 : trend[1]
trend := trend == 1 and not(sub_bull) and sub_bear ? 0 : trend == -1 and not(sub_bear) and sub_bull ? 0 : trend
// *********************************************** Plots ************************************************************
OB = hline(OverH, color=color.gray, linestyle=hline.style_dashed)
upperbull = hline(BullishH, color=color.gray, linestyle=hline.style_dashed)
lowerbull = hline(neutralH, color=color.gray, linestyle=hline.style_dashed)
median = hline(0, color=color.orange, linestyle = hline.style_dotted, linewidth = 2)
upperbear = hline(neutralL, color=color.gray, linestyle=hline.style_dashed)
lowerbear = hline(BearishL, color=color.gray, linestyle=hline.style_dashed)
OS = hline(OverL, color=color.gray, linestyle=hline.style_dashed)
fill( upperbull, OB, color.new(color.green,90))
fill( lowerbull, upperbull, color.new(color.green,80))
fill( lowerbull, upperbear, color.new(color.gray,90))
fill( upperbear, lowerbear, color.new(color.red,80))
fill( lowerbear, OS, color.new(color.red,90))
color bodyColour = C > O ? color.teal : color.red
color wickColour = color.gray
plotcandle( O_scaled, H_scaled, L_scaled, C_scaled, "HARSI", show_harsi ? bodyColour : na, show_harsi ? wickColour : na, bordercolor = show_harsi ? bodyColour : na )
plot(show_tick ? tickC : na, title='TICK shadow', color = t1 ? color.rgb( 0, 0, 0, 50 ) : na , style=plot.style_linebr, linewidth = 4)
plot(show_tick ? tickC : na, title='TICK', color = t1 ? tick_col : na , style=plot.style_linebr, linewidth = 2)
plot(show_tickema ? tickEMA : na, title='TICK EMA shadow', color = t1 ? color.rgb( 0, 0, 0, 50 ) : na , style=plot.style_linebr, linewidth = 4)
plot(show_tickema ? tickEMA : na, title='TICK EMA', color = t1 ? tickEMA_col : na , style=plot.style_linebr, linewidth = 2)
plot(show_rsi ? RSI_scaled : na, title='RSI shadow', color = color.rgb( 0, 0, 0, 50 ) , style=plot.style_linebr, linewidth = 4)
plot(show_rsi ? RSI_scaled : na, title='RSI', color = rsi_col , style=plot.style_linebr, linewidth = 2)
plotshape(TICKHA_bull_0,"Bull 0", color=color.new(color.green,70), style=shape.circle, location = location.bottom, size = size.tiny )
plotshape(TICKHA_bear_0,"Bear 0", color=color.new(color.red,70), style=shape.circle, location = location.top, size = size.tiny )
plotshape(TICKHA_bull_1,"Bull 1", color=color.new(color.green,70), style=shape.circle, location = location.bottom, size = size.tiny )
plotshape(TICKHA_bear_1,"Bear 1", color=color.new(color.red,70), style=shape.circle, location = location.top, size = size.tiny )
plotshape(TICKHA_bull_2,"Bull 2", color=color.new(color.green,70), style=shape.circle, location = location.bottom, size = size.tiny )
plotshape(TICKHA_bear_2,"Bear 2", color=color.new(color.red,70), style=shape.circle, location = location.top, size = size.tiny )
plotshape(TICKHA_bull_3,"Bull 3", color=color.new(color.green,70), style=shape.circle, location = location.bottom, size = size.tiny )
plotshape(TICKHA_bear_3,"Bear 3", color=color.new(color.red,70), style=shape.circle, location = location.top, size = size.tiny )
plotshape(TICKHA_bull,"Bull", color=color.new(color.green,0), style=shape.circle, location = location.bottom, size = size.tiny )
plotshape(TICKHA_bear,"Bear", color=color.new(color.red,0), style=shape.circle, location = location.top, size = size.tiny )
bgcolor(not(t1) ? color.new(color.white,95) : na)
bgcolor(trend == 1 ? color.new(color.green, 85) : trend == -1 ? color.new(color.red, 85) : na)
// ------------------------------------------ Stats Display -------------------------------------------------------------
tablePosition = tableLocation == 'Top' ? position.top_right : position.bottom_right
var table displayTable = table.new(tablePosition, 2, 1, border_width=3)
f_fillCell(_column, _cellText, _c_color) =>
table.cell(displayTable, _column, 0, _cellText, bgcolor=color.new(_c_color, 75), text_color=_c_color)
posColor = color.new(color.green,0)
negColor = color.new(color.red,0)
posDeColor = color.new(color.blue,0)
negDeColor = color.new(color.orange,0)
neuColor = color.new(color.gray,0)
// --- TICK stats ---
tick_neutral = tickEMA < neutralH and tickEMA > neutralL
tick_bull_ext = tickC > 800
tick_bear_ext = tickC < -800
tick_bull = trend > 0 and not(tick_neutral) and not(tick_bull_ext)
tick_bear = trend < 0 and not(tick_neutral) and not(tick_bear_ext)
tick_NeuBull = trend > 0 and tick_neutral
tick_NeuBear = trend < 0 and tick_neutral
if barstate.islast
f_fillCell(0, "TICK trend: " + (tick_bull ? "Bullish" : tick_bear ? "Bearish" : tick_NeuBull ? "Neutral w/ Bullish bias" : tick_NeuBear ? "Neutral, Bearish bias" : tick_bull_ext ? "Bullish, Extended" : tick_bear_ext ? "Bearish, Extended" : "Neutral" ), trend > 0 ? posColor : trend < 0 ? negColor : neuColor)
f_fillCell(1, "RSI: " + (RSI > 50 ? "Bullish" : RSI < 50 ? "Bearish" : "Neutral"), RSI > 50 ? posColor : RSI < 50 ? negColor : neuColor)
|
High Low Bars in Color | https://www.tradingview.com/script/vfD7D01T-High-Low-Bars-in-Color/ | MrJulius | https://www.tradingview.com/u/MrJulius/ | 12 | 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/
// © MrJulius
// @version=5
// Color is determined by change in midpoints between high and low (hl2). Traditional direction is indicated by "frosting" markers
// for open ("+") and close("x").
// Best used in combination with High Low Color Volume.
indicator("High Low Bars in Color", overlay=true)
// constants
string COLOR_METHOD_TOOLTIP = "Standard deviation threshold refers to vector change in hl2 from one bar to the next. The SMA delta absolute values method uses a percentage threshold. Percent change threshold is useful for an overview of volatility. Tritone is up/down/flat hl2 without any in-between shading."
// inputs
color upcolorInput = input.color(color.rgb(0, 137, 123, 0), "Up", group = "Color Palette")
color downcolorInput = input.color(color.rgb(255, 82, 82, 0), "Down", group = "Color Palette")
color flatcolorInput = input.color(color.rgb(97, 55, 145, 0), "Flat", group = "Color Palette")
color bordertoneInput = input.color(color.rgb(160, 160, 160, 0), "Border", group="Frosting")
bool drawborderInput = input.bool(true, "Border frosting", group = "Frosting")
bool showopencloseInput = input.bool(false, "Open and close frosting", group = "Frosting")
string colormethodInput = input.string("StDev", "Color method", ["StDev", "SMA D Abs", "Percent", "Tritone"],
COLOR_METHOD_TOOLTIP, group = "Color Method")
float stdevInput = input.float(1.2, "Standard deviation threshold", group = "Color Method")
int percentileInput = input.int(150, "Percentage of SMA for hl2 delta absolute values", group = "Color Method")
int deltasmalengthInput = input.int(30, "Length for St Dev or SMA", group = "Color Method")
float percentchangeInput = input.float(0.05, "Percent change threshold", group = "Color Method")
// traditional doji
traddoji = close == open
// set color
difference = hl2 - hl2[1]
deltapercent = 100*difference / hl2[1]
deltastdev = ta.stdev(difference, deltasmalengthInput)
deltaabs = math.abs(difference)
deltaabssma = ta.sma(deltaabs, deltasmalengthInput)
color candlecolor = switch colormethodInput
"StDev" => difference > deltastdev * stdevInput ? upcolorInput :
difference > 0 ?
color.from_gradient(difference * 100 / (deltastdev * stdevInput), 0, 100, flatcolorInput, upcolorInput) :
difference == 0 ? flatcolorInput :
difference > -1 * deltastdev * stdevInput ?
color.from_gradient(difference * 100 / (deltastdev * stdevInput), -100, 0, downcolorInput, flatcolorInput) :
downcolorInput
"SMA D Abs" => difference > deltaabssma * percentileInput / 100 ? upcolorInput :
difference > 0 ?
color.from_gradient(difference * 10000 / (deltaabssma * percentileInput), 0, 100, flatcolorInput, upcolorInput) :
difference == 0 ? flatcolorInput :
difference > -1 * deltaabssma * percentileInput / 100 ?
color.from_gradient(difference * 10000 / (deltaabssma * percentileInput), -100, 0, downcolorInput, flatcolorInput) :
downcolorInput
"Percent" => deltapercent > percentchangeInput ? upcolorInput :
deltapercent > 0 ?
color.from_gradient(deltapercent * 100 / percentchangeInput, 0, 100, flatcolorInput, upcolorInput) :
deltapercent == 0 ? flatcolorInput :
deltapercent > -1 * percentchangeInput ?
color.from_gradient(deltapercent * 100 / percentchangeInput, -100, 0, downcolorInput, flatcolorInput) :
downcolorInput
"Tritone" => hl2 > hl2[1] ? upcolorInput : hl2 < hl2[1] ? downcolorInput : flatcolorInput
// plot candle body
plotcandle(high, high, low, low, color=candlecolor, bordercolor = drawborderInput ? bordertoneInput : candlecolor, wickcolor=na, title="High Low Color")
// plot open and close frosting
plotshape(showopencloseInput and not traddoji ? open : na, "open", shape.cross, location.absolute, color.white, size=size.tiny)
plotshape(showopencloseInput and not traddoji ? close : na, "close", shape.xcross, location.absolute, color.white, size=size.tiny)
plotshape(showopencloseInput and traddoji ? open : na, "open = close", shape.diamond, location.absolute, color.white, size=size.tiny) |
High Low Color Volume | https://www.tradingview.com/script/QXKFKHfW-High-Low-Color-Volume/ | MrJulius | https://www.tradingview.com/u/MrJulius/ | 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/
// © MrJulius
// @version=5
// Companion to High Low Bars in Color. Color is determined by change in midpoints between high and low (hl2).
indicator("High Low Color Volume", overlay=true, scale=scale.left, format=format.volume)
// constants
string COLOR_METHOD_TOOLTIP = "Standard deviation threshold refers to vector change in hl2 from one bar to the next. The SMA delta absolute values method uses a percentile threshold. Percent change threshold is useful for an overview of volatility. Tritone colors the bars without any in-between shading."
// inputs
color upcolorInput = input.color(color.rgb(0, 137, 123, 0), "Up", group = "Color Palette")
color downcolorInput = input.color(color.rgb(255, 82, 82, 0), "Down", group = "Color Palette")
color flatcolorInput = input.color(color.rgb(97, 55, 145, 0), "Flat", group = "Color Palette")
int lumfactorInput = input.int(160, "Luminance factor", group = "Color Palette")
string colormethodInput = input.string("StDev", "Color method", ["StDev", "SMA D Abs", "Percent", "Tritone"],
COLOR_METHOD_TOOLTIP, group = "Color Method")
float stdevInput = input.float(1.2, "Standard deviation threshold", group = "Color Method")
int percentileInput = input.int(150, "Percentage of SMA for hl2 delta absolute values", group = "Color Method")
int deltasmalengthInput = input.int(30, "Length for St Dev or SMA", group = "Color Method")
float percentchangeInput = input.float(0.05, "Percent change threshold", group = "Color Method")
bool showsmaInput = input.bool(true, "Show SMA", group = "SMA")
int smalengthInput = input.int(30, "Julius volume SMA length", group = "SMA")
// set color
upcolor = color.rgb(color.r(upcolorInput) * lumfactorInput / 255,
color.g(upcolorInput) * lumfactorInput / 255,
color.b(upcolorInput) * lumfactorInput / 255,
color.t(upcolorInput))
downcolor = color.rgb(color.r(downcolorInput) * lumfactorInput / 255,
color.g(downcolorInput) * lumfactorInput / 255,
color.b(downcolorInput) * lumfactorInput / 255,
color.t(downcolorInput))
flatcolor = color.rgb(color.r(flatcolorInput) * lumfactorInput / 255,
color.g(flatcolorInput) * lumfactorInput / 255,
color.b(flatcolorInput) * lumfactorInput / 255,
color.t(flatcolorInput))
difference = hl2 - hl2[1]
deltapercent = 100*difference / hl2[1]
deltastdev = ta.stdev(difference, deltasmalengthInput)
deltaabs = math.abs(difference)
deltaabssma = ta.sma(deltaabs, deltasmalengthInput)
color candlecolor = switch colormethodInput
"StDev" => difference > deltastdev * stdevInput ? upcolor :
difference > 0 ?
color.from_gradient(difference * 100 / (deltastdev * stdevInput), 0, 100, flatcolor, upcolor) :
difference == 0 ? flatcolor :
difference > -1 * deltastdev * stdevInput ?
color.from_gradient(difference * 100 / (deltastdev * stdevInput), -100, 0, downcolor, flatcolor) :
downcolor
"SMA D Abs" => difference > deltaabssma * percentileInput / 100 ? upcolor :
difference > 0 ?
color.from_gradient(difference * 10000 / (deltaabssma * percentileInput), 0, 100, flatcolor, upcolor) :
difference == 0 ? flatcolor :
difference > -1 * deltaabssma * percentileInput / 100 ?
color.from_gradient(difference * 10000 / (deltaabssma * percentileInput), -100, 0, downcolor, flatcolor) :
downcolor
"Percent" => deltapercent > percentchangeInput ? upcolor :
deltapercent > 0 ?
color.from_gradient(deltapercent * 100 / percentchangeInput, 0, 100, flatcolor, upcolor) :
deltapercent == 0 ? flatcolor :
deltapercent > -1 * percentchangeInput ?
color.from_gradient(deltapercent * 100 / percentchangeInput, -100, 0, downcolor, flatcolor) :
downcolor
"Tritone" => hl2 > hl2[1] ? upcolor : hl2 < hl2[1] ? downcolor : flatcolor
// plot volume
plot(volume, "Color Vol", candlecolor, style=plot.style_columns)
plot(showsmaInput ? ta.sma(volume, smalengthInput) : na, "Vol SMA", color.rgb(129, 209, 255))
|
SessionAndTimeFct_public | https://www.tradingview.com/script/y6dDFMHP/ | LudoGH68 | https://www.tradingview.com/u/LudoGH68/ | 7 | 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/
// © LudoGH68
//@version=5
// @description: All functions to be used for session or time processing
library("SessionAndTimeFct_public", true)
// @function: Check if actual bar is in specific session with specific time zone
// @param sessionTime: session time to check
// @param sessionTimeZone: time zone to use
export is_in_session(string sessionTime, string sessionTimeZone) =>
not na(time(timeframe.period, sessionTime, sessionTimeZone))
// @function: Check if actual bar the first bar of a specific session
// @param sessionTime: session time to check
// @param sessionTimeZone: time zone to use
export is_session_start(string sessionTime, string sessionTimeZone=syminfo.timezone) =>
inSess = not na(time(timeframe.period, sessionTime, sessionTimeZone))
inSess and not inSess[1]
// @function: Check if a new day started
// @param sessionTime: time zone to use
export is_new_day(string timeZone) =>
dayofmonth(time, timeZone) != dayofmonth(time, timeZone)[1]
// @function: Check if a new week started
// @param sessionTime: time zone to use
export is_new_week(string timeZone) =>
weekofyear(time, timeZone) != weekofyear(time, timeZone)[1]
// @function: Check if a new month started
// @param sessionTime: time zone to use
export is_new_month(string timeZone) =>
month(time, timeZone) != month(time, timeZone)[1]
// @function: Check if an element is to show compared to a specific timeframe >
// @param base: S for seconds, m for minutes, D for days, W for weeks and M for months
// @param value: value of base to compare
export is_element_to_show_with_tf_up(string base, int value) =>
// value to return
bool res = false
// Seconds
if(base == 'S')
res := timeframe.multiplier > value
// Minutes
if(base == 'm')
res := (timeframe.isminutes and timeframe.multiplier > value) or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly
// Days
if(base == 'D')
res := timeframe.isdaily and timeframe.multiplier > value or timeframe.isweekly or timeframe.ismonthly
// Weeks
if(base == 'W')
res := timeframe.isweekly and timeframe.multiplier > value or timeframe.ismonthly
// Months
if(base == 'M')
res := timeframe.isminutes and timeframe.multiplier > value
// Return boolean result
res
// @function: Check if an element is to show compared to a specific timeframe <
// @param base: S for seconds, m for minutes, D for days, W for weeks and M for months
// @param value: value of base to compare
export is_element_to_show_with_tf_down(string base, int value) =>
// value to return
bool res = false
// Seconds
if(base == 'S')
res := timeframe.multiplier < value
// Minutes
if(base == 'm')
res := timeframe.isminutes and timeframe.multiplier < value
// Days
if(base == 'D')
res := (timeframe.isdaily and timeframe.multiplier < value) or timeframe.isminutes
// Weeks
if(base == 'W')
res := timeframe.isweekly and timeframe.multiplier < value or timeframe.isminutes or timeframe.isdaily
// Months
if(base == 'M')
res := timeframe.isminutes and timeframe.multiplier < value or timeframe.isminutes or timeframe.isdaily or timeframe.isweekly
// Return boolean result
res |
store - larger data storage for complex item types | https://www.tradingview.com/script/2gENSFAL-store-larger-data-storage-for-complex-item-types/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 13 | 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/
// © kaigouthro
//@version=5
//@description Object/Property Storage System.semi Simplified.
// Set an object up, and add as man properties as ou wish.
// a property can be one of any pine built in types. so a single
// object can contain sa, ohlc each with a color, a float, an assigned int
// and those 4 props each have 3 sub-assigned values.
// as in demo, the alternating table object has 2 different tables
// it's a pseudo more complex wa to create our own flexible
// version of a UDT, but that will not ~break~ on library updates
// so you can update awa without fear, as this libb will no change
// saving ou the hassle of creating UDT's that continually change.
library("store")
export type boxdict
matrix<string> keys
matrix<box> items
export type booldict
matrix<string> keys
matrix<bool> items
export type colordict
matrix<string> keys
matrix<color> items
export type floatdict
matrix<string> keys
matrix<float> items
export type intdict
matrix<string> keys
matrix<int> items
export type labeldict
matrix<string> keys
matrix<label> items
export type linedict
matrix<string> keys
matrix<line> items
export type linefilldict
matrix<string> keys
matrix<linefill> items
export type stringdict
matrix<string> keys
matrix<string> items
export type tabledict
matrix<string> keys
matrix<table> items
export type dictionary
boxdict boxs
booldict bools
colordict colors
floatdict floats
intdict ints
labeldict labels
linedict lines
linefilldict linefills
stringdict strings
tabledict tables
matrix<string> keys
export type item
int objCol = na
int propRow = na
string object = na
string property = na
string actionItem = ''
// @type Dictionar OF dictionaries
// for the intrepid mad scientists..
// theoretically, have as many as TV servers can handle
// dictionaries with slices (individual types)
// as many as ou want in any config ou want.
export type dictionaries
dictionary[] dicts
// set some constants internal
var _REMOVEOBJ = 'remove obj'
var _REMOVEPROP= 'remove prop'
var _GET = 'get'
var _DELETE = 'delete'
var _SET = 'set'
_createID(item _idx, matrix<string> _keys)=>
_newIDX = item.copy(_idx)
switch
na(_idx.objCol) or na(_idx.propRow) =>
_objkeys = matrix.row ( _keys , 0 )
_hasobject = array.includes ( _objkeys , _newIDX.object )
_newIDX.objCol := array.indexof ( _objkeys , _hasobject ? _newIDX.object : string(na))
if not _hasobject
matrix.set ( _keys, 0 , _newIDX.objCol , _newIDX.object )
_objprops = matrix.col ( _keys , _newIDX.objCol )
_hasproperty = array.includes ( _objprops , _newIDX.property )
_newIDX.propRow := array.indexof ( _objprops , _hasproperty ? _newIDX.property : string(na))
if not _hasproperty
matrix.set(_keys, _newIDX.propRow , _newIDX.objCol , _newIDX.property )
=>
_newIDX.objCol := _idx.objCol
_newIDX.propRow := _idx.propRow
_newIDX
_action( _item, subdict, item _idx )=>
// create index
_index = _createID(_idx,subdict.keys)
string _object = _idx.object
string _property = _idx.property
_keys = subdict.keys
_vals = subdict.items
_naItem = matrix.get(_vals ,0 , 0 )
_itemwas= matrix.get(_vals ,_index.propRow , _index.objCol )
_out = switch _idx.actionItem
_GET => matrix.get(_vals ,_index.propRow , _index.objCol )
_SET => matrix.set(_vals ,_index.propRow , _index.objCol , _item ), _item
_DELETE => matrix.set(_vals ,_index.propRow , _index.objCol , _naItem ), _itemwas
=> _naItem
_index.actionItem := ''
subdict.keys := _keys
subdict.items := _vals
[_out, _index]
import kaigouthro/columns/2
_remove(dictionary _dict, item _idx)=>
_newIDX = item.copy(_idx)
_objkeys = matrix.row ( _dict.keys , 0 )
_hasobject = array.includes ( _objkeys , _newIDX.object )
if _hasobject
_newIDX.objCol:= array.indexof ( _objkeys , _newIDX.object )
_objprops = matrix.col ( _dict.keys , _newIDX.objCol )
_hasproperty = array.includes ( matrix.col ( _dict.keys , _newIDX.objCol ) , _newIDX.property )
if _hasproperty
_newIDX.propRow := array.indexof ( _objprops , _newIDX.property )
switch _idx.actionItem
_REMOVEOBJ =>
int _rows = matrix.rows(_dict.bools.keys)
columns.set(_dict.bools.keys , _newIDX.objCol, array.new_string (_rows))
columns.set(_dict.boxs.items , _newIDX.objCol, array.new_box (_rows))
columns.set(_dict.bools.items , _newIDX.objCol, array.new_bool (_rows))
columns.set(_dict.colors.items , _newIDX.objCol, array.new_color (_rows))
columns.set(_dict.floats.items , _newIDX.objCol, array.new_float (_rows))
columns.set(_dict.ints.items , _newIDX.objCol, array.new_int (_rows))
columns.set(_dict.labels.items , _newIDX.objCol, array.new_label (_rows))
columns.set(_dict.lines.items , _newIDX.objCol, array.new_line (_rows))
columns.set(_dict.linefills.items , _newIDX.objCol, array.new_linefill(_rows))
columns.set(_dict.strings.items , _newIDX.objCol, array.new_string (_rows))
columns.set(_dict.tables.items , _newIDX.objCol, array.new_table (_rows))
_REMOVEPROP =>
if _hasproperty
matrix.set (_dict.bools.keys , _newIDX.propRow, _newIDX.objCol, string (na))
matrix.set (_dict.boxs.items , _newIDX.propRow, _newIDX.objCol, box (na))
matrix.set (_dict.bools.items , _newIDX.propRow, _newIDX.objCol, bool (na))
matrix.set (_dict.colors.items , _newIDX.propRow, _newIDX.objCol, color (na))
matrix.set (_dict.floats.items , _newIDX.propRow, _newIDX.objCol, float (na))
matrix.set (_dict.ints.items , _newIDX.propRow, _newIDX.objCol, int (na))
matrix.set (_dict.labels.items , _newIDX.propRow, _newIDX.objCol, label (na))
matrix.set (_dict.lines.items , _newIDX.propRow, _newIDX.objCol, line (na))
matrix.set (_dict.linefills.items , _newIDX.propRow, _newIDX.objCol, linefill(na))
matrix.set (_dict.strings.items , _newIDX.propRow, _newIDX.objCol, string (na))
matrix.set (_dict.tables.items , _newIDX.propRow, _newIDX.objCol, table (na))
_idx.actionItem := ''
_idx
//@function Add/Updates item to storage. Autoselects subclass dictionary on set
//@param dict (dictionary) dict.type subdictionary (req for overload)
//@param _object (string) object name
//@param _property (string) property name
//@param _item (<any>) item to set
//@param _idx (item) item to set
//@returns item item wwith column/row
export method set( dictionary dict , string _object ,string _prop, bool _item) =>
[_passthrough,_idx] = _action( _item, dict.bools , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, box _item) =>
[_passthrough,_idx] = _action( _item, dict.boxs , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, color _item) =>
[_passthrough,_idx] = _action( _item, dict.colors , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, float _item) =>
[_passthrough,_idx] = _action( _item, dict.floats , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, int _item) =>
[_passthrough,_idx] = _action( _item, dict.ints , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, label _item) =>
[_passthrough,_idx] = _action( _item, dict.labels , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, line _item) =>
[_passthrough,_idx] = _action( _item, dict.lines , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, linefill _item) =>
[_passthrough,_idx] = _action( _item, dict.linefills , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, string _item) =>
[_passthrough,_idx] = _action( _item, dict.strings , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , string _object ,string _prop, table _item) =>
[_passthrough,_idx] = _action( _item, dict.tables , item.new(na,na,_object,_prop, _SET) )
_idx
export method set( dictionary dict , item _index, bool _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.bools , _index)
_idx
export method set( dictionary dict , item _index, box _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.boxs , _index)
_idx
export method set( dictionary dict , item _index, color _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.colors , _index)
_idx
export method set( dictionary dict , item _index, float _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.floats , _index)
_idx
export method set( dictionary dict , item _index, int _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.ints , _index)
_idx
export method set( dictionary dict , item _index, label _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.labels , _index)
_idx
export method set( dictionary dict , item _index, line _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.lines , _index)
_idx
export method set( dictionary dict , item _index, linefill _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.linefills , _index)
_idx
export method set( dictionary dict , item _index, string _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.strings , _index)
_idx
export method set( dictionary dict , item _index, table _item) =>
_index.actionItem := _SET
[_passthrough,_idx] = _action( _item, dict.tables , _index)
_idx
//@function Get item by object name and property (string)
//@param typedict (<any>dict) dict.type subdictionary (req for overload)
//@param _object (string) object name
//@param _property (string) property name
//@param _index (string) item object with coords
//@returns <type> item from storage
export method get(boxdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( box(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(booldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( bool(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(colordict typedict, string _object , string _prop)=>
[_item,_idx] = _action( color(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(floatdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( float(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(intdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( int(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(labeldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( label(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(linedict typedict, string _object , string _prop)=>
[_item,_idx] = _action( line(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(linefilldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( linefill(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(stringdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( string(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(tabledict typedict, string _object , string _prop)=>
[_item,_idx] = _action( table(na) , typedict , item.new(na,na,_object,_prop, _GET))
_item
export method get(boxdict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( box(na) , typedict , _index)
_item
export method get(booldict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( bool(na) , typedict , _index)
_item
export method get(colordict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( color(na) , typedict , _index)
_item
export method get(floatdict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( float(na) , typedict , _index)
_item
export method get(intdict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( int(na) , typedict , _index)
_item
export method get(labeldict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( label(na) , typedict , _index)
_item
export method get(linedict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( line(na) , typedict , _index)
_item
export method get(linefilldict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( linefill(na) , typedict , _index)
_item
export method get(stringdict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( string(na) , typedict , _index)
_item
export method get(tabledict typedict, item _index)=>
_index.actionItem := _GET
[_item,_idx] = _action( table(na) , typedict , _index)
_item
//@function Remove a specific property from an object
//@param typedict (<any>dict) dict.type subdictionary (req for overload)
//@param _object (string) object name
//@param _property (string) property name
//@param _index (string) item object with coords
//@returns <type> item from storage
export method remove(boxdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( box(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(booldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( bool(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(colordict typedict, string _object , string _prop)=>
[_item,_idx] = _action( color(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(floatdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( float(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(intdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( int(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(labeldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( label(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(linedict typedict, string _object , string _prop)=>
[_item,_idx] = _action( line(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(linefilldict typedict, string _object , string _prop)=>
[_item,_idx] = _action( linefill(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(stringdict typedict, string _object , string _prop)=>
[_item,_idx] = _action( string(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(tabledict typedict, string _object , string _prop)=>
[_item,_idx] = _action( table(na) , typedict , item.new(na,na,_object,_prop, _DELETE))
_item
export method remove(boxdict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( box(na) , typedict , _index)
_item
export method remove(booldict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( bool(na) , typedict , _index)
_item
export method remove(colordict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( color(na) , typedict , _index)
_item
export method remove(floatdict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( float(na) , typedict , _index)
_item
export method remove(intdict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( int(na) , typedict , _index)
_item
export method remove(labeldict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( label(na) , typedict , _index)
_item
export method remove(linedict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( line(na) , typedict , _index)
_item
export method remove(linefilldict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( linefill(na) , typedict , _index)
_item
export method remove(stringdict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( string(na) , typedict , _index)
_item
export method remove(tabledict typedict, item _index)=>
_index.actionItem := _DELETE
[_item,_idx] = _action( table(na) , typedict , _index)
_item
//@function Remove a complete Object and all props
//@param typedict (<any>dict) dict.type subdictionary (req for overload)
//@param _object (string) object name
//@param _property (string) property name
//@param _index (string) item object with coords
//@returns <type> item from storage
export method delete(dictionary _dict, string _object )=>
_remove(_dict,item.new(na,na,_object,_object,_REMOVEOBJ))
export method delete(dictionary _dict, item _index)=>
_index.actionItem := _REMOVEOBJ
_remove(_dict, _index)
//@function Remove Property slot for all 10 item types
//@param _dict (dictionary) The full dictionary item
//@param _object (string) object name
//@param _property (string) property name
//@param _index (string) item object with coords
//@returns <type> item from storage
export method wipe(dictionary _dict, string _object , string _prop)=>
_remove(_dict,item.new(na,na,_object,_prop,_REMOVEPROP))
export method wipe(dictionary _dict, item _index)=>
_index.actionItem := _REMOVEPROP
_remove(_dict, _index)
//@function Create New Dictionary ready to use (9999 size limit - (_objlim +_Proplim) for row/column 0)
// # Full dictionary with all types
// > start with this
//@param _Objlim (int) maximum objects (think horizontal)
//@param _Proplim (int) maximum properties per obj (vertical)
//@returns dictionary typoe object
export method init(int _Objlim, int _Proplim)=>
varip _keystorage = matrix.new<string> (_Proplim,_Objlim, string (na))
var dict = dictionary.new()
if barstate.isfirst
matrix.set(_keystorage,0,0,'---NO_OBJECT_HERE---')
dict.keys := _keystorage
var _boxstorage = matrix.new<box> (_Proplim,_Objlim, box (na))
varip _boolstorage = matrix.new<bool> (_Proplim,_Objlim, bool (na))
var _colorstorage = matrix.new<color> (_Proplim,_Objlim, color (na))
varip _floatstorage = matrix.new<float> (_Proplim,_Objlim, float (na))
varip _intstorage = matrix.new<int> (_Proplim,_Objlim, int (na))
var _labelstorage = matrix.new<label> (_Proplim,_Objlim, label (na))
var _linestorage = matrix.new<line> (_Proplim,_Objlim, line (na))
var _linefillstorage = matrix.new<linefill> (_Proplim,_Objlim, linefill (na))
varip _stringstorage = matrix.new<string> (_Proplim,_Objlim, string (na))
var _tablestorage = matrix.new<table> (_Proplim,_Objlim, table (na))
dict.boxs := boxdict.new (_keystorage , _boxstorage )
dict.bools := booldict.new (_keystorage , _boolstorage )
dict.colors := colordict.new (_keystorage , _colorstorage )
dict.floats := floatdict.new (_keystorage , _floatstorage )
dict.ints := intdict.new (_keystorage , _intstorage )
dict.labels := labeldict.new (_keystorage , _labelstorage )
dict.lines := linedict.new (_keystorage , _linestorage )
dict.linefills := linefilldict.new (_keystorage , _linefillstorage )
dict.strings := stringdict.new (_keystorage , _stringstorage )
dict.tables := tabledict.new (_keystorage , _tablestorage )
// dict :=dictionary.new(boxsdict,boolsdict,colorsdict,floatsdict,intsdict,labelsdict,linesdict,linefillsdict,stringsdict,tablesdict,_keystorage)
dict
o = ' //////////////////////////////////// '
o := ' _____ '
o := ' | \.-----.--------.-----. '
o := ' | -- | -__| | _ | '
o := ' |_____/|_____|__|__|__|_____| '
_maxobjects = input.int(10,'Maximum objects',5,100)
_maxprops = input.int(10,'Maximum props',5,100)
// create main dictionary
var dict = init(_maxobjects,_maxprops)
// place some values to plot and get Index objects (matrix coords)
_open_IDX = dict.set ( "ohlc" , 'o' , open )
_high_IDX = dict.set ( "ohlc" , 'h' , high )
_low_IDX = dict.set ( "ohlc" , 'l' , low )
_close_IDX = dict.set ( "ohlc" , 'c' , close )
///////////////////////////////////
// a more complex example
// table1 and table2 each have a string, color, and table asigned.
// you cannot assignmore than 1 of the same type to the same property.
// normally each prop would be one item
// one of each type per prop is bonus.
// for each (in this example) each table prop
// has a color, title, and table (cannot overlap two colors on same prop name)
// the constants only get set once, the others update each calc
if barstate.isfirst
set ( dict, 'Alternating Table' , 'table1' , color.rgb(134, 176, 214) )
set ( dict, 'Alternating Table' , 'table2' , color.rgb(255, 248, 119) )
set ( dict, 'Alternating Table' , 'table1' , 'ONE' )
set ( dict, 'Alternating Table' , 'table2' , 'TWO' )
set ( dict, 'Alternating Table' , 'subtitle' , '\n\n Common Content' )
set ( dict, 'Alternating Table' , 'table1' , table.new(position.middle_center ,1,1) )
set ( dict, 'Alternating Table' , 'table2' , table.new(position.bottom_center ,1,1) )
set ( dict, 'Alternating Table' , 'current' , bar_index % 2 )
// fetch which prop of the alt table to use
_currentTable = get(dict.ints , 'Alternating Table', 'current') == 0 ? 'table1' : 'table2'
// update tablecell
table.cell( get( dict.tables , // object dictionary subclass
'Alternating Table' , // object name
_currentTable ),
0,0, // table row and column
// join title (alternatiung) and subtitle (common)
get(dict.strings , 'Alternating Table', _currentTable ) +
get(dict.strings , 'Alternating Table', 'subtitle' ) ,
bgcolor = get(dict.colors,'Alternating Table' , _currentTable ))
import kaigouthro/matrixautotable/12 as m
if not array.includes(matrix.row(dict.bools.keys,0),'replace del')
// set this for a one time, it will be deleted after read and placed to a non-updated position
set(dict,'del' ,'val' , close*1.002)
set(dict,'delete only prop1','prop1', close/1.002)
if bar_index% 7==0
// to remove just one prop
set(dict,'delete only prop1','prop2', close/1.002)
set(dict,'delete only prop1','prop3', close/1.002)
set(dict,'delete only prop1','prop4', close/1.002)
set(dict,'delete only prop1','prop5' , close*1.002)
plot(get(dict.floats,'del','val' )/2+close/2,'Delete before table',#ffffff,2)
plot(get(dict.floats,'ohlc', 'c' ),'Dict Close' ,#ffffff,2)
if bar_index% 3 == 0
// if del obj exists, get, ipe, place what was to new
if array.includes(matrix.row(dict.bools.keys,0),'del')and bar_index% 7==0
_delval = get(dict.floats,'del','val')
delete(dict,'del')
set (dict,'replace del','newwval',_delval)
wipe(dict,'delete only prop1','prop1')
// testing made visible
if barstate.islast
m.anytwo(dict.keys, dict.floats.items)
|
Drawings_public | https://www.tradingview.com/script/V0DVQd9q/ | LudoGH68 | https://www.tradingview.com/u/LudoGH68/ | 21 | 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/
// © LudoGH68
//@version=5
// @description : Functions to manage drawings on the chart
library("Drawings_public", true)
// @function: Extend specific line with its label
// @param lineId: Id of the line to extend
// @param labelId: Id of the label associated to the line to extend
export extend_line(line lineId, label labelId) =>
line.set_x2(lineId, bar_index)
label.set_x(labelId, label.get_x(labelId) + 1)
// @function: Update specific line coordinates with its label
// @param lineId: Id of the line to update
// @param labelId: Id of the label associated to the line to update
export update_line_coordinates(line lineId, label labelId, int x1, float y1, int x2, float y2) =>
line.set_xy1(lineId, x1, y1)
line.set_xy2(lineId, x2, y2)
label.set_xy(labelId, label.get_x(labelId) + 1, y2)
// @function: Update coordinates of a label
// @param labelId: Id of the label
// @param value: price to update (y axis)
export update_label_coordinates(label labelId, float value) =>
label.set_xy(labelId, label.get_x(labelId) + 1, value)
// @function: Delete specific line with its label
// @param lineId: Id of the line to delete
// @param labelId: Id of the label associated to the line to delete
export delete_line(line lineId, label labelId) =>
line.delete(lineId)
label.delete(labelId)
// @function: Update specific box coordinates with its label
// @param lineId: Id of the box to update
// @param labelId: Id of the label associated to the box to update
// @param left: Left box position
// @param top: Top box position
// @param right: Right box position
// @param bottom: Bottom box position
export update_box_coordinates(box boxId, label labelId, int left, float top, int right, float bottom) =>
box.set_lefttop(boxId, left, top)
box.set_rightbottom(boxId, right, bottom)
label.set_y(labelId, top)
// @function: Delete specific box with its label
// @param lineId: Id of the box to delete
// @param labelId: Id of the label associated to the box to delete
export delete_box(box boxId, label labelId) =>
box.delete(boxId)
label.delete(labelId)
|
composite_ticker_cleaner | https://www.tradingview.com/script/ZUuhdVKU-composite-ticker-cleaner/ | tartigradia | https://www.tradingview.com/u/tartigradia/ | 3 | 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/
// © tartigradia
//@version=5
// @description Extract a clean symbol from a composite ticker. E.g., (BINANCE:BTCUSD+KRAKEN:BTCUSD)/2 as input will return BTCUSD or BINANCE:BTCUSD
library("composite_ticker_cleaner")
// @function Extract the first symbol out of the supplied string (usually ticker.standard(syminfo.tickerid) )
// @param symbol <simple string> input string to search in
// @param keepexchange <simple bool> (optional) Keep exchange in the returned ticker? By default, we only return the symbol without the exchange.
// @returns <simple string> first occurrence of a symbol
export extract_first_symbol(simple string symbol, simple bool keepexchange=false) =>
// This is a generalization of an implementation of a similar code I made in this indicator: https://www.tradingview.com/script/kPIEzGqV-Liquidations-by-volume-TG-fork/
regexclean = not keepexchange ? "(?<=:)[a-zA-Z1-9]+" : "[a-zA-Z1-9]+:[a-zA-Z1-9]+" // clean up the extracted substring, as it can contain other characters, such as math operators and parenthesis, we only keep letters and numbers.
str.match(symbol, regexclean) // apply the cleaning regex on the ticker target (the target symbol) and extract the first occurrence
// @function Extract the first symbol out of the supplied string (usually ticker.standard(syminfo.tickerid) )
// @param symbol <series string> input string to search in
// @param keepexchange <series bool> (optional) Keep exchange in the returned ticker? By default, we only return the symbol without the exchange.
// @returns <series string> first occurrence of a symbol
export extract_first_symbol(series string symbol, series bool keepexchange=false) =>
// This is a generalization of an implementation of a similar code I made in this indicator: https://www.tradingview.com/script/kPIEzGqV-Liquidations-by-volume-TG-fork/
regexclean = not keepexchange ? "(?<=:)[a-zA-Z1-9]+" : "[a-zA-Z1-9]+:[a-zA-Z1-9]+" // clean up the extracted substring, as it can contain other characters, such as math operators and parenthesis, we only keep letters and numbers.
str.match(symbol, regexclean) // apply the cleaning regex on the ticker target (the target symbol) and extract the first occurrence
// @function Extract the first symbol out of the current tickerid (as provided by ticker.standard(syminfo.tickerid) )
// @param keepexchange <simple bool> (optional) Keep exchange in the returned ticker? By default, we only return the symbol without the exchange.
// @returns <simple string> first occurrence of a symbol in the current tickerid
export extract_first_symbol(simple bool keepexchange=false) =>
// Overloads the other function to use tickerid automatically
extract_first_symbol(ticker.standard(syminfo.tickerid), keepexchange)
// @function Extract the part of the string before the specified pattern
// @param symbol <simple string> Input string to search in
// @param pattern <simple string> Pattern to search
// @returns <simple string> Part of the string before the first occurrence of the matched pattern
export extract_before(simple string symbol, simple string pattern) =>
usd_start_location = str.pos(symbol, pattern) // autodetect where the pattern is located in the ticker symbol string
str.substring(symbol, 0, usd_start_location) // extract substring before the pattern
// @function Extract the part of the string before "USD" (includes USDT, USDC, etc). This is especially useful to extract the symbol out of USD* pair ticker. Eg, out of BTCUSD, we will extract BTC.
// @param symbol <simple string> Input string to search in
// @returns <simple string> Part of the string before the first occurrence of "USD".
export extract_before_usd(simple string symbol) =>
extract_before(symbol, "USD")
// @function Display some text on the last bar. Helper function to facilitate debugging or user display (eg, to confirm which symbol was detected).
// @param intext <simple string> Text to display.
// @param tooltip <simple string> (optional) Tooltip text to display on mouse hover.
// @returns <simple string> Nothing. Display the supplied text in a table in the top right corner. Note that this will not affect viewport scaling (ie, the viewport will still be scaled according to the content, not the text).
export display_table_text(simple string intext, simple string tooltip="") =>
// Display a popup with the currently detected symbol, so that the user can verify the indicator does indeed provide pertinent data for the currently selected chart
// We use `var` to only initialize the table on the first bar.
// Also we use a table instead of a label because table do not rescale the chart, so that the chart's scale is maximized to the metrics, not the text.
var table textDisplay = table.new(position.top_right, 1, 1, bgcolor=color.new(color.gray, 85))
if barstate.islast
// var label textLabel = na
//textLabel := label.new(x=bar_index + 2, y=0, text=intext, color=color.new(color.gray, 85), style=label.style_label_left, textcolor=color.gray, textalign=text.align_left, tooltip=tooltip)
table.cell(textDisplay, 0, 0, text=intext, text_color=color.gray, text_halign=text.align_left, tooltip=tooltip)
// Example, shown only when adding this library to a chart as an indicator: Show current market used as a label on the last bar
display_table_text('First symbol: ' + extract_first_symbol() + '\nFirst symbol with exchange: ' + extract_first_symbol(keepexchange=true) + '\nSymbol without USD: ' + extract_before_usd(extract_first_symbol()))
|
wbburgin_utils | https://www.tradingview.com/script/AAOdDl5n-wbburgin-utils/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 27 | 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/
// © wbburgin
//Changed to public
//@version=5
library("wbburgin_utils")
//TABLE OF CONTENTS NOTES
// 1. ESSENTIAL UTILS
// 2. INDICATORS
// 2.1 RANGE FILTER
// 2.2 FUSION INDICATOR
// 2.3 ZONE STRENGTH
// 2.4 ATR ANY SOURCE
// 2.5 SUPERTREND ANY SOURCE
// ---------------------------------------------------------------------------------------------------------------------
// 1. ESSENTIAL UTILS
// _____________________________________________________________________________________________________________________
export selective_ma(bool condition, float source, int length) =>
selective_data = condition ? source : na
sum_selective_data = 0.0
count = 0
for i = 0 to length - 1
if not na(selective_data[i])
sum_selective_data := sum_selective_data + selective_data[i]
count := count + 1
selma = count > 0 ? sum_selective_data / count : na
selma
export trendUp(float source)=>
upward = 0.0
upward := source > source[1] ? nz(upward[1]) + 1 : source < source[1] ? 0 : nz(upward[1])
upward
// ---------------------------------------------------------------------------------------------------------------------
// 1. INDICATORS
// _____________________________________________________________________________________________________________________
// RANGE FILTER ________________________________________________________________________________________________________
// Average Range SMOOTHING
export smoothrng(float source, int sampling_period = 50, float range_mult = 3)=>
wper = (sampling_period*2) - 1
avrng = ta.ema(math.abs(source - source[1]), sampling_period)
smoothrng = ta.ema(avrng, wper)*range_mult
smoothrng
// Range Filter
export rngfilt(float source, float smoothrng)=>
rngfilt = source
rngfilt := source > nz(rngfilt[1]) ? ((source - smoothrng) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (source - smoothrng))
: ((source + smoothrng) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (source + smoothrng))
rngfilt
// FUSION OSCILLATOR ___________________________________________________________________________________________________
export fusion(simple int overallLength = 3, simple int rsiLength=14, simple int mfiLength=14, simple int macdLength=12,
simple int cciLength=12, simple int tsiLength=13, simple int rviLength=10, simple int atrLength=14,
simple int adxLength=14) =>
// Directional Oscillators
rsi = (ta.rsi(close,rsiLength)-50)/20
mfi = (ta.mfi(close,mfiLength)-50)/20
[macdRaw, _, _] = ta.macd(close, macdLength*overallLength, macdLength*2*overallLength, 9)
mHighest = ta.highest(macdRaw,macdLength*overallLength)
mLowest = ta.lowest(macdRaw,macdLength*overallLength)
macd = switch
macdRaw > 0 => macdRaw/mHighest
macdRaw < 0 => macdRaw/math.abs(mLowest)
=> 0
cci = ta.cci(close,cciLength*overallLength)/100
tsiRaw = ta.tsi(close,tsiLength*overallLength,tsiLength*2*overallLength)
tHighest = ta.highest(tsiRaw,tsiLength*overallLength)
tLowest = ta.lowest(tsiRaw,tsiLength*overallLength)
tsi = switch
tsiRaw > 0 => tsiRaw/tHighest
tsiRaw < 0 => tsiRaw/math.abs(tLowest)
=> 0
src = close
len = 14
stddev = ta.stdev(src, rviLength*overallLength)
upper = ta.ema(ta.change(src) <= 0 ? 0 : stddev, len)
lower = ta.ema(ta.change(src) > 0 ? 0 : stddev, len)
rvi = ((upper / (upper + lower) * 100)-50)/20
super_dir = math.avg(rsi,mfi,macd,cci,tsi,rvi)
// Nondirectional Oscillators
atrRaw = ta.atr(atrLength)
atrStdev = ta.stdev(atrRaw,atrLength)
atrEMA = ta.ema(atrRaw,atrLength)
atr = (((atrRaw/atrEMA)-1)*(1+atrStdev))-1
[_, _, adxRaw] = ta.dmi(17, adxLength)
adxStdev = ta.stdev(adxRaw,adxLength)
adxEMA = ta.ema(adxRaw,adxLength)
adx = (((adxRaw/adxEMA)-1)*(1+adxStdev))
super_nondirRough = math.avg(atr,adx)
highestNondir = ta.highest(super_nondirRough,200)
lowestNondir = ta.lowest(super_nondirRough,200)
super_nondir = switch
super_nondirRough > 0 => super_nondirRough/highestNondir
super_nondirRough < 0 => super_nondirRough/math.abs(lowestNondir)
=> 0
[super_dir , super_nondir]
// ZONE STRENGTH _______________________________________________________________________________________________________
export zonestrength(int amplitude,int wavelength) =>
ohlc_avg = .25 * (open + high + low + close)
ocp_avg = .5 * (open[1] + close[1])
g = math.avg(ohlc_avg, ocp_avg)
h = g * (1 + (ohlc_avg > ocp_avg ? high > ohlc_avg ? high - ohlc_avg + high - ocp_avg : high - ocp_avg : low <
ohlc_avg ? low - ocp_avg - ohlc_avg + low : low - ocp_avg) * -1 / g)
amp_highest = ta.highest(h, amplitude)
amp_lowest = ta.lowest(h, amplitude)
high_deviation = amp_highest - high
low_deviation = low - amp_lowest
m = high_deviation > low_deviation ? amp_lowest : amp_highest
n = high_deviation < low_deviation ? amp_lowest : amp_highest
o = math.avg(amp_highest, amp_lowest)
q4 = math.avg(o, m)
q2 = math.avg(o, n)
s = ta.ema(amp_lowest, wavelength)
t = ta.ema(amp_highest, wavelength)
u = (ohlc_avg - s) / (t - s) - .5
zonestrength = u
zonestrength
// ATR ANY SOURCE ______________________________________________________________________________________________________
export atr_anysource(float source, int atr_length) =>
highest = ta.highest(source,atr_length)
lowest = ta.lowest(source,atr_length)
trueRange = na(highest[1])? highest-lowest : math.max(math.max(highest - lowest, math.abs(highest - source[1])),
math.abs(lowest-source[1]))
ta.rma(trueRange,atr_length)
// SUPERTREND ANY SOURCE _______________________________________________________________________________________________
export supertrend_anysource(float source, float factor, simple int atr_length) =>
atr = atr_anysource(source,atr_length)
upperBand = source + factor * atr
lowerBand = source - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or source[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or source[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := source > upperBand ? -1 : 1
else
direction := source < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction] |
DataChart | https://www.tradingview.com/script/ZWIR7vNo-DataChart/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 72 | 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/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Library to plot scatterplot or heatmaps for your own set of data samples
library("DataChart", overlay=true)
// @type Sample data for chart
// @field xValue x value of the sample data
// @field yValue y value of the sample data
export type Sample
float xValue
float yValue
// @type Properties of plotting chart
// @field title Title of the chart
// @field suffix Suffix for values. It can be used to reference 10X or 4% etc. Used only if format is not format.percent
// @field matrixSize size of the matrix used for plotting
// @field chartType Can be either scatterplot or heatmap. Default is scatterplot
// @field outliersStart Indicates the percentile of data to filter out from the starting point to get rid of outliers
// @field outliersEnd Indicates the percentile of data to filter out from the ending point to get rid of outliers.
// @filed backgroundColor chart background color. Default is color.black
// @field plotColor color of plots on the chart. Default is color.yellow. Only used for scatterplot type
// @field heatmapColor color of heatmaps on the chart. Default is color.red. Only used for heatmap type
// @field borderColor border color of the chart table. Default is color.yellow.
// @field plotSize size of scatter plots. Default is size.large
// @field format data representation format in tooltips. Use mintick.percent if measuring any data in terms of percent. Else, use format.mintick
// @field showCounters display counters which shows totals on each quadrants. These are single cell tables at the corners displaying number of occurences on each quadrant.
// @field showTitle display title at the top center. Uses the title string set in the properties
// @field counterBackground background color of counter table cells. Default is color.teal
// @field counterTextColor text color of counter table cells. Default is color.white
// @field counterTextSize size of counter table cells. Default is size.large
// @field titleBackground background color of chart title. Default is color.maroon
// @field titleTextColor text color of the chart title. Default is color.white
// @field titleTextSize text size of the title cell. Default is size.large
// @field addOutliersToBorder If set, instead of removing the outliers, it will be added to the border cells.
// @field useCommonScale Use common scale for both x and y. If not selected, different scales are calculated based on range of x and y values from samples. Default is set to false.
// @field plotchar scatter plot character. Default is set to ascii bullet.
export type ChartProperties
string title ="Scatterplot"
string suffix = ""
int matrixSize = 60
string chartType = 'scatterplot'
int outliersStart = 5
int outliersEnd = 5
color backgroundColor = color.black
color plotColor = color.yellow
color heatmapColor = color.red
color borderColor = color.yellow
string plotSize = size.large
string format = format.mintick
bool showCounters = true
bool showTitle = false
color counterBackground = color.teal
color counterTextColor = color.white
string counterTextSize = size.large
color titleBackground = color.maroon
color titleTextColor = color.white
string titleTextSize = size.large
bool addOutliersToBorder = false
bool useCommonScale = false
string plotchar = '•'
// @type Chart drawing objects collection
// @field properties ChartProperties object which determines the type and characteristics of chart being plotted
// @field titleTable table containing title of the chart.
// @field mainTable table containing plots or heatmaps.
// @field quadrantTables Array of tables containing counters of all 4 quandrants
export type ChartDrawing
ChartProperties properties
table titleTable
table mainTable
array<table> quadrantTables
// @type Chart type which contains all the information of chart being plotted
// @field properties ChartProperties object which determines the type and characteristics of chart being plotted
// @field samples Array of Sample objects collected over period of time for plotting on chart.
// @field displacements Array containing displacement values. Both x and y values
// @field displacementX Array containing only X displacement values.
// @field displacementY Array containing only Y displacement values.
// @field drawing ChartDrawing object which contains all the drawing elements
export type Chart
ChartProperties properties
array<Sample> samples
array<float> displacements
array<float> displacementX
array<float> displacementY
ChartDrawing drawing
// @type Configs used for adding specific type of samples called PriceSamples
// @field duration impact duration for which price displacement samples are calculated.
// @field useAtrReference Default is true. If set to true, price is measured in terms of Atr. Else is measured in terms of percentage of price.
// @field atrLength atrLength to be used for measuring the price based on ATR. Used only if useAtrReference is set to true.
export type PriceSampleConfig
int duration = 10
bool useAtrReference = true
int atrLength = 24
// @type Special type of sample called price sample. Can be used instead of basic Sample type
// @field trigger consider sample only if trigger is set to true. Default is true.
// @field source Price source. Default is close
// @field highSource High price source. Default is high
// @field lowSource Low price source. Default is low
// @field tr True range value. Default is ta.tr
export type PriceSampleData
bool trigger = true
float source = close
float highSource = high
float lowSource = low
float tr = ta.tr
method setTitle(ChartDrawing this)=>
if(this.properties.showTitle)
this.titleTable.delete()
this.titleTable := table.new(position.top_center, 1, 1, this.properties.titleBackground, this.properties.titleBackground, 1, this.properties.titleBackground, 1)
this.titleTable.cell(0, 0, this.properties.title, text_color = this.properties.titleTextColor, text_size = this.properties.titleTextSize)
method draw(ChartDrawing this, matrix<int> counts, array<Sample> samples, float minXRange, float minYRange, float maxXRange, float maxYRange)=>
this.setTitle()
table.clear(this.mainTable, 0, 0, this.properties.matrixSize, this.properties.matrixSize)
maxCount = matrix.max(counts)
totalCount = array.size(samples)
sums = array.new<int>(4,0)
for [i, columns] in counts
for [j, count] in columns
countPercent = int(count*100/maxCount)
transparency = countPercent==0? 100 : 90-countPercent*0.9
sumIndex = 2*(i < ((this.properties.matrixSize+1)/2) ? 0 : 1) + (j < ((this.properties.matrixSize+1)/2)? 0: 1)
array.set(sums, sumIndex, array.get(sums, sumIndex)+count)
xDisplacement = minXRange + (maxXRange- minXRange)*i/this.properties.matrixSize
xDisplacementNext = minXRange + (maxXRange- minXRange)*(i+1)/this.properties.matrixSize
xRange = 'X Displaecment : ' + (i == 0? '' : (str.tostring(xDisplacement, this.properties.format) + (this.properties.format == format.percent? '' : this.properties.suffix)))
+ ' to '
+ (i==this.properties.matrixSize? '' :
(str.tostring(xDisplacementNext, this.properties.format) + (this.properties.format == format.percent? '' : this.properties.suffix)))
yDisplacement = maxYRange - (maxYRange- minYRange)*j/this.properties.matrixSize
yDisplacementNext = maxYRange - (maxYRange- minYRange)*(j+1)/this.properties.matrixSize
yRange = 'Y Displaecment : ' + (j == this.properties.matrixSize? '' : (str.tostring(yDisplacement, this.properties.format) + (this.properties.format == format.percent? '' : this.properties.suffix)))
+ ' to '
+ (j== 0? '' :
(str.tostring(yDisplacementNext, this.properties.format) + (this.properties.format == format.percent? '' : this.properties.suffix)))
tooltip = 'Count '+str.tostring(count)+'/'+str.tostring(totalCount)+'\n'+xRange+'\n'+yRange+'\n('+str.tostring(i)+','+str.tostring(j)+')'
displaySymbol = this.properties.chartType == 'scatterplot'? this.properties.plotchar : ''
bgColor = this.properties.chartType == 'heatmap'? color.new(this.properties.heatmapColor, transparency) : na
this.mainTable.cell(i, j, displaySymbol, width=1, height = 1, text_color=color.new(this.properties.plotColor, transparency), bgcolor = bgColor,
text_size = this.properties.plotSize, tooltip = tooltip)
if(this.properties.showCounters)
positions = array.from(position.top_left, position.bottom_left, position.top_right, position.bottom_right)
for [i, sum] in sums
if(na(this.quadrantTables.get(i)))
this.quadrantTables.set(i, table.new(array.get(positions, i), 1,1, this.properties.counterBackground, this.properties.counterBackground, 1, this.properties.counterBackground, 1))
this.quadrantTables.get(i).cell(0, 0, str.tostring(sum), text_color = this.properties.counterTextColor, text_size = this.properties.counterTextSize)
method init(ChartDrawing this)=>
if(na(this.mainTable))
this.mainTable := table.new(position.middle_center, this.properties.matrixSize+1, this.properties.matrixSize+1, this.properties.backgroundColor,
this.properties.borderColor, 1, this.properties.backgroundColor, 0)
if(na(this.quadrantTables))
this.quadrantTables := array.new<table>(4)
// @function Initialize Chart object.
// @param this Chart object to be initialized
// @returns current chart object
export method init(Chart this)=>
if(na(this.samples))
this.samples := array.new<Sample>()
this.displacements := array.new<float>()
this.displacementX := array.new<float>()
this.displacementY := array.new<float>()
if(na(this.properties))
this.properties := ChartProperties.new()
if(na(this.drawing))
this.drawing := ChartDrawing.new(this.properties)
this.drawing.init()
this
// @function Add sample data to chart using Sample object
// @param this Chart object
// @param sample Sample object containing sample x and y values to be plotted
// @param trigger Samples are added to chart only if trigger is set to true. Default value is true
// @returns current chart object
export method addSample(Chart this, Sample sample, bool trigger = true)=>
if(trigger)
this.init()
if not na(sample.xValue) and not na(sample.yValue)
this.samples.push(sample)
this.displacements.push(sample.xValue)
this.displacements.push(sample.yValue)
this.displacementX.push(sample.xValue)
this.displacementY.push(sample.yValue)
this
// @function Add sample data to chart using x and y values
// @param this Chart object
// @param x x value of sample data
// @param y y value of sample data
// @param trigger Samples are added to chart only if trigger is set to true. Default value is true
// @returns current chart object
export method addSample(Chart this, float x, float y, bool trigger = true)=>
if(trigger)
this.init()
Sample sample = Sample.new(x, y)
this.addSample(sample, trigger)
this
// @function Add price sample data - special type of sample designed to measure price displacements of events
// @param this Chart object
// @param priceSampleData PriceSampleData object containing event driven displacement data of x and y
// @param config PriceSampleConfig object containing configurations for deriving x and y from priceSampleData
// @returns current chart object
export method addPriceSample(Chart this, PriceSampleData priceSampleData, PriceSampleConfig config = na)=>
this.init()
var _config = na(config)? PriceSampleConfig.new() : config
highest = ta.highest(priceSampleData.highSource, _config.duration)
lowest = ta.lowest(priceSampleData.lowSource, _config.duration)
atr = ta.sma(priceSampleData.tr, _config.atrLength)
if(priceSampleData.trigger[_config.duration+1])
price = priceSampleData.source[_config.duration]
positiveDisplacement = math.abs(highest-price)
negativeDisplacement = math.abs(price-lowest)
xValue = _config.useAtrReference? positiveDisplacement/atr[_config.duration] : positiveDisplacement*100/price
yValue = _config.useAtrReference? negativeDisplacement/atr[_config.duration] : negativeDisplacement*100/price
this.addSample(xValue, yValue)
this
// @function draw contents of the chart object
// @param this Chart object
// @returns current chart object
export method draw(Chart this) =>
if(barstate.islast)
minXRange = this.properties.useCommonScale ? array.percentile_linear_interpolation(this.displacements, this.properties.outliersStart):
array.percentile_linear_interpolation(this.displacementX, this.properties.outliersStart)
maxXRange = this.properties.useCommonScale ? array.percentile_linear_interpolation(this.displacements, 100-this.properties.outliersEnd):
array.percentile_linear_interpolation(this.displacementX, 100-this.properties.outliersEnd)
minYRange = this.properties.useCommonScale ? minXRange :
array.percentile_linear_interpolation(this.displacementY, this.properties.outliersStart)
maxYRange = this.properties.useCommonScale ? maxXRange :
array.percentile_linear_interpolation(this.displacementY, 100-this.properties.outliersEnd)
xRange = maxXRange - minXRange
yRange = maxYRange - minYRange
counts = matrix.new<int>(this.properties.matrixSize+1, this.properties.matrixSize+1, 0)
for sample in this.samples
if(this.properties.addOutliersToBorder or (sample.xValue <= maxXRange and sample.xValue >= minXRange and sample.yValue >= minYRange and sample.yValue <= maxYRange))
adjustedX = math.min(math.max(sample.xValue, minXRange), maxXRange)
adjustedY = math.min(math.max(sample.yValue, minYRange), maxYRange)
xIndex = int((adjustedX-minXRange)*this.properties.matrixSize/xRange)
yIndex = this.properties.matrixSize - int((adjustedY-minYRange)*this.properties.matrixSize/yRange)
counts.set(xIndex, yIndex, counts.get(xIndex, yIndex)+1)
this.drawing.draw(counts, this.samples, minXRange, minYRange, maxXRange, maxYRange)
this
// ***************************************************************** Indicator sample ****************************************************************//
// var Chart heatmap = Chart.new()
// heatmap.init()
// heatmap.addSample(ta.change(close, 10), ta.rsi(close, 10))
// heatmap.draw()
|
f_maSelect | https://www.tradingview.com/script/gHCoi1N8-f-maSelect/ | tartigradia | https://www.tradingview.com/u/tartigradia/ | 19 | 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/
// © tartigradia
//@version=5
// @description Easy to use drop-in facade function to lots of different moving average calculations, including some that are not natively available in PineScript v5 such as Zero-Lag EMA. Simply call f_maSelect(series float serie, simple string ma_type="sma", ma_length=14) instead of a ta.*ma() call and you get access to all MAs offered by PineScript and more.
library("f_maSelect")
// Note this is inspired by my work in the indicator: https://www.tradingview.com/script/oRO7g5ze-Generalized-Bollinger-Bands-B-And-Bandwidth-Tartigradia/ and others before.
// @function Zero-lag EMA (ZLMA)
// @param src Input series
// @param len Lookback period
// @returns Series smoothed with ZLMA
export zema(series float src, int len) =>
// by DreamsDefined in: https://www.tradingview.com/script/pFyPlM8z-Reverse-Engineered-RSI-Key-Levels-MTF/
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
d = ema1 - ema2
zlema = ema1 + d
zlema
// @function Approximate Standard Moving Average, which substracts the average instead of popping the oldest element, hence losing the base frequency and is why it is approximative. For some reason, this appears to give the same results as a standard RMA
// @param x Input series.
// @param ma_length Lookback period.
// @returns Approximate SMA series.
export approximate_sma(series float x, int ma_length) =>
sma = 0.0
sma := nz(sma[1]) - (nz(sma[1] / ma_length)) + x
sma
// @function Generalized moving average selector
// @param serie Input series
// @param ma_type String describing which moving average to use
// @param ma_length Lookback period
// @returns Serie smoothed with the selected moving average.
export f_maSelect(series float serie, simple string ma_type="sma", simple int ma_length=14) =>
switch ma_type
"sma" => ta.sma(serie, ma_length)
"ema" => ta.ema(serie, ma_length)
"rma" => ta.rma(serie, ma_length)
"wma" => ta.wma(serie, ma_length)
"vwma" => ta.vwma(serie, ma_length)
"swma" => ta.swma(serie)
"hma" => ta.hma(serie, ma_length)
"alma" => ta.alma(serie, ma_length, 0.85, 6)
"zlma" => zema(serie, ma_length)
"approximate_sma" => approximate_sma(serie, ma_length)
"median" => ta.percentile_nearest_rank(serie, ma_length, 50)
=>
runtime.error("No matching MA type found.")
float(na)
//generalized_dev_vectorized(series float src, simple int length, simple string ma_type, simple int lmode=2) =>
// If pinescript supported vectorization, we could write something like the following, but alas, it does not work as of pinescript v5, because src is not the vector but the current value, a scalar:
//avg = f_maSelect(src, ma_type, length)
//stdev = lmode == 1 ?
// f_maSelect(math.abs(src - avg), ma_type, length) :
// math.sqrt(f_maSelect(math.pow(src - avg, 2), ma_type, length))
// @function Generalized deviation calculation: Whereas other Bollinger Bands often just change the basis but not the stdev calculation, the correct way to change the basis is to also change it inside the stdev calculation.
// @param src Series to use (default: close)
// @param length Lookback period
// @param avg Average basis to use to calculate the standard deviation
// @param lmode L1 or L2 regularization? (ie, lmode=1 uses abs() to cutoff negative values hence it calculates the Mean Absolute Deviation as does the ta.dev(), lmode=2 uses sum of squares hence it calculates the true Standard Deviation as the ta.stdev() function does). See also the research works of everget: https://www.tradingview.com/script/qXc06HaE-RESEARCH-Mean-Absolute-Deviation/
// @returns stdev Standard deviation series
export generalized_dev(series float src, simple int length, float avg, simple int lmode=2) =>
// Inspired by the official pine_stdev from the v5 manual: https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}stdev
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
diff = src[i] - avg
sumOfSquareDeviations := lmode == 1 ? sumOfSquareDeviations + math.abs(diff) : sumOfSquareDeviations + diff * diff
stdev = lmode == 1 ? sumOfSquareDeviations / length : math.sqrt(sumOfSquareDeviations / length)
// @function Standard deviation calculation but with different probabilities assigned to each bar, with newer bars having more weights https://en.wikipedia.org/wiki/Standard_deviation#Discrete_random_variable
// @param src Series to use (default: close)
// @param length Lookback period
// @param avg Average basis to use to calculate the standard deviation
// @param lmode L1 or L2 regularization? (ie, lmode=1 uses abs() to cutoff negative values hence it calculates the Mean Absolute Deviation as does the ta.dev(), lmode=2 uses sum of squares hence it calculates the true Standard Deviation as the ta.stdev() function does). See also the research works of everget: https://www.tradingview.com/script/qXc06HaE-RESEARCH-Mean-Absolute-Deviation/
// @param temporal_discount Probabilistic gamma factor to discount old values in favor of new ones, higher value = more weight to newer bars
// @returns stdev Standard deviation series
export generalized_dev_discount(series float src, simple int length, float avg, simple int lmode=2, simple float temporal_discount=0.5) =>
// We use an Exponential Smoothing to make the parametrization easier for the user, so that there is only a single parameter to change https://en.wikipedia.org/wiki/Exponential_smoothing
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
diff = src[i] - avg
sumOfSquareDeviations := lmode == 1 ? (1-temporal_discount) * sumOfSquareDeviations + temporal_discount * math.abs(diff) : (1 - temporal_discount) * sumOfSquareDeviations + temporal_discount * diff * diff
stdev = lmode == 1 ? sumOfSquareDeviations : math.sqrt(sumOfSquareDeviations)
// @function Median Absolute Deviation
// @param src Input series
// @param length Lookback period
// @param median Median already calculated on the input series
// @returns mad, the median absolute deviation value
export median_absdev(series float src, simple int length, float median) =>
// median_absolute_deviation = median( abs(x_i - median(x)) )
float [] sum = array.new_float(0)
for i = 0 to length - 1
diff = src[i] - median
array.push(sum, math.abs(diff))
mad = array.percentile_nearest_rank(sum, 50)
//
// Example, if library is added as an indicator
//
// Inputs
src = input.source(close, title="Source")
ma_length = input.int(20, title="Lookback period (length of smoothing)", minval=1, maxval=100)
ma_type = input.string('ema', 'Moving Average Type', options=['sma', 'ema', 'rma', 'wma', 'vwma', 'swma', 'hma', 'alma', 'zlma', 'approximate_sma', 'median'])
ma_color = input.string('source', 'Color average according to either the difference between bars (interbars) or difference between average and source?', options=['interbars','source','none'])
ma_margin = input.float(0.01, 'Margin to consider the cloud as undecided (in percent change)', tooltip='If the moving average value difference between two bars is below this percent, then we consider the direction as undecided. Set to 0 to disable margin.')
// Calculate average using our facade function
ma = f_maSelect(src, ma_type, ma_length)
// Calculate color
// Calculating the percent change from values of two different signs is surprisingly difficult: https://math.stackexchange.com/a/3986352/72736
// The total change may be off but we mainly want to see the sign so that's a good enough approximation.
final_color = switch ma_color
"interbars" => ma > ma[1] * (1.0 + ma_margin) ? color.aqua : ma < ma[1] * (1.0 - ma_margin) ? color.red : color.yellow
"source" => (src - ma) / math.abs(src) > ma_margin ?
color.aqua :
(src - ma) / math.abs(src) < -1 * ma_margin ?
color.red :
color.yellow
"none" => color.gray
=>
runtime.error("No such option found.")
color.gray
// Plot unsmoothed current source (usually close price), this serves as a baseline to compare and better understand the moving average and ma_color (especially when "source" option is selected)
plot(src, color=color.purple, title="Source")
// Plot moving average
plot(ma, color=final_color, linewidth=2, title="Moving Average")
|
The Forbidden RSI [CHE] | https://www.tradingview.com/script/YNuerYJN/ | chervolino | https://www.tradingview.com/u/chervolino/ | 157 | 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/
// © chervolino
// This script is an advanced variant of the Onset Trend Detector, a technical indicator for trend analysis developed by John F. Ehlers.
// It is based on a non-linear quotient transformation and expands upon Mr. Ehlers' previous studies, the Super Smoother Filter and the Roofing Filter,
// to address the lag issue common to moving average type indicators.
// The algorithm in this script registers the most recent peak value and normalizes it. The normalized value then decays slowly until the next
// peak swing. The ratio of the previously filtered value to the corresponding peak value is then transformed using a quotient transformation to
// provide the resulting oscillator.
// This script implements an indicator called "The forbidden RSI" (TFRSI). This indicator was developed by chervolino as an improvement on the
// standard Relative Strength Index (RSI), which is a technical indicator used to measure the strength of a trend and identify potential buy and sell signals.
// The TFRSI is calculated based on the close price and is typically plotted on a scale from -20 to 120, with values above 100 indicating that
// the asset is overbought (likely to decline in value) and values below 1 indicating that it is oversold (likely to increase in value). The script
// allows the user to customize the length of the RSI and the length of the trigger used to smooth the signal.
// In order to calculate the TFRSI, the script first initializes some constants and then performs a series of calculations to determine the value of
// "HP", "ag", and "Sp". The RSI value is then calculated based on the values of "X", which is based on "ag" and "Sp", and "q1", which is based on "X"
// and the trigger length. The RSI value is plotted in a chart along with upper and lower bounds and a filled region representing the background.
// Please check it out, it works perfectly to find good analysis and entries for both, longs and shorts.
// Best regards
// Chervolino
//@version=5
indicator(title="The Forbidden RSI [CHE]", shorttitle=" TFRSI [CHE]", overlay=false, timeframe="")
// ————— Inputs
RSI_Length = input.int(6, title='RSI_Length')
tr = input.int(2, 'Trigger Length')
// ————— Constants
HP = 0.00, a1 = 0.00, b1 = 0.00, c1 = 0.00, c2 = 0.00, c3 = 0.00, ag = 0.00, Sp = 0.00, X = 0.00, Quotient1 = 0.00, Quotient2 = 0.00, w = math.sqrt(.5)
// ————— Calculations
HP := 2500 * (close - 2 * nz(close[1]) + nz(close[2])) + 1.92 * nz(HP[1]) - .9216 * nz(HP[2])
a1 := math.exp(-math.sqrt(2) * math.pi / RSI_Length)
b1 := 2 * a1 * math.cos(math.sqrt(2) * math.pi / RSI_Length)
c2 := b1
c3 := -a1 * a1
c1 := 1 - c2 - c3
ag := c1 * (HP + nz(HP[1])) / 2 + c2 * nz(ag[1]) + c3 * nz(ag[2])
Sp := .991 * nz(Sp[1])
if math.abs(ag) > Sp
Sp := math.abs(ag)
Sp
if Sp != 0
X := ag / Sp
X
q1 = X * 60 + 50
rsi= ta.sma(q1, tr)
// ————— Plots
plot(rsi, "RSI", color=#7E57C2)
rsiUpperBand = hline(100, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(0, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill") |
Expected Liquidity | https://www.tradingview.com/script/quRFWdPI-Expected-Liquidity/ | RickSimpson | https://www.tradingview.com/u/RickSimpson/ | 354 | 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/
// © RickSimpson
//@version=5
indicator('Expected Liquidity', 'Expected Liquidity Range', true, max_lines_count=500, max_labels_count=500)
//Inputs
i_period = input.int(25, 'Period', minval=15, maxval=60, group='Expected Liquidity Settings')
i_linewidth = input.int(2, 'Lines Size', minval=1, maxval=3, group='Expected Liquidity Settings', inline='style')
i_linestyle = input.string('⎯⎯⎯', 'Lines Style', options=['⎯⎯⎯', '····', '----'], group='Expected Liquidity Settings', inline='style')
i_extend = input.string('Right', 'Lines Extension', options=['Left', 'Right', 'Both', 'None'], group='Expected Liquidity Settings')
i_premiumcolor = input(color.red, 'Premium Liquidity', group='Expected Liquidity Settings', inline='colsetup')
i_discountcolor = input(color.green, 'Discount Liquidity', group='Expected Liquidity Settings', inline='colsetup')
//Constants Variables Declaration
line premium = (na)
line discount = (na)
highbar = true
highfractal = true
lowfractal = true
closefractal = true
//Lines Style String Function
f_i_linestyle(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
//Lines Extension String Function
f_i_line_extend(extend) =>
out = switch extend
'Left' => extend.left
'Right' => extend.right
'Both' => extend.both
'None' => extend.none
//Pivots Definition
hb = ta.highest(high, i_period)
lb = ta.lowest(low, i_period)
dist = hb - lb
//Premium Fibonacci Levels Calculation
hf = hb - dist * 0.236
chf = hb - dist * 0.382
//Discount Fibonacci Levels Calculation
clf = hb - dist * 0.618
lf = hb - dist * 0.764
//High/Low Fractals Scalling
pfractal = high > hb[1]
dfractal = low < lb[1]
premiumexpectstart = hb[3] == hb[2] and hb[2] == hb[1] and pfractal
discountexpectstart = lb[3] == lb[2] and lb[2] == lb[1] and dfractal
//Liquidity Range Calculation
highexpect = premiumexpectstart or high[1] == hb
lowexpect = discountexpectstart or low[1] == lb
highbar := highexpect ? true : lowexpect ? false : highbar[1]
barexpin = ta.crossover(close, hf)
barexpout = ta.crossunder(close, hf)
highfractal := barexpin ? true : barexpout ? false : highfractal[1]
fractexpin = ta.crossunder(close, lf)
fractexpout = ta.crossover(close, lf)
lowfractal := fractexpin ? true : fractexpout ? false : lowfractal[1]
closefractal := not highfractal and not lowfractal ? true : false
//Drawing Calculation
stateislast = barstate.islast
stateislast := barstate.isrealtime and timeframe.isintraday ? not barstate.isconfirmed : barstate.islast
hbdtrue = stateislast and highfractal
lbdtrue = stateislast and lowfractal
chfdtrue = stateislast and closefractal and highbar
clfdtrue = stateislast and closefractal and not highbar
//Expected Liquidity Range Conditions
hbexpect = hb
hbexpect := hbdtrue ? hb : lbdtrue ? lf : chfdtrue ? hf : clfdtrue ? chf : na
lbexpect = lb
lbexpect := hbdtrue ? hf : lbdtrue ? lb : chfdtrue ? clf : clfdtrue ? lf : na
//Plotting
premium := line.new(bar_index[1], hbexpect, bar_index, hbexpect, extend=f_i_line_extend(i_extend), color=i_premiumcolor, style=f_i_linestyle(i_linestyle), width=i_linewidth)
discount := line.new(bar_index[1], lbexpect, bar_index, lbexpect, extend=f_i_line_extend(i_extend), color=i_discountcolor, style=f_i_linestyle(i_linestyle), width=i_linewidth)
line.delete(premium[1])
line.delete(discount[1]) |
Root Mean Square (RMS) | https://www.tradingview.com/script/BjmFXR3A-Root-Mean-Square-RMS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("RMS", overlay = true)
rms(source, length)=>
math.sqrt(math.sum(math.pow(source, 2), length)/length)
source = input.source(close, "Source")
length = input.int(20, "Length", 1)
plot(rms(source, length))
|
SPX overnight | https://www.tradingview.com/script/T37xqwmD-SPX-overnight/ | domsito | https://www.tradingview.com/u/domsito/ | 32 | 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/
// © domsito
//@version=5
//purpose of this script is to display estimate of SPX and SPY ticker values in the period while the market is closed.
//it's meant to be used only with ES1! ticker (S&P 500 E-MINI FUTURES)
indicator("SPY SPX overnight", "", true)
max_bars_back(time, 5000)
var bool showDailyChange = input.bool(true, "Show change since previous day close", group = "General")
var bool showPrevDayLine = input.bool(true, "Mark prevous day close with horizontal line", group = "line")
var bool showPrevWeekCloseLine = input.bool(true, "Mark prevous week close with horizontal line", group = "line")
var lineStyle = input.string(line.style_solid, title="Line style", options=[line.style_solid, line.style_dashed, line.style_dotted], inline = "1", group = "line")
var lineColor = input(color.blue, "Line color", inline = "1", group = "line")
var lineColor2 = input(color.lime, "Line2 color", inline = "1", group = "line")
var table spxTable = table.new(position.top_right, 1, 4, frame_color= color.blue)
table.cell_set_width(spxTable,0,0, 15)
table.cell_set_width(spxTable,0,1, 15)
table.cell_set_width(spxTable,0,2, 15)
table.cell_set_width(spxTable,0,3, 15)
var simbol1 = "spx"
var simbol2 = "spy"
var bool error = true
if barstate.isfirst
// script will not work for timeframes < 120min and will display an error message in top right corner in that case
if timeframe.isintraday and timeframe.in_seconds(timeframe.period) <= 120*60
table.cell_set_text(spxTable,0,0, simbol1)
table.cell_set_text(spxTable,0,2, simbol2)
error := false
else
table.cell_set_text(spxTable,0,0, "Timeframe needs to be <= 120 min")
if syminfo.ticker != "ES1!"
error := true
table.cell_set_text(spxTable,0,0, "Works only with ES1! ticker")
var lbl = label.new(na, na, na, style = label.style_label_left)
var lineDay = line.new(na, na, na, na, color = lineColor, style = lineStyle, width = 2)
var lineWeek = line.new(na, na, na, na, color = lineColor2, style = lineStyle, width = 2)
var float spxAdjusted = 0
var float spyAdjusted = 0
var float prevDayClose = 0.0
var float prevWeekClose = 0.0
var int bar_time_prev_day_close = 0
var int bar_time_prev_week_close = 0
var string sessionInput = "0830-1500" //input.session("0830-1500", "Trading hours")
// InSession() returns 'true' when the current bar happens inside
// the specified session, and 'false' when the bar isn't inside
// that time period (or when the chart's time frame is 1 day or higher).
InSession(sessionTimes) =>
not na(time(timeframe.period, sessionTimes))
inSession = InSession(sessionInput)
spx = inSession ? request.security(simbol1, '1D',close[1]) : request.security(simbol1, '1D',close)
spy = inSession ? request.security(simbol2, '1D',close[1]) : request.security(simbol2, '1D',close)
//delta percentage between v1 and v2
delta(float v1, float v2) =>
(((v2 / v1)-1) * 100.0)
if (ta.change(inSession)) and not error
if inSession == false
prevDayClose := close[1] //previous bar close is previous day's closing price, since we just entered after hours
bar_time_prev_day_close := bar_index[1]
if (dayofweek == dayofweek.friday)
bar_time_prev_week_close := bar_index[1]
prevWeekClose := close[1]
if (barstate.islast) and not error
change = delta(prevDayClose, close)
spxAdjusted := spx * (1.0 + change/100)
spyAdjusted := spy * (1.0 + change/100)
backColor = change < 0.0 ? color.red : color.green
if showPrevDayLine
line.set_x1(lineDay, bar_time_prev_day_close )
line.set_x2(lineDay, bar_index)
line.set_y1(lineDay, prevDayClose)
line.set_y2(lineDay, prevDayClose)
if showPrevWeekCloseLine
line.set_x1(lineWeek, bar_time_prev_week_close)
line.set_x2(lineWeek, bar_index)
line.set_y1(lineWeek, prevWeekClose)
line.set_y2(lineWeek, prevWeekClose)
if showDailyChange
label.set_text(lbl, str.tostring(change, "0.00") + "% ")
table.cell_set_text(spxTable,0,1, str.tostring(spxAdjusted, "0.0"))
table.cell_set_text(spxTable,0,3, str.tostring(spyAdjusted, "0.0"))
label.set_color(lbl, backColor)
label.set_x(lbl, bar_index+1)
label.set_y(lbl, close) |
Slope Normalized (SN) | https://www.tradingview.com/script/Wzxa3flI-Slope-Normalized-SN/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 31 | 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/
// © peacefulLizard50262
//@version=5
indicator("Slope Normalized", explicit_plot_zorder = true)
diff(float src, int n) =>
float derivative = 0.0
if n == 1
derivative := (src - src[1])
if n == 2
derivative := (src - src[2]) / 2
derivative
else if n == 3
derivative := (src + src[1] - src[2] - src[3]) / 4
derivative
else if n == 4
derivative := (src + 2 * src[1] - 2 * src[3] - src[4]) / 8
derivative
else if n == 5
derivative := (src + 3 * src[1] + 2 * src[2] - 2 * src[3] - 3 * src[4] - src[5]) / 16
derivative
else if n == 6
derivative := (src + 4 * src[1] + 5 * src[2] - 5 * src[4] - 4 * src[5] - src[6]) / 32
derivative
else if n == 7
derivative := (src + 5 * src[1] + 9 * src[2] + 5 * src[3] - 5 * src[4] - 9 * src[5] - 5 * src[6] - src[7]) / 64
derivative
else if n == 8
derivative := (src + 6 * src[1] + 14 * src[2] + 14 * src[3] - 14 * src[5] - 14 * src[6] - 6 * src[7] - src[8]) / 128
derivative
else if n == 9
derivative := (src + 7 * src[1] + 20 * src[2] + 28 * src[3] + 14 * src[4] - 14 * src[5] - 28 * src[6] - 20 * src[7] - 7 * src[8] - src[9]) / 256
derivative
else if n == 10
derivative := (src + 8 * src[1] + 27 * src[2] + 48 * src[3] + 42 * src[4] - 42 * src[6] - 48 * src[7] - 27 * src[8] - 8 * src[9] - src[10]) / 512
derivative
derivative
source = input.source(close, "Source", inline = "Source", group = "Source")
length = input.int(20, "Length", 1, inline = "Source", group = "Source")
pre_smoothing = input.float(0.7, "Pre Smoothing", 0.05, 1, 0.05, inline = "Smooting", group = "Source")
post_smoothing = input.float(0.7, "Post Smoothing", 0.05, 1, 0.05, inline = "Smooting", group = "Source")
bounds = input.bool(false, "", inline = "Bounds", group = "Bounds")
bound_level = input.float(1, "Bound Level", 0.05, 1, 0.05, inline = "Bounds", group = "Bounds")
clip = input.bool(false, "Hard Clipping", inline = "Bounds", group = "Bounds")
outlier_level = input.float(2, "Outlier Level", 0, 100, 0.25, inline = "Outlier", group = "Outlier")
dev_lookback = input.int(20, "Outlier Length", 2, inline = "Outlier", group = "Outlier")
enable_diff = input.bool(false, "Enable Delta", group = "Delta")
diff = input.int(2, "Delta Pre Smoothing", 1, 10, inline = "Diff", group = "Delta")
diff_alpha = input.float(0.7, "Delta Post Smoothing", 0.05, 1, 0.05, inline = "Diff", group = "Delta")
center_line = input.bool(true, "Center Line", inline = "Center", group = "Center")
center_center = input.bool(true, "Mean Center", inline = "Center", group = "Center")
col_grow_below = input.color(color.new(#FFCDD2, 30), "Low Color", inline = "low", group = "Color")
col_fall_below = input.color(color.new(#FF5252, 30), "", inline = "low", group = "Color")
col_fall_above = input.color(color.new(#B2DFDB, 30), "High Color", inline = "high", group = "Color")
col_grow_above = input.color(color.new(#26A69A, 30), "", inline = "high", group = "Color")
bes(source, alpha)=>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
max(source, outlier_level, dev_lookback)=>
var float max = na
src = array.new<float>()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : -1.7976931348623157e+308)
max := math.max(nz(max[1]), array.get(src, 0))
min(source, outlier_level, dev_lookback)=>
var float min = na
src = array.new<float>()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : 1.7976931348623157e+308)
min := math.min(nz(min[1]), array.get(src, 0))
min_max(src, outlier_level, dev_lookback)=>
((src - min(src, outlier_level, dev_lookback))/(max(src, outlier_level, dev_lookback) - min(src, outlier_level, dev_lookback)) - 0.5) * 2
rms_slope(source, length, pre_smoothing, post_smoothing, outlier_level, dev_lookback)=>
src = bes(source, pre_smoothing)
avg = array.new<float>(length, na)
for i = 1 to length
array.push(avg, (src - src[i]))
slope = min_max(bes(array.avg(avg), post_smoothing), outlier_level, dev_lookback)
slope = rms_slope(source, length, pre_smoothing, post_smoothing, outlier_level, dev_lookback)
center = bes(slope, 0.001)
hist = bes(diff(slope, diff) * 2, diff_alpha)
hist_col = hist >= 0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)
slope_out = center_center ? slope - center : slope
hline(bounds ? bound_level : na, linestyle = hline.style_solid)
hline(bounds ? -bound_level : na, linestyle = hline.style_solid)
plot(center_line ? (center_center ? 0 : center) : na, "Center Line", color.silver)
plot(clip ? (slope_out > bound_level ? bound_level : slope_out < -bound_level ? -bound_level : slope_out) : slope_out, "Normalized Slope", color.orange)
plot(enable_diff ? hist : na, "Delta", hist_col, style = plot.style_columns)
|
Volatility Compression Ratio by M-Carlo | https://www.tradingview.com/script/tZIkymKQ/ | M-Carlo | https://www.tradingview.com/u/M-Carlo/ | 42 | 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/
// © M-Carlo
//@version=5
// @author M-Carlo email : [email protected]
// Hello traders. I created this simple indicator to use as a FILTER.
// He does not provide any operational signals but tells us if we are in a period of volatility compression or expansion.
// This filter works great for all strategies that work on breakouts
// The concept is this: I will enter at breakout of a price level that I consider important, only if there is a volatility compression (see image),
// and not in the case of expansion of volatility.
//Technically the calculation is very simple:
//Step 1: I calculate the ATR at "x" periods, I set 7 by default because I get better results but you can change it as you like
//using the "atr length" field. You can also choose whether to calculate the ATR via RMA, SMA or EMA.
//Step 2: I Calculate a simple average of the previous ATR over a longer period, longer period than set with the "length multiplier"
//parameter, which multiplies the "atr length" value by "x" times. Here I set the default 3 but you can change it as you like.
//Step 3: I divide the ATR value calculated in step1 by its long-term average calculated in step2, obtaining a value that will oscillate
// above and below the value of 1
//If the indicator is above the value of 1 it means that volatility is expanding
//If the indicator is below the value of 1 it means that we are in a period of volatility compression
//(and as we know volatility explodes sooner or later)
//If you have any questions write to me and I hope this filter helps you! Have good Trading!
// PS. This code is dedicated to ZEUS (2014-2020) my dog, my best friend, my brother, my all. RIP
indicator(title='Volatility Compression Ratio by M-Carlo', shorttitle='Zeus VCR', format=format.price)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Input
atrlength = input.int(title="ATR Length", defval=7, minval=1)
smoothing = input.string(title="ATR Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
lengthmultiplier = input.int(title="ATR Length Multiplier", defval=3, minval=1)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Calc
ma_function(source, atrlength) =>
switch smoothing
"RMA" => ta.rma(source, atrlength)
"SMA" => ta.sma(source, atrlength)
"EMA" => ta.ema(source, atrlength)
=> ta.wma(source, atrlength)
atrValue = ma_function(ta.tr(true), atrlength)
atrSmaValue = ta.sma(atrValue,(atrlength*lengthmultiplier))
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Zeus Volatility Compression Ratio
ZeusVolatilityCompressionRatio = atrValue / atrSmaValue
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Plot
plot(ZeusVolatilityCompressionRatio, title = "ATR", color=color.new(#317dc4, 0))
hline(1, color=color.new(color.red, transp=50)) |
Volume profile zones | https://www.tradingview.com/script/stGg6imU-Volume-profile-zones/ | mickes | https://www.tradingview.com/u/mickes/ | 444 | 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/
// © mickes
//@version=5
indicator("Volume profile zones", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500)
_timeNow = timenow
var _lightTheme = color.r(chart.bg_color) == 255
var _intMax = 2147483647
var _intMin = -2147483648
var _maxUnixTime = 2147483647000
_barVolumeProfileLevels = input.int(25, "Levels", minval = 6, group = "Volume profile")
_lookback = input.int(12, "Lookback", minval = 1, maxval = 150, group = "Volume profile", tooltip = "Set for viewing previous prices volume profile. If set high, all profiles might not be able to draw (because of TradingViews limitations on drawings) but can still be usefull for more potential zones. NOTE: if the range candle only covers one or two candlea from the viewing timeframe the profile is not included in the lookback")
_barVolumeProfileTimeFrame = input.timeframe('60', "Volume profile data source", group = "Volume profile")
_timeFrame = input.timeframe('M', "Range", group = "Volume profile")
_barVolumeProfileValueAreaPercentage = input.int(68, "Value area %", 0, 100, group = "Volume profile")
_barVolumeProfileBackgroundColor = input.color(color.new(color.blue, 90), "Background", group = "Volume profile")
_showVolumeProfileInfoLabel = input.bool(false, "Show info label", tooltip = "Shows the POC's value in relation to the avarage POC, the volume in relation to the mean volume (the same comparison to the previous volume profile is in parentheses), the touches and the score (and given scores)", group = "Volume profile")
_visualizeRange = input.bool(true, "Visualize range", tooltip = "Visualize the active range, usefull for when the data from lower time frame is not enough (for the volume prrofile); if this happens try to increase the time frame for the volume profile data source. If the range once was active the backround will not change", group = "Volume profile")
_showScore = input.bool(true, "Show score", tooltip = "Visualize the score position, the score and the relation to the scores over and under (%) (for zone calculation) in the volume profile", group = "Volume profile")
_barVolumeProfilePocColor = input.color(color.red, "Color", group = "Point Of Controll", inline = "poc")
_barVolumeProfilePocWidth = input.int(2, "Width", group = "Point Of Controll", inline = "poc")
_barVolumeProfileValueAreaUpColor = input.color(color.new(color.blue, 30), "Value area", group = "Up color", inline = "upcolor")
_barVolumeProfileValueAreaDownColor = input.color(color.new(color.orange, 30), "Value area", group = "Down color", inline = "downcolor")
_barVolumeProfileUpColor = input.color(color.new(color.blue, 75), "Volume", group = "Up color", inline = "upcolor")
_barVolumeProfileDownColor = input.color(color.new(color.orange, 75), "Volume", group = "Down color", inline = "downcolor")
_zoneType = input.string("Support or resistance", "Type", ["Support or resistance", "Number"], group = "Zones")
_zonesToShow = input.int(3, "Zones", group = "Zones")
_supportZones = input.int(0, "Support zones", group = "Zones", minval = 0)
_resistanceZones = input.int(2, "Resistance zones", group = "Zones", minval = 0)
_pocLineColor = input.color(color.black, "POC", group = "Zones", inline = "pocline")
_pocLineWidth = input.int(2, "Width", group = "Zones", inline = "pocline")
_zoneLinefillSupport = input.color(color.new(color.green, 90), "Linefill support color", group = "Zones")
_zoneLinefillResistance = input.color(color.new(color.red, 90), "Linefill resistance color", group = "Zones")
_showZoneStopLoss = input.bool(false, "Show stop loss", group = "Zones", tooltip = "Shows a line for stop loss (one ATR from the zone)")
_showZoneInfoLabel = input.bool(true, "Show info label", group = "Zones", tooltip = "Shows a zone label showing the number (number according to rating in parentheses), start/end times, volume to mean, value area part size, touches, retests and breakouts (false breakouts in parentheses), score ('/' maximum score) and given scores")
_showZoneTouchLabel = input.bool(true, "Show zone touch label", group = "Zones", tooltip = "Shows 'T' (for touch), 'R' (for retest), 'B' (for breakout) and 'FB' (for false breakout) on zone/price.\n\n- Touch: marked on the first bar that enters a zone\n- Retest: if price enters and exits a zone without price leaving the zone in the other direction. Marked on the highest/lowest bar in the retest\n- Breakout: marked on the bar that exits the zone\n- False breakout: marked on the highest/lowest bar that exits the zone")
_skipZones = input.string("", "Skip zones", tooltip = "Comma Separated Values (CSV) with no spaces, e.g. 1,2,3,4,5", group = "Zones")
_zoneRetestsLookback = input.int(10, "Lookback", group = "Retests", minval = 0, maxval = 500)
_zoneRetestsAtrFactorTolerance = input.float(0, "ATR factor tolerance", group = "Retests", minval = 0, tooltip = "If a 'retest' has happened within a 'tolerance' of a range of this factor times the ATR, it will count")
_zoneBreaksLookback = input.int(20, "Lookback", group = "Breakouts", minval = 0, maxval = 500)
_zoneFalseBreaksLookback = input.int(20, "Lookback", group = "False breakouts", minval = 0, maxval = 500)
_barsInZoneScores = input.string("10,9,8,7,6,5,4,3,2,1", "Bars in zone", group = "Scores", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_virginPocScore = input.float(30, "Virgin POC", group = "Scores", tooltip = "Score that's applied to all profiles that fulfills all the conditions")
_valueAreaPartScores = input.string("10,9,8,7,6,5,4,3,2,1", "Value area part", group = "Scores", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_valuAreaVolumeScores = input.string("10,9,8,7,6,5,4,3,2,1", "VA Volume", group = "Scores", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_closestPriceScores = input.string("10,9,8,7,6,5,4,3,2,1", "Scores", group = "Closest price", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_closestPriceScorePercentageLimit = input.int(80, "Limit %", minval = 0, maxval = 100, group = "Closest price", tooltip = "For the score to be given the profile must be in the earlier profiles (by the percentage given)")
_reactionScore = input.float(10, "Score", group = "Zone reaction score", tooltip = "Score that's applied to all profiles that fulfills all the conditions")
_reactionLookahead = input.int(5, "Lookahead", group = "Zone reaction score", minval = 0, tooltip = "Number of bars to look for a zone base reaction")
_reactionAtrFactor = input.float(.4, "ATR factor", group = "Zone reaction score", minval = 0, tooltip = "ATR (length 14) factor that's needed per bar (average) for the score to be applied")
_pivotScore = input.float(10, "Score", group = "Pivot score", tooltip = "Score that's applied to all profiles that fulfills all the conditions. Even if the period contains multiple pivots only one score is given")
_pivotBars = input.int(50, "Length", group = "Pivot score")
_showPivots = input.bool(true, "Show", group = "Pivot score")
_priceAwayScoreFactor = input.float(3, "Score factor", group = "Price away score", tooltip = "The score is multiplied with the risk/reward that's given")
_priceAwayScoreMargin = input.float(10, "Margin from base", group = "Price away score", minval = 1, tooltip = "Margin from the base at witch to start. 'Minval' is limited to 1 because profiles can have incomple candles (not have a candle at all on the last time of the range)")
_priceAwayScores = input.string("10,9,8,7,6,5,4,3,2,1", "Scores", group = "Price away score", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_barsAwayScores = input.string("10,9,8,7,6,5,4,3,2,1", "Scores", group = "Price away score", tooltip = "Comma Separated Values (CSV) with no spaces, top score first, e.g. 5,4,3,2,1")
_showSummary = input.bool(true, "Show summary", group = "summary")
_showSummaryInfo = input.bool(false, "Show info", group = "summary")
_alertFrequency = input.string("Once per bar close", "Frequency", ["All", "Once per bar", "Once per bar close"], group = "Alert")
_alertOn = input.string("None", "Alert", ["None", "All", "Entry/crossing", "Retest", "Breakout", "Breakout and retest", "False breakouts"], group = "Alert", tooltip = "Must be set if you want to create an alert. 'Breakout and retest' also includes 'Breakout and false breakout'. NOTE: If you pause and resume an alert new zones will be used! Alerts are not effected by if a touch is removed after it happens (like a breakout that becomes a false breakout) and if a touch (e.g. a breakout) has started before the alert is created the user will be notified anyway. At the moment alerts can only be set if 'Last range bar index' is set (this is due to var/varip and unknown pine history error)")
_alertDirection = input.string("All", "Direction", ["All","Bull", "Bear"], group = "Alert")
_alertDelay = input.int(0, "Delay", minval = 0, tooltip = "Use if you want to be notified a little bit later (number of bars). If a touch (e.g. a breakout) of the same type happens between the previous touch and the delay it will not be alerted!", group = "Alert")
_activeBarIndexDefaultTime = 2147483647000 // max unix time
_activeBarIndexTime = input.time(_activeBarIndexDefaultTime, "Bar index label", group = "Advanced", tooltip = "Change this to show one specific profile. Put the time in a range and it will show (usefull for viewing older profiles and specific onces)")
_lastRangeBarIndex = input.int(-1, "Last range bar index", group = "Advanced", tooltip = "If set to not -1 will define the latest range bar (if you can figure out the bar index or chech the from end box). Touches after the active period will be shown but the original 'touch' will never be shown")
_lastRangeBarIndexFromEnd = input.bool(true, "Last range bar index from end", group = "Advanced", tooltip = "Set if you want to use the 'last range bar index' as bars from end. Set to '-1' to deactivate")
_barVolumeProfileBullVolumeStartIndex = 0
_barVolumeProfileBearVolumeStartIndex = _barVolumeProfileLevels
_barVolumeProfilePricesStartIndex = _barVolumeProfileLevels * 2
_barVolumeProfileMetaDataLowPriceIndex = _barVolumeProfilePricesStartIndex
_barVolumeProfileMetaDataHighPriceIndex = _barVolumeProfilePricesStartIndex + 1
_barVolumeProfileMetaDataPriceWidthIndex = _barVolumeProfilePricesStartIndex + 2
_barVolumeProfileMetaDataTimeIndex = _barVolumeProfilePricesStartIndex + 3
_barVolumeProfileMetaDataStartBarIndexIndex = _barVolumeProfilePricesStartIndex + 4
_barVolumeProfileMetaDataEndBarIndexIndex = _barVolumeProfilePricesStartIndex + 5
_barVolumeProfileMetaDataPocIndex = _barVolumeProfilePricesStartIndex + 6
_barVolumeProfileMetaDataPocVolumeIndex = _barVolumeProfilePricesStartIndex + 7
_barVolumeProfileMetaDataValueAreaLowIndex = _barVolumeProfilePricesStartIndex + 8
_barVolumeProfileMetaDataValueAreaHighIndex = _barVolumeProfilePricesStartIndex + 9
_barVolumeProfileMetaDataStartTimeIndex = _barVolumeProfilePricesStartIndex + 10
_barVolumeProfileMetaDataEndTimeIndex = _barVolumeProfilePricesStartIndex + 11
_metaDataLowPriceIndex = 0
_metaDataHighPriceIndex = 1
_metaDataPriceWidthIndex = 2
_metaDataTimeIndex = 3
_scoreMetaDataReactionBullTrend = 0
_scoreMetaDataReactionBearTrend = 1
_atr = ta.atr(14)
type interval
int Start
int End
bool IncompleteCandles
bool PreviousIncompleteCandles
int StartTime = time
int EndTime = -time_close
int PreviousStartTime = time
int PreviousEndTime = time_close
int PreviousStart
int PreviousEnd
type zoneInfo
int BarIndex
float Price
bool IsLabelUp
int StartBarIndex
int EndBarIndex
int Length
type volumeProfile
float Poc
float Volume
int StartTime
int EndTime
int Start
int End
float PriceWidth
float Low
float High
float ValueAreaLow
float ValueAreaHigh
float UpVolume
float DownVolume
array<zoneInfo> Breakouts
array<int> BreakoutIndices
array<zoneInfo> Retests
array<int> RetestIndices
array<zoneInfo> FalseBreakouts
array<int> FalseBreakoutIndices
array<int> TouchIndices
int BarsInZone = 0 // almost the same as touches, but every bar
array<int> Scores // meta data used by scores
array<string> ScoresGiven
float Score
array<line> ZoneLines
array<linefill> ZoneLinefills
array<label> ZoneLabels
label InfoLabel
array<line> Lines
array<linefill> Linefills
array<box> Boxes
int LatestBullRetestConfirmationBarIndex = -1
int LatestBearRetestConfirmationBarIndex = -1
int LatestBullFalseBreakoutConfirmationBarIndex = -1
int LatestBearFalseBreakoutConfirmationBarIndex = -1
int LatestBullBreakoutConfirmationBarIndex = -1
int LatestBearBreakoutConfirmationBarIndex = -1
int LatestBullTouchConfirmationBarIndex = -1
int LatestBearTouchConfirmationBarIndex = -1
bool Incomplete = false
float MinimumBeforeTouch = 2147483647
float MaximumBeforeTouch = -2147483648
bool IsTouched = false
int BarsAwayUntilFirstTouch = 0
float PriceAwayUntilFirstTouch = 0
float ValueAreaVolume = 0
box AreaBox
type volumeProfilesSummary
float AvaragePoc = 0.
float AvarageVolume = 0.
int Count = 0
type scoreMetaData
float Max = 0
float MaxScore
float MaxScoreEnd
type rangeBar
bool Active = false
bool HasBeenActive = false
bool LastActiveBar = false
int LastActiveBarTimeClose = -1
int StartTime = -1
var _lowerTimeFrameValues = matrix.new<float>()
var _barVolumeProfile = matrix.new<float>(150, (_barVolumeProfileLevels * 4), 0.)
var _scores = matrix.new<float>(_lookback, 4, 0) // row, score, score from end, total score
var _pivots = array.new<int>()
var _summary = matrix.new<string>(3, 2) // zones, vpoc, score std dev
var _interval = interval.new()
var _volumeProfiles = array.new<volumeProfile>()
var _volumeProfilesVolumes = array.new<float>()
var _volumeProfilesPocs = array.new<float>()
var _singleZone = _activeBarIndexTime != _activeBarIndexDefaultTime
var _singleLookback = _lookback == 1
var _scoreMetaData = scoreMetaData.new()
var _zones = array.new<volumeProfile>()
var _alertVolumeProfiles = array.new<volumeProfile>()
unixTimeToString(unixTime) =>
timeString = str.format_time(unixTime, "yyyy-MM-dd HH:mm:ss", syminfo.timezone)
timeString
getMetaData(m) =>
metaData = array.new_float(_barVolumeProfileLevels)
rows = matrix.rows(m)
if rows > 0
lows = matrix.col(m, 2)
highs = matrix.col(m, 3)
min = array.min(lows)
max = array.max(highs)
barSize = max - min
priceWidth = barSize / _barVolumeProfileLevels
array.set(metaData, _metaDataLowPriceIndex, min)
array.set(metaData, _metaDataHighPriceIndex, max)
array.set(metaData, _metaDataPriceWidthIndex, priceWidth)
metaData
getPriceLevels(metaData) =>
priceLevels = array.new_float(_barVolumeProfileLevels)
lowPriceHigherTime = array.get(metaData, _metaDataLowPriceIndex)
priceWidth = array.get(metaData, _metaDataPriceWidthIndex)
for i = 0 to _barVolumeProfileLevels - 1
price = lowPriceHigherTime + ((priceWidth) * i)
array.set(priceLevels, i, price)
priceLevels
setBarVolumePriceLevels(row, metaData) =>
priceLevels = getPriceLevels(metaData)
for column = 0 to _barVolumeProfileLevels - 1
price = array.get(priceLevels, column)
matrix.set(_barVolumeProfile, row, column + (_barVolumeProfileLevels * 3), price)
setMetaData(row, metaData) =>
lowPrice = array.get(metaData, _metaDataLowPriceIndex)
highPrice = array.get(metaData, _metaDataHighPriceIndex)
priceWidth = array.get(metaData, _metaDataPriceWidthIndex)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataLowPriceIndex, lowPrice)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataHighPriceIndex, highPrice)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataPriceWidthIndex, priceWidth)
setMetaDataAfter(row, startBarIndex, endBarIndex, startTime, endTime) =>
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataStartBarIndexIndex, startBarIndex)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataEndBarIndexIndex, endBarIndex)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataStartTimeIndex, startTime)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataEndTimeIndex, endTime)
rowArray = matrix.row(_barVolumeProfile, row)
bullVolumes = array.slice(rowArray, _barVolumeProfileBullVolumeStartIndex, _barVolumeProfileBearVolumeStartIndex)
bearVolumes = array.slice(rowArray, _barVolumeProfileBearVolumeStartIndex, _barVolumeProfileBearVolumeStartIndex + _barVolumeProfileLevels)
totalVolumes = array.copy(bullVolumes)
for [i, bearVolume] in bearVolumes
totalVolume = array.get(bullVolumes, i)
totalVolume += bearVolume
array.set(totalVolumes, i, totalVolume)
pocVolume = array.max(totalVolumes)
pocIndex = array.indexof(totalVolumes, pocVolume)
lowPrice = array.get(rowArray, _barVolumeProfileMetaDataLowPriceIndex)
priceWidth = array.get(rowArray, _barVolumeProfileMetaDataPriceWidthIndex)
highPrice = array.get(rowArray, _barVolumeProfileMetaDataHighPriceIndex)
poc = lowPrice + ((priceWidth) * pocIndex)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataPocIndex, poc)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataPocVolumeIndex, pocVolume)
// calculate value area
totalVolume = array.sum(totalVolumes)
maxValueAreaVolume = totalVolume * (_barVolumeProfileValueAreaPercentage / 100.)
toI = _barVolumeProfileLevels - 1
fromI = pocIndex + 1
if pocIndex == _barVolumeProfileLevels - 1
fromI := pocIndex
if (fromI - toI) > fromI
toI := 0
up = pocIndex + 1, down = pocIndex - 1, valueAreaLow = poc, valueAreaHigh = poc + priceWidth, valueAreaVolume = pocVolume
for unused = fromI to toI
if valueAreaVolume >= maxValueAreaVolume
break
volumeUp = 0.
if up <= _barVolumeProfileLevels - 1
volumeUp := array.get(totalVolumes, up)
valueAreaHigh := lowPrice + (priceWidth * up)
volumeDown = 0.
if down >= 0
volumeDown := array.get(totalVolumes, down)
valueAreaLow := lowPrice + (priceWidth * down)
if volumeUp == 0
and volumeDown == 0
break
if volumeUp >= volumeDown
valueAreaVolume += volumeUp
up += 1
else
valueAreaVolume += volumeDown
down -= 1
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataValueAreaLowIndex, valueAreaLow)
matrix.set(_barVolumeProfile, row, _barVolumeProfileMetaDataValueAreaHighIndex, valueAreaHigh)
setInterval() =>
if time >= _interval.EndTime // new interval
_interval.PreviousStartTime := _interval.StartTime
_interval.PreviousEndTime := _interval.EndTime
_interval.PreviousStart := _interval.Start
_interval.PreviousEnd := _interval.End
_interval.StartTime := time(_timeFrame)
_interval.EndTime := time_close(_timeFrame)
if _interval.PreviousIncompleteCandles
_interval.PreviousIncompleteCandles := false
_interval.Start := bar_index - 1 // previous incomplete candles were drawn later
else
_interval.Start := bar_index
_interval.IncompleteCandles := false
_interval.End := bar_index // always update to latest
getData(active) =>
// must be called in lower time frame
bullVolume = 0.
bearVolume = 0.
lowPrice = 0.
highPrice = 0.
openTime = 0
if active
lowPrice := low
highPrice := high
if close >= open // green candle
bullVolume := volume
else
bearVolume := volume
openTime := time
[bullVolume, bearVolume, lowPrice, highPrice, openTime]
getVolumeProfileMatrix(active, previousActive, previousTimeClose, incomplete) =>
m = matrix.new<float>()
incompleteCandles = previousTimeClose < _interval.PreviousEndTime
and time_close > _interval.PreviousEndTime
activeAndIntervalCloseTime = active and (time_close == _interval.EndTime)
activeAndAndLastActiveIncompleteCandlesNonRealtimeBar = active and ((barstate.islast and timenow > _interval.EndTime) and not barstate.isrealtime) // incomplete candles and closed range
previousActiveAndIncompleteCandles = previousActive and incompleteCandles // incomplete candles and previous bar was active
incompleteAndLastBar = barstate.islast and incomplete
if (activeAndIntervalCloseTime or activeAndAndLastActiveIncompleteCandlesNonRealtimeBar or previousActiveAndIncompleteCandles)
or incompleteAndLastBar
m := matrix.copy(_lowerTimeFrameValues)
removeRowIndices = array.new<int>()
rows = matrix.rows(m)
toI = rows > 0 ? rows - 1 : na
for row = 0 to toI
openTime = matrix.get(m, row, 4)
if incompleteCandles
if openTime > _interval.PreviousEndTime
array.push(removeRowIndices, row) // remove from returned matrix later
else if not incompleteAndLastBar
matrix.remove_row(_lowerTimeFrameValues, toI - row) // remove from 'next' matrix, all but the current once
else if not incompleteAndLastBar
matrix.remove_row(_lowerTimeFrameValues, 0)
removedRows = 0
for removeRowIndex in removeRowIndices
removedRow = matrix.remove_row(m, removeRowIndex - removedRows)
removedRows += 1
_interval.IncompleteCandles := incompleteCandles
if matrix.rows(m) == 0
runtime.error("Cannot fetch enough data for volume profile (try increasing the volume profile data source)")
m
isActive(lastRangeBarIndex, lastRangeBarIndexFromEnd) =>
bar = rangeBar.new()
lastBarIndex = lastRangeBarIndex != -1 ? lastRangeBarIndexFromEnd ? last_bar_index - lastRangeBarIndex : lastRangeBarIndex : last_bar_index
var lastActiveBarCloseTime = _maxUnixTime
var hasBeenActive = false
if not _singleZone
bar.Active := bar_index > lastBarIndex - _lookback
and bar_index <= lastBarIndex
if bar_index == lastBarIndex
bar.LastActiveBar := true
lastActiveBarCloseTime := time_close
else // one zone selected to show
bar.Active := _activeBarIndexTime >= time
and _activeBarIndexTime < time_close
if bar.Active
lastActiveBarCloseTime := time_close
bar.LastActiveBarTimeClose := lastActiveBarCloseTime
if bar.Active
hasBeenActive := true
if hasBeenActive
and not bar.Active
bar.HasBeenActive := true
bar.StartTime := time
bar
setVolumeProfileData(active, bullVolumes, bearVolumes, lowPrices, highPrices, openTimes) =>
if active
toI = array.size(bullVolumes) - 1
if toI < 0
toI := na
for i = 0 to toI
matrix.add_row(_lowerTimeFrameValues, 0, array.from(
array.get(bullVolumes, i),
array.get(bearVolumes, i),
array.get(lowPrices, i),
array.get(highPrices, i),
array.get(openTimes, i)))
inRangeShare(lowPriceLimit, highPriceLimit, lowPrice, highPrice) =>
lowPriceShareInRange = 0.
highPriceShareInRange = 0.
isInRange = false
if lowPrice <= highPriceLimit
and highPrice >= lowPriceLimit
lowPriceShareInRange := highPriceLimit - math.max(lowPrice, lowPriceLimit)
highPriceShareInRange := highPrice - math.max(lowPriceLimit, lowPrice)
isInRange := true
inRange = math.min(lowPriceShareInRange, highPriceShareInRange)
rangeWidth = highPriceLimit - lowPriceLimit
barSize = highPrice - lowPrice
wholeBarInRange = (barSize <= rangeWidth and (inRange > 0 or barSize == 0)) and isInRange
share = 0.
switch wholeBarInRange
false =>
if barSize > 0
share := inRange / barSize
true =>
share := 1
if share > 1
runtime.error("Share is to large " + str.tostring(lowPriceShareInRange) + "\n" + str.tostring(highPriceShareInRange) + "\n" + str.tostring(share) + "\n" + str.tostring(inRange) + "\n" + str.tostring(barSize))
if na(share)
runtime.error("Share is na " + str.tostring(lowPriceShareInRange) + "\n" + str.tostring(highPriceShareInRange) + "\n" + str.tostring(share) + "\n" + str.tostring(inRange) + "\n" + str.tostring(barSize))
share
getVolumes(lowPrice, highPrice, bullVolume, bearVolume, metaData) =>
volumeMatrix = matrix.new<float>()
priceLevels = getPriceLevels(metaData)
priceWidth = array.get(metaData, _metaDataPriceWidthIndex)
for row = 0 to array.size(priceLevels) - 1
priceLevel = array.get(priceLevels, row)
lowPriceHigherTime = priceLevel
highPriceHigherTime = priceLevel + priceWidth
share = inRangeShare(lowPriceHigherTime, highPriceHigherTime, lowPrice, highPrice)
if share > 0
bullVolumeShare = bullVolume * share
bearVolumeShare = bearVolume * share
matrix.add_row(volumeMatrix, 0, array.from(
row,
bullVolumeShare,
bearVolumeShare,
lowPrice,
highPrice,
bullVolume,
bearVolume))
volumeMatrix
updateBarVolumeProfile(row, volumeMatrix) =>
for rowArray in volumeMatrix
column = math.round(array.get(rowArray, 0))
bullVolume = array.get(rowArray, 1)
bearVolume = array.get(rowArray, 2)
bullColumn = column + _barVolumeProfileBullVolumeStartIndex
bearColumn = column + _barVolumeProfileBearVolumeStartIndex
matrixBullVolume = matrix.get(_barVolumeProfile, row, bullColumn)
matrixBullVolume += bullVolume
matrix.set(_barVolumeProfile, row, bullColumn, matrixBullVolume)
matrixBearVolume = matrix.get(_barVolumeProfile, row, bearColumn)
matrixBearVolume += bearVolume
matrix.set(_barVolumeProfile, row, bearColumn, matrixBearVolume)
volumeProfileScoreString(profile, i) =>
scores = ""
for score in profile.ScoresGiven
scores += "\n" + score
string scoreString = na
if str.length(scores) > 0
profiles = array.size(_volumeProfiles)
scoreString := str.format("\nScore ({0}): {1,number,#.#}/{2,number,#.#}{3}{4}", i == 0 ? "highest" : str.format("top {0,number,#}%", ((i + 1) / profiles) * 100) , profile.Score, _scoreMetaData.Max, str.length(scores) == 0 ? "" : ":", scores)
scoreString
volumeProfileInfoLabel(i, profile, start, end, lowPrice, highPrice, poc, totalVolume, upVolume, downVolume) =>
infoLabel = label.new(start + ((end - start) / 2), 0, "")
profile.InfoLabel := infoLabel
updateVolumeProfileInfoLabel(profile, i) =>
var calls = 0
pocPreviousPercentage = 0.
pocPercentage = 0.
volumePreviousPercentage = 0.
volumePercentage = 0.
averageVolume = array.sum(_volumeProfilesVolumes) / array.size(_volumeProfilesVolumes)
averagePoc = array.sum(_volumeProfilesPocs) / array.size(_volumeProfilesPocs)
previousVolumeProfile = i > 0 ? array.get(_volumeProfiles, i - 1) : volumeProfile.new()
pocPreviousPercentage := ((profile.Poc / previousVolumeProfile.Poc) - 1) * 100
pocPercentage := ((profile.Poc / averagePoc) - 1) * 100
volumePreviousPercentage := ((profile.Volume / previousVolumeProfile.Volume) - 1) * 100
volumePercentage := ((profile.Volume / averageVolume) - 1) * 100
location = calls % 2 == 0 ? profile.High : profile.Low
txt = str.format("POC: {0,number,##.#}% ({1,number,##.#}%)\n", pocPercentage, pocPreviousPercentage)
+ str.format("Volume: {0,number,##.#}% ({1,number,##.#}%)\n", volumePercentage, volumePreviousPercentage)
+ str.tostring(profile.UpVolume, format.volume) + "x" + str.tostring(profile.DownVolume, format.volume) + " (" + str.tostring(profile.Volume, format.volume) + ")"
+ volumeProfileScoreString(profile, i)
color labelColor = na
if volumePercentage > 0
labelColor := color.new(color.green, 40)
else if volumePercentage < 0
labelColor := color.new(color.red, 40)
else if volumePercentage == 0
labelColor := color.new(color.gray, 40)
txt := str.tostring(profile.Volume, format.volume)
label.set_text(profile.InfoLabel, txt)
label.set_style(profile.InfoLabel, location == profile.High ? label.style_label_down : label.style_label_up)
label.set_y(profile.InfoLabel, location)
label.set_color(profile.InfoLabel, labelColor)
if i == array.size(_volumeProfiles) - 1
calls := 0
else
calls += 1
updateVolumeProfileInfoLabels() =>
for [i, profile] in _volumeProfiles
updateVolumeProfileInfoLabel(profile, i)
visulize(volumes, row, incomplete) =>
start = math.round(array.get(volumes, _barVolumeProfileMetaDataStartBarIndexIndex))
end = math.round(array.get(volumes, _barVolumeProfileMetaDataEndBarIndexIndex))
startTime = math.round(array.get(volumes, _barVolumeProfileMetaDataStartTimeIndex))
endTime = math.round(array.get(volumes, _barVolumeProfileMetaDataEndTimeIndex))
lowPrice = array.get(volumes, _barVolumeProfileMetaDataLowPriceIndex)
highPrice = array.get(volumes, _barVolumeProfileMetaDataHighPriceIndex)
pocVolume = array.get(volumes, _barVolumeProfileMetaDataPocVolumeIndex)
priceWidth = array.get(volumes, _barVolumeProfileMetaDataPriceWidthIndex)
valueAreaLow = array.get(volumes, _barVolumeProfileMetaDataValueAreaLowIndex)
valueAreaHigh = array.get(volumes, _barVolumeProfileMetaDataValueAreaHighIndex)
poc = array.get(volumes, _barVolumeProfileMetaDataPocIndex)
boxes = array.new<box>()
lines = array.new<line>()
linefills = array.new<linefill>()
valueAreaVolume = 0.
xFactor = (end - start) * (float(2) / 3)
for i = 0 to _barVolumeProfileLevels - 1
bullVolume = array.get(volumes, _barVolumeProfileBullVolumeStartIndex + i)
bearVolume = array.get(volumes, _barVolumeProfileBearVolumeStartIndex + i)
totalVolume = bullVolume + bearVolume
price = lowPrice + (priceWidth * i)
volumeShare = totalVolume / pocVolume
bullShare = nz((bullVolume / totalVolume) * volumeShare)
bearShare = nz((bearVolume / totalVolume) * volumeShare)
rightUp = start + math.round(bullShare * xFactor)
rightDown = rightUp + math.round(bearShare * xFactor)
left = start
top = (price + priceWidth) - (priceWidth * 0.07)
right = rightUp
bottom = price + (priceWidth * 0.07)
upBoxColor = _barVolumeProfileValueAreaUpColor
downBoxColor = _barVolumeProfileValueAreaDownColor
if price < valueAreaLow
or price >= valueAreaHigh
upBoxColor := _barVolumeProfileUpColor
downBoxColor := _barVolumeProfileDownColor
else
valueAreaVolume += totalVolume
if left != right
if price == poc
upLowLine = line.new(left, bottom, right, bottom, color = upBoxColor)
upHighLine = line.new(left, top, right, top, color = upBoxColor)
upLeftLine = line.new(left, bottom, left, top, color = upBoxColor)
upRightLine = line.new(right, bottom, right, top, color = upBoxColor)
array.push(lines, upLowLine), array.push(lines, upHighLine), array.push(lines, upLeftLine), array.push(lines, upRightLine)
boxishLinefill = linefill.new(upLowLine, upHighLine, upBoxColor)
array.push(linefills, boxishLinefill)
else
upBox = box.new(left, top, right, bottom, border_color = color.black, bgcolor = upBoxColor, border_width = 0)
array.push(boxes, upBox)
left := rightUp
right := rightDown
if left != right
if price == poc
downLowLine = line.new(left, bottom, right, bottom, color = downBoxColor)
downHighLine = line.new(left, top, right, top, color = downBoxColor)
downLeftLine = line.new(left, bottom, left, top, color = downBoxColor)
downRightLine = line.new(right, bottom, right, top, color = downBoxColor)
array.push(lines, downLowLine), array.push(lines, downHighLine), array.push(lines, downLeftLine), array.push(lines, downRightLine)
boxishLinefill = linefill.new(downLowLine, downHighLine, downBoxColor)
array.push(linefills, boxishLinefill)
else
downBox = box.new(left, top, right, bottom, bgcolor = downBoxColor, border_width = 0)
array.push(boxes, downBox)
valueAreaLowLine = line.new(start, valueAreaLow, end, valueAreaLow, color = color.blue, width = 2)
valueAreaHighLine = line.new(start, valueAreaHigh, end, valueAreaHigh, color = color.blue, width = 2)
pocLine = line.new(start, poc + (priceWidth / 2), end, poc + (priceWidth / 2), color = _barVolumeProfilePocColor, width = _barVolumeProfilePocWidth)
array.push(lines, valueAreaLowLine), array.push(lines, valueAreaHighLine), array.push(lines, pocLine)
upVolume = array.sum(array.slice(volumes, 0, _barVolumeProfileLevels))
downVolume = array.sum(array.slice(volumes, _barVolumeProfileLevels, _barVolumeProfileLevels * 2))
totalVolume = array.sum(array.slice(volumes, 0, _barVolumeProfileLevels * 2))
profile = volumeProfile.new(poc + (priceWidth / 2), totalVolume, startTime, endTime, start, end, priceWidth, lowPrice, highPrice, valueAreaLow, valueAreaHigh, upVolume, downVolume) // add price width to value area low to match
profile.Breakouts := array.new<zoneInfo>()
profile.BreakoutIndices := array.new<int>()
profile.Retests := array.new<zoneInfo>()
profile.RetestIndices := array.new<int>()
profile.FalseBreakouts := array.new<zoneInfo>()
profile.FalseBreakoutIndices := array.new<int>()
profile.TouchIndices := array.new<int>()
profile.Scores := array.new<int>()
profile.ScoresGiven := array.new<string>()
profile.ZoneLines := array.new<line>()
profile.ZoneLinefills := array.new<linefill>()
profile.ZoneLabels := array.new<label>()
profile.Lines := lines
profile.Linefills := linefills
profile.Boxes := boxes
profile.Incomplete := incomplete
profile.ValueAreaVolume := valueAreaVolume
areaBox = box.new(start, highPrice, end, lowPrice, bgcolor = _barVolumeProfileBackgroundColor, border_width = 0, text_valign = text.align_top, text_halign = text.align_right, text_size = size.tiny, text_color = _lightTheme ? color.black : color.gray)
array.push(boxes, areaBox)
profile.AreaBox := areaBox
array.push(_volumeProfiles, profile)
array.push(_volumeProfilesVolumes, totalVolume)
array.push(_volumeProfilesPocs, poc)
if _showVolumeProfileInfoLabel
volumeProfileInfoLabel(row, profile, start, end, lowPrice, highPrice, poc, totalVolume, upVolume, downVolume)
sort(m, col, order) =>
if matrix.rows(m) > 0
matrix.sort(m, col, order)
removeLatestProfileIfIncomplete() =>
volumeProfiles = array.size(_volumeProfiles)
if volumeProfiles == _lookback
profile = array.get(_volumeProfiles, volumeProfiles - 1)
if profile.Incomplete
for profileLine in profile.Lines
line.delete(profileLine)
for profileLinefill in profile.Linefills
linefill.delete(profileLinefill)
for profileBox in profile.Boxes
box.delete(profileBox)
label.delete(profile.InfoLabel)
array.remove(_volumeProfiles, volumeProfiles - 1)
sort(_scores, 0, order.ascending) // sort scores by row
updateProfilesIfNeeded() =>
volumeProfiles = array.size(_volumeProfiles)
if volumeProfiles == _lookback
profile = array.remove(_volumeProfiles, 0)
for profileLine in profile.Lines
line.delete(profileLine)
for profileLinefill in profile.Linefills
linefill.delete(profileLinefill)
for profileBox in profile.Boxes
box.delete(profileBox)
label.delete(profile.InfoLabel)
sort(_scores, 0, order.ascending) // sort scores by row
for i = 1 to _lookback - 1
matrix.set(_scores, i, 0, i - 1) // make every score drop one row
matrix.add_row(_scores, _lookback, array.from(_lookback - 1, 0, 0, 0)) // add empty row for new profile
matrix.remove_row(_scores, 0) // remove earliest score
volumeProfile(m, metaData, incomplete) =>
rows = matrix.rows(m)
if rows > 0
updateProfilesIfNeeded()
bullVolumes = matrix.col(m, 0)
bearVolumes = matrix.col(m, 1)
lowPrices = matrix.col(m, 2)
highPrices = matrix.col(m, 3)
var row = 0
setBarVolumePriceLevels(row, metaData)
setMetaData(row, metaData)
priceLevels = getPriceLevels(metaData)
for [i, bullVolume] in bullVolumes
bearVolume = array.get(bearVolumes, i)
lowPrice = array.get(lowPrices, i)
highPrice = array.get(highPrices, i)
volumeMatrix = getVolumes(lowPrice, highPrice, bullVolume, bearVolume, metaData)
updateBarVolumeProfile(row, volumeMatrix)
if _interval.IncompleteCandles
setMetaDataAfter(row, _interval.PreviousStart, _interval.PreviousEnd, _interval.PreviousStartTime, _interval.PreviousEndTime)
_interval.IncompleteCandles := false
_interval.PreviousIncompleteCandles := true
else
setMetaDataAfter(row, _interval.Start, _interval.End, _interval.StartTime, _interval.EndTime)
_interval.PreviousIncompleteCandles := false
visulize(matrix.row(_barVolumeProfile, row), row, incomplete)
row += 1
isSupport(price) =>
price < high
skipZone(i) =>
var skips = str.split(_skipZones, ',')
skip = array.indexof(skips, str.tostring(i))
skip != -1
closestIsInRange(indices, types, index) =>
size = array.size(indices)
inRange = false
if size > 0
leftIndex = array.binary_search_leftmost(indices, index)
left = array.get(types, leftIndex)
if index >= left.StartBarIndex
and index <= left.EndBarIndex
// earlier bars
inRange := true
else
// later bars
rightIndex = array.binary_search_rightmost(indices, index)
zoneInfo right = na
if rightIndex < size
right := array.get(types, rightIndex)
else
right := zoneInfo.new(-1, 0, false, last_bar_index + 1, last_bar_index + 2)
if index >= right.StartBarIndex
and index <= right.EndBarIndex
inRange := true
inRange
showZoneInfo(zoneInfos, txt, labelColor, minTransparancy, maxTransparancy, zoneLabels, int from = na) =>
size = array.size(zoneInfos)
if size > 0
sorted = matrix.new<float>(size, 2)
for [i, touch] in zoneInfos
matrix.set(sorted, i, 0, i)
matrix.set(sorted, i, 1, touch.Length)
matrix.sort(sorted, 1, order.descending)
sortedRows = matrix.col(sorted, 0)
for [i, touch] in zoneInfos
if touch.EndBarIndex < from
continue
lengthIndex = array.indexof(sortedRows, i)
style = touch.IsLabelUp ? label.style_label_up : label.style_label_down
transparancy = maxTransparancy
if size > 1
transparancy := maxTransparancy - ((((size - 1) - lengthIndex) * ((maxTransparancy - minTransparancy)) / (size - 1)))
touchLabel = label.new(touch.BarIndex, touch.Price, txt, tooltip = str.format("bar length: {0}", touch.Length), style = style, color = color.new(labelColor, transparancy))
array.push(zoneLabels, touchLabel)
showZoneTouch(profile) =>
for touchIndex in profile.TouchIndices
breaksAlso = closestIsInRange(profile.BreakoutIndices, profile.Breakouts, touchIndex)
retestsAlso = closestIsInRange(profile.RetestIndices, profile.Retests, touchIndex)
falseBreakoutAlso = closestIsInRange(profile.FalseBreakoutIndices, profile.FalseBreakouts, touchIndex)
if not breaksAlso
and not retestsAlso
and not falseBreakoutAlso
touchLabel = label.new(touchIndex, 0, "T", yloc = yloc.abovebar, color = color.new(color.white, 70))
array.push(profile.ZoneLabels, touchLabel)
zoneTouchLabels(profile, int from = na) =>
showZoneInfo(profile.Breakouts, "B", color.red, 40, 70, profile.ZoneLabels, from)
showZoneInfo(profile.Retests, "R", color.blue, 40, 70, profile.ZoneLabels, from)
showZoneInfo(profile.FalseBreakouts, "FB", color.orange, 40, 70, profile.ZoneLabels, from)
if na(from)
showZoneTouch(profile)
valueAreaPercentage(profile) =>
((profile.ValueAreaHigh - profile.ValueAreaLow) / (profile.High - profile.Low)) * 100
drawZone(profile, shown, entierVolume, support, index, scoreIndex, valueAreaPercentage) =>
averageVolume = array.sum(_volumeProfilesVolumes) / array.size(_volumeProfilesVolumes)
volumePercentage = ((profile.Volume / averageVolume) - 1) * 100
valueAreaLowLine = line.new(last_bar_index, profile.ValueAreaLow, last_bar_index + 1, profile.ValueAreaLow, color = color.black, extend = extend.both)
valueAreaHighLine = line.new(last_bar_index, profile.ValueAreaHigh, last_bar_index + 1, profile.ValueAreaHigh, color = color.black, extend = extend.both)
zoneLinefill = linefill.new(valueAreaLowLine, valueAreaHighLine, support ? _zoneLinefillSupport : _zoneLinefillResistance)
array.push(profile.ZoneLines, valueAreaLowLine)
array.push(profile.ZoneLines, valueAreaHighLine)
array.push(profile.ZoneLinefills, zoneLinefill)
pocLine = line.new(bar_index, profile.Poc, bar_index + 1, profile.Poc, color = _pocLineColor, width = _pocLineWidth, style = line.style_dashed, extend = extend.both)
array.push(profile.ZoneLines, pocLine)
if _showZoneStopLoss
switch support
false =>
stopLossLine = line.new(last_bar_index + 10, profile.ValueAreaHigh + _atr, bar_index + 20, profile.ValueAreaHigh + _atr, color = color.black)
array.push(profile.ZoneLines, stopLossLine)
true =>
stopLossLine = line.new(last_bar_index + 10, profile.ValueAreaLow - _atr, bar_index + 20, profile.ValueAreaLow - _atr, color = color.black)
array.push(profile.ZoneLines, stopLossLine)
if _showZoneInfoLabel
string txt = na
if not _singleZone // only show scores and volume to mean if multiple profiles
scoreString = volumeProfileScoreString(profile, scoreIndex)
txt := str.format("{0} ({1})\nStart: {2}\nEnd: {3}\nVolume to mean: {4,number,##.#}%\nVA part: {5,number,##.#}%\nTouches: {6}\nRetests: {7}\nBreakouts: {8} ({9}){10}", index + 1, scoreIndex + 1, unixTimeToString(profile.StartTime), unixTimeToString(profile.EndTime), volumePercentage, valueAreaPercentage, array.size(profile.TouchIndices), array.size(profile.Retests), array.size(profile.BreakoutIndices), array.size(profile.FalseBreakouts), scoreString)
else
txt := str.format("Start: {0}\nEnd: {1}\nVA part: {2,number,##.#}%\nTouches: {3}\nRetests: {4}\nBreakouts: {5} ({6})", unixTimeToString(profile.StartTime), unixTimeToString(profile.EndTime), valueAreaPercentage, array.size(profile.TouchIndices), array.size(profile.Retests), array.size(profile.BreakoutIndices), array.size(profile.FalseBreakouts))
zoneInfoLabel = label.new(last_bar_index + 10 + (shown % 2 ? 0 : 20), profile.ValueAreaHigh, txt, color = support ? color.new(color.green, 40) : color.new(color.red, 40))
array.push(profile.ZoneLabels, zoneInfoLabel)
if _showZoneTouchLabel
zoneTouchLabels(profile)
array.push(_zones, profile)
clearZones() =>
for profile in _zones
for zoneLine in profile.ZoneLines
line.delete(zoneLine)
array.clear(profile.ZoneLines)
for zoneLinefill in profile.ZoneLinefills
linefill.delete(zoneLinefill)
array.clear(profile.ZoneLinefills)
for zoneLabel in profile.ZoneLabels
label.delete(zoneLabel)
array.clear(profile.ZoneLabels)
drawZones() =>
array.clear(_zones)
entierVolume = array.sum(_volumeProfilesVolumes)
if not _singleZone
supportZones = 0, resistanceZones = 0
volumeProfiles = array.size(_volumeProfiles)
toI = volumeProfiles - 1 < 0 ? na : volumeProfiles - 1
for i = 0 to toI
scoreIndex = math.round(matrix.get(_scores, i, 0))
if skipZone(scoreIndex)
continue
profile = array.get(_volumeProfiles, scoreIndex)
support = isSupport(profile.ValueAreaLow)
switch _zoneType
"Support or resistance" =>
if support
if supportZones >= _supportZones
and resistanceZones >= _resistanceZones
break
else if supportZones >= _supportZones
continue
else
if resistanceZones >= _resistanceZones
and supportZones >= _supportZones
break
else if resistanceZones >= _resistanceZones
continue
"Number" =>
if supportZones + resistanceZones == _zonesToShow
break
if support
supportZones += 1
else
resistanceZones += 1
drawZone(profile, supportZones + resistanceZones, entierVolume, support, scoreIndex, i, valueAreaPercentage(profile))
matrix.set(_summary, 0, 0, "zones:")
matrix.set(_summary, 0, 1, str.tostring(supportZones) + "/" + str.tostring(resistanceZones))
else
profile = array.get(_volumeProfiles, 0)
support = isSupport(profile.ValueAreaLow)
profile.Score := matrix.get(_scores, 0, 1)
drawZone(profile, 0, entierVolume, support, 0, 0, valueAreaPercentage(profile))
summaryTable() =>
var rows = matrix.rows(_summary)
if rows > 0
var t = table.new(position.bottom_right, 2, rows, bgcolor = color.teal)
table.clear(t, 0, 0, 1, rows - 1)
for row = 0 to rows - 1
if _showSummaryInfo
info = matrix.get(_summary, row, 0)
table.cell(t, 0, row, info, text_size = size.small)
value = matrix.get(_summary, row, 1)
table.cell(t, 1, row, value, text_size = size.small)
getVolumeProfiles() =>
array<volumeProfile> volumeProfiles = na
alertVolumeProfiles = array.size(_alertVolumeProfiles)
if alertVolumeProfiles > 0
volumeProfiles := _alertVolumeProfiles
else
volumeProfiles := _volumeProfiles
volumeProfiles
setBreaks(volumeProfiles) =>
for profile in volumeProfiles
// /
if low > profile.ValueAreaHigh
and low[1] < profile.ValueAreaHigh
for i = 1 to _zoneBreaksLookback + 2
if high[i] < profile.ValueAreaLow
if bar_index - i > profile.End
breakSize = array.size(profile.BreakoutIndices)
breakValue = -1
if breakSize != 0
breakIndex = array.binary_search_leftmost(profile.BreakoutIndices, bar_index)
breakValue := array.get(profile.BreakoutIndices, breakIndex)
if breakValue < bar_index - i // did not break before
profile.LatestBullBreakoutConfirmationBarIndex := bar_index
array.push(profile.Breakouts, zoneInfo.new(bar_index, profile.ValueAreaLow, true, bar_index - i, bar_index, i - 1))
array.push(profile.BreakoutIndices, bar_index)
while true
falseBreakSize = array.size(profile.FalseBreakoutIndices)
if falseBreakSize != 0
falseBreakIndex = array.binary_search_leftmost(profile.FalseBreakoutIndices, bar_index)
falseBreakValue = array.get(profile.FalseBreakoutIndices, falseBreakIndex)
if falseBreakValue >= bar_index - i
array.remove(profile.FalseBreakouts, falseBreakIndex)
array.remove(profile.FalseBreakoutIndices, falseBreakIndex) // also registered as a false breakout
continue
break
break
else if low[i] > profile.ValueAreaHigh // already added
break
// \
if high < profile.ValueAreaLow
and high[1] > profile.ValueAreaLow
for i = 1 to _zoneBreaksLookback + 2
if low[i] > profile.ValueAreaHigh
if bar_index - i > profile.End
breakSize = array.size(profile.BreakoutIndices)
breakValue = -1
if breakSize != 0
breakIndex = array.binary_search_leftmost(profile.BreakoutIndices, bar_index)
breakValue := array.get(profile.BreakoutIndices, breakIndex)
if breakValue < bar_index - i // did not break before
profile.LatestBearBreakoutConfirmationBarIndex := bar_index
array.push(profile.Breakouts, zoneInfo.new(bar_index, profile.ValueAreaLow, true, bar_index - i, bar_index, i - 1))
array.push(profile.BreakoutIndices, bar_index)
while true
falseBreakSize = array.size(profile.FalseBreakoutIndices)
if falseBreakSize != 0
falseBreakIndex = array.binary_search_leftmost(profile.FalseBreakoutIndices, bar_index)
falseBreakValue = array.get(profile.FalseBreakoutIndices, falseBreakIndex)
if falseBreakValue >= bar_index - i
array.remove(profile.FalseBreakouts, falseBreakIndex)
array.remove(profile.FalseBreakoutIndices, falseBreakIndex) // also registered as a false breakout
continue
break
break
else if high[i] < profile.ValueAreaLow // already added
break
setRetests(volumeProfiles) =>
for profile in volumeProfiles
highZoneLimit = profile.ValueAreaHigh + (_atr * _zoneRetestsAtrFactorTolerance)
// \/
if low > highZoneLimit
and low[1] < highZoneLimit
int lowestBarIndex = na
for i = 1 to _zoneRetestsLookback + 1
if low[i] < profile.ValueAreaLow
break
if low[i] < low[bar_index - lowestBarIndex]
or na(lowestBarIndex)
lowestBarIndex := bar_index - i
if low[i] > highZoneLimit
if bar_index - i <= profile.End
break
exists = array.includes(profile.RetestIndices, lowestBarIndex)
if exists
break
profile.LatestBearRetestConfirmationBarIndex := bar_index
array.push(profile.Retests, zoneInfo.new(lowestBarIndex, low[bar_index - lowestBarIndex] - _atr, true, bar_index - i, bar_index, i - 1))
array.push(profile.RetestIndices, lowestBarIndex)
break
lowZoneLimit = profile.ValueAreaLow - (_atr * _zoneRetestsAtrFactorTolerance)
// /\
if high < lowZoneLimit
and high[1] > lowZoneLimit
int highestBarIndex = na
for i = 1 to _zoneRetestsLookback + 1
if high[i] > profile.ValueAreaHigh
break
if high[i] > high[bar_index - highestBarIndex]
or na(highestBarIndex)
highestBarIndex := bar_index - i
if high[i] < lowZoneLimit
if bar_index - i <= profile.End
break
exists = array.includes(profile.RetestIndices, highestBarIndex)
if exists
break
profile.LatestBullRetestConfirmationBarIndex := bar_index
array.push(profile.Retests, zoneInfo.new(highestBarIndex, high[bar_index - highestBarIndex] + _atr, false, bar_index - i, bar_index, i - 1))
array.push(profile.RetestIndices, highestBarIndex)
break
setFalseBreaks(volumeProfiles) =>
for profile in volumeProfiles
// /'\ \
// / \ \ /'\
// / or \/ \
if high < profile.ValueAreaLow
and high[1] > profile.ValueAreaLow
lowBreak = false, highBreak = false, highestBarIndex = bar_index
for i = 1 to _zoneFalseBreaksLookback + 1
if high[i] > profile.ValueAreaHigh
highBreak := true
if low[i] > profile.ValueAreaHigh
lowBreak := true
if high[i] > high[bar_index - highestBarIndex]
highestBarIndex := bar_index - i
if highBreak
and high[i] < profile.ValueAreaLow
if bar_index - i <= profile.End
break
exists = array.includes(profile.FalseBreakoutIndices, highestBarIndex)
if exists
break
profile.LatestBullFalseBreakoutConfirmationBarIndex := bar_index
array.push(profile.FalseBreakouts, zoneInfo.new(highestBarIndex, high[bar_index - highestBarIndex], false, bar_index - i, bar_index, i - (bar_index - highestBarIndex)))
array.push(profile.FalseBreakoutIndices, highestBarIndex)
if lowBreak
while true
breakSize = array.size(profile.BreakoutIndices)
if breakSize != 0
breakIndex = array.binary_search_leftmost(profile.BreakoutIndices, highestBarIndex)
breakValue = array.get(profile.BreakoutIndices, breakIndex)
if breakValue >= bar_index - i
array.remove(profile.Breakouts, breakIndex)
array.remove(profile.BreakoutIndices, breakIndex) // also registered as a breakout
profile.LatestBearBreakoutConfirmationBarIndex := -1
continue
break
break
if high[i] < profile.ValueAreaLow // already added
break
// \ /\ /
// \ / / \./
// \./ or /
if low > profile.ValueAreaHigh
and low[1] < profile.ValueAreaHigh
lowBreak = false, highBreak = false, lowestBarIndex = bar_index
for i = 1 to _zoneFalseBreaksLookback + 1
if low[i] < profile.ValueAreaLow
lowBreak := true
if high[i] < profile.ValueAreaLow
highBreak := true
if low[i] < low[bar_index - lowestBarIndex]
lowestBarIndex := bar_index - i
if lowBreak
and low[i] > profile.ValueAreaHigh
if bar_index - i <= profile.End
break
exists = array.includes(profile.FalseBreakoutIndices, lowestBarIndex)
if exists
break
profile.LatestBearFalseBreakoutConfirmationBarIndex := bar_index
array.push(profile.FalseBreakouts, zoneInfo.new(lowestBarIndex, low[bar_index - lowestBarIndex], true, bar_index - i, bar_index, i - (bar_index - lowestBarIndex)))
array.push(profile.FalseBreakoutIndices, lowestBarIndex)
if highBreak
while true
breakSize = array.size(profile.BreakoutIndices)
if breakSize != 0
breakIndex = array.binary_search_leftmost(profile.BreakoutIndices, lowestBarIndex)
breakValue = array.get(profile.BreakoutIndices, breakIndex)
if breakValue >= bar_index - i
array.remove(profile.Breakouts, breakIndex)
array.remove(profile.BreakoutIndices, breakIndex) // also registered as a breakout
profile.LatestBullBreakoutConfirmationBarIndex := -1
continue
break
break
if low[i] > profile.ValueAreaHigh // already added
break
setTouches(volumeProfiles) =>
for [i, profile] in volumeProfiles
lowPrice = profile.ValueAreaLow
highPrice = profile.ValueAreaHigh
touchBullTrend = (low < highPrice and high > lowPrice)
and ((low[1] < lowPrice and high[1] < lowPrice) or (bar_index - 1 == profile.End or bar_index == profile.End))
touchBearTrend = (low < highPrice and high > lowPrice)
and ((low[1] > highPrice and high[1] > highPrice) or (bar_index - 1 == profile.End or bar_index == profile.End))
if touchBullTrend
or touchBearTrend
if bar_index > profile.End
array.push(profile.TouchIndices, bar_index)
if touchBullTrend
profile.LatestBullTouchConfirmationBarIndex := bar_index
else
profile.LatestBearTouchConfirmationBarIndex := bar_index
toScoreArray(arr) =>
var scoreStrings = str.split(arr, ',')
var numScores = array.size(scoreStrings)
scores = array.new<float>(numScores)
for [i, scoreString] in scoreStrings
scoreFloat = str.tonumber(scoreString)
array.set(scores, i, scoreFloat)
scores
updateScore(addedScore, row, source, bool end = true, int scoreNum = -1, int scores = -1) =>
profile = array.get(_volumeProfiles, row)
score = matrix.get(_scores, row, end ? 2 : 1)
score += addedScore
matrix.set(_scores, row, end ? 2 : 1, score)
scoreString = scoreNum != -1 and scores != -1 ? str.format("({0}/{1} ({2,number,#.#}))", scoreNum, scores, addedScore) : str.format("({0,number,#.#})", addedScore)
txt = str.format("{0} {1}", scoreString, source)
array.push(profile.ScoresGiven, txt)
updateScores(m, scores, source, int scoreIndex = 1, int rowIndex = 0, bool skipZero = true, int factorIndex = -1) =>
allScores = array.copy(scores)
scoresTotalSize = array.size(allScores)
scoreNum = 1
rows = matrix.rows(m)
toI = rows > 0 ? rows - 1 : na
for i = 0 to toI
scoresSize = array.size(allScores)
if scoresSize == 0
break // no more scores to give out
addedScore = array.get(allScores, 0)
value = matrix.get(m, i, scoreIndex), nextValue = 0.0
if i != toI
nextValue := matrix.get(m, i + 1, scoreIndex)
if na(value)
or value == _intMax
or value == _intMin
or (skipZero and value == 0)
break
row = math.round(matrix.get(m, i, rowIndex))
if row == _intMax
or row == _intMin
break
if factorIndex != -1
factor = matrix.get(m, i, factorIndex)
addedScore := addedScore * factor
if addedScore != 0
updateScore(addedScore, row, source, scoreNum = scoreNum, scores = scoresTotalSize)
if value != nextValue
array.remove(allScores, 0)
scoreNum += 1
getVolumeProfileTouches(profile) =>
highTouch = high > profile.ValueAreaLow
and high < profile.ValueAreaHigh
lowTouch = low > profile.ValueAreaLow
and low < profile.ValueAreaHigh
barBreaksTouch = high > profile.ValueAreaHigh
and low < profile.ValueAreaLow
[highTouch, lowTouch, barBreaksTouch]
isInRange(value, min, max) =>
inRange = false
if value >= min
and value <= max
inRange := true
inRange
setBarsInZone() =>
for [i, profile] in _volumeProfiles
if profile.End == bar_index
continue
[highTouch, lowTouch, barBreaksTouch] = getVolumeProfileTouches(profile)
if highTouch
or lowTouch
or barBreaksTouch
profile.BarsInZone += 1
addToMaxScore(score) =>
var called = false
if not called
_scoreMetaData.Max += score
called := true
setZoneReactionScore() =>
addToMaxScore(_reactionScore)
var previousProfileIndex = 0
profiles = array.size(_volumeProfiles)
if profiles > previousProfileIndex
profile = array.get(_volumeProfiles, previousProfileIndex)// + 1)
endHistoryIndex = bar_index - profile.End
if endHistoryIndex == _reactionLookahead
atrFactorSize = _atr * _reactionAtrFactor
averageReactionSizeBull = (high - profile.ValueAreaHigh) / _reactionLookahead
averageReactionSizeBear = (profile.ValueAreaLow - low) / _reactionLookahead
previousProfile = volumeProfile.new()
previousProfile.Scores := array.new<int>()
if previousProfileIndex > 1
previousProfile := array.get(_volumeProfiles, previousProfileIndex - 1)
reaction = math.max(averageReactionSizeBull, averageReactionSizeBear)
reactionTrendCode = reaction == averageReactionSizeBull ? _scoreMetaDataReactionBullTrend : _scoreMetaDataReactionBearTrend
if reaction > atrFactorSize
and not array.includes(previousProfile.Scores, reactionTrendCode) // same trend on previous profile
updateScore(_reactionScore, previousProfileIndex, "Base reaction", end = false)
array.push(profile.Scores, reactionTrendCode)
previousProfileIndex += 1
setValueAreaVolumeScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_valuAreaVolumeScores)))
values = matrix.new<float>(_lookback, 2, _intMin) // row, volume
for [i, profile] in _volumeProfiles
matrix.set(values, i, 0, i)
matrix.set(values, i, 1, profile.ValueAreaVolume)
sort(values, 1, order.descending)
updateScores(values, toScoreArray(_valuAreaVolumeScores), "VA Volume")
setClosestPriceScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_closestPriceScores)))
values = matrix.new<float>(_lookback, 3, _intMax) // row, poc price to current price ratio, factor
for [i, profile] in _volumeProfiles
matrix.set(values, i, 0, i)
priceDiff = math.abs(close - profile.Poc)
matrix.set(values, i, 1, priceDiff)
if i > (_lookback - 1) * (_closestPriceScorePercentageLimit * 0.01)
matrix.set(values, i, 2, 0)
else
matrix.set(values, i, 2, ((_lookback - 1) - i) / (_lookback - 1))
sort(values, 1, order.ascending)
updateScores(values, toScoreArray(_closestPriceScores), "Closest price", factorIndex = 2)
setValueAreaPartScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_valueAreaPartScores)))
values = matrix.new<float>(_lookback, 2, _intMax) // row, va part
for [i, profile] in _volumeProfiles
valueAreaPart = (profile.ValueAreaHigh - profile.ValueAreaLow) / (profile.High - profile.Low)
matrix.set(values, i, 0, i)
matrix.set(values, i, 1, valueAreaPart)
sort(values, 1, order.ascending)
updateScores(values, toScoreArray(_valueAreaPartScores), "VA part")
setBarsInZoneScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_barsInZoneScores)))
values = matrix.new<float>(_lookback, 2, _intMax) // row, bars
virginPocs = 0 // for summary table
for [i, profile] in _volumeProfiles
if profile.BarsInZone == 0
virginPocs += 1
continue // score given sepparetly
matrix.set(values, i, 0, i)
matrix.set(values, i, 1, profile.BarsInZone)
sort(values, 1, order.ascending)
updateScores(values, toScoreArray(_barsInZoneScores), "Bars in zone", skipZero = false)
matrix.set(_summary, 1, 0, "virgin zones (POCs):")
matrix.set(_summary, 1, 1, str.tostring(virginPocs))
setVirginPocScoreEnd() =>
s = ""
for [i, profile] in _volumeProfiles
if profile.BarsInZone == 0
and i != _lookback - 1
score = _virginPocScore * ((_lookback - 1) - i) / (_lookback - 1) // more weigth on earler profiles
s += str.format("\n{0} {1}", i, score)
updateScore(score, i, "Virgin POC")
setPivotScoreEnd() =>
addToMaxScore(_pivotScore)
toPivots = array.size(_pivots) - 1
jj = 0, previousJj = 0 // skip outside of range pivots
end = false
for [i, profile] in _volumeProfiles
if end
break
for j = jj to toPivots
if j > toPivots
end := true
break // last pivot
pivot = array.get(_pivots, j)
if isInRange(pivot, profile.Start, profile.End)
if j == previousJj // set one score, even if multiple breaks
updateScore(_pivotScore, i, "Base pivot")
jj += 1
continue
else
break // not inside the profile, move on
previousJj := jj
setPriceAwayAndBarsAway() =>
for [i, profile] in _volumeProfiles
if profile.End == bar_index
or profile.IsTouched
continue
if low < profile.MinimumBeforeTouch
profile.MinimumBeforeTouch := low
if high > profile.MaximumBeforeTouch
profile.MaximumBeforeTouch := high
zoneWidth = profile.ValueAreaHigh - profile.ValueAreaLow
priceAwayWidth = profile.MinimumBeforeTouch < profile.ValueAreaLow ? profile.ValueAreaLow - profile.MinimumBeforeTouch : profile.MaximumBeforeTouch - profile.ValueAreaHigh
riskRewardRatio = priceAwayWidth / zoneWidth
profile.PriceAwayUntilFirstTouch := riskRewardRatio
profile.BarsAwayUntilFirstTouch := bar_index - profile.End
if bar_index < profile.End + _priceAwayScoreMargin
continue
[highTouch, lowTouch, barBreaksTouch] = getVolumeProfileTouches(profile)
if highTouch
or lowTouch
or barBreaksTouch
profile.IsTouched := true
setPriceAwayScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_priceAwayScores)))
values = matrix.new<float>(_lookback, 2, _intMin) // row, price away
for [i, profile] in _volumeProfiles
if profile.PriceAwayUntilFirstTouch < 0
continue
matrix.set(values, i, 0, i)
matrix.set(values, i, 1, profile.PriceAwayUntilFirstTouch)
sort(values, 1, order.descending)
updateScores(values, toScoreArray(_priceAwayScores), "Price away")
setBarsAwayScoreEnd() =>
addToMaxScore(array.max(toScoreArray(_barsAwayScores)))
values = matrix.new<float>(_lookback, 2, _intMin) // row, bars away
for [i, profile] in _volumeProfiles
if na(profile.BarsAwayUntilFirstTouch)
continue
matrix.set(values, i, 0, i)
matrix.set(values, i, 1, profile.BarsAwayUntilFirstTouch)
sort(values, 1, order.descending)
updateScores(values, toScoreArray(_barsAwayScores), "Bars away")//, scoreIndex = 1)
setScores() =>
setBarsInZone()
setPriceAwayAndBarsAway()
// odd enhancers:
setZoneReactionScore()
setEndScores() =>
// odd enhancers:
setVirginPocScoreEnd()
setBarsInZoneScoreEnd()
setValueAreaPartScoreEnd()
setValueAreaVolumeScoreEnd()
setClosestPriceScoreEnd()
setPivotScoreEnd()
setPriceAwayScoreEnd()
setBarsAwayScoreEnd()
setTotalScores() =>
for i = 0 to matrix.rows(_scores) - 1
matrix.set(_scores, i, 0, i)
score = matrix.get(_scores, i, 1)
scoreEnd = matrix.get(_scores, i, 2)
matrix.set(_scores, i, 2, 0) // reset end scores
totalScore = score + scoreEnd
matrix.set(_scores, i, 3, totalScore)
sortScoresByScore() =>
sort(_scores, 3, order.descending)
standardDeviation = array.stdev(matrix.col(_scores, 0))
matrix.set(_summary, 2, 0, "score std dev %:")
matrix.set(_summary, 2, 1, str.format("{0,number,##.#}%", (standardDeviation / _scoreMetaData.Max) * 100))
validateAlert(alert) =>
if alert
and _lastRangeBarIndex == -1
runtime.error("At the moment alerts can only be set if 'Last range bar index' is set (this is due to var/varip and unknown pine history error).")
validateActive(active) =>
if active
and bar_index == 0
runtime.error("Is active at bar 0, probably not enough data available (choose shorter lookback, narrower range or view at a higher timeframe)")
showPivots(isLow, barIndex, price) =>
var float previousPivotPrice = na
var int previousPivotBarIndex = na
if isLow
label.new(barIndex, price, "▼", style = label.style_label_up, color = color.new(color.red, 70))
if not na(previousPivotBarIndex)
line.new(previousPivotBarIndex, previousPivotPrice, barIndex, price, color = color.new(color.orange, 80), style = line.style_dashed)
previousPivotBarIndex := barIndex
previousPivotPrice := price
else
label.new(barIndex, price, "▲", color = color.new(color.green, 70))
if not na(previousPivotBarIndex)
line.new(previousPivotBarIndex, previousPivotPrice, barIndex, price, color = color.new(color.green, 80), style = line.style_dashed)
previousPivotBarIndex := barIndex
previousPivotPrice := price
setPivots(active) =>
pivotLow = ta.pivotlow(low, _pivotBars, _pivotBars)
pivotHigh = ta.pivothigh(high, _pivotBars, _pivotBars)
if active
var int firstActiveBarIndex = na
if na(firstActiveBarIndex)
firstActiveBarIndex := bar_index
pivotBarIndex = bar_index - _pivotBars
if (not na(pivotHigh) or not na(pivotLow))
and pivotBarIndex >= firstActiveBarIndex
if _showPivots
lowPivot = not na(pivotLow)
price = not na(pivotLow) ? low[bar_index - pivotBarIndex] : high[bar_index - pivotBarIndex]
showPivots(lowPivot, pivotBarIndex, price)
array.push(_pivots, pivotBarIndex)
setVolumeProfileScores() =>
for [profileIndex, profile] in _volumeProfiles
for [scoreIndex, score] in _scores
row = math.round(array.get(score, 0))
if row == profileIndex
profile.Score := matrix.get(_scores, scoreIndex, 3)
break
getTrendString(bullBarIndex, bearBarIndex) =>
string trendString = na, string trend = na
delayString = _alertDelay != 0 ? str.format(", {0} bars delay", _alertDelay) : ""
if bullBarIndex == bar_index - _alertDelay
trendString := str.format("(from bull trend{0})", delayString)
trend := "Bull"
else if bearBarIndex == bar_index - _alertDelay
trendString := str.format("(from bear trend{0})", delayString)
trend := "Bear"
[trend, trendString]
_alertTexts = array.new<string>()
addAlert(type, latestBullRetestConfifmation, latestBearRetestConfifmation, profile, string extraText = "") =>
if type == _alertOn
or _alertOn == "All"
[trend, trendText] = getTrendString(latestBullRetestConfifmation, latestBearRetestConfifmation)
if _alertDirection == trend
or _alertDirection == "All"
txt = str.format("{0} {1}{2} (zone from {3} {4} to {5} {6}, between {7} and {8})", type, trendText, extraText == "" ? "" : str.format(" {0}", extraText), unixTimeToString(profile.StartTime), syminfo.timezone, unixTimeToString(profile.EndTime), syminfo.timezone, str.tostring(profile.ValueAreaLow), str.tostring(profile.ValueAreaHigh))
array.push(_alertTexts, txt)
sendAlert() =>
alerts = array.size(_alertTexts)
if alerts > 0
string alertText = na
for [i, txt] in _alertTexts
if i == 0
alertText := txt
else
alertText += "\n" + txt
switch _alertFrequency
"All" =>
alert(alertText, alert.freq_all)
"Once per bar" =>
alert(alertText, alert.freq_once_per_bar)
"Once per bar close" =>
alert(alertText, alert.freq_once_per_bar_close)
alertIfInZone() =>
for profile in _alertVolumeProfiles
if profile.LatestBullTouchConfirmationBarIndex == bar_index - _alertDelay
or profile.LatestBearTouchConfirmationBarIndex == bar_index - _alertDelay
addAlert("Entry/crossing", profile.LatestBullTouchConfirmationBarIndex, profile.LatestBearTouchConfirmationBarIndex, profile)
alertIfRetest() =>
for profile in _alertVolumeProfiles
if profile.LatestBullRetestConfirmationBarIndex == bar_index - _alertDelay
or profile.LatestBearRetestConfirmationBarIndex == bar_index - _alertDelay
retests = array.size(profile.Retests)
retest = array.get(profile.Retests, retests - 1)
addAlert("Retest", profile.LatestBullRetestConfirmationBarIndex, profile.LatestBearRetestConfirmationBarIndex, profile, str.format("({0} bars)", retest.Length))
alertIfBreakout() =>
for profile in _alertVolumeProfiles
if profile.LatestBullBreakoutConfirmationBarIndex == bar_index - _alertDelay
or profile.LatestBearBreakoutConfirmationBarIndex == bar_index - _alertDelay
breakouts = array.size(profile.Breakouts)
breakout = array.get(profile.Breakouts, breakouts - 1)
addAlert("Breakout", profile.LatestBullBreakoutConfirmationBarIndex, profile.LatestBearBreakoutConfirmationBarIndex, profile, str.format("({0} bars)", breakout.Length))
alertIfBreakoutAndX(profile, latestBullRetestConfifmation, latestBearRetestConfifmation, retestIndices, string source = na) =>
if latestBullRetestConfifmation == bar_index - _alertDelay
or latestBearRetestConfifmation == bar_index - _alertDelay // alert only on retest and not on every bar after
latestRetestIndex = array.size(retestIndices) - 1
if latestRetestIndex >= 0 // check has done retest
latestBreakIndex = array.size(profile.BreakoutIndices) - 1
if latestBreakIndex >= 0 // check has broken
latestRetestBarIndex = array.get(retestIndices, latestRetestIndex)
latestBreakoutBarIndex = array.get(profile.BreakoutIndices, latestBreakIndex)
if latestRetestBarIndex > latestBreakoutBarIndex
string retestString = na, retests = 1
if latestRetestIndex != 0
for i = latestRetestIndex - 1 to 0
retest = array.get(retestIndices, i)
if retest > latestBreakoutBarIndex
retests += 1
else
break
if retests == 1
retestString := str.format("({0}) ({1} bars from break)", source, latestRetestBarIndex - latestBreakoutBarIndex)
else
firstRetestBarIndex = array.get(profile.RetestIndices, 0)
retestString := str.format("({0}) ({1} {2}s within {3} bars, {4} bars from break)", source, retests, source, latestRetestBarIndex - firstRetestBarIndex, latestRetestBarIndex - latestBreakoutBarIndex, latestBreakoutBarIndex)
addAlert("Breakout and retest", latestBearRetestConfifmation, latestBullRetestConfifmation, profile, retestString) // reverse the latest retest/false break because the break is the trend
alertIfBreakoutAndRetest() =>
for profile in _alertVolumeProfiles
alertIfBreakoutAndX(profile, profile.LatestBullRetestConfirmationBarIndex, profile.LatestBearRetestConfirmationBarIndex, profile.RetestIndices, "Retest")
alertIfBreakoutAndX(profile, profile.LatestBullFalseBreakoutConfirmationBarIndex, profile.LatestBearFalseBreakoutConfirmationBarIndex, profile.FalseBreakoutIndices, "false breakout")
alertIfFalseBreakout() =>
for profile in _alertVolumeProfiles
if profile.LatestBullFalseBreakoutConfirmationBarIndex == bar_index - _alertDelay
or profile.LatestBearFalseBreakoutConfirmationBarIndex == bar_index - _alertDelay
falseBreakouts = array.size(profile.FalseBreakouts)
falseBreakout = array.get(profile.FalseBreakouts, falseBreakouts - 1)
addAlert("False breakout", profile.LatestBullFalseBreakoutConfirmationBarIndex, profile.LatestBearFalseBreakoutConfirmationBarIndex, profile, str.format("({0} bars)", falseBreakout.Length))
setAlerts() =>
switch _alertOn
"Entry/crossing" =>
alertIfInZone()
"Retest" =>
alertIfRetest()
"Breakout" =>
alertIfBreakout()
"Breakout and retest" =>
alertIfBreakoutAndRetest()
"False breakouts" =>
alertIfFalseBreakout()
"All" =>
alertIfInZone()
alertIfRetest()
alertIfBreakout()
alertIfBreakoutAndRetest()
alertIfFalseBreakout()
setAlertZones() =>
zones = array.size(_alertVolumeProfiles)
if zones == 0
for profile in _zones
array.push(_alertVolumeProfiles, profile)
GetIndicatorBackground(active, alert) =>
color background = na
if alert
if active
background := color.new(color.red, 90)
else if _visualizeRange
and active
background := color.new(color.green, 90)
background
showPastZonesTouchLabels() =>
for profile in _zones
zoneTouchLabels(profile, bar_index)
clearScoresGiven() =>
for profile in _volumeProfiles
array.clear(profile.ScoresGiven)
showScore() =>
profiles = array.size(_volumeProfiles)
for [i, score] in _scores
if i == profiles
break
scoreRow = math.round(array.get(score, 0))
profile = array.get(_volumeProfiles, scoreRow)
previousProfileString = i > 0 ? str.format("{0,number,#.#}%>", (-(profile.Score - matrix.get(_scores, i - 1, 3)) / profile.Score) * 100) : ""
nextProfileString = i < profiles - 1 ? str.format(">{0,number,#.#}%", (1 - (matrix.get(_scores, i + 1, 3) / profile.Score)) * 100) : ""
box.set_text(profile.AreaBox, str.format("{0}\n{1}{2,number,#.#}{3}", i + 1, previousProfileString, profile.Score, nextProfileString))
rangeBar = request.security(syminfo.tickerid, _timeFrame, isActive(_lastRangeBarIndex, _lastRangeBarIndexFromEnd), lookahead = barmerge.lookahead_on)
alert = _alertOn != "None"
alertAndLastBar = alert
and barstate.islast
incomplete = rangeBar.LastActiveBarTimeClose != _maxUnixTime
and rangeBar.LastActiveBarTimeClose > _timeNow
and time != rangeBar.StartTime // only one bar, don't draw profile
active = rangeBar.Active
previousActive = active[1]
previousTimeClose = time_close[1]
validateAlert(alert)
if incomplete
and not alertAndLastBar[1]
removeLatestProfileIfIncomplete()
setPivots(active)
[bullVolumes, bearVolumes, lowPrices, highPrices, openTimes] = request.security_lower_tf(syminfo.tickerid, _barVolumeProfileTimeFrame, getData(active))
if rangeBar.Active
and not alertAndLastBar[1]
validateActive(active)
setInterval()
setVolumeProfileData(active, bullVolumes, bearVolumes, lowPrices, highPrices, openTimes)
m = getVolumeProfileMatrix(active, previousActive, previousTimeClose, incomplete)
metaData = getMetaData(m)
volumeProfile(m, metaData, incomplete)
volumeProfiles = getVolumeProfiles()
setBreaks(volumeProfiles)
setRetests(volumeProfiles)
setFalseBreaks(volumeProfiles)
setTouches(volumeProfiles)
if not _singleZone
and not alertAndLastBar[1]
setScores()
var done = false
if barstate.islast
and not (done and alert)
if not (_singleZone or _singleLookback)
setEndScores()
setTotalScores()
sortScoresByScore()
setVolumeProfileScores()
clearZones()
drawZones()
if _showVolumeProfileInfoLabel
updateVolumeProfileInfoLabels()
if not (_singleZone or _singleLookback)
clearScoresGiven()
if _showSummary
summaryTable()
if _showScore
showScore()
done := true
if alertAndLastBar
setAlertZones()
setAlerts()
sendAlert()
if _showZoneTouchLabel
and rangeBar.HasBeenActive
and not alertAndLastBar[1]
showPastZonesTouchLabels()
bgcolor(GetIndicatorBackground(active, alert)) |
Multi-Polar World | https://www.tradingview.com/script/EX8Kw2Do-Multi-Polar-World/ | EsIstTurnt | https://www.tradingview.com/u/EsIstTurnt/ | 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/
// © EsIstTurnt
//@version=5
indicator("Multi-Polar World")
string1=input.string("ED",'Statistic 1',options=['GDP','GDPPC','GD','ED','M0','M1','M2','EXP','IMP','GRES','EMP',
'ME','POP','BOT','CBBS','CPI','INTR','BLR','OE','DPI','PS','CS'],group='Statistic')
Combine=input.bool(false,'Enable (Breaks w/ Some Combinations)' ,group='Combine Values')
Average=input.bool(false,'Combine via Average instead of Addition',group='Combine Values')
calc=input.bool(false,title='Enable Custom Formuala Calculation' ,group='Custom Formulas')
string2=input.string("POP",'Statistic 2 (Enable "Custom Formula Calculation" Below)',
options=['GDP','GDPPC','GD','ED','M0','M1','M2','EXP','IMP','GRES','EMP',
'ME','POP','BOT','CBBS','CPI','INTR','BLR','OE','DPI','PS','CS'],group='Statistic')
math=input.string("/",'Math Operation' ,options=['+','-','*','/'],group='Custom Formulas')
West=input.bool(true,'Show West' ,group='Plot')
Rest=input.bool(true,'Show BRICSS' ,group='Plot')
Custom=input.bool(false,'Show User Selected Group of Countries' ,group='Plot')
C1=input.string("",' Country #1of Custom Group ' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
C2=input.string("",' Country #2 of Custom Group' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
C3=input.string("",' Country #3 of Custom Group' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
C4=input.string("",' Country #4 of Custom Group' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
C5=input.string("",' Country #5 of Custom Group' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
C6=input.string("",' Country #6 of Custom Group' ,group='User Selected Group',tooltip='2 Character Prefix Used by TradingView, example="CA","US","EU" etc.')
var string Brazil =calc? "BR"+string1+math+"BR"+string2:"BR"+string1
var string Russia =calc? "RU"+string1+math+"RU"+string2:"RU"+string1
var string India =calc? "IN"+string1+math+"IN"+string2:"IN"+string1
var string China =calc? "CN"+string1+math+"CN"+string2:"CN"+string1
var string SouthAfrica =calc? "ZA"+string1+math+"ZA"+string2:"ZA"+string1
var string SaudiArabia =calc? "SA"+string1+math+"SA"+string2:"SA"+string1
var string Australia =calc? "AU"+string1+math+"AU"+string2:"AU"+string1
var string Canada =calc? "CA"+string1+math+"CA"+string2:"CA"+string1
var string NewZealand =calc? "NZ"+string1+math+"NZ"+string2:"NZ"+string1
var string Britain =calc? "GB"+string1+math+"GB"+string2:"GB"+string1
var string UnitedStates =calc? "US"+string1+math+"US"+string2:"US"+string1
var string EuropeanUnion=calc? "EU"+string1+math+"EU"+string2:"EU"+string1
var string Custom1=calc? C1+string1+math+C1+string2:C1+string1
var string Custom2=calc? C2+string1+math+C2+string2:C2+string1
var string Custom3=calc? C3+string1+math+C3+string2:C3+string1
var string Custom4=calc? C4+string1+math+C4+string2:C4+string1
var string Custom5=calc? C5+string1+math+C5+string2:C5+string1
var string Custom6=calc? C6+string1+math+C6+string2:C6+string1
//BRICSS
BR=request.security(Brazil ,timeframe.period,close,ignore_invalid_symbol = true)
RU=request.security(Russia ,timeframe.period,close,ignore_invalid_symbol = true)
IN=request.security(India ,timeframe.period,close,ignore_invalid_symbol = true)
CN=request.security(China ,timeframe.period,close,ignore_invalid_symbol = true)
ZA=request.security(SouthAfrica ,timeframe.period,close,ignore_invalid_symbol = true)
SA=request.security(SaudiArabia ,timeframe.period,close,ignore_invalid_symbol = true)
BRICSS=Average?math.avg(BR,RU,IN,CN,ZA,SA):BR+RU+IN+CN+ZA+SA
//West
AU=request.security(Australia ,timeframe.period,close,ignore_invalid_symbol = true)
CA=request.security(Canada ,timeframe.period,close,ignore_invalid_symbol = true)
NZ=request.security(NewZealand ,timeframe.period,close,ignore_invalid_symbol = true)
GB=request.security(Britain ,timeframe.period,close,ignore_invalid_symbol = true)
US=request.security(UnitedStates ,timeframe.period,close,ignore_invalid_symbol = true)
EU=request.security(EuropeanUnion,timeframe.period,close,ignore_invalid_symbol = true)
WEST=Average?math.avg(AU,CA,NZ,GB,US,EU):AU+CA+NZ+GB+US+EU
//Custom
cSym1=Custom?request.security(Custom1,timeframe.period,close, ignore_invalid_symbol = true):na
cSym2=Custom?request.security(Custom2,timeframe.period,close, ignore_invalid_symbol = true):na
cSym3=Custom?request.security(Custom3,timeframe.period,close, ignore_invalid_symbol = true):na
cSym4=Custom?request.security(Custom4,timeframe.period,close, ignore_invalid_symbol = true):na
cSym5=Custom?request.security(Custom5,timeframe.period,close, ignore_invalid_symbol = true):na
cSym6=Custom?request.security(Custom6,timeframe.period,close, ignore_invalid_symbol = true):na
CustomAvg=Average?math.avg(cSym1,cSym2,cSym3,cSym4,cSym5,cSym6):cSym1+cSym2+cSym3+cSym4+cSym5+cSym6
transpW=input.int(0,'WEST Plot Transparency' ,group='Appearance')
transpB=input.int(0,'BRICSS Plot Transparency' ,group='Appearance')
transpC=input.int(0,'User Selected Group Plot Transparency' ,group='Appearance')
plot(Combine?BRICSS:na,title='BRICSS' ,color=color.new(input.color(#ff0a0a ,'BRICSS' ,group='Appearance'),transpB))
plot(Combine?na:Rest?BR:na,title='BR' ,color=color.new(input.color(#ee0038 ,'BRAZIL' ,group='Appearance'),transpB))
plot(Combine?na:Rest?RU:na,title='RU' ,color=color.new(input.color(#d40051 ,'RUSSIA' ,group='Appearance'),transpB))
plot(Combine?na:Rest?IN:na,title='IN' ,color=color.new(input.color(#b20062 ,'INDIA ' ,group='Appearance'),transpB))
plot(Combine?na:Rest?CN:na,title='CN' ,color=color.new(input.color(#8d1b68 ,'CHINA ' ,group='Appearance'),transpB))
plot(Combine?na:Rest?ZA:na,title='ZA' ,color=color.new(input.color(#672765 ,'SOUTH AFRICA' ,group='Appearance'),transpB))
plot(Combine?na:Rest?SA:na,title='SA' ,color=color.new(input.color(#452a58 ,'SAUDI ARABIA' ,group='Appearance'),transpB))
plot(Combine?WEST:na ,title='WEST' ,color=color.new(input.color(#01bd1b ,'WEST ' ,group='Appearance'),transpW))
plot(Combine?na:West?AU:na,title='AU' ,color=color.new(input.color(#00b766 ,'AUSTRALIA' ,group='Appearance'),transpW))
plot(Combine?na:West?CA:na,title='CA' ,color=color.new(input.color(#00adad ,'CANADA' ,group='Appearance'),transpW))
plot(Combine?na:West?NZ:na,title='NZ' ,color=color.new(input.color(#00a0f0 ,'NEW ZEALAND' ,group='Appearance'),transpW))
plot(Combine?na:West?GB:na,title='GB' ,color=color.new(input.color(#008eff ,'GREAT BRITAIN' ,group='Appearance'),transpW))
plot(Combine?na:West?US:na,title='US' ,color=color.new(input.color(#0072ff ,'UNITED STATES' ,group='Appearance'),transpW))
plot(Combine?na:West?EU:na,title='EU' ,color=color.new(input.color(#0d3bff ,'EUROPEAN UNION',group='Appearance'),transpW))
plot(Custom?Combine?CustomAvg:na:na,'Custom Alliance',color=color.new(input.color(#ee6600,'Color for User Selected Group',group='Appearance'),transpC))
plot(Combine?na:Custom?cSym1:na ,'1' ,color=color.new(input.color(#c33600,'Color for User Selection #1' ,group='Appearance'),transpC))
plot(Combine?na:Custom?cSym2:na ,'2' ,color=color.new(input.color(#a94400,'Color for User Selection #2' ,group='Appearance'),transpC))
plot(Combine?na:Custom?cSym3:na ,'3' ,color=color.new(input.color(#914b00,'Color for User Selection #3' ,group='Appearance'),transpC))
plot(Combine?na:Custom?cSym4:na ,'4' ,color=color.new(input.color(#7b4e0c,'Color for User Selection #4' ,group='Appearance'),transpC))
plot(Combine?na:Custom?cSym5:na ,'5' ,color=color.new(input.color(#684e1c,'Color for User Selection #5' ,group='Appearance'),transpC))
plot(Combine?na:Custom?cSym6:na ,'6' ,color=color.new(input.color(#584b2a,'Color for User Selection #6' ,group='Appearance'),transpC))
|
Delox EMA Cross | https://www.tradingview.com/script/n8tEecJ3/ | Cryptoleal | https://www.tradingview.com/u/Cryptoleal/ | 36 | 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/
// © Cryptoleal
//@version=5
indicator("Delox EMA Cross", overlay= true)
EmasGrup = 'EmasGrup'
showBarwhite = input.bool (true, 'Show Bar White', group=EmasGrup)
EmaFast= input.int(14, title="Ema Fast", minval=1, group=EmasGrup)
EmaSlow= input.int(21, title="Ema Slow", minval=1, group=EmasGrup)
stochasticGrup = 'Stochastic Grup'
periodK = input.int(14, title="%K Length", minval=1, group=stochasticGrup)
smoothK = input.int(1, title="%K Smoothing", minval=1, group=stochasticGrup)
periodD = input.int(3, title="%D Smoothing", minval=1, group=stochasticGrup)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
///// Emas
Ema14 = ta.sma(close,EmaFast)
Ema21 = ta.sma(close,EmaSlow)
h0=plot(Ema14, title = "Ema Fast 14", color = Ema14>Ema21 ? color.green : color.red)
h1=plot(Ema21, title = "Ema Slow 21", color = Ema14>Ema21 ? color.green : color.red)
LongCross= ta.crossover(Ema14,Ema21)
DownCross= ta.crossunder(Ema14,Ema21)
WhiteBar= ta.cross(Ema14,Ema21)
barcolor(WhiteBar and showBarwhite? color.rgb(255, 255, 255) : na)
fill(h0, h1, color = Ema14>Ema21 ? color.rgb(76, 175, 79, 32) : color.rgb(255, 82, 82, 36))
// Table Props
gr50 = 'Table'
showTable = input.bool (true, 'Showtable', group=gr50)
tabPosI_ = input.string('Top', 'Table Position', ['Top', 'Middle', 'Bot'], group=gr50)
tabPos_ = tabPosI_=='Top'? position.top_right : tabPosI_=='Bot'? position.bottom_right : position.middle_right
tabColor = input.color(color.black , 'Background', group=gr50)
TrendColor = input.color(color.rgb(165, 21, 178), 'backgroundBollcolor', group=gr50)
stochasticBluecolor = input.color(color.rgb(1, 132, 203, 21), 'backgroundBollcolor', group=gr50)
stochasticOrangecolor = input.color(color.rgb(240, 123, 5, 20), 'backgroundBollcolor', group=gr50)
borderCol = input.color(color.black , 'Border', group=gr50)
tabTextCol = input.color(color.white, 'tabTextColor', group=gr50)
trendtext = 'Hi Error '
if Ema21<Ema14
TrendColor:= color.rgb(4, 255, 54, 44)
trendtext:= 'Upward trend 🎉🦾📈'
else if Ema21>Ema14
TrendColor:= color.rgb(252, 5, 5, 46)
trendtext:= 'Downward trend 🪂📉'
/////// Table plot
saTable = table.new(tabPos_, 10, 10, tabColor, borderCol, 1, borderCol, 1)
if showTable
table.cell(saTable, 0, 0, 'Ema 14: ' +str.tostring(Ema14) , text_color=tabTextCol, text_size=size.small,bgcolor= TrendColor)
table.cell(saTable, 0, 1, 'Ema 21 ' + str.tostring(Ema21) , text_color=tabTextCol, text_size=size.small,bgcolor= TrendColor)
table.cell(saTable, 0, 3, trendtext , text_color=tabTextCol, text_size=size.small,bgcolor= TrendColor)
table.cell(saTable, 0, 4, 'Stochastic K Blue :'+ str.tostring(k) , text_color=tabTextCol, text_size=size.small,bgcolor= stochasticBluecolor)
table.cell(saTable, 0, 5, 'Stochastic D Orange :' + str.tostring(d), text_color=tabTextCol, text_size=size.small,bgcolor= stochasticOrangecolor)
bgcolor(LongCross and d< 40? color.rgb(0, 230, 46, 41) :na)
bgcolor(DownCross and d> 60? color.rgb(255, 0, 0, 45) :na)
alertcondition(LongCross and d< 40, title='Buy Alert', message='Buy Alert')
alertcondition(DownCross and d> 60, title='Sell Alert', message='Sell Alert')
alertcondition(WhiteBar, title='White Bar', message='White Bar')
|
Band Pass Normalized Suite (BPNS) | https://www.tradingview.com/script/cTo6TTUA-Band-Pass-Normalized-Suite-BPNS/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("BPNS", explicit_plot_zorder = true)
bes(float source = close, float alpha = 0.7) =>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
sma(source, length) =>
// Initialize the moving average to the first element of the source
float average = source[0]
// Initialize the count to 1
int count = 1
// Calculate the moving average using the Welford method
for i = 1 to length
count := count + 1
delta = source[i] - average
average := average + delta / count
// Return the moving average
average
ssmma(src, len, smooth)=>
smma = 0.0
avg = sma(src, len)
smma := na(smma[1]) ? avg : bes((smma[1] * (len - 1) + src) / len, smooth)
smma(src, len)=>
smma = 0.0
avg = sma(src, len)
smma := na(smma[1]) ? avg : (smma[1] * (len - 1) + src) / len
ema(src, len, smoothing, a) => //{
alpha = a / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * bes(src, smoothing) + (1 - alpha) * nz(bes(sum[1], smoothing))
dema(src, length, smooth, a)=>
e1 = ema(src, length, smooth, a)
e2 = ema(e1, length, smooth, a)
dema = 2 * e1 - e2
tema(src, length, smooth, a) =>
e1 = ema(src, length, smooth, a)
e2 = ema(e1, length, smooth, a)
e3 = ema(e2, length, smooth, a)
tema = 3 * (e1 - e2) + e3
wma(src, len) =>
ta.wma(src, len)
//// dont look for too long...
hma(src, len)=>
wma(2 * wma(src, int(len/2)) - wma(src, len), int(math.sqrt(len/2)))
thma(src, len) =>
wma1 = wma(src, len)
wma2 = wma(src, int(len/2))
wma3 = 2 * wma2 - wma1
hma = wma(wma3, int(math.sqrt(len/2)))
3 * (wma1 - wma2) + hma
ehma(src, len, smoothing, a)=>
ema(2 * ema(src, int(len/2), smoothing, a) - ema(src, len, smoothing, a), int(math.sqrt(len/2)), smoothing, a)
gma(values, length) =>
// Define the standard deviation of the Gaussian distribution
stddev = length / 4
// Generate an array of indices from 1 to length
indices = ta.range(1, length)
// Calculate the Gaussian weights for each value in the array
weights = math.exp(-0.5 * (math.pow((indices - length), 2) / math.pow(stddev, 2)))
// Calculate the weighted sum of the values
sum = math.sum(values * weights, length)
// Return the moving average
sum / math.sum(weights, length)
rms(source, length)=>
math.sqrt(math.sum(math.pow(source, 2), length)/length)
max(source, outlier_level, dev_lookback)=>
var float max = na
src = array.new<float>()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : -1.7976931348623157e+308)
max := math.max(nz(max[1]), array.get(src, 0))
min(source, outlier_level, dev_lookback) =>
var float min = na
src = array.new<float>()
stdev = math.abs((source - bes(source, 0.1))/ta.stdev(source, dev_lookback))
array.push(src, stdev < outlier_level ? source : 1.7976931348623157e+308)
min := math.min(nz(min[1]), array.get(src, 0))
min_max(src, outlier_level, dev_lookback) =>
(src - min(src, outlier_level, dev_lookback))/(max(src, outlier_level, dev_lookback) - min(src, outlier_level, dev_lookback)) * 100
source = input.source(close, "Source", group = "Source")
moving = input.string("BES", "MA Style", ["BES","SSMMA","SMMA","SMA","RMS","EMA","DEMA","TEMA","WMA","HMA","EHMA","THMA","GMA"], group = "Source")
blur = input.float(1, "Global Smoothing", 0.005, 1, 0.005, group = "Source")
bound = input.float(70, "Bounds", 50, 100, group = "Source")
lf_brown = input.float(0.15, "BES Low Pass Filter Cutoff", 0.001, 1, 0.001, tooltip = "Adjusts BES", group = "Browns")
hf_brown = input.float(0.01, "BES High Pass Filter Cutoff", 0.001, 1, 0.001, tooltip = "Adjusts BES", group = "Browns")
lf_len = input.int(200, "Low Pass Filter Length", 1, tooltip = "Inputs for the MA's.", group = "MA")
hf_len = input.int(12, "High Pass Filter Length", 1, tooltip = "Inputs for the MA's.", group = "MA")
lf_alpha = input.float(2, "Low Pass Filter Alpha", 0.05, 10, 0.05, tooltip = "Inputs for the MA's.", group = "MA")
hf_alpha = input.float(2, "High Pass Filter Alpha", 0.05, 10, 0.05, tooltip = "Inputs for the MA's.", group = "MA")
lf_smooth = input.float(0.7, "Low Pass Filter Smoothing", 0.005, 1, 0.005, tooltip = "Inputs for the MA's.", group = "MA")
hf_smooth = input.float(0.7, "High Pass Filter Smoothing", 0.005, 1, 0.005, tooltip = "Inputs for the MA's.", group = "MA")
outlier_level = input.float(2, "Outlier Level", 0.01, 100, 0.01, group = "Outlier Detection")
dev_lookback = input.int(30, "Outlier Length", 2, group = "Outlier Detection")
enable = input.bool(false, "Enable Global Mean", group = "Mean")
mean = input.string("BES", "MA Style", ["BES","SSMMA","SMMA","SMA","RMS","EMA","DEMA","TEMA","WMA","HMA","EHMA","THMA","GMA"], group = "Mean")
mean_brn = input.float(0.01, "Global Smoothing Browns Alpha", group = "Mean")
mean_len = input.int(14, "Global Smoothing MA Length", group = "Mean")
mean_alp = input.float(2, "Low Pass Filter Alpha", 0.05, 10, 0.05, group = "Mean")
mean_smo = input.float(0.7, "Low Pass Filter Smoothing", 0.005, 1, 0.005), group = "Mean"
ma(src, len, smooth, alpha, brown, moving)=>
switch moving
"BES" => bes(src, brown)
"SSMMA" => ssmma(src, len, smooth)
"SMMA" => smma(src, len)
"SMA" => sma(src, len)
"RMS" => rms(src, len)
"EMA" => ema(src, len, smooth, alpha)
"DEMA" => dema(src, len, smooth, alpha)
"TEMA" => tema(src, len, smooth, alpha)
"WMA" => wma(src, len)
"HMA" => hma(src, len)
"EHMA" => ehma(src, len, smooth, alpha)
"THMA" => thma(src, len)
"GMA" => gma(src, len)
"RMS" => rms(src, len)
band_pass = bes(min_max(ma(source - ma(source, hf_len, hf_smooth, hf_alpha, hf_brown, moving), lf_len, lf_smooth, lf_alpha, lf_brown, moving), outlier_level, dev_lookback), blur)
g_mean = ma(band_pass, mean_len, mean_smo, mean_alp, mean_brn, mean)
plot(band_pass > 100 ? 100 : band_pass < 0 ? 0 : band_pass, "Band Pass", color.blue)
plot(enable ? g_mean : na, "Global Mean", color.orange)
_100 = hline(bound, "Upper Bound", linestyle = hline.style_solid)
_50 = hline(50, "50", color.new(color.gray, 50))
_0 = hline(100 - bound, "Lower Bound", linestyle = hline.style_solid)
fill(_100, _0, color.new(color.navy, 90)) |
Quarterly Revenue Label | https://www.tradingview.com/script/J3aGpgpl-Quarterly-Revenue-Label/ | Deriko_ | https://www.tradingview.com/u/Deriko_/ | 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/
// © Deriko_
//@version=5
indicator("Quarterly Revenue", overlay=true)//, scale=scale.left))
//-------------------------//
//-----USER INPUTS---------//
//-------------------------//
p_arrowColor = input(color.black, title='Shape Color', inline="2")
p_TextColor = input(color.new(color.white,0), title='Revenue Text Color', inline="3")
p_Textsize = input.string("default", title="Label Size", inline="4",options=["very small", "small", "default", "large", "very large"])
p_Shapes = input.string("triangleup", title="Shape dDefault", inline="4",options=["xcross", "cross", "triangleup", "triangledown","flag","square","diamond"])
p_posShapeColor= input(color.rgb(91, 209, 203), title='Positive Text Color' ,inline="5")
p_negShapeColor= input(color.rgb(245, 110, 110), title='Negative Text Color' , inline="6")
labelSizeOption = switch p_Textsize
"very small" => size.tiny
"small" => size.small
"default" => size.normal
"large" => size.large
"very large" => size.huge
labelShapeOption = switch p_Shapes
"xcross" => label.style_xcross
"cross" => label.style_cross
"triangleup" => label.style_triangleup //default
"triangledown" => label.style_triangledown
"flag" => label.style_flag
"circle" => label.style_circle
//"arrowup" => label.style_arrowup
//"arrowdown" => label.style_arrowdown
"square" => label.style_square
"diamond" => label.style_diamond
// Financial Data
TotREV = request.financial(syminfo.tickerid,'TOTAL_REVENUE','FQ', ignore_invalid_symbol=true)
EPS = request.earnings(syminfo.tickerid, earnings.actual, ignore_invalid_symbol=true)
//------------------------//
//---------REVENUE--------//
//------------------------//
revenueBarsNumber = ta.barssince(TotREV != TotREV[1]) == 0
revenue = TotREV
prevRev = ta.valuewhen(revenueBarsNumber, TotREV, 1)
//plotchar(revenue, "revenue", "", location = location.top)
// Revenue QoQ
RevenueChangeQoQ = (revenue -prevRev) /math.abs(prevRev) *100
//plotchar(revenue, "revenue", "", location = location.top)
//plotchar(revenue1, "revenue1", "", location = location.top)
//bars since the last change
vChangedetected = ta.barssince(EPS != EPS[1]) == 0
// value since change
revValue = ta.valuewhen(vChangedetected, TotREV, 0)
//plotchar(vChangedetected, "salesValue", "", location = location.top)
textHeader = 'Revenue '
textRevenueChanged = RevenueChangeQoQ > 999 ? '\n+999%':RevenueChangeQoQ > 0 ? '\n+' + str.tostring(RevenueChangeQoQ, '0') + '%':'\n' + str.tostring(RevenueChangeQoQ, '0') + '%'
textTotals = revValue > 999999999 ? str.tostring(revValue/1000000000,'0.00B') :str.tostring(revValue/1000000,'0.00M')
//--------------------//
//----PLOT VALUES-----//
//--------------------//
if(vChangedetected)
label1 = label.new(bar_index, bar_index, xloc=xloc.bar_index, yloc=yloc.belowbar, text=textHeader, style=labelShapeOption, color=color.new(color.aqua,100), textcolor=p_TextColor, size=labelSizeOption)
if(vChangedetected)
label2 = label.new(bar_index, bar_index, xloc=xloc.bar_index, yloc=yloc.belowbar, text=textRevenueChanged+' | '+ textTotals, style=labelShapeOption, color=p_arrowColor, textcolor=RevenueChangeQoQ > 0 ? p_posShapeColor:p_negShapeColor, size=labelSizeOption)
|
ThemeLibrary | https://www.tradingview.com/script/Cixu98sf-ThemeLibrary/ | Asgardian_ | https://www.tradingview.com/u/Asgardian_/ | 5 | 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/
// © Asgardian_
//@version=5
// @description TODO: add library description here
library("ThemeLibrary", false)
// @function : a library of themed colors
// @param _theme : the theme color to fetch
// @returns : an array of colors
export theme(string _theme = "Rainbow") =>
var color[] v = array.new_color(na)
v := switch _theme
'Rainbow' =>
array.push(v, color.new(#00ff00, 48))
array.push(v, color.new(#33ff00, 46))
array.push(v, color.new(#66ff00, 44))
array.push(v, color.new(#99ff00, 42))
array.push(v, color.new(#ccff00, 40))
array.push(v, color.new(#e3dc00, 38))
array.push(v, color.new(#f4b600, 36))
array.push(v, color.new(#fe8d00, 34))
array.push(v, color.new(#ff5d00, 32))
array.push(v, color.new(#ff0000, 30))
v
'Green' =>
array.push(v, color.new(#a0ffa0, 48))
array.push(v, color.new(#8eff8e, 46))
array.push(v, color.new(#7cff7c, 44))
array.push(v, color.new(#6bff6b, 42))
array.push(v, color.new(#59ff59, 40))
array.push(v, color.new(#47ff47, 38))
array.push(v, color.new(#35ff35, 36))
array.push(v, color.new(#24ff24, 34))
array.push(v, color.new(#12ff12, 32))
array.push(v, color.new(#00ff00, 30))
v
'Blue' =>
array.push(v, color.new(#a1e3ff, 48))
array.push(v, color.new(#8fdeff, 46))
array.push(v, color.new(#7dd9ff, 44))
array.push(v, color.new(#6bd3ff, 42))
array.push(v, color.new(#59ceff, 40))
array.push(v, color.new(#48c9ff, 38))
array.push(v, color.new(#36c4ff, 36))
array.push(v, color.new(#24beff, 34))
array.push(v, color.new(#12b9ff, 32))
array.push(v, color.new(#00b4ff, 30))
v
'Red' =>
array.push(v, color.new(#ffa1a1, 48))
array.push(v, color.new(#ff8f8f, 46))
array.push(v, color.new(#ff7d7d, 44))
array.push(v, color.new(#ff6b6b, 42))
array.push(v, color.new(#ff5959, 40))
array.push(v, color.new(#ff4848, 38))
array.push(v, color.new(#ff3636, 36))
array.push(v, color.new(#ff2424, 34))
array.push(v, color.new(#ff1212, 32))
array.push(v, color.new(#ff0000, 30))
v
=>
na
//====================
i_theme = input.string(defval='Rainbow', title='Choose theme', options=['Rainbow', 'Green', 'Blue', 'Red'])
var color[] colors = theme(i_theme)
plot(0, color=array.get(colors, 0), linewidth = 4)
plot(1, color=array.get(colors, 1), linewidth = 4)
plot(2, color=array.get(colors, 2), linewidth = 4)
plot(3, color=array.get(colors, 3), linewidth = 4)
plot(4, color=array.get(colors, 4), linewidth = 4)
plot(5, color=array.get(colors, 5), linewidth = 4)
plot(6, color=array.get(colors, 6), linewidth = 4)
plot(7, color=array.get(colors, 7), linewidth = 4)
plot(8, color=array.get(colors, 8), linewidth = 4)
plot(9, color=array.get(colors, 9), linewidth = 4) |
L_Trade_Boundaries | https://www.tradingview.com/script/Xqnbx6Ou-L-Trade-Boundaries/ | fourkhansolo | https://www.tradingview.com/u/fourkhansolo/ | 6 | 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/
// © fourkhansolo
//@version=5
library("L_Trade_Boundaries", overlay = true)
export litmus_color(float value1, float value2)=>
// Litmus
color_return = if value1 >= value2
color.green
else
color.red
export lister(int length) =>
// This goes back in history in a form of an array
array_values_via_length = array.new_float(length, 0)
for i = 1 to length+1
array.insert(array_values_via_length,i,low[i])
array_values_via_length
//
export moving_averages()=>
// Moving Averages
ma_14 = ta.sma(close,14)
ma_28 = ta.sma(close,28)
ma_200 = ta.sma(close,200)
// color_cord
close_ma_14_color = litmus_color(close, ma_14)
close_ma_28_color = litmus_color(close, ma_28)
close_ma_200_color = litmus_color(close, ma_200)
// Table
table_ma = table.new(position.bottom_right, 2,4, color.gray)
table.cell(table_ma,0,1,"MA-20")
table.cell(table_ma,0,2,"MA-28")
table.cell(table_ma,0,3,"MA-200")
table.cell(table_ma,1,1,str.tostring(math.round(ma_14,2)), text_color = close_ma_14_color)
table.cell(table_ma,1,2,str.tostring(math.round(ma_28,2)), text_color = close_ma_28_color)
table.cell(table_ma,1,3,str.tostring(math.round(ma_200,2)), text_color = close_ma_200_color)
[ma_14,ma_28,ma_200]
//
export timeframe_upper()=>
timeframe_output = if timeframe.period == "D"
timeframe.change("W")
else if timeframe.period == "W"
timeframe.change("M")
else if timeframe.period == "M"
timeframe.change("12M")
else
timeframe.change("D")
//
export timeframe_highlight(simple string timeframe)=>
return_value = if timeframe == "Disable" // Show highlight or no?
na // Don't Show
else
if timeframe == "Auto" // Auto
timeframe_upper() // Daily -> Weekly -> Monthly -> Yearly
else
if timeframe.period != timeframe // Manual
timeframe.change(timeframe) // Changing the value with the timeframe (manual Input)
else
na
//
length_input_trend = input.int(4,"Input Trend",1)
array_length_based_trend = lister(length_input_trend)
plot(array.max(array_length_based_trend), color=color.new(color.yellow,60))
time_frame_select = input.timeframe("D","Custom TimeFrame",["Auto","Disable","D","W","M","3M","12M"])
[ma_14,ma_28,ma_200]=moving_averages()
variable_timeframe = timeframe_highlight(time_frame_select)
bgcolor( variable_timeframe ? color.new(color.red,70): na)
//bgcolor(close < open ? color.new(color.red,70) : color.new(color.green, 70)) |
[VWMA] Net Volume Library | https://www.tradingview.com/script/3C02Xm6j-VWMA-Net-Volume-Library/ | TheKaoticS | https://www.tradingview.com/u/TheKaoticS/ | 8 | 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/
// © TheKaoticS
//@version=5
// @description TODO: add library description here
library("VWMANetVolume")
// ————— Types
//@type Contains 7 bands of net volume data points
//@field h2 Highest positive band
//@field h1 Higher positive band
//@field h High positive band
//@field n Normal neutral band
//@field l Low negative band
//@field l1 Lower negative band
//@field l2 Lowest negative band
export type nvPoint
float h2 = na
float h1 = na
float h = na
float n = na
float l = na
float l1 = na
float l2 = na
// @function Gets the VWMA Net Volume or just pure Net Volume value
// @param src (float) The source price value
// @param length (int) The lookback length
// @param useVwma (bool) To use VWMA in the calculation or not
// @returns The VMWA smoothed or pure net volume value
method getNv(
float src,
int length,
bool useVwma
) =>
srcChange = ta.change(src)
srcPositive = srcChange > 0
srcNegative = srcChange < 0
netVolume = srcPositive ? volume : (srcNegative ? -volume : 0)
vwmaNetVolume = ta.vwma(netVolume, length)
useVwma ? vwmaNetVolume : netVolume
// @function Gets the ALMA point part value for a band in the nvPoint object
// @param nv (float) The current net volume value
// @param length (int) The current net volume lookback length
// @param offset (float) The ALMA offset value
// @param sigma (int) The ALMA sigma value
// @param mult (float) The current multiplier value
// @param direction (int) The multiplier direction of the band (bearish, bullish, or neutral)
// @returns The ALMA smoothed value for the net volume given a multiplier and direction
method getAlmaPointPart(
float nv,
int length,
simple float offset,
simple int sigma,
simple float mult,
int direction
) =>
int almaLength = na
switch direction
1 => almaLength := math.floor(length * mult)
0 => almaLength := length
-1 => almaLength := math.ceil(length / mult)
ta.alma(nv, almaLength, offset, sigma)
// @function Get the current net volume band values at current point
// @param nv (float) The current net volume value
// @param length (int) The current net volume lookback length
// @param offset (float) The ALMA offset value
// @param sigma (int) The ALMA sigma value
// @param multHigh (float) The multiplier high band
// @param multMed (float) The multiplier medium band
// @param multLow (float) The multiplier low band
// @returns Returns a nvPoint object that contains the values of each of the seven net volume bands
method getNvPoint(
float nv,
int length,
simple float offset,
simple int sigma,
simple float multHigh,
simple float multMed,
simple float multLow
) =>
nvPoint nvp = nvPoint.new()
nvp.l2 := getAlmaPointPart(nv, length, offset, sigma, multHigh, -1)
nvp.l1 := getAlmaPointPart(nv, length, offset, sigma, multMed, -1)
nvp.l := getAlmaPointPart(nv, length, offset, sigma, multLow, -1)
nvp.n := getAlmaPointPart(nv, length, offset, sigma, 1, 0 )
nvp.h := getAlmaPointPart(nv, length, offset, sigma, multLow, 1 )
nvp.h1 := getAlmaPointPart(nv, length, offset, sigma, multMed, 1 )
nvp.h2 := getAlmaPointPart(nv, length, offset, sigma, multHigh, 1 )
nvp
// ————— Methods
// @function Gets the band color based on a positive or negative alma value
// @param value (float) The value to pass in to check against
// @param transp (int) The transparency value. Ex: 0 = solid, 100 = fully opaque
// @param negative (color) The color to show when result is below but not equal to 0
// @param positive (color) The color to show when result is above but not equal to 0
// @returns (color) The color that matches the result of being above or below 0
export method getBandColor(
float value,
int transp = 0,
color negative = color.red,
color positive = color.yellow
) =>
color.new(value < 0 ? negative : positive, transp)
// @function
// @param src (float) The source price value
// @param length (int) The lookback length
// @param useVwma (bool) To use VWMA in the calculation or not
// @param offset (float) The ALMA offset value
// @param sigma (int) The ALMA sigma value
// @param multHigh (float) The multiplier high band
// @param multMed (float) The multiplier medium band
// @param multLow (float) The multiplier low band
// @returns Returns the calculated net volume for each band in an nvPoint object
export method nv(
float src = close,
int length = 60,
bool useVwma = false,
simple float offset = 0.85,
simple int sigma = 6,
simple float multHigh = 2.00,
simple float multMed = 1.50,
simple float multLow = 1.25
) =>
getNvPoint(getNv(src, length, useVwma), length, offset, sigma, multHigh, multMed, multLow) |
TICK Grid (TheMas7er) | https://www.tradingview.com/script/9ctSOWp2-TICK-Grid-TheMas7er/ | bmistiaen | https://www.tradingview.com/u/bmistiaen/ | 1,798 | 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/
// © TheMas7er and bmistiaen
//@version=5
indicator('TICK Grid (TheMas7er)', 'TICK Grid')
// Constants
var string c_0_em_5 = ' ' // 0.5 em space
var string c_1_em = ' ' // 1 em space
var string c_5_em = c_1_em + c_1_em + c_1_em + c_1_em + c_1_em // 5 em spaces
var string c_15_em = c_5_em + c_5_em + c_5_em // 15 em spaces
var string c_18_em_5 = c_15_em + c_1_em + c_1_em + c_1_em + c_0_em_5 // 18.5 em spaces
// Defaults
var int d_L1 = 600
var int d_L2 = 800
var string d_ticker = 'USI:TICK'
var color d_colorHi = color.green
var color d_colorLo = color.red
var color d_colorDown = color.black
var color d_colorUp = color.green
var color d_colorZero = color.black
var color d_colorWick = color.black
var color d_colorBorder = color.black
// Inputs
var bool i_showTickHi = input.bool(true, 'Positive' + c_0_em_5, group='levels', inline='hi')
var int i_tickHi = input.int(d_L1, '', minval=0, group='levels', inline='hi')
var int i_tickHi1 = input.int(d_L2, '', minval=0, group='levels', inline='hi')
var color i_colorHi = input.color(d_colorHi, '', group='levels', inline='hi')
var bool i_showTickLo = input.bool(true, 'Negative', group='levels', inline='lo')
var int i_tickLo = input.int(-d_L1, '', maxval=0, group='levels', inline='lo')
var int i_tickLo1 = input.int(-d_L2, '', maxval=0, group='levels', inline='lo')
var color i_colorLo = input.color(d_colorLo, '', group='levels', inline='lo')
var bool i_showZero = input.bool(true, 'Zero' + c_18_em_5, group='levels', inline='ze')
var color i_colorZero = input.color(d_colorZero, '', group='levels', inline='ze')
var color i_colorUp = input.color(d_colorUp, 'Up', group='bar colors', inline='ba')
var color i_colorDown = input.color(d_colorDown, 'Down', group='bar colors', inline='ba')
var color i_colorWick = input.color(d_colorWick, 'Wick', group='bar colors', inline='ba')
var color i_colorBorder = input.color(d_colorBorder, 'Border', group='bar colors', inline='ba')
var string i_ticker = input.symbol(d_ticker, 'Ticker', group='symbol', inline='ti')
// Functions
f_showLevel(_show, _level) => _show ? _level ? _level : na : na // Hide level when value is zero.
// Levels
var int tickhi = f_showLevel(i_showTickHi, i_tickHi)
var int tickhi1 = f_showLevel(i_showTickHi, i_tickHi1)
var int zero = i_showZero ? 0 : na
var int ticklo = f_showLevel(i_showTickLo, i_tickLo)
var int ticklo1 = f_showLevel(i_showTickLo, i_tickLo1)
// Other variables
var bool canPlot = na
// Data Retrieval
[ticko, tickh, tickl, tickc, tickfb, ticklb] = request.security(i_ticker, timeframe.period, [open, high, low, close, session.isfirstbar, session.islastbar])
// Only plot candles when there is tick data available
canPlot := tickfb ? true : ticklb[1] ? false : canPlot
if not canPlot
ticko := na
tickh := na
tickl := na
tickc := na
// Plot Candles
candleColor = ticko < tickc ? i_colorUp : i_colorDown
plotcandle(ticko, tickh, tickl, tickc, 'Tick', candleColor, i_colorWick, bordercolor = i_colorBorder)
// Plot levels
hline(tickhi, 'High', i_colorHi)
hline(tickhi1, 'High1', i_colorHi)
hline(zero, 'Zero', i_colorZero)
hline(ticklo, 'Low', i_colorLo)
hline(ticklo1, 'Low1', i_colorLo)
|
Welford Bollinger Bands (WBB) | https://www.tradingview.com/script/H1t5bdeB-Welford-Bollinger-Bands-WBB/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 57 | 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/
// © peacefulLizard50262
//@version=5
indicator("Welford Bollinger Bands", overlay = true)
source = input.source(close, "Source")
length = input.int(100, "Length", 1)
multiplier = input.float(2, "Multiplier", 0)
// Define the average() function
average() =>
// Initialize the moving average to the first element of the source
float average = source[0]
// Initialize the count to 1
int count = 1
// Calculate the moving average using the Welford method
for i = 1 to length
count := count + 1
delta = source[i] - average
average := average + delta / count
// Return the moving average
average
// Define the stdev() function
stdev() =>
// Initialize the moving average and variance to the first element of the source
float average = source[0]
float variance = 0.0
// Initialize the count to 1
int count = 1
// Calculate the moving average and variance using the Welford method
for i = 1 to length
count := count + 1
delta = source[i] - average
average := average + delta / count
variance := variance + delta * (source[i] - average)
// Return the moving standard deviation
math.sqrt(variance / (count - 1)) * multiplier
plot(average(), "Average", color.orange)
p1 = plot(average() + stdev(), "Upper")
p2 = plot(average() - stdev(), "Lower")
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) |
Triple Brown's Exponential Smoothing (TBES) | https://www.tradingview.com/script/S3WyosWG-Triple-Brown-s-Exponential-Smoothing-TBES/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("TBES", overlay = true)
source = input.source(close, "Source")
alpha = input.float(0.007, "Alpha", 0.001, 1, 0.001)
bes(source, alpha)=>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
tbes() =>
e1 = bes(source, alpha)
e2 = bes(e1, alpha)
e3 = bes(e2, alpha)
tema = 3 * (e1 - e2) + e3
plot(tbes(), "TBES", color.green)
|
Zones Detector | https://www.tradingview.com/script/scr4qF8s-Zones-Detector/ | CaLaHe | https://www.tradingview.com/u/CaLaHe/ | 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/
// © CaLaHe - HL
//@version=5
indicator("Zones Detector", "Zones Detector"
, overlay = true
, max_labels_count = 500
, max_lines_count = 500
, max_boxes_count = 500
, max_bars_back = 500)
max_bars_back(time, 500)
//-----------------------------------------------------------------------------{
//Constants
//-----------------------------------------------------------------------------{
int DEMAND_ZONE = 1
int SUPPLY_ZONE = 2
int TBD_ZONE = 0
//-----------------------------------------------------------------------------{
//Settings
//-----------------------------------------------------------------------------{
// -- Indecision ----
indecision_factor = input.int(2, 'Min. Factor', minval = 1, group = "Indecision")
volume_periods = input.int(20, 'Previous Periods', minval = 1, group = "Indecision")
volume_chg = input.int(10, 'Volume Change (%)', minval = 1, group = "Indecision")
confirm_bars = input.int(5, 'Confirmation Bars', minval = 1, group = 'Indecision')
invalidation = input.string('Close', 'Invalidation Method', options = ['Close', 'Wick'], group = "Indecision")
// -- Zones ----
showlast = input.int(10, 'Show Last', minval = 1, group = 'Zones')
demand_zone_css = input.color(color.new(#66bb6a, 70), 'Demand', inline = "Zones", group = 'Zones')
supply_zone_css = input.color(color.new(#f77c80, 70), 'Supply', inline = "Zones", group = 'Zones')
indecision_zone_css = input.color(color.new(#777575, 70), 'Indecision', inline = "Zones",group = 'Zones')
text_size = input.string('Small', 'Text Size', options = ['Tiny', 'Small', 'Normal'], group = "Zones")
// -- Signals ----
use_signals = input.bool(true, 'Use Signals', group = 'Signals')
bars_below_above = input.int(2, 'Bars Below/Above', minval = 1, group = 'Signals')
//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
var zone_boxes = array.new_box(0)
var zone_labels = array.new_label(0)
type Zone
float top
float bottom
float volume
int left
int type = 0
color css
int reached = 0
int bars_outside = 0
var zones = array.new<Zone>(0)
var last_zone_reached = Zone.new()
bool demand_zone_confirmed = false
bool supply_zone_confirmed = false
bool price_enter_supply_zone = false
bool price_enter_demand_zone = false
var label_size = text_size == 'Tiny' ? size.tiny: text_size == 'Small' ? size.small : size.normal
//------------------------------------------------------------------
// FUNCTIONS
//-----------------------------------------------------------------
get_volume(include_current_bar, bars) =>
past_vol = array.new_float(0)
for i = include_current_bar ? 0: 1 to bars
array.push(past_vol, volume[i])
array.avg(past_vol)
is_indecision_bar() =>
//Is an indecision candle?
float high_change = 0.
float low_change = 0.
float body_change = math.abs((close - open) / open)
if close > open
high_change := math.abs((high - close) / close)
low_change := math.abs((low - open) / open)
else
high_change := math.abs((high - open) / open)
low_change := math.abs((low - close) / close)
float factor = math.floor(math.max(high_change, low_change) / body_change)
factor := na(factor) or factor > 999999 ? 999999 : factor
bool add_as_new_zone = false
if factor >= indecision_factor
add_as_new_zone := true
for zone in zones
//if the candle its include in some previous candle don't add
if (high < zone.top and high > zone.bottom) and (low < zone.top and low > zone.bottom)
add_as_new_zone := false
break
else if zone.type == DEMAND_ZONE and (low < zone.top and low > zone.bottom) and (high >= zone.top)
add_as_new_zone := false
break
else if zone.type == SUPPLY_ZONE and (high < zone.top and high > zone.bottom) and (low <= zone.bottom)
add_as_new_zone := false
break
add_as_new_zone
valid_zone(zone, bclose, bhigh, blow) =>
if zone.type == DEMAND_ZONE
demand_bar_price = invalidation == 'Close' ? bclose : blow
demand_bar_price >= zone.bottom //and bopen > zone.bottom
else if zone.type == SUPPLY_ZONE
supply_bar_price = invalidation == 'Close' ? bclose : bhigh
supply_bar_price <= zone.top //and bopen < zone.top
else
true
bar_reached_zone(zone, wick) =>
(wick >= zone.bottom and wick <= zone.top) or (close >= zone.bottom and close <= zone.top) or (open >= zone.bottom and open <= zone.top)
is_lateral_movement(zone, candles) =>
int inside = 0
for i = 1 to candles
if (close[i] < zone.top and close[i] > zone.bottom) and (open[i] < zone.top and open[i] > zone.bottom)
inside += 1
inside >= candles
confirm_zone(zone) =>
valid_zone = true
new_volume = get_volume(true, confirm_bars)
zone.volume := math.round((new_volume - zone.volume) / zone.volume * 100, 0)
if math.max(open, close) > zone.top
zone.type := DEMAND_ZONE
zone.css := demand_zone_css
else if math.min(open, close) < zone.bottom
zone.type := SUPPLY_ZONE
zone.css := supply_zone_css
if math.abs(zone.volume) >= volume_chg
and zone.type != TBD_ZONE
and not is_lateral_movement(zone, confirm_bars)
for i = 0 to confirm_bars - 1
if not valid_zone(zone, close[i], high[i], low[i])
valid_zone := false
break
else
valid_zone := false
valid_zone
display_zones(boxes, labels, dzones, show_last, zsize) =>
for i = 0 to math.min(show_last - 1, zsize - 1)
zindex = zsize - (1 + i)
get_box = array.get(boxes, i)
get_label = array.get(labels, i)
zone = array.get(dzones, zindex)
box.set_lefttop(get_box, zone.left, zone.top)
box.set_rightbottom(get_box, zone.left, zone.bottom)
box.set_border_color(get_box, zone.css)
box.set_bgcolor(get_box, zone.css)
label.set_textcolor(get_label, color.new(zone.css, 0))
label.set_xy(get_label, bar_index + 5, zone.bottom)
if zone.type == TBD_ZONE
label.set_text(get_label, "")
else
label.set_text(get_label, "Volume change: " + str.tostring(zone.volume) + "%\nReached: " + str.tostring(zone.reached))
//------------------------------------------------------------------
// CALCULATE ZONES
//------------------------------------------------------------------
if barstate.isfirst
for i = 0 to showlast - 1
array.push(zone_boxes, box.new(na,na,na,na, xloc = xloc.bar_time , extend = extend.right))
array.push(zone_labels, label.new(na,na,na, size = label_size, style = label.style_none))
if barstate.isconfirmed
if is_indecision_bar()
period_volume = get_volume(include_current_bar = false, bars = volume_periods)
array.push(zones, Zone.new(top = high, bottom = low, volume = period_volume, left = time, css= indecision_zone_css))
for zone in zones
index = array.indexof(zones, zone)
if zone.type == TBD_ZONE and zone.left == time[confirm_bars]
// Confirm zone o delete it
if confirm_zone(zone)
demand_zone_confirmed := zone.type == DEMAND_ZONE
supply_zone_confirmed := zone.type == SUPPLY_ZONE
for i = 1 to confirm_bars
pindex = index + 1
if pindex < array.size(zones)
array.remove(zones, pindex)
else
array.remove(zones, index)
break
for zone in zones
index = array.indexof(zones, zone)
if not valid_zone(zone, close, high, low)
if last_zone_reached.left == zone.left
last_zone_reached := Zone.new()
array.remove(zones, index)
else
// Check if price reached any zone
if zone.type == DEMAND_ZONE and bar_reached_zone(zone, low)
zone.reached += 1
price_enter_demand_zone := true
if zone.type == SUPPLY_ZONE and bar_reached_zone(zone, high)
zone.reached += 1
price_enter_supply_zone := true
if price_enter_demand_zone or price_enter_supply_zone
zone.bars_outside := 0
last_zone_reached := zone
if last_zone_reached.type == DEMAND_ZONE and close > last_zone_reached.top //and open > last_zone_reached.top
last_zone_reached.bars_outside += 1
else if last_zone_reached.type == SUPPLY_ZONE and close < last_zone_reached.bottom //and open < last_zone_reached.bottom
last_zone_reached.bars_outside += 1
if barstate.islast
int zones_size = array.size(zones)
if zones_size > 0
display_zones(zone_boxes, zone_labels, zones, showlast, zones_size)
//------------
// SIGNALS
//------------
bool buySignal = last_zone_reached.type == DEMAND_ZONE ? last_zone_reached.bars_outside > bars_below_above : false
bool sellSignal = last_zone_reached.type == SUPPLY_ZONE ? last_zone_reached.bars_outside > bars_below_above : false
plotshape(buySignal and use_signals, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(sellSignal and use_signals, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)
//Reset
if last_zone_reached.bars_outside > bars_below_above
last_zone_reached := Zone.new()
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
alertcondition(price_enter_demand_zone or price_enter_supply_zone, 'Zone Reached', "The price reached a zone")
alertcondition(price_enter_demand_zone, 'Reached Demand Zone', 'The price reached a DEMAND zone')
alertcondition(price_enter_supply_zone, 'Reached Supply Zone', 'The price reached a SUPPLY zone')
alertcondition(demand_zone_confirmed or supply_zone_confirmed, 'New Zone Confirmed', 'There is new zone')
alertcondition(demand_zone_confirmed, 'Demand Zone Confirmed', 'There is new DEMAND zone')
alertcondition(supply_zone_confirmed, 'Supply Zone Confirmed', 'There is new SUPPLY zone')
alertcondition(buySignal and use_signals, 'Buy', 'Buy')
alertcondition(sellSignal and use_signals, 'Sell', 'Sell') |
Double Brown's Exponential Smoother (DBES) | https://www.tradingview.com/script/JqvedCim-Double-Brown-s-Exponential-Smoother-DBES/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("DBES", overlay = true)
source = input.source(close, "Source")
alpha = input.float(0.007, "Alpha", 0.001, 1, 0.001)
bes(source, alpha)=>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
dbes()=>
e1 = bes(source, alpha)
e2 = bes(e1, alpha)
dema = 2 * e1 - e2
plot(dbes(), "DBES", color.red)
|
Brown's Exponential Smoothing Tool (BEST) | https://www.tradingview.com/script/0xo4Kclf-Brown-s-Exponential-Smoothing-Tool-BEST/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 22 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("Brown's Exponential Smoothing Tool", "BEST", overlay = true)
source = input.source(close, "Source")
alpha = input.float(0.01, "Alpha", 0.001, 1, 0.001)
style = input.string("BES", "Style", ["BES","DBES","TBES"])
bes(source, alpha)=>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
tbes() =>
e1 = bes(source, alpha)
e2 = bes(e1, alpha)
e3 = bes(e2, alpha)
tema = 3 * (e1 - e2) + e3
dbes()=>
e1 = bes(source, alpha)
e2 = bes(e1, alpha)
dema = 2 * e1 - e2
ma()=>
switch style
"BES" => bes(source, alpha)
"DBES" => dbes()
"TBES" => tbes()
plot(ma(), "MA", color.orange) |
Musashi_Fractal_Dimension | https://www.tradingview.com/script/ertRXbpf-Musashi-Fractal-Dimension/ | Musashi-Alchemist | https://www.tradingview.com/u/Musashi-Alchemist/ | 1,403 | 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/
// © Musashi-Alchemist
//@version=5
indicator(title = "Musashi_Fractal_Dimension_v2", overlay = false, max_bars_back = 5000)
//===================================
// GENERAL INPUTS
//===================================
// ----------------------------------
show_fdi = input.bool(true, title = "FDI ", group='STUDIES', inline='studies')
show_rsi = input.bool(false, title = "RSI ", group='STUDIES', inline='studies')
show_bbwp = input.bool(false, title = "BBWP", group='STUDIES', inline='studies')
// ----------------------------------
//===================================
// FDI INPUTS
//===================================
// ----------------------------------
fdi_src = input.source(close, title = "FDI Source ", group='FDI - FRACTAL DIMENSION INDEX', inline='fdi_a')
fdi_length = input.int(21, title = "Slow FDI Length ", minval = 2, group='FDI - FRACTAL DIMENSION INDEX', inline='fdi_0')
fdi_length_2 = input.int(13, title = "Fast FDIs Length 1:", minval = 2, group='FDI - FRACTAL DIMENSION INDEX', inline='fdi_1')
fdi_length_3 = input.int(12, title = "2:", minval = 2, group='FDI - FRACTAL DIMENSION INDEX', inline='fdi_1')
fdi_length_4 = input.int(11, title = "3:", minval = 2, group='FDI - FRACTAL DIMENSION INDEX', inline='fdi_1')
// ----------------------------------
bandLength = input.int(21, minval = 1, title = "Baseline Length ", group='FDI - FRACTAL DIMENSION INDEX', inline='base_1')
// ----------------------------------
ultra_show_fdi = input.bool(false, title = "Show Ultra-Slow FDI", group='ULTRA-SLOW FDI', inline='base_0')
ultra_fdi_length = input.int(34, title = " Length", minval = 2, group='ULTRA-SLOW FDI', inline='base_0')
// ----------------------------------
ultra_show_fdi_baseline = input.bool(false, title = "Show Baseline", group='ULTRA-SLOW FDI', inline='base_2')
ultra_bandLength = input.int(15, minval = 1, title = " Length", group='ULTRA-SLOW FDI', inline='base_2')
// ----------------------------------
//===================================
// PLOT HORIZONTAL LINES
//===================================
// ----------------------------------
adjust_number = show_fdi or ultra_show_fdi or ultra_show_fdi_baseline ? 1 : 0
// ----------------------------------
p_scaleHi = hline (show_bbwp or show_rsi ? 1 + adjust_number : na, 'High', color.new(#f57c00,50), hline.style_dotted )
p_scaleHi_1 = hline (show_fdi or show_bbwp or show_rsi ? 0.8 + adjust_number : na, 'Level 6', color.new(#b71c1c,50), hline.style_dotted )
p_scaleHi_2 = hline (show_fdi or show_rsi ? 0.75 + adjust_number : na,'Level 5', color.new(#b71c1c,50), hline.style_dotted )
p_scaleHi_3 = hline (show_fdi? 0.6 + adjust_number : na, 'Level 4', color.new(#b71c1c,50), hline.style_dotted )
p_midLine = hline (show_fdi or show_bbwp or show_rsi or ultra_show_fdi or ultra_show_fdi_baseline? 0.5 + adjust_number : na, 'Mid-Line', color.new(#f57c00,42), hline.style_dashed )
p_scaleLo = hline (show_fdi ? 0.4 + adjust_number : na, 'Level 3', color.new(#b71c1c,50), hline.style_dotted )
p_scaleLo_1 = hline (show_fdi or show_rsi ? 0.25 + adjust_number : na,'Level 2', color.new(#b71c1c,50), hline.style_dotted )
p_scaleLo_2 = hline (show_fdi or show_bbwp or show_rsi ? 0.2 + adjust_number : na, 'Level 1', color.new(#b71c1c,50), hline.style_dotted )
p_scaleLo_3 = hline (show_bbwp or show_rsi ? 0 + adjust_number : na, 'Low', color.new(#f57c00,50), hline.style_dotted )
// ----------------------------------
//===================================
// FDI CALCULATIONS
//===================================
// ----------------------------------
calculate_FDI(fdi_src, fdi_length) =>
highest_high = ta.highest(fdi_src, fdi_length)
lowest_low = ta.lowest(fdi_src, fdi_length)
// ----------------------------------
diff = float(0.0)
length = float(0.0)
for i = 1 to fdi_length - 1
diff := (fdi_src[i] - lowest_low) / (highest_high - lowest_low)
length := length + math.sqrt(math.pow(diff[i] - diff[i+1], 2) + (1 / math.pow(fdi_length, 2)))
fdi = 1 + (math.log(length) + math.log(2)) / math.log(2*fdi_length)
fdi
// ----------------------------------
fdi = float(0.0)
fdi := calculate_FDI(fdi_src, fdi_length)
// ----------------------------------
fdi_2 = float(0.0)
fdi_2 := calculate_FDI(fdi_src, fdi_length_2)
// ----------------------------------
fdi_3 = float(0.0)
fdi_3 := calculate_FDI(fdi_src, fdi_length_3)
// ----------------------------------
fdi_4 = float(0.0)
fdi_4 := calculate_FDI(fdi_src, fdi_length_4)
// ----------------------------------
offs = (1.6185 * ta.stdev(fdi, bandLength))
ma = ta.sma(fdi, bandLength)
// ------------------------------------
fdi_color = fdi_2 > fdi ? show_fdi ? color.new(color.silver,25) : na : show_fdi ? color.new(#e92727, 0) : na
fdi_plot = plot(show_fdi ? fdi : na, title = "Slow FDI", color = fdi_color, linewidth=2)
// ----------------------------------
fdi_color_2 = fdi_2 > fdi ? show_fdi ? color.new(color.silver,66) : na : show_fdi ? color.new(#e92727, 56) : na
fdi_plot_2 = plot(show_fdi ? fdi_2 : na, title = "Fast FDI 1", color = fdi_color_2, linewidth=2)
// ----------------------------------
fdi_color_3 = fdi_3 > fdi_2 ? show_fdi ? color.new(#434651,46) : na : show_fdi ? color.new(#e92727, 45) : na
fdi_plot_3 = plot(show_fdi ? fdi_3 : na, title = "Fast FDI 2", color = fdi_color_3, linewidth=1)
// ----------------------------------
fdi_color_4 = fdi_4 > fdi_3 ? show_fdi ? color.new(#434651,46) : na : show_fdi ? color.new(#e92727, 62) : na
fdi_plot_4 = plot(show_fdi ? fdi_4 : na, title = "Fast FDI 3", color = fdi_color_4, linewidth=1)
// ----------------------------------
plot(show_fdi and ta.cross(fdi, fdi_2) and fdi>=fdi_2? fdi : na, title = "FDI_0 x FDI_1 ABOVE 1.5", color = color.white, linewidth = 2, style = plot.style_circles) //, title = "Slow FDI"
plot(show_fdi and ta.cross(fdi_3, fdi_2) and fdi_3<=fdi_2 and fdi_3>=1.5? fdi_2 : na, title = "FDI_1 x FDI_2 ABOVE 1.5", color = color.new(color.silver, 28), linewidth = 2, style = plot.style_circles)
plot(show_fdi and ta.cross(fdi_4, fdi_3) and fdi_4<=fdi_3 and fdi_4>=1.5? fdi_3 : na, title = "FDI_2 x FDI_3 ABOVE 1.5", color = color.new(color.silver, 36), linewidth = 2, style = plot.style_circles)
// ----------------------------------
plot(show_fdi and ta.cross(fdi, fdi_2) and fdi<=fdi_2? fdi : na, title = "FDI_0 x FDI_1 BELOW 1.4", color = #ff8919, linewidth = 2, style = plot.style_circles)
plot(show_fdi and ta.cross(fdi_3, fdi_2) and fdi_3>=fdi_2 and fdi_3<=1.4? fdi_2 : na, title = "FDI_1 x FDI_2 BELOW 1.4", color = color.new(#e92727, 28), linewidth = 2, style = plot.style_circles)
plot(show_fdi and ta.cross(fdi_4, fdi_3) and fdi_4>=fdi_3 and fdi_4<=1.4? fdi_3 : na, title = "FDI_2 x FDI_3 BELOW 1.4", color = color.new(#e92727, 36), linewidth = 2, style = plot.style_circles)
// ----------------------------------
upb = fdi + offs // Upper Bands
dnb = fdi - offs // Lower Bands
mid = ((ma + offs) + (ma - offs)) / 2
midl = plot(show_fdi ? mid : na, "FDI Baseline", color = color.new(#7e57c2, 38), linewidth = 2, style=plot.style_line)
// ----------------------------------
plot(show_fdi and ta.cross(fdi, mid) ? mid : na, color = color.new(#7e57c2, 0), title = "Primary FDI x Baseline", linewidth = 3, style = plot.style_circles) //plot.style_cross
// ----------------------------------
// ----------------------------------
// FDI - ULTRA SLOW
// ----------------------------------
ultra_fdi = float(0.0)
ultra_fdi := calculate_FDI(fdi_src, ultra_fdi_length)
// ----------------------------------
ultra_offs = (1.6185 * ta.stdev(ultra_fdi, ultra_bandLength))
ultra_ma = ta.sma(ultra_fdi, ultra_bandLength)
// ----------------------------------
ultra_upb = ultra_fdi + ultra_offs // Upper Bands
ultra_dnb = ultra_fdi - ultra_offs // Lower Bands
ultra_mid = ((ultra_ma + ultra_offs) + (ultra_ma - ultra_offs)) / 2
// ----------------------------------
ultra_midl = plot(ultra_show_fdi_baseline ? ultra_mid : na, "Ultra-Slow FDI Baseline", color = color.new(#5d606b, 28), linewidth = 2, style=plot.style_line)
// ----------------------------------
plot(ultra_show_fdi_baseline and ta.cross(ultra_fdi, ultra_mid) ? ultra_mid : na, color = color.new(#5d606b, 12), title = "Ultra Slow Baseline x Short Term baseline", linewidth = 3, style = plot.style_circles) //plot.style_cross
// ----------------------------------
ultra_fdi_color = ultra_show_fdi and (ultra_mid < ultra_fdi) ? color.new(color.silver,0) : color.new(#e92727, 0)
ultra_fdi_plot = plot(ultra_show_fdi ? ultra_fdi : na, title = "Ultra-Slow FDI", color = ultra_fdi_color, linewidth=2)
// ------------------------------------
//===================================
//=== RSI INPUTS
//===================================
// ----------------------------------
rsiPeriod = input.int(9, minval=1, title='Primary RSI Period', group='RSI - RELATIVE STERNGTH INDEX', inline='base_1')
second_rsiPeriod = input.int(7, minval=1, title='Secondary RSI Period', group='RSI - RELATIVE STERNGTH INDEX', inline='base_1')
// ----------------------------------
rsibandLength = input.int(21, minval = 1, title = "Baseline Length ", group='RSI - RELATIVE STERNGTH INDEX', inline='base_1')
// ----------------------------------
//===================================
//=== RSI CALCULATIONS & PLOT
//===================================
// ----------------------------------
prim_rsi = ta.rsi(close, rsiPeriod)
second_rsi = ta.rsi(close, second_rsiPeriod)
// ----------------------------------
p_rsi_f = show_rsi ? adjust_number + prim_rsi/100 : na
s_rsi_f = show_rsi ? adjust_number + second_rsi/100 : na
// ----------------------------------
offs_rsi = (1.6185 * ta.stdev(p_rsi_f, rsibandLength))
ma_rsi = ta.sma(p_rsi_f, rsibandLength)
// ----------------------------------
upb_rsi = p_rsi_f + offs_rsi // Upper Bands
dnb_rsi = p_rsi_f - offs_rsi // Lower Bands
mid_rsi = ((ma_rsi + offs_rsi) + (ma_rsi - offs_rsi)) / 2
// ----------------------------------
midl_rsi = plot(show_rsi ? mid_rsi : na, "RSI Baseline", color = color.new(#1848cc, 25), linewidth = 2, style=plot.style_line)
plot(show_rsi and ta.cross(p_rsi_f, mid_rsi) ? mid_rsi : na, color = color.new(#1848cc, 0) , title = "RSI x Baseline", linewidth = 3, style = plot.style_circles) //plot.style_cross
// ----------------------------------
prim_rsi_plot = plot(show_rsi ? p_rsi_f : na, 'Primary RSI', color=color.new(#3179f5, 60), linewidth=2) //#f57c00 color.white
sec_rsi_plot = plot(show_rsi ? s_rsi_f : na, 'Secondary RSI', color=color.new(#3179f5, 80), linewidth=2) //#d1d4dc
// ----------------------------------
//===================================
//=== RSI DIVERGENCES & PLOT
//===================================
// ----------------------------------
// Inputs
lbR = input(title='Pivot Lookback Right', defval=2, group='RSI - DIVERGENCES', inline='div_1')
lbL = input(title='Pivot Lookback Left', defval=9, group='RSI - DIVERGENCES', inline='div_1')
// ----------------------------------
rangeUpper = input(title='Max of Lookback ', defval=120, group='RSI - DIVERGENCES', inline='div_2')
rangeLower = input(title=' Min of Lookback', defval=1, group='RSI - DIVERGENCES', inline='div_2')
// ----------------------------------
plotBull = input(title='Bullish', defval=true, group='RSI - DIVERGENCES', inline='div_3')
plotBear = input(title='Bearish ', defval=true, group='RSI - DIVERGENCES', inline='div_3')
plotHiddenBull = input(title='Hidden Bullish', defval=true, group='RSI - DIVERGENCES', inline='div_3')
plotHiddenBear = input(title='Hidden Bearish', defval=true, group='RSI - DIVERGENCES', inline='div_3')
// ----------------------------------
showLabels = input(title='Show Labels', defval=false, group='RSI - DIVERGENCES', inline='div_4')
// ----------------------------------
// Color setup
bullColor = color.new(#5b9cf6, 28)
hiddenBullColor = color.new(#5b9cf6, 25) //orange: #ff9800
bearColor = color.new(#d32f2f, 28) //red: #b71c1c
hiddenBearColor = color.new(#d32f2f, 25) //gray:#9598a1 red:#d32f2f
textColor = #d1d4dc //color.white
noneColor = color.new(color.white, 100)
// ----------------------------------
bull_line_width = 2
bear_line_width = 2
// ----------------------------------
plFound = na(ta.pivotlow(p_rsi_f, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(p_rsi_f, lbL, lbR)) ? false : true
// ----------------------------------
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
// ----------------------------------
// ==================
// RSI DIVERGENCES
// ==================
// ----------------------------------
// Regular Bullish
// ----------------------------------
oscHL = p_rsi_f[lbR] > ta.valuewhen(plFound, p_rsi_f[lbR], 1) and _inRange(plFound[1]) // Osc: Higher Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1) // Price: Lower Low
bullCond = plotBull and priceLL and oscHL and plFound // Regular Bull condition
plot(plFound ? p_rsi_f[lbR] : na, offset=-lbR, title='Regular Bullish line', linewidth=2, color=show_rsi and bullCond ? bullColor : na)
plotshape(show_rsi and showLabels and bullCond ? p_rsi_f[lbR] : na, offset=-lbR, title='Regular Bullish Label', text='R', style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor)
// ----------------------------------
// Hidden Bullish
// ----------------------------------
oscLL = p_rsi_f[lbR] < ta.valuewhen(plFound, p_rsi_f[lbR], 1) and _inRange(plFound[1]) // Osc: Lower Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1) // Price: Higher Low
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound // Hidden Bull condition
plot(plFound ? p_rsi_f[lbR] : na, offset=-lbR, title='Hidden Bullish line', linewidth=2, color=show_rsi and hiddenBullCond ? hiddenBullColor : na)
plotshape(show_rsi and showLabels and hiddenBullCond ? p_rsi_f[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H', style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor)
// ----------------------------------
// Regular Bearish
// ----------------------------------
oscLH = p_rsi_f[lbR] < ta.valuewhen(phFound, p_rsi_f[lbR], 1) and _inRange(phFound[1]) // Osc: Lower High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1) // Price: Higher High
bearCond = plotBear and priceHH and oscLH and phFound // Regular Bear condition
plot(phFound ? p_rsi_f[lbR] : na, offset=-lbR, title='Regular Bearish line', linewidth=2, color=show_rsi and bearCond ? bearColor : na)
plotshape(show_rsi and showLabels and bearCond ? p_rsi_f[lbR] : na, offset=-lbR, title='Regular Bearish Label', text='R', style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor)
// ----------------------------------
// Hidden Bearish
// ----------------------------------
oscHH = p_rsi_f[lbR] > ta.valuewhen(phFound, p_rsi_f[lbR], 1) and _inRange(phFound[1]) // Osc: Higher High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1) // Price: Lower High
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound // Hidden Bear condition
plot(phFound ? p_rsi_f[lbR] : na, offset=-lbR, title='Hidden Bearish line', linewidth=2, color=show_rsi and hiddenBearCond ? hiddenBearColor : na)
plotshape(show_rsi and showLabels and hiddenBearCond ? p_rsi_f[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text='H', style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor)
// ----------------------------------
//===================================
// BBWP
//===================================
// ----------------------------------
hide_lava = input.bool (true, 'Hide high values', inline='4', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
// ----------------------------------
//===================================
// BBWP FUNCTIONS
//===================================
// ----------------------------------
f_maType ( _price, _len, _type ) =>
_type == 'SMA' ? ta.sma ( _price, _len ) : _type == 'EMA' ? ta.ema ( _price, _len ) : ta.vwma ( _price, _len )
// ----------------------------------
f_bbwp ( _price, _bbwLen, _bbwpLen, _type ) =>
float _basis = f_maType ( _price, _bbwLen, _type )
float _dev = ta.stdev ( _price, _bbwLen )
_bbw = ( _basis + _dev - ( _basis - _dev )) / _basis
_bbwSum = 0.0
_len = bar_index < _bbwpLen ? bar_index : _bbwpLen
for _i = 1 to _len by 1
_bbwSum += ( _bbw[_i] > _bbw ? 0 : 1 )
_bbwSum
_return = bar_index >= _bbwLen ? ( _bbwSum / _len) * 100 : na
_return
// ----------------------------------
f_clrSlct ( _percent, _select, _type, _solid, _array1 ) =>
_select == 'Solid' ? _solid : array.get (_array1, math.round ( _percent ) )
// ----------------------------------
var c_prcntSpctrm2 = array.new_color(na)
if barstate.isfirst
array.push ( c_prcntSpctrm2, #0000FF )
array.push ( c_prcntSpctrm2, #0200FC ), array.push ( c_prcntSpctrm2, #0500F9 ), array.push ( c_prcntSpctrm2, #0700F7 ), array.push ( c_prcntSpctrm2, #0A00F4 ), array.push ( c_prcntSpctrm2, #0C00F2 ),
array.push ( c_prcntSpctrm2, #0F00EF ), array.push ( c_prcntSpctrm2, #1100ED ), array.push ( c_prcntSpctrm2, #1400EA ), array.push ( c_prcntSpctrm2, #1600E8 ), array.push ( c_prcntSpctrm2, #1900E5 ),
array.push ( c_prcntSpctrm2, #1C00E2 ), array.push ( c_prcntSpctrm2, #1E00E0 ), array.push ( c_prcntSpctrm2, #2100DD ), array.push ( c_prcntSpctrm2, #2300DB ), array.push ( c_prcntSpctrm2, #2600D8 ),
array.push ( c_prcntSpctrm2, #2800D6 ), array.push ( c_prcntSpctrm2, #2B00D3 ), array.push ( c_prcntSpctrm2, #2D00D1 ), array.push ( c_prcntSpctrm2, #3000CE ), array.push ( c_prcntSpctrm2, #3300CC ),
array.push ( c_prcntSpctrm2, #3500C9 ), array.push ( c_prcntSpctrm2, #3800C6 ), array.push ( c_prcntSpctrm2, #3A00C4 ), array.push ( c_prcntSpctrm2, #3D00C1 ), array.push ( c_prcntSpctrm2, #3F00BF ),
array.push ( c_prcntSpctrm2, #4200BC ), array.push ( c_prcntSpctrm2, #4400BA ), array.push ( c_prcntSpctrm2, #4700B7 ), array.push ( c_prcntSpctrm2, #4900B5 ), array.push ( c_prcntSpctrm2, #4C00B2 ),
array.push ( c_prcntSpctrm2, #4F00AF ), array.push ( c_prcntSpctrm2, #5100AD ), array.push ( c_prcntSpctrm2, #5400AA ), array.push ( c_prcntSpctrm2, #5600A8 ), array.push ( c_prcntSpctrm2, #5900A5 ),
array.push ( c_prcntSpctrm2, #5B00A3 ), array.push ( c_prcntSpctrm2, #5E00A0 ), array.push ( c_prcntSpctrm2, #60009E ), array.push ( c_prcntSpctrm2, #63009B ), array.push ( c_prcntSpctrm2, #660099 ),
array.push ( c_prcntSpctrm2, #680096 ), array.push ( c_prcntSpctrm2, #6B0093 ), array.push ( c_prcntSpctrm2, #6D0091 ), array.push ( c_prcntSpctrm2, #70008E ), array.push ( c_prcntSpctrm2, #72008C ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#750089 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #770087 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #7A0084 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #7C0082 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #7F007F ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#82007C ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #84007A ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#870077 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #890075 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #8C0072 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#8E0070 ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#91006D ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #93006B ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #960068 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #990066 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#9B0063 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #9E0060 ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#A0005E ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #A3005B ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #A50059 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#A80056 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #AA0054 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #AD0051 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #AF004F ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #B2004C ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#B50049 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #B70047 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #BA0044 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #BC0042 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #BF003F ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#C1003D ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #C4003A ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#C60038 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #C90035 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #CC0033 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#CE0030 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #D1002D ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#D3002B ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #D60028 ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#D80026 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#DB0023 ), array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#DD0021 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #E0001E ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #E2001C ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #E50019 ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#E80016 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #EA0014 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #ED0011 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #EF000F ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #F2000C ),
array.push ( c_prcntSpctrm2, hide_lava?color.new(color.white,100):#F4000A ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #F70007 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #F90005 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #FC0002 ), array.push ( c_prcntSpctrm2,hide_lava?color.new(color.white,100): #FF0000 )
// ----------------------------------
var string STM = 'Spectrum'
var string SLD = 'Solid'
// var string BGR = 'Blue Green Red'
var string BR = 'Blue Red'
// ----------------------------------
//===================================
// BBWP INPUTS
//===================================
// ----------------------------------
i_priceSrc = input.source ( close, 'Price Source', group='BBWP - BOLLINGER BANDS WITH PERCENTILE', inline='bbwp_0')
i_basisType = input.string ( 'SMA', ' Basis Type', options=['SMA', 'EMA', 'VWMA'], group='BBWP - BOLLINGER BANDS WITH PERCENTILE', inline='bbwp_0')
i_bbwpLen = input.int ( 13, 'Length ', minval=1, group='BBWP - BOLLINGER BANDS WITH PERCENTILE', inline='bbwp_1')
i_bbwpLkbk = input.int ( 252, ' Lookback ', minval=1, group='BBWP - BOLLINGER BANDS WITH PERCENTILE', inline='bbwp_1')
// ----------------------------------
i_c_bbwpTyped = input.string ( STM, 'Color Type ', options=[STM, SLD], inline='1', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_c_spctrmType = input.string ( BR, ' Spectrum ', options=[BR], inline='1', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_c_bbwpsolid = color.new(color.silver,50)
// ----------------------------------
i_ma1On = input.bool ( true, '', inline='1', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_ma1Type = input.string ( 'SMA', 'MA 1 Type ', options=['SMA', 'EMA', 'VWMA'], inline='1', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_ma1Len = input.int ( 5, ' MA 1 Length', minval=1, inline='1', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
// ----------------------------------
i_ma2Type = input.string ( 'SMA', 'MA 2 Type ', options=['SMA', 'EMA', 'VWMA'], inline='2', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_ma2Len = input.int ( 55, ' MA 2 Length ', minval=1, inline='2', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_ma2On = input.bool ( true, '', inline='2', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
// ----------------------------------
i_bbwpWidth = input.int ( 2, 'Line Width ', minval=1, maxval=4, inline='3', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_alrtsOn = input.bool ( true, 'Highlight extreme values', inline='3', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_upperLevel = input.int ( 98, 'Extreme High', minval=1, inline='3', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
i_lowerLevel = input.int ( 2, 'Extreme Low', minval=1, inline='3', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
// ----------------------------------
// hide_lava = input.bool (true, 'Hide high values', inline='4', group='BBWP - BOLLINGER BANDS WITH PERCENTILE')
// ----------------------------------
//===================================
// BBWP CALCULATIONS & PLOT
//===================================
// ----------------------------------
bbwp = show_bbwp ? f_bbwp ( i_priceSrc, i_bbwpLen, i_bbwpLkbk, i_basisType ) : na
c_bbwp = show_bbwp ? f_clrSlct ( bbwp, i_c_bbwpTyped, i_c_spctrmType, i_c_bbwpsolid, c_prcntSpctrm2 ) : na
bbwpMA1 = show_bbwp and i_ma1On ? f_maType ( bbwp, i_ma1Len, i_ma1Type ) : na
bbwpMA2 = show_bbwp and i_ma2On ? f_maType ( bbwp, i_ma2Len, i_ma2Type ) : na
// ----------------------------------
bdf = bbwp/100
bdf_calc = adjust_number + bdf
// ----------------------------------
hiAlrtBar = i_alrtsOn and bbwp >= i_upperLevel ? bdf_calc : na
loAlrtBar = i_alrtsOn and bbwp <= i_lowerLevel ? bdf_calc : na
// ----------------------------------
p_bbwp = plot (show_bbwp ? bdf_calc : na, 'BBWP', c_bbwp, i_bbwpWidth, plot.style_line, editable=true )
// ----------------------------------
p_hiAlrt = plot ( show_bbwp ? hiAlrtBar : na, 'Extreme Hi', color.new(#cb0101,85), 1, plot.style_columns, histbase=adjust_number, editable=true )
p_loAlrt = plot ( show_bbwp ? loAlrtBar : na, 'Extreme Lo', color.new(#3000d9,60), 1, plot.style_columns, histbase=adjust_number+1, editable=true )
// ---------------------------------- |
ICT Killzone by Jeaw | https://www.tradingview.com/script/InIZ5BOl-ICT-Killzone-by-Jeaw/ | jotastorres | https://www.tradingview.com/u/jotastorres/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("ICT Killzone", "ICT Killzones by Jeaw", true, max_boxes_count = 500, max_labels_count = 500)
lno_time = input.session(title="London Open Killzone", defval="0700-1000")
nyo_time = input.session(title="New York Open Killzone", defval="1200-1500")
asb_time = input.session(title="Asian Range", defval="1500-1700")
lnc_time = input.session(title="London Close Killzone", defval="0000-0600")
lno_ = input.bool(true, "London Open Killzone", "07:00-10:00 London timezone", "", "Session")
nyo_ = input.bool(true, "New York Open Killzone", "12:00-15:00 London timezone", "", "Session")
lnc_ = input.bool(false, "London Close Killzone", "15:00-17:00 London timezone", "", "Session")
asb_ = input.bool(true, "Asian Range", "00:00-0600 London timezone", "", "Session")
lno_b = input.bool(true, "London Open box", "", "", "session in box")
nyo_b = input.bool(true, "New York Open box", "", "", "session in box")
lnc_b = input.bool(true, "London Close box", "", "", "session in box")
asb_b = input.bool(true, "Asian Range box", "", "", "session in box")
info = input.bool(false, "info over box", "this will show the range of the session in pips (make sense only on forex)", "", "session in box")
spec = input.int(90, "Transparency", 0, 100, 1, "from 0 to 100, how much you want the color transparent?", "", "Visual Features")
lno_c = input.color(color.green, "London Open Killzone", "", "", "Visual Features")
nyo_c = input.color(color.blue, "New York Open Killzone", "", "", "Visual Features")
lnc_c = input.color(color.orange, "London Close Killzone", "", "", "Visual Features")
asb_c = input.color(color.yellow, "Asian Range", "", "", "Visual Features")
b_color = color.new(color.gray,95)
lno = time('', lno_time, 'Europe/London') and lno_ and timeframe.isintraday and timeframe.multiplier <= 60
nyo = time('', nyo_time, 'Europe/London') and nyo_ and timeframe.isintraday and timeframe.multiplier <= 60
lnc = time('', asb_time, 'Europe/London') and lnc_ and timeframe.isintraday and timeframe.multiplier <= 60
asb = time('', lnc_time, 'Europe/London') and asb_ and timeframe.isintraday and timeframe.multiplier <= 60
bgcolor(lno and not lno_b and lno_? color.new(lno_c, spec) : na)
bgcolor(nyo and not nyo_b and nyo_? color.new(nyo_c, spec) : na)
bgcolor(lnc and not lnc_b and lnc_? color.new(lnc_c, spec) : na)
bgcolor(asb and not asb_b and asb_? color.new(asb_c, spec) : na)
var box lno_box = na
var box nyo_box = na
var box lnc_box = na
var box asb_box = na
var label lno_l = na
var label nyo_l = na
var label lnc_l = na
var label asb_l = na
if lno_ and lno_b and timeframe.multiplier<=60 and timeframe.isintraday
if lno and not lno[1]
lno_box := box.new(bar_index,high,bar_index+1,low,b_color,bgcolor = color.new(lno_c,spec))
if info
lno_l := label.new(bar_index,high,str.tostring((high-low)/10/syminfo.mintick)+" pip",textcolor = #ffffff, size = size.small,style = label.style_none)
if lno and lno[1]
if high > box.get_top(lno_box)
box.set_top(lno_box,high)
if low < box.get_bottom(lno_box)
box.set_bottom(lno_box,low)
box.set_right(lno_box,bar_index+1)
if info
label.set_text(lno_l,str.tostring((box.get_top(lno_box)-box.get_bottom(lno_box))/10/syminfo.mintick)+" pip")
label.set_x(lno_l,(box.get_left(lno_box)+box.get_right(lno_box))/2)
label.set_y(lno_l,box.get_top(lno_box))
if not lno and lno[1]
box.set_right(lno_box,bar_index-1)
if nyo_ and nyo_b and timeframe.multiplier<=60 and timeframe.isintraday
if nyo and not nyo[1]
nyo_box := box.new(bar_index,high,bar_index+1,low,b_color,bgcolor = color.new(nyo_c,spec))
if info
nyo_l := label.new(bar_index,high,str.tostring((high-low)/10/syminfo.mintick)+" pip",textcolor = #ffffff, size = size.small,style = label.style_none)
if nyo and nyo[1]
if high > box.get_top(nyo_box)
box.set_top(nyo_box,high)
if low < box.get_bottom(nyo_box)
box.set_bottom(nyo_box,low)
box.set_right(nyo_box,bar_index+1)
if info
label.set_text(nyo_l,str.tostring((box.get_top(nyo_box)-box.get_bottom(nyo_box))/10/syminfo.mintick)+" pip")
label.set_x(nyo_l,(box.get_left(nyo_box)+box.get_right(nyo_box))/2)
label.set_y(nyo_l,box.get_top(nyo_box))
if not nyo and nyo[1]
box.set_right(nyo_box,bar_index-1)
if lnc_ and lnc_b and timeframe.multiplier<=60 and timeframe.isintraday
if lnc and not lnc[1]
lnc_box := box.new(bar_index,high,bar_index+1,low,b_color,bgcolor = color.new(lnc_c,spec))
if info
lnc_l := label.new(bar_index,high,str.tostring((high-low)/10/syminfo.mintick)+" pip",textcolor = #ffffff, size = size.small,style = label.style_none)
if lnc and lnc[1]
if high > box.get_top(lnc_box)
box.set_top(lnc_box,high)
if low < box.get_bottom(lnc_box)
box.set_bottom(lnc_box,low)
box.set_right(lnc_box,bar_index+1)
if info
label.set_text(lnc_l,str.tostring((box.get_top(lnc_box)-box.get_bottom(lnc_box))/10/syminfo.mintick)+" pip")
label.set_x(lnc_l,(box.get_left(lnc_box)+box.get_right(lnc_box))/2)
label.set_y(lnc_l,box.get_top(lnc_box))
if not lnc and lnc[1]
box.set_right(lnc_box,bar_index-1)
if asb_ and asb_b and timeframe.multiplier<=60 and timeframe.isintraday
if asb and not asb[1]
asb_box := box.new(bar_index,high,bar_index+1,low,b_color,bgcolor = color.new(asb_c,spec))
if info
asb_l := label.new(bar_index,high,str.tostring((high-low)/10/syminfo.mintick)+" pip",textcolor = #ffffff, size = size.small,style = label.style_none)
if asb and asb[1]
if high > box.get_top(asb_box)
box.set_top(asb_box,high)
if low < box.get_bottom(asb_box)
box.set_bottom(asb_box,low)
box.set_right(asb_box,bar_index+1)
if info
label.set_text(asb_l,str.tostring((box.get_top(asb_box)-box.get_bottom(asb_box))/10/syminfo.mintick)+" pip")
label.set_x(asb_l,(box.get_left(asb_box)+box.get_right(asb_box))/2)
label.set_y(asb_l,box.get_top(asb_box))
if not asb and asb[1]
box.set_right(asb_box,bar_index-1)
|
Imbalance Detector [LuxAlgo] | https://www.tradingview.com/script/C0cC294Q-Imbalance-Detector-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,699 | 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("Imbalance Detector [LuxAlgo]"
, overlay = true
, max_boxes_count = 500
, max_labels_count = 500
, max_lines_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//Fair Value Gaps
show_fvg = input(true, 'Fair Value Gaps (FVG)'
, inline = 'fvg_css'
, group = 'Fair Value Gaps')
bull_fvg_css = input.color(#2157f3, ''
, inline = 'fvg_css'
, group = 'Fair Value Gaps')
bear_fvg_css = input.color(#ff1100, ''
, inline = 'fvg_css'
, group = 'Fair Value Gaps')
fvg_usewidth = input(false, 'Min Width'
, inline = 'fvg_width'
, group = 'Fair Value Gaps')
fvg_gapwidth = input.float(0, ''
, inline = 'fvg_width'
, group = 'Fair Value Gaps')
fvg_method = input.string('Points', ''
, options = ['Points', '%', 'ATR']
, inline = 'fvg_width'
, group = 'Fair Value Gaps')
fvg_extend = input.int(0, 'Extend FVG'
, minval = 0
, group = 'Fair Value Gaps')
//Opening Gaps
show_og = input(true, 'Show Opening Gaps (OG)'
, inline = 'og_css'
, group = 'Opening Gaps')
bull_og_css = input.color(#2157f3, ''
, inline = 'og_css'
, group = 'Opening Gaps')
bear_og_css = input.color(#ff1100, ''
, inline = 'og_css'
, group = 'Opening Gaps')
og_usewidth = input(false, 'Min Width'
, inline = 'og_width'
, group = 'Opening Gaps')
og_gapwidth = input.float(0, ''
, inline = 'og_width'
, group = 'Opening Gaps')
og_method = input.string('Points', ''
, options = ['Points', '%', 'ATR']
, inline = 'og_width'
, group = 'Opening Gaps')
og_extend = input.int(0, 'Extend OG'
, minval = 0
, group = 'Opening Gaps')
//Volume Imbalance
show_vi = input(true, 'Show Volume Imbalances (VI)'
, inline = 'vi_css'
, group = 'Volume Imbalance')
bull_vi_css = input.color(#2157f3, ''
, inline = 'vi_css'
, group = 'Volume Imbalance')
bear_vi_css = input.color(#ff1100, ''
, inline = 'vi_css'
, group = 'Volume Imbalance')
vi_usewidth = input(false, 'Min Width'
, inline = 'vi_width'
, group = 'Volume Imbalance')
vi_gapwidth = input.float(0, ''
, inline = 'vi_width'
, group = 'Volume Imbalance')
vi_method = input.string('Points', ''
, options = ['Points', '%', 'ATR']
, inline = 'vi_width'
, group = 'Volume Imbalance')
vi_extend = input.int(5, 'Extend VI'
, minval = 0
, group = 'Volume Imbalance')
//Dashboard
show_dash = input(false, 'Show Dashboard'
, group = 'Dashboard')
dash_loc = input.string('Bottom Right', 'Dashboard Location'
, options = ['Top Right', 'Bottom Right', 'Bottom Left']
, group = 'Dashboard')
text_size = input.string('Tiny', 'Dashboard Size'
, options = ['Tiny', 'Small', 'Normal']
, group = 'Dashboard')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
atr = ta.atr(200)
//Detect imbalance and return count over time
imbalance_detection(show, usewidth, method, width, top, btm, condition)=>
var is_width = true
var count = 0
if usewidth
dist = top - btm
is_width := switch method
'Points' => dist > width
'%' => dist / btm * 100 > width
'ATR' => dist > atr * width
is_true = show and condition and is_width
count += is_true ? 1 : 0
[is_true, count]
//Detect if bullish imbalance is filled and return count over time
bull_filled(condition, btm)=>
var btms = array.new_float(0)
var count = 0
if condition
array.unshift(btms, btm)
size = array.size(btms)
for i = (size > 0 ? size-1 : na) to 0
value = array.get(btms, i)
if low < value
array.remove(btms, i)
count += 1
count
//Detect if bearish imbalance is filled and return count over time
bear_filled(condition, top)=>
var tops = array.new_float(0)
var count = 0
if condition
array.unshift(tops, top)
size = array.size(tops)
for i = (size > 0 ? size-1 : na) to 0
value = array.get(tops, i)
if high > value
array.remove(tops, i)
count += 1
count
//Set table data cells
set_cells(tb, column, bull_filled, bull_count, bear_filled, bear_count, bull_css, bear_css, table_size)=>
table.cell(tb, column, 1, str.tostring(bull_count)
, text_color = bull_css
, text_size = table_size
, text_halign = text.align_left)
table.cell(tb, column, 2, str.format('{0,number,percent}', bull_filled / bull_count)
, text_color = bull_css
, text_size = table_size
, text_halign = text.align_left)
table.cell(tb, column, 3, str.tostring(bear_count)
, text_color = bear_css
, text_size = table_size
, text_halign = text.align_left)
table.cell(tb, column, 4, str.format('{0,number,percent}', bear_filled / bear_count)
, text_color = bear_css
, text_size = table_size
, text_halign = text.align_left)
//-----------------------------------------------------------------------------}
//Volume Imbalances
//-----------------------------------------------------------------------------{
//Bullish
bull_gap_top = math.min(close, open)
bull_gap_btm = math.max(close[1], open[1])
[bull_vi, bull_vi_count] = imbalance_detection(
show_vi
, vi_usewidth
, vi_method
, vi_gapwidth
, bull_gap_top
, bull_gap_btm
, open > close[1] and high[1] > low and close > close[1] and open > open[1] and high[1] < bull_gap_top)
bull_vi_filled = bull_filled(bull_vi[1], bull_gap_btm[1])
//Bearish
bear_gap_top = math.min(close[1], open[1])
bear_gap_btm = math.max(close, open)
[bear_vi, bear_vi_count] = imbalance_detection(
show_vi
, vi_usewidth
, vi_method
, vi_gapwidth
, bear_gap_top
, bear_gap_btm
, open < close[1] and low[1] < high and close < close[1] and open < open[1] and low[1] > bear_gap_btm)
bear_vi_filled = bear_filled(bear_vi[1], bear_gap_top[1])
if bull_vi
box.new(n-1, bull_gap_top, n + vi_extend, bull_gap_btm, border_color = bull_vi_css, bgcolor = na, border_style = line.style_dotted)
if bear_vi
box.new(n-1, bear_gap_top, n + vi_extend, bear_gap_btm, border_color = bear_vi_css, bgcolor = na, border_style = line.style_dotted)
//-----------------------------------------------------------------------------}
//Opening Gaps
//-----------------------------------------------------------------------------{
//Bullish
[bull_og, bull_og_count] = imbalance_detection(
show_og
, og_usewidth
, og_method
, og_gapwidth
, bull_gap_top
, bull_gap_btm
, low > high[1])
bull_og_filled = bull_filled(bull_og, bull_gap_btm)
//Bullish
[bear_og, bear_og_count] = imbalance_detection(
show_og
, og_usewidth
, og_method
, og_gapwidth
, bear_gap_top
, bear_gap_btm
, high < low[1])
bear_og_filled = bear_filled(bear_og, bear_gap_top)
if bull_og
box.new(n-1, bull_gap_top, n + og_extend, bull_gap_btm, border_color = na, bgcolor = color.new(bull_og_css, 50), text = 'OG', text_color = chart.fg_color)
if bear_og
box.new(n-1, bear_gap_top, n + og_extend, bear_gap_btm, border_color = na, bgcolor = color.new(bear_og_css, 50), text = 'OG', text_color = chart.fg_color)
//-----------------------------------------------------------------------------}
//Fair Value Gaps
//-----------------------------------------------------------------------------{
//Bullish
[bull_fvg, bull_fvg_count] = imbalance_detection(
show_fvg
, fvg_usewidth
, fvg_method
, fvg_gapwidth
, low
, high[2]
, low > high[2] and close[1] > high[2] and not (bull_og or bull_og[1]))
bull_fvg_filled = bull_filled(bull_fvg, high[2])
//Bearish
[bear_fvg, bear_fvg_count] = imbalance_detection(
show_fvg
, fvg_usewidth
, fvg_method
, fvg_gapwidth
, low[2]
, high
, high < low[2] and close[1] < low[2] and not (bear_og or bear_og[1]))
bear_fvg_filled = bear_filled(bear_fvg, low[2])
if bull_fvg
avg = math.avg(low, high[2])
box.new(n-2, low, n + fvg_extend, high[2], border_color = na, bgcolor = color.new(bull_fvg_css, 80))
line.new(n-2, avg, n + fvg_extend, avg, color = bull_fvg_css)
if bear_fvg
avg = math.avg(low[2], high)
box.new(n-2, low[2], n + fvg_extend, high, border_color = na, bgcolor = color.new(bear_fvg_css, 80))
line.new(n-2, avg, n + fvg_extend, avg, color = bear_fvg_css)
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dash_loc == 'Bottom Left' ? position.bottom_left
: dash_loc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = text_size == 'Tiny' ? size.tiny
: text_size == 'Small' ? size.small
: size.normal
var table tb = na
//Set table legends
if barstate.isfirst and show_dash
tb := table.new(table_position, 5, 7
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if show_fvg
table.cell(tb, 2, 0, '〓 FVG', text_color = color.white, text_size = table_size)
if show_og
table.cell(tb, 3, 0, '◼ OG', text_color = color.white, text_size = table_size)
if show_vi
table.cell(tb, 4, 0, '⬚ VI', text_color = color.white, text_size = table_size)
//Set vertical legends
table.merge_cells(tb, 0, 0, 1, 0)
table.cell(tb, 0, 1, 'Bullish', text_color = #089981, text_size = table_size)
table.cell(tb, 1, 1, 'Frequency', text_color = #089981, text_size = table_size, text_halign = text.align_left)
table.cell(tb, 1, 2, 'Filled', text_color = #089981, text_size = table_size, text_halign = text.align_left)
table.merge_cells(tb, 0, 1, 0, 2)
table.cell(tb, 0, 3, 'Bearish', text_color = #f23645, text_size = table_size)
table.cell(tb, 1, 3, 'Frequency', text_color = #f23645, text_size = table_size, text_halign = text.align_left)
table.cell(tb, 1, 4, 'Filled', text_color = #f23645, text_size = table_size, text_halign = text.align_left)
table.merge_cells(tb, 0, 3, 0, 4)
//Set dashboard data
if barstate.islast and show_dash
if show_fvg
set_cells(tb, 2, bull_fvg_filled, bull_fvg_count, bear_fvg_filled, bear_fvg_count, bull_fvg_css, bear_fvg_css, table_size)
if show_og
set_cells(tb, 3, bull_og_filled, bull_og_count, bear_og_filled, bear_og_count, bull_og_css, bear_og_css, table_size)
if show_vi
set_cells(tb, 4, bull_vi_filled, bull_vi_count, bear_vi_filled, bear_vi_count, bull_vi_css, bear_vi_css, table_size)
//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//FVG
alertcondition(bull_fvg, 'Bullish FVG', 'Bullish FVG detected')
alertcondition(bear_fvg, 'Bearish FVG', 'Bearish FVG detected')
//OG
alertcondition(bull_og, 'Bullish OG', 'Bullish OG detected')
alertcondition(bear_og, 'Bearish OG', 'Bearish OG detected')
//VI
alertcondition(bull_vi, 'Bullish VI', 'Bullish VI detected')
alertcondition(bear_vi, 'Bearish VI', 'Bearish VI detected')
//-----------------------------------------------------------------------------} |
Market Internals | https://www.tradingview.com/script/yH4IFjU5-Market-Internals/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 125 | 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/
// © syntaxgeek
//@version=5
indicator("Market Internals", shorttitle="MI", overlay=true, max_labels_count=500)
// <consts>
v_y1 = low - (ta.atr(30) * 2)
v_y1B = low - ta.atr(30)
v_y2 = high + (ta.atr(30) * 2)
v_y2B = high + ta.atr(30)
// </consts>
// <funcs>
f_newLabel(_text, _bias) =>
v_labelColor = color.green
v_labelTextColor = color.white
v_labelPosition = v_y1
v_labelStyle = label.style_label_up
if _bias == 'bullish'
v_labelColor := color.green
v_labelPosition := v_y1
v_labelTextColor := color.white
v_labelStyle := label.style_label_up
else if _bias == 'bearish'
v_labelColor := color.red
v_labelPosition := v_y2
v_labelTextColor := color.white
v_labelStyle := label.style_label_down
else if _bias == 'neutral'
v_labelColor := color.white
v_labelPosition := close[1] < close ? v_y2 : v_y1
v_labelTextColor := color.black
v_labelStyle := close[1] < close ? label.style_label_down : label.style_label_up
label.new(bar_index, v_labelPosition, _text, xloc.bar_index, yloc.price, v_labelColor, v_labelStyle, v_labelTextColor)
// </funcs>
// <vars>
usTicks = request.security("USI:UPTKS.US-USI:DNTKS.US", timeframe.period, close)
spxOptions = request.security("USI:CVSPX-USI:PVSPX", timeframe.period, close)
spxGamma = request.security("CBOE:CDSPG", timeframe.period, ta.change(close, 1))
bidAskVol = request.security("USI:VOL.ASK.US-USI:VOL.BID.US", timeframe.period, close)
issues = request.security("USI:ADVN.US-USI:DECL.US", timeframe.period, close)
bullishTickCross = ta.crossover(usTicks, 0)
bearishTickCross = ta.crossunder(usTicks, 0)
bullishOptionCross = ta.crossover(spxOptions, 0)
bearishOptionCross = ta.crossunder(spxOptions, 0)
bullishBidAskVolCross = ta.crossover(bidAskVol, 0)
bearishBidAskVolCross = ta.crossunder(bidAskVol, 0)
bullishIssuesCross = ta.crossover(issues, 0)
bearishIssuesCross = ta.crossunder(issues, 0)
spxGammaSpike = spxGamma > 0.08
// </vars>
// <plots>
if spxGammaSpike
f_newLabel("G", "neutral")
if bullishTickCross
f_newLabel("T", "bullish")
if bearishTickCross
f_newLabel("T", "bearish")
if bullishOptionCross
f_newLabel("O", "bullish")
if bearishOptionCross
f_newLabel("O", "bearish")
if bullishBidAskVolCross
f_newLabel("V", "bullish")
if bearishBidAskVolCross
f_newLabel("V", "bearish")
if bullishIssuesCross
f_newLabel("I", "bullish")
if bearishIssuesCross
f_newLabel("I", "bearish")
// </plots> |
[Pt] Periodic Volume Profile | https://www.tradingview.com/script/MplWbXfb-Pt-Periodic-Volume-Profile/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 806 | 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
// Based on the following amazing script:
//
// Study : Volume Profile, Pivot Anchored
// Author : © dgtrd
//
indicator("[Pt] Periodic Volume Profile", "[Pt] PVP", true, max_bars_back = 500, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
priceTxt = str.tostring(close, format.mintick)
tickerTxt = syminfo.ticker
// Functions -----------------------------------------------------------------------------------
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
_resInMinutes
f_tfResInMinutes(_res) =>
request.security(syminfo.tickerid, _res, f_resInMinutes())
f_tfIsIntraday(_res) =>
[intraday, daily, weekly, monthly] = request.security(syminfo.tickerid, _res, [timeframe.isintraday, timeframe.isdaily, timeframe.isweekly, timeframe.ismonthly])
check = intraday ? "Intraday" : daily ? "Daily" : weekly ? "Weekly" : monthly ? "Monthly" : "Error"
check
f_drawOnlyLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
line.set_xy1(id, _x1, _y1)
line.set_xy2(id, _x2, _y2)
line.set_color(id, _color)
id
f_drawOnlyBoxX(_left, _top, _right, _bottom, _border_color, _border_width, _border_style) =>
box.new(_left, _top, _right, _bottom, _border_color, _border_width, _border_style, bgcolor=_border_color)
f_drawOnlyLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) =>
var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip)
label.set_xy(id, _x, _y)
label.set_text(id, _text)
label.set_tooltip(id, _tooltip)
f_getHighLow(_len, _calc, _offset) =>
if _calc
htf_l = low [_offset]
htf_h = high[_offset]
vol = 0.
if _len > 0
for x = 0 to _len - 1
htf_l := math.min(low [_offset + x], htf_l)
htf_h := math.max(high[_offset + x], htf_h)
vol += volume[_offset + x]
// htf_l := math.min(low [_offset + _len], htf_l)
// htf_h := math.max(high[_offset + _len], htf_h)
[htf_h, htf_l, vol]
f_checkBreaches(arrayOfLines, extend) =>
int qtyOfLines = array.size(arrayOfLines)
for lineNo = 0 to (qtyOfLines > 0 ? qtyOfLines - 1 : na)
if lineNo < array.size(arrayOfLines)
line currentLine = array.get(arrayOfLines, lineNo)
float lineLevel = line.get_y1(currentLine)
bool lineWasCrossed = math.sign(close[1] - lineLevel) != math.sign(close - lineLevel)
bool lineWasTouched = math.sign(close[1] - lineLevel) != math.sign(low - lineLevel) or math.sign(close[1] - lineLevel) != math.sign(high - lineLevel)
if lineWasCrossed and extend == 'Until Bar Cross'
array.remove(arrayOfLines, lineNo)
// int(na)
else if lineWasTouched and extend == 'Until Bar Touch'
array.remove(arrayOfLines, lineNo)
// int(na)
else
line.set_x2(currentLine, bar_index)
// int(na)
int(na)
f_checkBreaches_alert(arrayOfLines, extend) =>
poc_alert_id = 0
int qtyOfLines = array.size(arrayOfLines)
for lineNo = 0 to (qtyOfLines > 0 ? qtyOfLines - 1 : na)
if lineNo < array.size(arrayOfLines)
line currentLine = array.get(arrayOfLines, lineNo)
float lineLevel = line.get_y1(currentLine)
bool lineWasCrossed = math.sign(close[1] - lineLevel) != math.sign(close - lineLevel)
bool lineWasTouched = math.sign(close[1] - lineLevel) != math.sign(low - lineLevel) or math.sign(close[1] - lineLevel) != math.sign(high - lineLevel)
if lineWasCrossed //and boxNo != qtyOfBoxes - 1
poc_alert_id := 1
else if lineWasTouched //and boxNo != qtyOfBoxes - 1
poc_alert_id := 2
poc_alert_id
// Inputs ---------------------------------------------------------------------------------------
group_volume_profile = 'Periodic Volume Profile'
periodic_tf = input.timeframe("30", "Periodic Timeframe", group = group_volume_profile, tooltip= 'Note that some higher timeframe may not work properly due to maximum historical bars limitation')
regular_sess = input.bool(false, 'Profile resets on Regular Session', group = group_volume_profile, tooltip = 'For tickers with Extended Trading Hours')
tooltip_vp = 'Volume Profile - displays total trading activity over a specified time period at specific price levels'
volumeProfile = input.bool(true, 'Volume Profile (Common Interest)', inline='BB3', group = group_volume_profile, tooltip = tooltip_vp)
totalVolumeColor = input.color(color.new(color.orange, 50), '' , inline='BB3', group = group_volume_profile)
vaVolumeColor = input.color(color.new(color.gray, 50), '' , inline='BB3', group = group_volume_profile)
tooltip_va = 'Value Area (VA) – The range of price levels in which a specified percentage of all volume was traded during the time period'
isValueArea = input.float(68, "Value Area Volume %", minval = 0, maxval = 100 , group = group_volume_profile, tooltip = tooltip_va) / 100
profileLevels = input.int(24, 'Number of Rows' , minval = 10, maxval = 100 , step = 1 , group = group_volume_profile)
profilePlacement = input.string('Left', 'Placment', options = ['Right', 'Left', 'Next Period'] , group = group_volume_profile)
profileWidth = input.int(50, 'Profile Width %', minval = 0, maxval = 100 , group = group_volume_profile) / 100
tooltip_poc = 'Point of Control (POC) - The price level for the time period with the highest traded volume'
pointOfControl = input.bool(true, 'Point of Control (PoC)' , inline='PoC', group = group_volume_profile, tooltip = tooltip_poc)
pocColor = input.color(color.new(color.red, 0), '' , inline='PoC', group = group_volume_profile)
pocExtend = input.string('Until Bar Touch', 'Extend Point of Control (PoC)', options=['Until Last Bar', 'Until Bar Cross', 'Until Bar Touch', 'None'], group = group_volume_profile)
tooltip_vah = 'Value Area High (VAH) - The highest price level within the value area'
valueAreaHigh = input.bool(true, 'Value Area High (VAH)' , inline='VAH', group = group_volume_profile, tooltip = tooltip_vah)
vahColor = input.color(color.new(color.blue, 0), '' , inline='VAH', group = group_volume_profile)
tooltip_val = 'Value Area Low (VAL) - The lowest price level within the value area'
valueAreaLow = input.bool(true, 'Value Area Low (VAL) ' , inline='VAL', group = group_volume_profile, tooltip = tooltip_val)
valColor = input.color(color.new(color.blue, 0), '' , inline='VAL', group = group_volume_profile)
vaBackground = input.bool(true, 'Background Fill of Value Area (VA)' , inline='vBG', group = group_volume_profile)
vaBackgroundColor = input.color(color.new(color.blue, 90), '' , inline='vBG', group = group_volume_profile)
backgroundFill = input.bool(true, 'Background Fill of Profile Range' , inline ='BG', group = group_volume_profile)
backgroundColor = input.color(color.new(color.blue, 95), '' , inline ='BG', group = group_volume_profile)
show_cross = input.bool(true, 'Show POC Crosses', group = group_volume_profile)
show_touch = input.bool(true, 'Show POC Crosses', group = group_volume_profile)
show_previous = input.bool(true, 'Show Previous POC, VAH, VAL', group = group_volume_profile)
show_dvp = input.bool(true, 'Show Developing Profile', group = group_volume_profile)
show_dpoc = input.bool(true, '└ Show Developing POC path', group = group_volume_profile, inline = 'dpoc')
dpoc_col = input.color(color.yellow, '', group = group_volume_profile, inline = 'dpoc')
show_dvah = input.bool(true, '└ Show Developing VAH path', group = group_volume_profile, inline = 'dvah')
dvah_col = input.color(color.aqua, '', group = group_volume_profile, inline = 'dvah')
show_dval = input.bool(true, '└ Show Developing VAL path', group = group_volume_profile, inline = 'dval')
dval_col = input.color(color.aqua, '', group = group_volume_profile, inline = 'dval')
// Definitions ---------------------------------------------------------------------------------- //
nzVolume = nz(volume)
volumeStorageT = array.new_float(profileLevels + 1, 0.)
var a_poc_lines = array.new_line()
var x1 = 0
var x2 = 0
var levelAbovePoc = 0
var levelBelowPoc = 0
var pvtHigh1 = 0.
var pvtLow1 = 0.
var pvtLast = ''
var pPOC = 0.
var pvah = 0.
var pval = 0.
// Calculations ---------------------------------------------------------------------------------
min_of_day = hour * 60 + minute
intv = 0
C_bar = 0
bar_start = false
period = f_tfIsIntraday(periodic_tf)
daily_start = regular_sess ? ta.barssince(session.isfirstbar_regular) : ta.barssince(session.isfirstbar)
weekly_start = ta.barssince(ta.change(time("W")))
monthly_start = ta.barssince(ta.change(time("1M")))
threeM_start = ta.barssince(ta.change(time("3M")))
sixM_start = ta.barssince(ta.change(time("6M")))
yearly_start = ta.barssince(ta.change(time("12M")))
profileLength = 0
if period == "Intraday"
intv := int(f_tfResInMinutes(periodic_tf))
C_bar := (min_of_day % intv)
profileLength := ta.barssince(C_bar[1] == 0) +1
else if period == "Daily"
C_bar := daily_start
profileLength := daily_start[1]+1
else if period == "Weekly"
C_bar := weekly_start
profileLength := weekly_start[1]+1
else if period == "Monthly"
C_bar := periodic_tf == "1M" ? monthly_start : periodic_tf == "3M" ? threeM_start : periodic_tf == "6M" ? sixM_start : periodic_tf == "12M" ? yearly_start : monthly_start
profileLength := C_bar[1]+1
// plot(intv, "intv")
// plot(C_bar, "C_bar")
bar_start := C_bar == 0
// adjust for regular hour start
profileLength_adj = ta.barssince((session.islastbar_regular[1]))
profileLength_adj_ex = ta.barssince((session.isfirstbar_regular))
if regular_sess
bar_start := bar_start or session.isfirstbar_regular
if not session.isfirstbar_regular
if syminfo.session == session.regular
profileLength := math.min(profileLength_adj, profileLength)
else
profileLength := math.min(profileLength_adj_ex, profileLength)
proceed = bar_start
if proceed
x1 := x2
x2 := bar_index
[priceHighest, priceLowest, tradedVolume] = f_getHighLow(profileLength, proceed, 1)
priceStep = (priceHighest - priceLowest) / profileLevels
pvtHigh = priceHighest
pvtLow = priceLowest
if not na(pvtHigh)
pvtHigh1 := pvtHigh
pvtLast := 'H'
if not na(pvtLow)
pvtLow1 := pvtLow
pvtLast := 'L'
if proceed and nzVolume and priceStep > 0 and bar_index > profileLength and profileLength > 0
for barIndexx = 1 to profileLength
level = 0
barIndex = barIndexx
for priceLevel = priceLowest to priceHighest by priceStep
candleSize = high[barIndex] - low[barIndex]
if high[barIndex] >= priceLevel and low[barIndex] < priceLevel + priceStep
if high[barIndex] <= priceLevel + priceStep and low[barIndex] >= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex])
else if high[barIndex] >= priceLevel + priceStep and low[barIndex] <= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * (priceStep/ candleSize))
else if high[barIndex] >= priceLevel + priceStep
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * ((priceLevel + priceStep - low[barIndex]) / candleSize))
else if low[barIndex] <= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * ((high[barIndex] - priceLevel) / candleSize))
level += 1
pocLevel = array.indexof(volumeStorageT, array.max(volumeStorageT))
totalVolumeTraded = array.sum(volumeStorageT) * isValueArea
valueArea = array.get(volumeStorageT, pocLevel)
levelAbovePoc := pocLevel
levelBelowPoc := pocLevel
while valueArea < totalVolumeTraded
if levelBelowPoc == 0 and levelAbovePoc == profileLevels - 1
break
volumeAbovePoc = 0.
if levelAbovePoc < profileLevels - 1
volumeAbovePoc := array.get(volumeStorageT, levelAbovePoc + 1)
volumeBelowPoc = 0.
if levelBelowPoc > 0
volumeBelowPoc := array.get(volumeStorageT, levelBelowPoc - 1)
if volumeBelowPoc == 0 and volumeAbovePoc == 0
break
if volumeAbovePoc >= volumeBelowPoc
valueArea += volumeAbovePoc
levelAbovePoc += 1
else
valueArea += volumeBelowPoc
levelBelowPoc -= 1
for level = 0 to profileLevels - 1
if volumeProfile
startBoxIndex = profilePlacement == 'Right' ? bar_index - int(array.get(volumeStorageT, level) / array.max(volumeStorageT) * profileLength * profileWidth) : profilePlacement == 'Left' ? bar_index - profileLength : bar_index
endBoxIndex = profilePlacement == 'Right' ? bar_index : startBoxIndex + int( array.get(volumeStorageT, level) / array.max(volumeStorageT) * profileLength * profileWidth)
f_drawOnlyBoxX(startBoxIndex, priceLowest + (level + 0.1) * priceStep, endBoxIndex, priceLowest + (level + 0.9) * priceStep, level >= levelBelowPoc and level <= levelAbovePoc ? totalVolumeColor : vaVolumeColor, 1, line.style_solid)
if backgroundFill
f_drawOnlyBoxX(bar_index - profileLength, priceHighest, bar_index - 1, priceLowest, backgroundColor, 1, line.style_dotted)
if pointOfControl
array.push(a_poc_lines, line.new(bar_index - profileLength, priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + 0.5) * priceStep, bar_index, priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + 0.5) * priceStep, color=pocColor))
vah = f_drawOnlyLineX(bar_index - profileLength, priceLowest + (levelAbovePoc + 1.00) * priceStep, bar_index-1, priceLowest + (levelAbovePoc + 1.00) * priceStep, xloc.bar_index, extend.none, valueAreaHigh ? vahColor : #00000000, line.style_solid, 2)
val = f_drawOnlyLineX(bar_index - profileLength, priceLowest + (levelBelowPoc + 0.00) * priceStep, bar_index-1, priceLowest + (levelBelowPoc + 0.00) * priceStep, xloc.bar_index, extend.none, valueAreaLow ? valColor : #00000000, line.style_solid, 2)
if vaBackground
linefill.new(vah, val, vaBackgroundColor)
pPOC := priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + 0.5) * priceStep
pvah := priceLowest + (levelAbovePoc + 1.00) * priceStep
pval := priceLowest + (levelBelowPoc + 0.00) * priceStep
current_start = ta.barssince(bar_start)
var a_profileD = array.new_box()
profileLength := current_start
priceHighest := ta.highest(high, profileLength > 0 ? profileLength + 1 : 1)
priceLowest := ta.lowest (low , profileLength > 0 ? profileLength + 1 : 1)
priceStep := (priceHighest - priceLowest) / profileLevels
var pocLevel = 0
[_, _, tradedVolume1] = f_getHighLow(profileLength, true, 0)
if nzVolume and profileLength > 0 and priceStep > 0 and show_dvp
if array.size(a_profileD) > 0
for i = 0 to array.size(a_profileD) - 1
box.delete(array.shift(a_profileD))
for barIndex = 0 to profileLength
level = 0
for priceLevel = priceLowest to priceHighest by priceStep
candleSize = high[barIndex] - low[barIndex]
if high[barIndex] >= priceLevel and low[barIndex] < priceLevel + priceStep
if high[barIndex] <= priceLevel + priceStep and low[barIndex] >= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex])
else if high[barIndex] >= priceLevel + priceStep and low[barIndex] <= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * (priceStep/ candleSize))
else if high[barIndex] >= priceLevel + priceStep
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * ((priceLevel + priceStep - low[barIndex]) / candleSize))
else if low[barIndex] <= priceLevel
array.set(volumeStorageT, level, array.get(volumeStorageT, level) + nzVolume[barIndex] * ((high[barIndex] - priceLevel) / candleSize))
level += 1
pocLevel := array.indexof(volumeStorageT, array.max(volumeStorageT))
totalVolumeTraded = array.sum(volumeStorageT) * isValueArea
valueArea = array.get(volumeStorageT, pocLevel)
levelAbovePoc := pocLevel
levelBelowPoc := pocLevel
while valueArea < totalVolumeTraded and totalVolumeTraded > 0
if levelBelowPoc == 0 and levelAbovePoc == profileLevels - 1
break
volumeAbovePoc = 0.
if levelAbovePoc < profileLevels - 1
volumeAbovePoc := array.get(volumeStorageT, levelAbovePoc + 1)
volumeBelowPoc = 0.
if levelBelowPoc > 0
volumeBelowPoc := array.get(volumeStorageT, levelBelowPoc - 1)
if volumeBelowPoc == 0 and volumeAbovePoc == 0
break
if volumeAbovePoc >= volumeBelowPoc
valueArea += volumeAbovePoc
levelAbovePoc += 1
else
valueArea += volumeBelowPoc
levelBelowPoc -= 1
if levelAbovePoc - levelBelowPoc >= profileLevels
break
for level = 0 to profileLevels - 1
if volumeProfile
startBoxIndex = profilePlacement == 'Right' ? bar_index - int(array.get(volumeStorageT, level) / array.max(volumeStorageT) * profileLength * profileWidth) : profilePlacement == 'Left' ? bar_index - profileLength : bar_index
endBoxIndex = profilePlacement == 'Right' ? bar_index : startBoxIndex + int( array.get(volumeStorageT, level) / array.max(volumeStorageT) * profileLength * profileWidth)
array.push(a_profileD, box.new(startBoxIndex, priceLowest + (level + 0.1) * priceStep, endBoxIndex, priceLowest + (level + 0.9) * priceStep, level >= levelBelowPoc and level <= levelAbovePoc ? totalVolumeColor : vaVolumeColor, bgcolor = level >= levelBelowPoc and level <= levelAbovePoc ? totalVolumeColor : vaVolumeColor ))
if backgroundFill
array.push(a_profileD, box.new(bar_index - profileLength, priceHighest, bar_index, priceLowest, backgroundColor, bgcolor = backgroundColor ))
if pointOfControl and not show_dpoc
array.push(a_profileD, box.new(bar_index - profileLength, priceLowest + (pocLevel + .40) * priceStep, bar_index, priceLowest + (pocLevel + .60) * priceStep, pocColor, bgcolor = pocColor ))
vah = f_drawLineX(bar_index - profileLength, priceLowest + (levelAbovePoc + 1.00) * priceStep, bar_index, priceLowest + (levelAbovePoc + 1.00) * priceStep, xloc.bar_index, extend.none, valueAreaHigh ? vahColor : #00000000, line.style_solid, 2)
val = f_drawLineX(bar_index - profileLength, priceLowest + (levelBelowPoc + 0.00) * priceStep, bar_index, priceLowest + (levelBelowPoc + 0.00) * priceStep, xloc.bar_index, extend.none, valueAreaLow ? valColor : #00000000, line.style_solid, 2)
if vaBackground
linefill.new(vah, val, vaBackgroundColor)
DPoC = priceLowest + (array.indexof(volumeStorageT, array.max(volumeStorageT)) + .50) * priceStep
DVAH = priceLowest + (levelAbovePoc + 1.00) * priceStep
DVAL = priceLowest + (levelBelowPoc + 0.00) * priceStep
var line DPoC_l = line.new(na, na, na, na, color=pocColor, width = 2)
var line DVAH_l = line.new(na, na, na, na, color=vahColor, width = 2)
var line DVAL_l = line.new(na, na, na, na, color=valColor, width = 2)
var line PPoC_l = line.new(na, na , na, na, color=pocColor, style = line.style_dashed, width = 2)
var line PVAH_l = line.new(na, na , na, na, color=vahColor, style = line.style_dashed, width = 2)
var line PVAL_l = line.new(na, na , na, na, color=valColor, style = line.style_dashed, width = 2)
if barstate.islast and show_dvp
if not show_dpoc
line.delete(DPoC_l)
DPoC_l := line.new(last_bar_index - profileLength, DPoC , last_bar_index, DPoC, color=pocColor, width = 2)
if not show_dvah
line.delete(DVAH_l)
DVAH_l := line.new(last_bar_index - profileLength, DVAH , last_bar_index, DVAH, color=vahColor, width = 2)
if not show_dval
line.delete(DVAL_l)
DVAL_l := line.new(last_bar_index - profileLength, DVAL , last_bar_index, DVAL, color=valColor, width = 2)
if barstate.islast and show_previous
line.delete(PPoC_l)
line.delete(PVAH_l)
line.delete(PVAL_l)
PPoC_l := line.new(last_bar_index - profileLength, pPOC , last_bar_index, pPOC, color=pocColor, style = line.style_dashed, width = 2)
PVAH_l := line.new(last_bar_index - profileLength, pvah , last_bar_index, pvah, color=vahColor, style = line.style_dashed, width = 2)
PVAL_l := line.new(last_bar_index - profileLength, pval , last_bar_index, pval, color=valColor, style = line.style_dashed, width = 2)
if vaBackground
linefill.new(PVAH_l, PVAL_l, color.new(vaBackgroundColor, 95))
poc_alert = 0
if pointOfControl
poc_alert := f_checkBreaches_alert(a_poc_lines, pocExtend)
poc_alert := proceed ? 0 : poc_alert
if pointOfControl and pocExtend != 'None'
f_checkBreaches(a_poc_lines, pocExtend)
plot(show_dpoc and show_dvp? DPoC : na, 'DPOC Path', proceed ? na : dpoc_col, 2)
plot(show_dvah and show_dvp? DVAH : na, 'DVAH Path', proceed ? na : dvah_col, 2)
plot(show_dval and show_dvp? DVAL : na, 'DPOC Path', proceed ? na : dval_col, 2)
// Cross / Touch Plots ----------------------------------------------------------------------------
plotshape(show_cross and poc_alert == 1 and close > open ? close : na, location = location.abovebar, style = shape.xcross, color= color.white, size = size.small)
plotshape(show_cross and poc_alert == 1 and close < open ? close : na, location = location.belowbar, style = shape.xcross, color= color.white, size = size.small)
plotshape(show_touch and poc_alert == 2 and close > open ? close : na, location = location.abovebar, style = shape.triangledown, color=color.yellow, size = size.small)
plotshape(show_touch and poc_alert == 2 and close < open ? close : na, location = location.belowbar, style = shape.triangleup, color=color.yellow, size = size.small)
// Alerts ---------------------------------------------------------------------------------------
alertcondition(poc_alert == 1, "nPOC Crossed", "Naked POC Crossed")
alertcondition(poc_alert == 2, "nPOC Touched", "Naked POC Touched")
|
Simple Trendlines | https://www.tradingview.com/script/85fU3JnE-Simple-Trendlines/ | HoanGhetti | https://www.tradingview.com/u/HoanGhetti/ | 220 | 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/
// © HoanGhetti
//@version=5
// @description An accessible and semi-effortless way to draw trendlines with automatic slope and angle calculation.
library("SimpleTrendlines", overlay = true)
// @type The object containing the essential values for proper library execution.
// @field x_axis The x-axis provided by the user to determine the distance between point A and point B
// @field offset The offset from x2 and the current bar_index. Used in situations where conditions execute ahead of where the x2 location is, such as pivot events.
// @field strictMode Strict mode works in the backend to ensure that price hasn't closed below or above the trendline before the trendline is drawn.
// @field strictType 0 if price is above line, 1 if price is below line.
export type TrendlineSettings
int x_axis
int offset
bool strictMode
int strictType
// @type The object containing values that the user can use for further calculation.
// @field slope The slope of the initial line.
// @field x1 The bar_index value of point A.
// @field x2 The bar_index value of point B.
// @field changeInX How many bars since the bar_index value of point B.
export type TrendlineData
float slope
int x1
int x2
float y1
float y2
int changeInX
// @type The object containing both the start line and trend line for manipulation.
// @field startline The initial line that gets drawn when instantiating the drawLine() method.
// @field trendline The trendline that gets drawn when instantiating the drawTrendline() method.
export type TrendlineLines
line startline
line trendline
// @type The object that serves as the class of the library. Inherits all properties and methods.
// @field info Contains properties inside the TrendlineSettings object.
// @field values Contains properties inside the TrendlineData object.
// @field lines Contains properties inside the TrendlineLines object.
export type Trendline
TrendlineSettings info
TrendlineData values
TrendlineLines lines
// @function Creates an instance of the trendline library, accepting parameters that allow the library to function accordingly.
// @param x_axis The x-axis distance between point A and point B.
// @param offset The offset from x2 and the current bar_index. Used in situations where conditions execute ahead of where the x2 location is, such as pivot events.
// @param strictMode Strict mode works in the backend of things to ensure that price hasn't closed below the trendline before the trendline is drawn.
// @param strictType 0 ensures that price during slope calculation is above line, 1 ensures that price during slope calculation is below line.
export new(int x_axis, int offset = 0, bool strictMode = na, int strictType = na) =>
var line l1 = line.new(na, na, na, na)
var line l2 = line.new(na, na, na, na)
Trendline this = Trendline.new(
TrendlineSettings.new(x_axis, offset, strictMode, strictType),
TrendlineData.new(na, bar_index - (x_axis + offset), bar_index - offset, na, na, na),
TrendlineLines.new(l1, l2)
)
switch
strictType > 1 or strictType < 0 =>
runtime.error('strictType must be a value of 0 or 1.')
strictType > 0 and (na(strictMode) or not strictMode) =>
runtime.error('strictType can\'t have an assigned value without strictMode being true.')
strictMode and offset < 1 =>
runtime.error('Offset must be over 0 in order to use strictMode.')
this
// @function Draws a new line from the given y-value parameters based on a condition.
// @param condition The condition in order to draw a new line.
// @param y1 The y-value of point A.
// @param y2 the y-value of point B.
// @param src Determines which value strict mode will actively check for leakage before a trendline is drawn.
export method drawLine(Trendline this, bool condition, float y1, float y2, float src = na) =>
var float savedSlope = na
var float savedY1 = na
var float savedY2 = na
if condition and (na(this.info.strictMode) or not this.info.strictMode)
this.lines.startline.set_xy1(this.values.x1, y1)
this.lines.startline.set_xy2(this.values.x2, y2)
savedSlope := (this.lines.startline.get_y2() - this.lines.startline.get_y1()) / this.info.x_axis
savedY1 := this.lines.startline.get_y1()
savedY2 := this.lines.startline.get_y2()
if condition and this.info.strictMode
this.values.slope := (y2 - y1) / this.info.x_axis
bool validElements = na
for i = 0 to this.info.offset
j = this.info.offset - i
if this.info.strictType == 0 ? (na(src) ? close[j] : src[j]) >= y2 + (this.values.slope * (i)) : (na(src) ? close[j] : src[j]) <= y2 + (this.values.slope * (i))
validElements := true
else
validElements := na
break
if not na(validElements)
this.lines.startline.set_xy1(this.values.x1, y1)
this.lines.startline.set_xy2(this.values.x2, y2)
savedSlope := (this.lines.startline.get_y2() - this.lines.startline.get_y1()) / this.info.x_axis
savedY1 := this.lines.startline.get_y1()
savedY2 := this.lines.startline.get_y2()
this.values.slope := savedSlope
this.values.y1 := savedY1
this.values.y2 := savedY2
this.values.changeInX := ta.barssince(ta.change(this.lines.startline.get_y1())) + this.info.offset
// @function Draws a trendline from the line generated from the drawLine() method.
// @param condition The conditon to maintain the trendline.
export method drawTrendline(Trendline this, bool condition) =>
if condition
this.lines.trendline.set_xy1(this.lines.startline.get_x2(), this.lines.startline.get_y2())
this.lines.trendline.set_xy2(bar_index, this.lines.startline.get_y2() + (this.values.slope * this.values.changeInX)) |
McGinley Dynamic x Donchian Channels | https://www.tradingview.com/script/Myv2r24W-McGinley-Dynamic-x-Donchian-Channels/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 25 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PlantFi
//@version=5
indicator(title="McGinley Dynamic x Donchian Channels", shorttitle='McGxD Channels', overlay=true, timeframe='', timeframe_gaps=true)
len_hc = input.int(14, minval=1)
src = input.source(ohlc4, title='Source')
hc_lower = ta.lowest(len_hc)
hc_upper = ta.highest(len_hc)
hc_u = 0.0
hc_l = 0.0
hc_u := na(hc_u[1]) ? ta.ema(hc_upper, len_hc) : hc_u[1] + (hc_upper - hc_u[1]) / (len_hc * math.pow(hc_upper/hc_u[1], 4))
hc_l := na(hc_l[1]) ? ta.ema(hc_lower, len_hc) : hc_l[1] + (hc_lower - hc_l[1]) / (len_hc * math.pow(hc_lower/hc_l[1], 4))
basis = math.avg(hc_u, hc_l)
dev_1 = 1 * ta.stdev(src, len_hc)
dev_2 = 2 * ta.stdev(src, len_hc)
dev_3 = 3 * ta.stdev(src, len_hc)
upper_1 = hc_u + dev_1
upper_2 = hc_u + dev_2
upper_3 = hc_u + dev_3
lower_1 = hc_l - dev_1
lower_2 = hc_l - dev_2
lower_3 = hc_l - dev_3
plot(hc_u, color=color.green, linewidth=3)
plot(upper_1, color=color.lime, linewidth=2)
plot(upper_2, color=color.lime, linewidth=2)
plot(upper_3, color=color.lime, linewidth=2)
plot(hc_l, color=color.red, linewidth=3)
plot(lower_1, color=color.orange, linewidth=2)
plot(lower_2, color=color.orange, linewidth=2)
plot(lower_3, color=color.orange, linewidth=2)
plot(basis, color=color.white, linewidth=3)
|
LineWrapper | https://www.tradingview.com/script/Is67zul0-LineWrapper/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 32 | 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/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
// @description Wrapper Type for Line. Useful when you want to store the line details without drawing them. Can also be used in scnearios where you collect lines to be drawn and draw together towards the end.
library("LineWrapper", overlay=true)
// @type Line Wrapper object
// @field x1 (series int) Bar index (if xloc = xloc.bar_index) or bar UNIX time (if xloc = xloc.bar_time) of the first point of the line. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @field y1 (series int/float) Price of the first point of the line.
// @field x2 (series int) Bar index (if xloc = xloc.bar_index) or bar UNIX time (if xloc = xloc.bar_time) of the second point of the line. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @field y2 (series int/float) Price of the second point of the line.
// @field xloc (series string) See description of x1 argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
// @field extend (series string) If extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none.
// @field color (series color) Line color.
// @field style (series string) Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
// @field width (series int) Line width in pixels.
// @field obj line object
export type Line
int x1
float y1
int x2
float y2
string xloc = xloc.bar_index
string extend = extend.none
color color = color.blue
string style = line.style_solid
int width = 1
line obj = na
// @function draws line as per the wrapper object contents
// @param this (series Line) Line object.
// @returns current Line object
export method draw(Line this)=>
if(not na(this.x1) and not na(this.x2) and not na(this.y1) and not na(this.y2))
this.obj.delete()
this.obj := line.new(this.x1, this.y1, this.x2, this.y2, this.xloc, this.extend, this.color, this.style, this.width)
this
// @function draws lines as per the wrapper object array
// @param this (series array<Line>) Array of Line object.
// @returns current Array of Line objects
export method draw(array<Line> this)=>
for ln in this
ln.draw()
this
// @function updates or redraws line as per the wrapper object contents
// @param this (series Line) Line object.
// @returns current Line object
export method update(Line this)=>
this.obj.delete()
this.draw()
this
// @function updates or redraws lines as per the wrapper object array
// @param this (series array<Line>) Array of Line object.
// @returns current Array of Line objects
export method update(array<Line> this)=>
for ln in this
ln.update()
this
// @function get line price based on bar
// @param this (series Line) Line object.
// @param bar (series/int) bar at which line price need to be calculated
// @returns line price at given bar.
export method get_price(Line this, int bar)=>
stepPerBar = (this.y2 - this.y1)/(this.x2 - this.x1)
distance = bar - this.x1
this.y1 + distance*stepPerBar
// @function Returns UNIX time or bar index (depending on the last xloc value set) of the first point of the line.
// @param this (series Line) Line object.
// @returns UNIX timestamp (in milliseconds) or bar index.
export method get_x1(Line this)=>this.x1
// @function Returns UNIX time or bar index (depending on the last xloc value set) of the second point of the line.
// @param this (series Line) Line object.
// @returns UNIX timestamp (in milliseconds) or bar index.
export method get_x2(Line this)=>this.x2
// @function Returns price of the first point of the line.
// @param this (series Line) Line object.
// @returns Price value.
export method get_y1(Line this)=>this.y1
// @function Returns price of the second point of the line.
// @param this (series Line) Line object.
// @returns Price value.
export method get_y2(Line this)=>this.y2
// @function Sets bar index or bar time (depending on the xloc) of the first point.
// @param this (series Line) Line object.
// @param x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_x1(Line this, int x, bool draw = true, bool update = true)=>
this.x1 := x
if(draw)
if(update)
this.obj.set_x1(x)
this
else
this.draw()
this
this
// @function Sets bar index or bar time (depending on the xloc) of the second point.
// @param this (series Line) Line object.
// @param x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_x2(Line this, int x, bool draw = true, bool update = true)=>
this.x2 := x
if(draw)
if(update)
this.obj.set_x2(x)
this
else
this.draw()
this
this
// @function Sets price of the first point
// @param this (series Line) Line object.
// @param y (series int/float) Price.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_y1(Line this, float y, bool draw = true, bool update = true)=>
this.y1 := y
if(draw)
if(update)
this.obj.set_y1(y)
this
else
this.draw()
this
this
// @function Sets price of the second point
// @param this (series Line) Line object.
// @param y (series int/float) Price.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_y2(Line this, float y, bool draw = true, bool update = true)=>
this.y2 := y
if(draw)
if(update)
this.obj.set_y2(y)
this
else
this.draw()
this
this
// @function Sets the line color
// @param this (series Line) Line object.
// @param color (series color) New line color
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_color(Line this, color color, bool draw = true, bool update = true)=>
this.color := color
if(draw)
if(update)
this.obj.set_color(color)
this
else
this.draw()
this
this
// @function Sets extending type of this line object. If extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points.
// @param this (series Line) Line object.
// @param extend (series string) New extending type.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_extend(Line this, string extend, bool draw = true, bool update = true)=>
this.extend := extend
if(draw)
if(update)
this.obj.set_extend(extend)
this
else
this.draw()
this
this
// @function Sets the line style
// @param this (series Line) Line object.
// @param style (series string) New line style.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_style(Line this, string style, bool draw = true, bool update = true)=>
this.style := style
if(draw)
if(update)
this.obj.set_style(style)
this
else
this.draw()
this
this
// @function Sets the line width.
// @param this (series Line) Line object.
// @param width (series int) New line width in pixels.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_width(Line this, int width, bool draw = true, bool update = true)=>
this.width := width
if(draw)
if(update)
this.obj.set_width(width)
this
else
this.draw()
this
this
// @function Sets x-location and new bar index/time values.
// @param this (series Line) Line object.
// @param x1 (series int) Bar index or bar time of the first point.
// @param x2 (series int) Bar index or bar time of the second point.
// @param xloc (series string) New x-location value.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_xloc(Line this, int x1, int x2, string xloc, bool draw = true, bool update = true)=>
this.xloc := xloc
this.x1 := x1
this.x2 := x2
if(draw)
if(update)
this.obj.set_xloc(x1, x2, xloc)
this
else
this.draw()
this
this
// @function Sets bar index/time and price of the first point.
// @param this (series Line) Line object.
// @param x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @param y (series int/float) Price.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_xy1(Line this, int x, float y, bool draw = true, bool update = true)=>
this.x1 := x
this.y1 := y
if(draw)
if(update)
this.obj.set_xy1(x, y)
this
else
this.draw()
this
this
// @function Sets bar index/time and price of the second point
// @param this (series Line) Line object.
// @param x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than 500 bars into the future.
// @param y (series int/float) Price.
// @param draw (series bool) draw line after setting attribute
// @param update (series bool) update line instead of redraw. Only valid if draw is set.
// @returns Current Line object
export method set_xy2(Line this, int x, float y, bool draw = true, bool update = true)=>
this.x2 := x
this.y2 := y
if(draw)
if(update)
this.obj.set_xy2(x, y)
this
else
this.draw()
this
this
// @function Deletes the underlying line drawing object
// @param this (series Line) Line object.
// @returns Current Line object
export method delete(Line this)=>
this.obj.delete()
this
// @function Clones the Line object.
// @param this (series Line) Line object.
// @returns Cloned line object
export method copy(Line this)=>
newLine = this.copy()
newLine.draw()
newLine
|
Percentile Nearest Rank Rainbow Overlay (PNRV) | https://www.tradingview.com/script/PSdH2A8t-Percentile-Nearest-Rank-Rainbow-Overlay-PNRV/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("PNRV", overlay = true)
grad(src)=>
color out = switch int(src)
0 => color.new(#1500FF , 90)
1 => color.new(#1709F6 , 90)
2 => color.new(#1912ED , 90)
3 => color.new(#1B1AE5 , 90)
4 => color.new(#1D23DC , 90)
5 => color.new(#1F2CD3 , 90)
6 => color.new(#2135CA , 90)
7 => color.new(#233EC1 , 90)
8 => color.new(#2446B9 , 90)
9 => color.new(#264FB0 , 90)
10 => color.new(#2858A7 , 90)
11 => color.new(#2A619E , 90)
12 => color.new(#2C6A95 , 90)
13 => color.new(#2E728D , 90)
14 => color.new(#307B84 , 90)
15 => color.new(#32847B , 90)
16 => color.new(#348D72 , 90)
17 => color.new(#36956A , 90)
18 => color.new(#389E61 , 90)
19 => color.new(#3AA758 , 90)
20 => color.new(#3CB04F , 90)
21 => color.new(#3EB946 , 90)
22 => color.new(#3FC13E , 90)
23 => color.new(#41CA35 , 90)
24 => color.new(#43D32C , 90)
25 => color.new(#45DC23 , 90)
26 => color.new(#47E51A , 90)
27 => color.new(#49ED12 , 90)
28 => color.new(#4BF609 , 90)
29 => color.new(#4DFF00 , 90)
30 => color.new(#53FF00 , 90)
31 => color.new(#59FF00 , 90)
32 => color.new(#5FFE00 , 90)
33 => color.new(#65FE00 , 90)
34 => color.new(#6BFE00 , 90)
35 => color.new(#71FE00 , 90)
36 => color.new(#77FD00 , 90)
37 => color.new(#7DFD00 , 90)
38 => color.new(#82FD00 , 90)
39 => color.new(#88FD00 , 90)
40 => color.new(#8EFC00 , 90)
41 => color.new(#94FC00 , 90)
42 => color.new(#9AFC00 , 90)
43 => color.new(#A0FB00 , 90)
44 => color.new(#A6FB00 , 90)
45 => color.new(#ACFB00 , 90)
46 => color.new(#B2FB00 , 90)
47 => color.new(#B8FA00 , 90)
48 => color.new(#BEFA00 , 90)
49 => color.new(#C4FA00 , 90)
50 => color.new(#CAF900 , 90)
51 => color.new(#D0F900 , 90)
52 => color.new(#D5F900 , 90)
53 => color.new(#DBF900 , 90)
54 => color.new(#E1F800 , 90)
55 => color.new(#E7F800 , 90)
56 => color.new(#EDF800 , 90)
57 => color.new(#F3F800 , 90)
58 => color.new(#F9F700 , 90)
59 => color.new(#FFF700 , 90)
60 => color.new(#FFEE00 , 90)
61 => color.new(#FFE600 , 90)
62 => color.new(#FFDE00 , 90)
63 => color.new(#FFD500 , 90)
64 => color.new(#FFCD00 , 90)
65 => color.new(#FFC500 , 90)
66 => color.new(#FFBD00 , 90)
67 => color.new(#FFB500 , 90)
68 => color.new(#FFAC00 , 90)
69 => color.new(#FFA400 , 90)
70 => color.new(#FF9C00 , 90)
71 => color.new(#FF9400 , 90)
72 => color.new(#FF8C00 , 90)
73 => color.new(#FF8300 , 90)
74 => color.new(#FF7B00 , 90)
75 => color.new(#FF7300 , 90)
76 => color.new(#FF6B00 , 90)
77 => color.new(#FF6200 , 90)
78 => color.new(#FF5A00 , 90)
79 => color.new(#FF5200 , 90)
80 => color.new(#FF4A00 , 90)
81 => color.new(#FF4200 , 90)
82 => color.new(#FF3900 , 90)
83 => color.new(#FF3100 , 90)
84 => color.new(#FF2900 , 90)
85 => color.new(#FF2100 , 90)
86 => color.new(#FF1900 , 90)
87 => color.new(#FF1000 , 90)
88 => color.new(#FF0800 , 90)
89 => color.new(#FF0000 , 90)
90 => color.new(#F60000 , 90)
91 => color.new(#DF0505 , 90)
92 => color.new(#C90909 , 90)
93 => color.new(#B20E0E , 90)
94 => color.new(#9B1313 , 90)
95 => color.new(#851717 , 90)
96 => color.new(#6E1C1C , 90)
97 => color.new(#572121 , 90)
98 => color.new(#412525 , 90)
99 => color.new(#2A2A2A , 90)
100 => color.new(#220027 , 90)
out
length = input.int(20)
source = input.source(close)
_1 = plot(ta.percentile_nearest_rank(source, length, 0), color = color.new(color.white, 100))
_2 = plot(ta.percentile_nearest_rank(source, length, 2), color = color.new(color.white, 100))
fill(_1, _2, color = grad(1))
_3 = plot(ta.percentile_nearest_rank(source, length, 4), color = color.new(color.white, 100))
fill(_2, _3, color = grad(3))
_4 = plot(ta.percentile_nearest_rank(source, length, 6), color = color.new(color.white, 100))
fill(_3, _4, color = grad(5))
_5 = plot(ta.percentile_nearest_rank(source, length, 8), color = color.new(color.white, 100))
fill(_4, _5, color = grad(7))
_6 = plot(ta.percentile_nearest_rank(source, length, 10), color = color.new(color.white, 100))
fill(_5,_6, color = grad(9))
_7 = plot(ta.percentile_nearest_rank(source, length, 12), color = color.new(color.white, 100))
fill(_6,_7, color = grad(11))
_8 = plot(ta.percentile_nearest_rank(source, length, 14), color = color.new(color.white, 100))
fill(_7,_8, color = grad(13))
_9 = plot(ta.percentile_nearest_rank(source, length, 16), color = color.new(color.white, 100))
fill(_8,_9, color = grad(15))
_10 = plot(ta.percentile_nearest_rank(source, length, 18), color = color.new(color.white, 100))
fill(_9,_10, color = grad(17))
_11 = plot(ta.percentile_nearest_rank(source, length, 20), color = color.new(color.white, 100))
fill(_10,_11, color = grad(19))
_12 = plot(ta.percentile_nearest_rank(source, length, 22), color = color.new(color.white, 100))
fill(_11,_12, color = grad(21))
_13 = plot(ta.percentile_nearest_rank(source, length, 24), color = color.new(color.white, 100))
fill(_12,_13, color = grad(23))
_14 = plot(ta.percentile_nearest_rank(source, length, 26), color = color.new(color.white, 100))
fill(_13,_14, color = grad(25))
_15 = plot(ta.percentile_nearest_rank(source, length, 28), color = color.new(color.white, 100))
fill(_14,_15, color = grad(27))
_16 = plot(ta.percentile_nearest_rank(source, length, 30), color = color.new(color.white, 100))
fill(_15,_16, color = grad(29))
_17 = plot(ta.percentile_nearest_rank(source, length, 32), color = color.new(color.white, 100))
fill(_16,_17, color = grad(31))
_18 = plot(ta.percentile_nearest_rank(source, length, 34), color = color.new(color.white, 100))
fill(_17,_18, color = grad(33))
_19 = plot(ta.percentile_nearest_rank(source, length, 36), color = color.new(color.white, 100))
fill(_18,_19, color = grad(35))
_20 = plot(ta.percentile_nearest_rank(source, length, 38), color = color.new(color.white, 100))
fill(_19,_20, color = grad(37))
_21 = plot(ta.percentile_nearest_rank(source, length, 40), color = color.new(color.white, 100))
fill(_20,_21, color = grad(39))
_22 = plot(ta.percentile_nearest_rank(source, length, 42), color = color.new(color.white, 100))
fill(_21,_22, color = grad(41))
_23 = plot(ta.percentile_nearest_rank(source, length, 44), color = color.new(color.white, 100))
fill(_22,_23, color = grad(43))
_24 = plot(ta.percentile_nearest_rank(source, length, 46), color = color.new(color.white, 100))
fill(_23,_24, color = grad(45))
_25 = plot(ta.percentile_nearest_rank(source, length, 48), color = color.new(color.white, 100))
fill(_24,_25, color = grad(49))
_26 = plot(ta.percentile_nearest_rank(source, length, 50), color = color.new(color.white, 100))
fill(_25,_26, color = grad(51))
_27 = plot(ta.percentile_nearest_rank(source, length, 52), color = color.new(color.white, 100))
fill(_26,_27, color = grad(53))
_28 = plot(ta.percentile_nearest_rank(source, length, 54), color = color.new(color.white, 100))
fill(_27,_28, color = grad(55))
_29 = plot(ta.percentile_nearest_rank(source, length, 56), color = color.new(color.white, 100))
fill(_28,_29, color = grad(57))
_30 = plot(ta.percentile_nearest_rank(source, length, 58), color = color.new(color.white, 100))
fill(_29,_30, color = grad(59))
_31 = plot(ta.percentile_nearest_rank(source, length, 60), color = color.new(color.white, 100))
fill(_30,_31, color = grad(61))
_32 = plot(ta.percentile_nearest_rank(source, length, 62), color = color.new(color.white, 100))
fill(_31,_32, color = grad(63))
_33 = plot(ta.percentile_nearest_rank(source, length, 64), color = color.new(color.white, 100))
fill(_32,_33, color = grad(65))
_34 = plot(ta.percentile_nearest_rank(source, length, 66), color = color.new(color.white, 100))
fill(_33,_34, color = grad(67))
_35 = plot(ta.percentile_nearest_rank(source, length, 68), color = color.new(color.white, 100))
fill(_34,_35, color = grad(69))
_36 = plot(ta.percentile_nearest_rank(source, length, 70), color = color.new(color.white, 100))
fill(_35,_36, color = grad(71))
_37 = plot(ta.percentile_nearest_rank(source, length, 72), color = color.new(color.white, 100))
fill(_36,_37, color = grad(73))
_38 = plot(ta.percentile_nearest_rank(source, length, 74), color = color.new(color.white, 100))
fill(_37,_38, color = grad(75))
_39 = plot(ta.percentile_nearest_rank(source, length, 76), color = color.new(color.white, 100))
fill(_38,_39, color = grad(77))
_40 = plot(ta.percentile_nearest_rank(source, length, 78), color = color.new(color.white, 100))
fill(_39,_40, color = grad(79))
_41 = plot(ta.percentile_nearest_rank(source, length, 80), color = color.new(color.white, 100))
fill(_40,_41, color = grad(81))
_42 = plot(ta.percentile_nearest_rank(source, length, 82), color = color.new(color.white, 100))
fill(_41,_42, color = grad(83))
_43 = plot(ta.percentile_nearest_rank(source, length, 84), color = color.new(color.white, 100))
fill(_42,_43, color = grad(85))
_44 = plot(ta.percentile_nearest_rank(source, length, 86), color = color.new(color.white, 100))
fill(_43,_44, color = grad(87))
_45 = plot(ta.percentile_nearest_rank(source, length, 88), color = color.new(color.white, 100))
fill(_44,_45, color = grad(89))
_46 = plot(ta.percentile_nearest_rank(source, length, 90), color = color.new(color.white, 100))
fill(_45,_46, color = grad(91))
_47 = plot(ta.percentile_nearest_rank(source, length, 92), color = color.new(color.white, 100))
fill(_46,_47, color = grad(93))
_48 = plot(ta.percentile_nearest_rank(source, length, 94), color = color.new(color.white, 100))
fill(_47,_48, color = grad(95))
_49 = plot(ta.percentile_nearest_rank(source, length, 96), color = color.new(color.white, 100))
fill(_48,_49, color = grad(97))
_50 = plot(ta.percentile_nearest_rank(source, length, 98), color = color.new(color.white, 100))
fill(_49,_50, color = grad(99))
_51 = plot(ta.percentile_nearest_rank(source, length, 100), color = color.new(color.white, 100))
fill(_50,_51, color = grad(100)) |
Bitwise, Encode, Decode | https://www.tradingview.com/script/MpxBD4q2-Bitwise-Encode-Decode/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 13 | 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/
// © FFriZz
frizlabz =
"\n
███████╗███████╗██████╗ ██╗███████╗███████╗
██╔════╝██╔════╝██╔══██╗██║╚══███╔╝╚══███╔╝
█████╗ █████╗ ██████╔╝██║ ███╔╝ ███╔╝
██╔══╝ ██╔══╝ ██╔══██╗██║ ███╔╝ ███╔╝
██║ ██║ ██║ ██║██║███████╗███████╗
'█████╗████╗ █╗████╗ █╗'╝╚═'███╗ ████╗ ████╗
'██╔═══█╔══█╗█║╚══█║ █║ █╔══█╗█╔══█╗╚══█║
'████╗ ████╔╝█║ █╔╝ █║ █████║████╔╝ █╔╝
'██╔═╝ █╔══█╗█║ █╔╝ █║ █╔══█║█╔══█╗ █╔╝
'██║ █║ █╗█║█╔╝ █║ █║ █║█║ █║█╔╝
'██║ █║ █║█║█████╗█████╗█║ █║████║ ████╗
'╚═╝ ╚╝ ╚╝╚╝╚════╝╚════╝╚╝ ╚╝╚═══╝ ╚═══╝
Decode, Encode, Binary(bitwise) Library
Import the Library and Call docs() use hoverover to see Docs in Editor!
import FFriZz/Bitwise/1 as bit
bit.docs()
"
// Refrences to Read
// https://en.wikipedia.org/wiki/Bitwise_operation
// https://byjus.com/maths/binary-number-system/#:~:text=A%20binary%20number%20system%20is,2%20is%20a%20binary%20number.
// @description Bitwise, Encode, Decode, and more Library
// The bitwise functions library offers a range of tools for performing bitwise operations that are not
// available in Pinescript.
// These operations can be particularly useful in optimizing storage and indexing in specific
// applications by combining two integers into one.
// For instance, encoding the row and column location of a matrix into
// a single array index can expedite the indexing process by accessing only one array index.
//
// It's important to note that binary numbers are referenced from right to left.
// Therefore, keeping the encoded integers within the 32-bit system range
// is crucial for effectively utilizing this technique.
// As a rule of thumb, the sum of the two integers being encoded should not exceed 65535.
// This ensures that the resulting encoded integer can fit within a 32-bit number with 2 16-bit integers,
//
// The library includes both an encoding function,
// which accepts two integers and returns a single encoded integer,
// and a decoding function, which accepts the encoded integer and returns the two original integers.
// and many more potential permormance tools.
// It's worth noting that while it's possible to encode multiple integers together,
// this can become impractical due to the rounding up of numbers past 16 digits in Pinescript.
//
// Overall, the bitwise functions library provides
// a valuable tool for optimizing storage and indexing in specific applications.
// By utilizing bitwise operations to encode 2 integers into a single value,
// it's possible to significantly improve the efficiency of certain algorithms and processes.
//@version=5
library("Bitwise")
// import FFriZz/FrizBug/14 as p
// Bitwise operator psudo functions [<<, >>, &, ^, |, ~]
// -----------------------------------------------------
// @function Returns the bitwise AND of two integers [&]
// @param a `int` - The first integer
// @param b `int` - The second integer
// @returns `int` - The bitwise AND of the two integers
export method bAnd(int a,int b) =>
_a=a, _b=b
result = 0
bit = 1
while _a > 0 and _b > 0
if (_a % 2) == 1 and (_b % 2) == 1
result += bit
bit *= 2
_a := math.floor(_a / 2)
_b := math.floor(_b / 2)
result
// @function Performs a bitwise OR operation on two integers. [|]
// @param a `int` - The first integer.
// @param b `int` - The second integer.
// @returns `int` - The result of the bitwise OR operation.
export method bOr(int a,int b) =>
_a=a, _b=b
bit = 1
result = 0
while _a > 0 or _b > 0
if (_a % 2) == 1 or (_b % 2) == 1
result += bit
bit *= 2
_a := math.floor(_a / 2)
_b := math.floor(_b / 2)
result
// @function Performs a bitwise Xor operation on two integers. [^]
// @param a `int` - The first integer.
// @param b `int` - The second integer.
// @returns `int` - The result of the bitwise Xor operation.
export method bXor(int a,int b) =>
_a=a, _b=b
bit = 1
result = 0
while _a > 0 or _b > 0
if (_a % 2) != (_b % 2)
result += bit
bit *= 2
_a := math.floor(_a / 2)
_b := math.floor(_b / 2)
result
// @function Performs a bitwise NOT operation on an integer. [~]
// @param n `int` - The integer to perform the bitwise NOT operation on.
// @returns `int` - The result of the bitwise NOT operation.
export method bNot(int n) => bXor(n, -1)
// @function Performs a bitwise left shift operation on an integer. [<<]
// @param n `int` - The integer to perform the bitwise left shift operation on.
// @param step `int` - The number of positions to shift the bits to the left.
// @returns `int` - The result of the bitwise left shift operation.
export method bShiftLeft(int n, int step) =>
// Check if the step is negative or too large
out = if step < 0 or step > 31
// Invalid step, return an error value
int(0)
else
// Perform the bitwise shift
result = n * math.pow(2, step)
// Handle overflow
if result > 2147483647
result := -(4294967296 - result)
int(result)
out
// bShiftLeft(48765,6).print("\n\nbShiftLeft(48765,6)",pos="3",text_size="normal")
// @function Performs a bitwise right shift operation on an integer. [>>]
// @param n `int` - The integer to perform the bitwise right shift operation on.
// @param step `int` - The number of bits to shift by.
// @returns `int` - The result of the bitwise right shift operation.
export method bShiftRight(int n, int step) =>
if step >= 0
int(math.floor(n / math.pow(2, step)))
else
int(bShiftLeft(n, -step))
// bShiftRight(48765,28).print(pos="7")
// @function Performs a bitwise right shift operation on an integer.
// @param n `int` - The int to perform the bitwise Left rotation on the bits.
// @param step `int` - The number of bits to shift by.
// @returns `int`- The result of the bitwise right shift operation.
export method bRotateLeft(int n,int step) =>
_step = step
bits = 32
_step %= bits
bOr(bShiftLeft(n,_step),bShiftRight(n,bits-_step))
// bRotateLeft(48765,28).print(pos="4")
// @function Performs a bitwise right shift operation on an integer.
// @param n `int` - The int to perform the bitwise Right rotation on the bits.
// @param step `int` - The number of bits to shift by.
// @returns `int` - The result of the bitwise right shift operation.
export method bRotateRight(int n, int step) =>
_step = step
bits = 32
_step %= bits
bOr(bShiftRight(n,_step), bShiftLeft(n,bits -_step))
// bRotateRight(48765,24).print(pos="1")
// @function Checks if the bit at the given position is set to 1.
// @param n `int` - The integer to check.
// @param pos `int` - The position of the bit to check.
// @returns `bool` - True if the bit is set to 1, False otherwise.
export method bSetCheck(int n, int pos) => bAnd(n,bShiftLeft(1,pos)) > 0
// str.format("\n4={0}\n7={1}",bSetBit(48765,4),bSetBit(48765,7)).print(pos="4")
// 10111110 0 11 1 1101
// @function Clears a particular bit of an integer (changes from 1 to 0) passes if bit at pos is 0.
// @param n `int` - The integer to clear a bit from.
// @param pos `int` - The zero-based index of the bit to clear.
// @returns `int` - The result of clearing the specified bit.
export method bClear(int n,int pos) =>
_n = n
if bSetCheck(n,pos)
mask = math.floor(math.pow(2, pos))
_n -= mask
_n
// bClear(48765,3).print(pos="2")
// 101111100111 1 101 = 101111100111 0 101
// 48765 48757
// @function Flips all 0 bits in the number to 1.
// @param n `int` - The integer to flip the bits of.
// @returns `int` - The result of flipping all 0 bits in the number.
export method bFlip0s(int n) => bNot(n)
// bFlip0s(3365).print(pos="7")
// 110100100101 = 111111111111
// 3365 4095
// @function Flips all 1 bits in the number to 0.
// @param n `int` - The integer to flip the bits of.
// @returns `int` - The result of flipping all 1 bits in the number.
export method bFlip1s(int n) => n*0
// bFlip1s(3365).print(pos="9")
// 110100100101 = 000000000000
// 3365 0
// @function Flips all bits in the number.
// @param n `int` - The integer to flip the bits of.
// @returns `int` - The result of flipping all bits in the number.
export method bFlipAll(int n) =>
result = 0
bit = 1
_n = n
while _n > 0
if (_n % 2) == 0
result += bit
bit *= 2
_n := math.floor(_n / 2)
result
// bFlipAll(5565).print("\n\nbFlipAll(5565)",pos="2",text_size="normal")
// 1 0 1 0 11 0 1111 0 1 = 0 1 0 1 00 1 0000 1 0
// 5565 2626
// @function Changes the value of the bit at the given position.
// @param n `int` - The integer to modify.
// @param pos `int` - The position of the bit to change.
// @param newBit `int` - na = flips bit at pos reguardless 1 or 0 | The new value of the bit (0 or 1).
// @returns `int` - The modified integer.
export method bSet(int n,int pos,int newBit=na) =>
_n = n
_newBit = newBit
if na(newBit)
if bSetCheck(n,pos)
_newBit := 0
else
_newBit := 1
if _newBit < 1
mask = math.floor(math.pow(2, pos))
if bAnd(_n,mask) > 0
_n -= mask
else if _newBit >= 1
mask = math.floor(math.pow(2, pos))
if bAnd(_n,mask) == 0
_n += mask
_n
// bSet(48765,4,0).print("\n\nbSet(48765,4,0)",pos="7",text_size="normal")
// 10111110011 1 1101 = 10111110011 0 1101
// 48765 48749
// @function Changes the value of the digit at the given position.
// @param n `int` - The integer to modify.
// @param pos `int` - The position of the digit to change.
// @param newDigit `int` - The new value of the digit (0-9).
// @returns `int` - The modified integer.
export method changeDigit(int n,int pos,int newDigit) =>
digits = array.new_int(0)
temp = n
while temp > 0
digit = temp % 10
digits.push(digit)
temp := math.floor(temp / 10)
digits.set(pos, newDigit)
result = 0
multiplier = 1
for i = 0 to digits.size() - 1
result := result + (digits.get(i)*multiplier)
multiplier := multiplier * 10
result
// changeDigit(48765,3,13).print(pos="5")
//
// 4 8 765 = 53 765
// @function Switch the position of 2 bits of an int
// @param n `int` - int to manipulate
// @param i `int` - bit pos to switch with j
// @param j `int` - bit pos to switch with i
// @returns `int` - new int with bits switched
export method bSwap(int n, int i, int j) =>
num = n
int bit_i = bAnd(bShiftRight(num,i),1)
int bit_j = bAnd(bShiftRight(num,j),1)
if bit_i != bit_j
num := bXor(num,bOr(bShiftLeft(1,i),bShiftLeft(1,j)))
num
// bSwap(48765,6,14).print("\n\nbSwap(48765,6,14)",pos="1",text_size="normal")
// 48765 = 1 0 1111100 1 111101 | 65085 = 1 1 1111100 0 111101
// ^ ^ ^ ^
// @function Checks to see if the binary form is a Palindrome (reads the same left to right and vice versa)
// @param n `int` - int to check
// @returns `bool` - result of check
export method bPalindrome(int n) =>
int rev = 0
int temp = n
while temp > 0
rev := bOr(bShiftLeft(rev,1),bAnd(temp,1))
temp := bShiftRight(temp,1)
n == rev
// bPalindrome(5).print(pos="7") // 101
// bPalindrome(48765).print(pos="8") // 10111110|01111101
// bPalindrome(48764).print(pos="9") // 1011111001111100
// @function Checks if n is Even
// @param n `int` - The integer to check.
// @returns `bool` - result.
export method bEven(int n) => bAnd(n, 1) == 0
// bEven(64).print("\n\nbEven(64)",pos="4",text_size="normal")
// @function checks if n is Even if not even Odd
// @param n `int` - The integer to check.
// @returns `bool` - result.
export method bOdd(int n) => bAnd(n, 1) != 0
// bOdd(64).print("\n\nbOdd(64)",pos="5",text_size="normal")
// @function Checks if n is a Power of 2.
// @param n `int` - number to check.
// @returns `bool` - result.
export method bPowerOfTwo(int n) => bAnd(n, (n - 1)) == 0 and n > 0
// str.format("64={0}\n62={1}",bPowerOfTwo(64),bPowerOfTwo(62)).print(pos="5")
// @function Counts the number of bits that are equal to 1 in an integer.
// @param n `int` - The integer to count the bits in.
// @returns `int` - The number of bits that are equal to 1 in n.
export method bCount(int n,string to_count="all") =>
grab = false
_count = 0
_to = switch to_count
"all" => grab := true
"1" => _count := 1
"0" => _count := 0
_n = n
count = 0
while _n > 0
if _n % 2 == _count
count +=1
else if grab
count +=1
_n := math.floor(_n / 2)
count
// bCount(48765).print("\n\nbCount(48765)",pos="8",text_size="normal")
// @function Finds the greatest common divisor (GCD) of two numbers.
// @param a `int` - The first number.
// @param b `int` - The second number.
// @returns `int` - The GCD of a and b.
export method GCD(int a, int b) =>
_a = a, _b = b
while _b > 0
temp = _b
_b := _a % _b
_a := temp
_a
// GCD(5,25).str()print("5")
// @function Finds the least common multiple (LCM) of two integers.
// @param a `int` - The first integer.
// @param b `int` - The second integer.
// @returns `int` - The LCM of a and b.
export method LCM(int a, int b) =>
(a * b) / GCD(a, b)
// LCM(5,84).str()print("2")
// @function Finds the LCM of an array of integers.
// @param nums `int[]` - The list of integers.
// @returns `int` - The LCM of the integers in nums.
export method aLCM(array<int> nums) =>
result = nums.get(0)
for i = 1 to nums.size()-1
result := LCM(result, nums.get(i))
result
// aLCM(array.from(55,43,80)).str()print("3")
// @function adjust an array of integers to Least Common Multiple (LCM)
// @param nums `int[]` - The first integer
// @param LCM `int` - The second integer
// @returns int[] - array of ints with LCM
export method adjustedLCM(array<int> nums,int LCM) =>
for i in nums
nums.unshift(((nums.pop()/LCM)*100000)/5)
nums
// @function gets a Char at a given position.
// @param str `string` - string to pull char from.
// @param pos `int` - pos to get char from string (left to right index).
// @returns `string` - char from pos of string or "" if pos is not within index range
export method charAt(string str, int pos) =>
len = str.length(str)
if pos >= 0 and pos < len
str.substring(str, pos, pos+1)
else
""
//charAt("FrizLabz",3).print(pos="8")
// 3 == z
// @function Converts a decimal number to binary
// @param num `int` - The decimal number to convert to binary
// @returns `string` - The binary representation of the decimal number
export method decimalToBinary(int num) =>
_num = num
binary = ""
while _num > 0
binary := str.tostring(_num%2)+binary
_num := math.floor(_num/2)
binary
// @function Converts a decimal number to binary
// @param num `int` - The decimal number to convert to binary
// @param to_binary_int `bool` - bool to convert to int or to string (true for int, false for string)
// @returns `string` - The binary representation of the decimal number
export method decimalToBinary(int num=na,bool to_binary_int=true) =>
to_binary_int ? int(str.tonumber(decimalToBinary(num))) : na
// @function Converts a binary number to decimal
// @param binary `string` - The binary number to convert to decimal
// @returns `int` - The decimal representation of the binary number
export method binaryToDecimal(string binary) =>
decimal = 0.0
for [n,i] in str.split(binary,"")
if i == "1"
decimal += math.pow(2,str.length(binary)-1-n)
int(decimal)
export method binaryToDecimal(int binary) =>
binaryToDecimal(str.tostring(binary))
// @function way of finding decimal length using arithmetic
// @param x `float` - value to find number of decimal places
// @returns `int` - number of decimal places
export method decimal_len(float n) =>
var count = 0
var _n = math.abs(n)
var carry = int(_n)
_n -= carry
while _n != int(_n)
_n *= 10
count += 1
if count > 10
break
count
// decimal_len(0.55523235).print(pos="3") // 8
// @function way of finding number length using arithmetic
// @param n `int`- value to find length of number
// @returns `int` - lenth of nunber i.e. 23 == 2
export method int_len(int n) =>
x = 1
count = 0
while (n - x) > 0
x *= 10
count += 1
count
// int_len(555422222).print() //9
// @function Converts a float decimal number to an integer `0.365 to 365`.
// @param n `string` - The decimal number represented as a string.
// @returns `int` - The integer obtained by removing the decimal point and leading zeroes from s.
export method float_decimal_to_whole(float n) =>
str.tonumber(str.split(str.tostring(n),'.').get(1))
// float_decimal_to_whole(0.4545).print(pos="9") // 4545
// @function Returns the fractional part of a float.
// @param x `float` - The float to get the fractional part of.
// @returns `float` - The fractional part of the float.
export method fractional_part(float x) =>
x - math.floor(x)
// fractional_part(48765.6656).print(pos="6") //0.6656
// @function helper to form 2 ints into 1 float seperated by the decimal
// @param a `int` - a int
// @param b `int` - b int
// @param zero_fix `bool` - fix for trailing zeros being truncated when converting to float
// @returns [decimal,convert] - decimal = decimal of ints | convert = string version of last for future use to ref length
export method form_decimal(int a,int b,bool zero_fix=false) =>
convert = str.tostring(b)
dec = a+str.tonumber("0."+convert+(zero_fix?'1':''))
[dec,str.length(convert)]
// [dec,_] = form_decimal(212,696)
// dec.print(pos="2") //212.696
// @function Encodes two numbers into one using bit OR. (fastest)
// @param n1 `int` - The first number to Encodes.
// @param n2 `int` - The second number to Encodes.
// @returns `int` - The result of combining the two numbers using bit OR.
export method bEncode(int n1, int n2) => bOr(n1,bShiftLeft(n2,16))
// _number_ = bEncode(44,785).print("\n\nbEncode(44,785)",pos="9",text_size="normal")
// @function Decodes an integer created by the bCombine function.(fastest)
// @param n `int` - The integer to decode.
// @returns `[int, int]` - A tuple containing the two decoded components of the integer.
export method bDecode(int n) => [n%65536, math.floor(n/65536)]
// [_n1_,_n2_] = bDecode(_number_)
// str.format("[{0}, {1}]",_n1_,_n2_).print("\n\nbDecode(bEncode(44,785))",pos="6",text_size="normal")
// @function Encodes by seperating ints into left and right of decimal float
// @param a `int` - a int
// @param b `int` - b int
// @returns `float` - new float of encoded ints one on left of decimal point one on right
export method Encode(int a, int b) =>
[_a,_] = a.form_decimal(b,true)
_a
// En = Encode(232,97).print(pos="5") // 232.971
// @function Decodes float of 2 ints seperated by decimal point
// @param encoded `float` - the encoded float value
// @returns `[int, int]` - tuple of the 2 ints from encoded float
export method Decode(float encoded) =>
a = int(encoded)
_b = str.tostring(encoded-a)
b = str.tonumber(str.substring(_b,2,str.length(_b)-1))
[a,b]
// [__a,__b]= Decode(En) // 232,97
// str.format("\na={0}\nb={1}\n",__a,__b).print(pos="6")
// @function Encodes by combining numbers and tracking size in the
// decimal of a floating number (slowest)
// @param a `int` - a int
// @param b `int` - b int
// @returns `float` - new decimal of encoded ints
export method encode_heavy(int a,int b) =>
[dec,len] = a.form_decimal(b)
factor = math.pow(10,len)
out = math.floor(dec*factor)*10+len/factor
// EN = encode_heavy(232,97).print(pos="8") // 232970.02
// @function Decodes encoded float that tracks size of ints in
// decimal of float (slowest)
// @param encoded `float` - the encoded float value
// @returns `[int, int]` - tuple of the 2 ints from encoded float
export method decode_heavy(float encoded) =>
len = str.length(str.split(str.tostring(encoded),'.').get(1))
factor = math.pow(10,len)
decoded = math.floor(encoded/10)/factor
_a = int(decoded)
_b = (decoded-_a)*factor
[_a,_b]
// [___a,___b]= decode_heavy(EN) // 232,97
// str.format("\na={0}\nb={1}\n",___a,___b).print(pos="9")
// @function
//
//---
//# **Bitwise, Encode, Decode Docs**
//---
// - In the documentation you may notice the word decimal
// not used as normal this is because when refering to
// binary a decimal number is a number that
// can be represented with base 10 numbers 0-9
// (the wiki below explains better)
// - A rule of thumb for the two integers being
// encoded it to keep both numbers
// less than 65535 this is because anything lower uses 16 bits or less
// this will maintain 100% accuracy when decoding
// although it is possible to do numbers up to 2147483645 with
// this library doesnt seem useful enough
// to explain or demonstrate.
// - The functions provided work within this 32-bit range,
// where the highest number is all 1s and
// the lowest number is all 0s. These functions were created
// to overcome the lack of built-in bitwise functions in Pinescript.
// By combining two integers into a single number,
// the code can access both values i.e when
// indexing only one array index
// for a matrices row/column, thus improving execution time.
// This technique can be applied to various coding
// scenarios to enhance performance.
// - Bitwise functions are a way to use integers in binary form
// that can be used to speed up several different processes
// most languages have operators to perform these function such as
// `<<, >>, &, ^, |, ~` [Wiki](https://en.wikipedia.org/wiki/Bitwise_operation)
//***
// ```
// method bEncode(int n1, int n2) => int
//| bOr(n1,bShiftLeft(n2,16))
//```
// Encodes two numbers into one using bit OR. (fastest)
//### Parameters
// n1 **`(int)`** - The first number to encode.
// n2 **`(int)`** - The second number to encode.
//#### Returns
// **`int`** - The result of combining the two numbers using bit OR.
//***
// ```
// method bDecode(int n) => int
//| [n%65536, math.floor(n/65536)]
//```
// Decodes an integer created by the bCombine function.(fastest)
//### Parameters
// n **`(int)`** - The integer to decode.
//#### Returns
// **`[int, int]`** - A tuple containing the two decoded components of the integer.
//***
// ```
// method Encode(int a, int b) => float
//```
// Encodes by seperating ints into left and right of decimal float
//### Parameters
// a **`(int)`** - a int
// b **`(int)`** - b int
//#### Returns
// **`float`** - new float of encoded ints one on left of decimal point one on right
//***
// ```
// method Decode(float encoded) => [int, int]
//```
// Decodes float of 2 ints seperated by decimal point
//### Parameters
// encoded `float` - the encoded float value
//#### Returns
// **`[int,int]`** - the 2 ints from encoded float
//***
// ```
// method encode_heavy(int a,int b) => float
//```
// Encodes by combining numbers and tracking size in the decimal of a floating number (slowest)
//### Parameters
// a **`(int)`** - a int
// b **`(int)`** - b int
//#### Returns
// **`float`** - new decimal of encoded ints
//***
// ```
// method decode_heavy(float encoded) => [int, int]
//```
// Decodes encoded float that tracks size of ints in decimal of float (slowest)
//### Parameters
// encoded `float` - the encoded float value
//#### Returns
// **`[int,int]`** - the 2 ints from encoded float
//***
//```
// method bAnd(int a,int b) => int
//```
// Returns the bitwise AND of two integers
//### Parameters
// **`a (int)`** - The first integer
// **`b (int)`** - The second integer
//#### Returns
// **`int`** The bitwise AND of the two integers
//***
//```
// method bOr(int a,int b) => int
//```
// Performs a bitwise OR operation on two integers.
//### Parameters
// **`a (int)`** - The first integer.
// **`b (int)`** - The second integer.
//#### Returns
// **`int`** The result of the bitwise OR operation.
//***
//```
// method bXor(int a,int b) => int
//```
// Performs a bitwise Xor operation on two integers.
//### Parameters
// **`a (int)`** - The first integer.
// **`b (int)`** - The second integer.
//#### Returns
// **`int`** The result of the bitwise Xor operation.
//***
//```
// method bNot(int n) => int
//```
// Performs a bitwise NOT operation on an integer.
//### Parameters
// **`n (int)`** - The integer to perform the bitwise NOT operation on.
//#### Returns
// **`int`** The result of the bitwise NOT operation.
//***
//```
// method bShiftLeft(int n, int step) => int
//```
// Performs a bitwise left shift operation on an integer.
//### Parameters
// **`n (int)`** - The integer to perform the bitwise left shift operation on.
// **`step (int)`** - The number of positions to shift the bits to the left.
//#### Returns
// **`int`** The result of the bitwise left shift operation.
//***
//```
// method bShiftRight(int n, int step) => int
//```
// Performs a bitwise right shift operation on an integer.
//### Parameters
// **`n (int)`** - The integer to perform the bitwise right shift operation on.
// **`step (int)`** - The number of bits to shift by.
//#### Returns
// **`int`** The result of the bitwise right shift operation.
//***
//```
// method bRotateLeft(int n,int step) => int
//```
// Performs a bitwise right shift operation on an integer.
//### Parameters
// **`n (int)`** - The int to perform the bitwise Left rotation on the bits.
// **`step (int)`** - The number of bits to shift by.
//#### Returns
// **`int`** The result of the bitwise right shift operation.
//***
//```
// method bRotateRight(int n, int step) => int
//```
// Performs a bitwise right shift operation on an integer.
//### Parameters
// **`n (int)`** - The int to perform the bitwise Right rotation on the bits.
// **`step (int)`** - The number of bits to shift by.
//#### Returns
// **`int`** The result of the bitwise right shift operation.
//***
//```
// method bSetCheck(int n, int pos) => bool
//```
// Checks if the bit at the given position is set to 1.
//### Parameters
// **`n (int)`** - The integer to check.
// **`pos (int)`** - The position of the bit to check.
//#### Returns
// **`bool`** True if the bit is set to 1, False otherwise.
//***
//```
// method bClear(int n,int pos) => int
//```
// Clears a particular bit of an integer (changes from 1 to 0) passes if bit at pos is 0.
//### Parameters
// **`n (int)`** - The integer to clear a bit from.
// **`pos (int)`** - The zero-based index of the bit to clear.
//#### Returns
// **`int`** The result of clearing the specified bit.
//***
//```
// method bFlip0s(int n) => int
//```
// Flips all 0 bits in the number to 1.
//### Parameters
// **`n (int)`** - The integer to flip the bits of.
//#### Returns
// **`int`** The result of flipping all 0 bits in the number.
//***
//```
// method bFlip1s(int n) => int
//```
// Flips all 1 bits in the number to 0.
//### Parameters
// **`n (int)`** - The integer to flip the bits of.
//#### Returns
// **`int`** The result of flipping all 1 bits in the number.
//***
//```
// method bFlipAll(int n) => int
//```
// Flips all bits in the number.
//### Parameters
// **`n (int)`** - The integer to flip the bits of.
//#### Returns
// **`int`** The result of flipping all bits in the number.
//***
//```
// method bSet(int n,int pos,int newBit=na) => int
//```
// Changes the value of the bit at the given position.
//### Parameters
// **`n (int)`** - The integer to modify.
// **`pos (int)`** - The position of the bit to change.
// **`newBit (int)`** - na = flips bit at pos | The new value of the bit (0 or 1).
//#### Returns
// **`int`** The modified integer.
//***
//```
// method changeDigit(int n,int pos,int newDigit) => int
//```
// Changes the value of the digit at the given position.
//### Parameters
// **`n (int)`** - The integer to modify.
// **`pos (int)`** - The position of the digit to change.
// **`newDigit (int)`** - The new value of the digit (0-9).
//#### Returns
// **`int`** The modified integer.
//***
//```
// method bSwap(int n, int i, int j) => int
//```
// Switch the position of 2 bits of an `int`
//### Parameters
// **`n (int)`** - int to manipulate
// **`i (int)`** - bit pos to switch with `j`
// **`j (int)`** - bit pos to switch with `i`
//#### Returns
// **`int`** new int with bits switched
//***
//```
// method bPalindrome(int n) => bool
//```
// Checks to see if the binary form is a `Palindrome`
// (reads the same left to right and vice versa)
//### Parameters
// **`n (int)`** - int to check
//#### Returns
// **`bool`** result of check
//***
//```
// method bEven(int n) => bool
//```
// Checks if n is `Even`
//### Parameters
// **`n (int)`** - The integer to check.
//#### Returns
// **`bool`** result.
//***
//```
// method bOdd(int n) => bool
//```
// Checks if n is `Even` if not even `Odd`
//### Parameters
// **`n (int)`** - The integer to check.
//#### Returns
// **`bool`** result.
//***
//```
// method bPowerOfTwo(int n) => bool
//```
// Checks if n is a Power of 2.
//### Parameters
// **`n (int)`** - number to check.
//#### Returns
// **`bool`** result.
//***
//```
// method bCount(int n,string to_count="all") => int
//```
// Counts the number of bits that are equal to 1 in an integer.
//### Parameters
// **`n (int)`** - The integer to count the bits in.
//#### Returns
// **`int`** The number of bits that are equal to 1 in `n`.
//***
//```
// method GCD(int a, int b) => int
//```
// Finds the greatest common divisor (GCD) of two numbers.
//### Parameters
// **`a (int)`** - The first number.
// **`b (int)`** - The second number.
//#### Returns
// **`int`** The GCD of `a` and `b`.
//***
//```
// method LCM(int a, int b) => int
//```
// Finds the least common multiple (LCM) of two integers.
//### Parameters
// **`a (int)`** - The first integer.
// **`b (int)`** - The second integer.
//#### Returns
// **`int`** The LCM of `a` and `b`.
//***
//```
// method aLCM(int a, int b) => int
//```
// Finds the least common multiple (LCM) of a list of integers.
//### Parameters
// **`nums (int[])`** - The list of integers.
//#### Returns
// **`int`** The LCM of the integers in `nums`.
//***
//```
// method adjustedLCM(array<int> nums,int LCM) =>
//```
// Adjust array of integers to Least Common Multiple (LCM)
//### Parameters
// **`nums (int[])`** - The first integer
// **`LCM (int)`** - The second integer
//#### Returns
// **`int[]`** - array of ints with LCM
//***
//```
// method charAt(string str, int pos) => string
//```
// Gets the char at the given position (index left to right).
//### Parameters
// **`str (string)`** - string to pull char from.
// **`pos (int)`** - pos to get char from string.
//#### Returns
// **`string`** char from pos of string or "" if pos is not within index range
//***
//```
// method decimalToBinary(int num) => string
//```
// Converts a decimal number to binary
//### Parameters
// **`num (int)`** - The decimal number to convert to binary
//#### Returns
// **`string`** The binary representation of the decimal number
//***
//```
// method binaryToDecimal(string binary) => int
//```
// Converts a binary number to decimal number
//### Parameters
// **`binary (string)`** - The binary number to convert to decimal
//#### Returns
// **`int`** The decimal representation of the binary number
//***
//```
// method float_decimal_len(float n) => int
//```
// Way of finding float decimal length using arithmetic
//### Parameters
// **`x (float)`** value to find number of decimal places
//#### Returns
// **`int`** number of decimal places
//***
//```
// method int_len(int n) => int
//```
// Way of finding number length using arithmetic
//### Parameters
// **`n (int)`** value to find length of number
//#### Returns
// **`int`** lenth of nunber i.e. 23 == 2
//***
//```
// method float_decimal_to_whole(float s) => int
//```
// Converts a float decimal number to a whole integer number
// by removing the decimal point and leading zeroes. `0.22 to 2`
//### Parameters
// **`s (string)`** - The decimal number represented as a string.
//#### Returns
// **`int`** - The integer obtained by removing the decimal point and leading zeroes from `s`.
//***
//```
// method fractional_part(float x) => float
//```
// Returns the fractional part of a float.
//### Parameters
// **`x (float)`** - The float to get the fractional part of.
//#### Returns
// **`float`** The fractional part of the float.
//***
//```
// method form_decimal(int a,int b,bool zero_fix=false) => [float , int]
//```
// Helper to form 2 ints into 1 float seperated by the decimal
//### Parameters
// **`a (float)`** - a int
// **`b (float)`** - b int
// **`zero_fix (bool)`** - fix for trailing zeros being truncated when converting to float
//#### Returns
// **`[decimal,convert]`**
// decimal = decimal of ints
// convert = string version of last for future use to ref length
//***
export docs() =>
''
|
Clean ADX with bidirectional Breakout Volume | https://www.tradingview.com/script/KIaacLRS/ | chervolino | https://www.tradingview.com/u/chervolino/ | 226 | 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/
// © chervolino
//@version=5
indicator('Clean ADX with bidirectional Breakout Volume', 'CAWDBV [CHE]', overlay=false)
//--------------------------------------------------------------------
// Inputs
//--------------------------------------------------------------------
string GRP1 = 'Clean ADX Settings :'
string GRP2 = 'Bidirectional Breakout Volume Settings:'
int length = input(99, "Lookback Period for Clean ADX", group = GRP1)
src = input.source(hlc3, "Source for Clean ADX", group = GRP1)
bool show = input(true, "Display Breakout Volume", group = GRP2)
int n = input(50, 'Breakout Volume Length', group = GRP2)
//--------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------
super(float src, int len) =>
f = (1.414 * math.pi)/len
a = math.exp(-f)
c2 = 2 * a * math.cos(f)
c3 = -a*a
c1 = 1-c2-c3
smooth = 0.0
smooth := c1*(src+src[1])*0.5+c2*nz(smooth[1])+c3*nz(smooth[2])
[smooth]
//--------------------------------------------------------------------
// Logic 1
//--------------------------------------------------------------------
hh = math.max(math.sign(ta.change(ta.highest(length))), 0)
ll = math.max(math.sign(ta.change(ta.lowest(length)) * -1), 0)
[mmh]=super(hh, length)
[mml]=super(ll, length)
tch = math.pow(mmh, 2)
tcl = math.pow(mml, 2)
//--------------------------------------------------------------------
// Logic 2
//--------------------------------------------------------------------
Volume_Direction = close > close[1] ? volume : -volume
hi = ta.highest(Volume_Direction, n)
hp = hi[1]
co = Volume_Direction> 0 and ta.rsi(close,14) <=50 and Volume_Direction > hp ? color.green : na
co1 = Volume_Direction> 0 and ta.rsi(close,14) <=50 and Volume_Direction > hp ? true : false
LO = ta.lowest(Volume_Direction, n)
Lp = LO[1]
cp = Volume_Direction<0 and ta.rsi(close,14) >=50 and Volume_Direction< Lp ? color.red : na
cp1 = Volume_Direction<0 and ta.rsi(close,14) >=50 and Volume_Direction< Lp ? true : false
//--------------------------------------------------------------------
// Plot 1
//--------------------------------------------------------------------
plot(-tch, color=color.red)
plot(tcl, color=color.green)
//--------------------------------------------------------------------
// Plot 2
//--------------------------------------------------------------------
plot(show?tcl:na, style=plot.style_columns, color=co)
plotshape(co1 and show?tcl:na, style=shape.triangleup, location=location.absolute, color=color.new(color.green, 0), size=size.small)
plot(show?-tch:na, style=plot.style_columns, color=cp)
plotshape(cp1 and show?-tch:na, style=shape.triangledown, location=location.absolute, color=color.new(color.red, 0), size=size.small)
|
candle count | https://www.tradingview.com/script/y0OkzTxk-candle-count/ | Shauryam_or | https://www.tradingview.com/u/Shauryam_or/ | 171 | 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/
// © Shauryam_or
//@version=5
indicator(title='candle count', overlay=true,max_labels_count=500)
//backtest engine
start = input.time(timestamp('2022-12-16'), title='Start calculations',group='Backtest Period')
end=input.time(timestamp('2025-03-01'), title='End calculations',group='Backtest Period')
time_cond = time >= start and time<=end
text_color=input.color(color.blue,title="Text Color Input")
numBars = 1
if time_cond
numBars := nz(numBars[1]) + 1
numBars
else
numBars := 0
numBars
label.new(bar_index, high, str.tostring(numBars), textcolor=text_color, style=label.style_none)
|
Channel Based Zigzag [HeWhoMustNotBeNamed] | https://www.tradingview.com/script/QWj7mtEF-Channel-Based-Zigzag-HeWhoMustNotBeNamed/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 455 | 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/
// © HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Channel Based Zigzag [HeWhoMustNotBeNamed]", "cZigzag", overlay=true)
import HeWhoMustNotBeNamed/ta/1 as eta
import HeWhoMustNotBeNamed/arrays/1 as pa
bandType = input.string('Bollinger Bands', '', ['Bollinger Bands', 'Keltner Channel', 'Donchian Channel'], group='Bands', inline='b1')
maType = input.string('sma', '', options=['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'highlow', 'linreg', 'median'], inline = 'b1', group='Bands')
maLength = input.int(20, '', minval = 5, step=5, inline = 'b1', group='Bands')
multiplier = input.float(2.0, '', step=0.5, minval=0.5, group='Bands', inline='b1', tooltip = 'Band parameters let you select type of band/channel, moving average base, length and multiplier')
useTrueRange = input.bool(true, 'Use True Range (For KC only)', group='Bands', tooltip = 'Used only for keltener channel calculation')
sticky = input.bool(true, 'Sticky', group='Bands', tooltip = 'Sticky bands avoids changing the band unless there is breach. Meaning, band positions only change when price is outside the band.')
showBands = input.bool(true, 'Display Bands', group='Bands', tooltip = 'If selected, displays bands on chart')
highlightBreakout = input.bool(false, 'Highlight Breakout Bars', group='Bands', tooltip = 'If selected, only breakout candles are highlighted. Rest of the candles will have silver color')
float upper = 0.0
float lower = 0.0
float middle = 0.0
type Pivot
float price
int bar
int bartime
int direction
unshift(zigzag, p)=>
if(array.size(zigzag) > 1)
llastPivot = array.get(zigzag, 1)
p.direction := p.price*p.direction > llastPivot.price*p.direction ? p.direction*2 : p.direction
array.unshift(zigzag, p)
if(array.size(zigzag)>15)
array.pop(zigzag)
if(bandType == 'Bollinger Bands')
[bmiddle, bupper, blower] = eta.bb(close, maType, maLength, multiplier, sticky)
upper := bupper
lower := blower
middle := bmiddle
if(bandType == 'Keltner Channel')
[kmiddle, kupper, klower] = eta.kc(close, maType, maLength, multiplier, useTrueRange, sticky)
upper := kupper
lower := klower
middle := kmiddle
if(bandType == 'Donchian Channel')
[dmiddle, dupper, dlower] = eta.dc(maLength, false, close, sticky)
upper := dupper
lower := dlower
middle := dmiddle
addPivot(zigzag, direction)=>
lastRemoved = false
price = direction > 0? high : low
Pivot p = Pivot.new(price, bar_index, time, int(direction))
if(array.size(zigzag) == 0)
unshift(zigzag, p)
else
lastPivot = array.get(zigzag, 0)
lastPivotDirection = math.sign(lastPivot.direction)
if (lastPivotDirection != p.direction)
unshift(zigzag, p)
if(lastPivotDirection == p.direction and lastPivot.price*direction < p.price*direction)
array.remove(zigzag, 0)
unshift(zigzag, p)
lastRemoved := true
lastRemoved
add_pivots(zigzag, pHigh, pLow)=>
count = 0
removeLast = false
if(array.size(zigzag) == 0)
if(pHigh)
addPivot(zigzag, 1)
count+=1
if(pLow)
addPivot(zigzag, -1)
count+=1
else
lastPivot = array.get(zigzag, 0)
lastDir = math.sign(lastPivot.direction)
if(pHigh and lastDir == 1) or (pLow and lastDir == -1)
removeLast := addPivot(zigzag, lastDir)
count := removeLast ? count+1 : count
if(pHigh and (lastDir == -1)) or (pLow and (lastDir == 1))
addPivot(zigzag, -lastDir)
count+=1
[count, removeLast]
draw_zigzag(zigzag, count, removeLast)=>
var zigzaglines = array.new<line>()
if(removeLast and array.size(zigzaglines) > 0)
pa.shift(zigzaglines)
if(array.size(zigzag) > count and count >= 1)
for i=count to 1
startPivot = array.get(zigzag, count)
endPivot = array.get(zigzag, count-1)
startDirection = startPivot.direction
endDirection = endPivot.direction
lineColor = endDirection == 2? color.green : endDirection == -2? color.red : color.silver
ln = line.new(startPivot.bartime, startPivot.price, endPivot.bartime, endPivot.price, xloc.bar_time, color=lineColor, width = 2)
pa.unshift(zigzaglines, ln, 500)
zigzaglines
var zigzag = array.new<Pivot>()
pHigh = high >= upper
pLow = low <= lower
[count, removeLast] = add_pivots(zigzag, pHigh, pLow)
barcolor(pHigh or pLow or not highlightBreakout? na : color.silver)
plot(showBands? upper:na, 'Upper', color.green, 0, plot.style_linebr)
plot(showBands? lower:na, 'Lower', color.red, 0, plot.style_linebr)
zigzaglines = draw_zigzag(zigzag, count, removeLast) |
RTH & ETH MAs [vnhilton] | https://www.tradingview.com/script/2NVn5fhz-RTH-ETH-MAs-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 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/
// © vnhilton
//@version=5
indicator("RTH & ETH MAs [vnhilton]", "RTHÐ MAs", true)
//RTH Timezone
rth = time(timeframe.period, session.regular, syminfo.timezone)
//Parameters
partialBBLinesToggle = input.bool(false, "Enable partial BB Convergence lines?", "If disabled, will show bollinger bands in its entirety. Enabled would show the upper/lower band if candle range is above/below basis line.")
ethToggle = input.bool(false, "ETH MAs on ETH only?")
ni1 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #1")
tf1 = input.timeframe("", "MA Timeframe", group="MA Pair #1")
src1 = input(close, "Source", group="MA Pair #1")
len1 = input.int(5, "MA Length", 1, group="MA Pair #1")
maType1 = input.string("WMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #1")
ni2 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #2")
tf2 = input.timeframe("", "MA Timeframe", group="MA Pair #2")
src2 = input(close, "Source", group="MA Pair #2")
len2 = input.int(10, "MA Length", 1, group="MA Pair #2")
maType2 = input.string("SMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #2")
ni3 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #3")
tf3 = input.timeframe("", "MA Timeframe", group="MA Pair #3")
src3 = input(close, "Source", group="MA Pair #3")
len3 = input.int(20, "MA Length", 1, group="MA Pair #3")
maType3 = input.string("SMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #3")
ni4 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #4")
tf4 = input.timeframe("", "MA Timeframe", group="MA Pair #4")
src4 = input(close, "Source", group="MA Pair #4")
len4 = input.int(50, "MA Length", 1, group="MA Pair #4")
maType4 = input.string("SMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #4")
ni5 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #5")
tf5 = input.timeframe("", "MA Timeframe", group="MA Pair #5")
src5 = input(close, "Source", group="MA Pair #5")
len5 = input.int(100, "MA Length", 1, group="MA Pair #5")
maType5 = input.string("SMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #5")
ni6 = input.bool(false, "Show on Non-Intraday Timeframes Only?", group = "MA Pair #6")
tf6 = input.timeframe("", "MA Timeframe", group="MA Pair #6")
src6 = input(close, "Source", group="MA Pair #6")
len6 = input.int(200, "MA Length", 1, group="MA Pair #6")
maType6 = input.string("SMA", "MA Type", ["EMA", "HMA", "RMA", "SMA", "SWMA", "VWMA", "WMA"], group="MA Pair #6")
mult1 = input.float(2, "Converging MA #1 STDDEV", 0, tooltip="For bollinger bands of converging MA", group="BB Parameters")
mult2 = input.float(2, "Converging MA #2 STDDEV", 0, group="BB Parameters")
mult3 = input.float(2, "Converging MA #3 STDDEV", 0, group="BB Parameters")
mult4 = input.float(2, "Converging MA #4 STDDEV", 0, group="BB Parameters")
mult5 = input.float(2, "Converging MA #5 STDDEV", 0, group="BB Parameters")
mult6 = input.float(2, "Converging MA #6 STDDEV", 0, group="BB Parameters")
//Moving Average (MA) Selection
ma(src, len, type) =>
switch type
"EMA" => ta.ema(src, len)
"HMA" => ta.hma(src, len)
"RMA" => ta.rma(src, len)
"SMA" => ta.sma(src, len)
"VWMA" => ta.vwma(src, len)
"WMA" => ta.wma(src, len)
//MA & BB Assignments
ma1 = ma(src1, len1, maType1)
[bb1M, bb1U, bb1L] = ta.bb(src1, len1, mult1)
ma2 = ma(src2, len2, maType2)
[bb2M, bb2U, bb2L] = ta.bb(src2, len2, mult2)
ma3 = ma(src3, len3, maType3)
[bb3M, bb3U, bb3L] = ta.bb(src3, len3, mult3)
ma4 = ma(src4, len4, maType4)
[bb4M, bb4U, bb4L] = ta.bb(src4, len4, mult4)
ma5 = ma(src5, len5, maType5)
[bb5M, bb5U, bb5L] = ta.bb(src5, len5, mult5)
ma6 = ma(src6, len6, maType6)
[bb6M, bb6U, bb6L] = ta.bb(src6, len6, mult6)
//RTH & ETH MAs
rthMA1 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf1, ma1, barmerge.gaps_on)
ethMA1 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf1, ma1, barmerge.gaps_on)
rthMA2 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf2, ma2, barmerge.gaps_on)
ethMA2 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf2, ma2, barmerge.gaps_on)
rthMA3 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf3, ma3, barmerge.gaps_on)
ethMA3 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf3, ma3, barmerge.gaps_on)
rthMA4 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf4, ma4, barmerge.gaps_on)
ethMA4 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf4, ma4, barmerge.gaps_on)
rthMA5 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf5, ma5, barmerge.gaps_on)
ethMA5 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf5, ma5, barmerge.gaps_on)
rthMA6 = request.security(ticker.modify(syminfo.tickerid, session.regular), tf6, ma6, barmerge.gaps_on)
ethMA6 = request.security(ticker.modify(syminfo.tickerid, session.extended), tf6, ma6, barmerge.gaps_on)
//Plots
rthPlot1 = plot(ni1 ? timeframe.isdwm ? rthMA1 : na : rth ? rthMA1 : na, "RTH MA #1", color=rthMA1 >= rthMA1[1] ? color.new(#002652, 52) : color.new(#002652, 51), style=plot.style_linebr, display=display.none)
ethPlot1 = plot(ni1 ? timeframe.isdwm ? ethMA1 : na : ethToggle ? rth ? na : ethMA1 : ethMA1, "ETH MA #1", ethMA1 >= ethMA1[1] ? color.new(#002652, 52) : color.new(#002652, 51), style=plot.style_linebr)
convPlot1 = plot(rth and rthMA1 == ethMA1 ? rthMA1 : na, "Convergence MA #1", color=color.new(#002652, 52), display=display.none)
convBandU1 = plot(rth and rthMA1 == ethMA1 ? not partialBBLinesToggle ? bb1U : high >= rthMA1 ? bb1U : na : na, "Convergence Upper BB #1", color.new(#002652, 75), style=plot.style_linebr, display=display.none)
convBandL1 = plot(rth and rthMA1 == ethMA1 ? not partialBBLinesToggle ? bb1L : low < rthMA1 ? bb1L : na : na, "Convergence Lower BB #1", color.new(#002652, 75), style=plot.style_linebr, display=display.none)
rthPlot2 = plot(ni2 ? timeframe.isdwm ? rthMA2 : na : rth ? rthMA2 : na, "RTH MA #2", color=rthMA2 >= rthMA2[1] ? color.new(#FFFF00, 0) : color.new(#FFFF00, 1), style=plot.style_linebr, display=display.none)
ethPlot2 = plot(ni2 ? timeframe.isdwm ? ethMA2 : na : ethToggle ? rth ? na : ethMA2 : ethMA2, "ETH MA #2", ethMA2 >= ethMA2[1] ? color.new(#FFFF00, 0) : color.new(#FFFF00, 1), style=plot.style_linebr)
convPlot2 = plot(rth and rthMA2 == ethMA2 ? rthMA2 : na, "Convergence MA #2", color=color.new(#FFFF00, 0), style=plot.style_linebr, display=display.none)
convBandU2 = plot(rth and rthMA2 == ethMA2 ? not partialBBLinesToggle ? bb2U : high >= rthMA2 ? bb2U : na : na, "Convergence Upper BB #2", color.new(#FFFF00, 75), style=plot.style_linebr, display=display.none)
convBandL2 = plot(rth and rthMA2 == ethMA2 ? not partialBBLinesToggle ? bb2L : low < rthMA2 ? bb2L : na : na, "Convergence Lower BB #2", color.new(#FFFF00, 75), style=plot.style_linebr, display=display.none)
rthPlot3 = plot(ni3 ? timeframe.isdwm ? rthMA3 : na : rth ? rthMA3 : na, "RTH MA #3", color=rthMA3 >= rthMA3[1] ? color.new(#00ff00, 0) : color.new(#00ff00, 1), style=plot.style_linebr, display=display.none)
ethPlot3 = plot(ni3 ? timeframe.isdwm ? ethMA3 : na : ethToggle ? rth ? na : ethMA3 : ethMA3, "ETH MA #3", ethMA3 >= ethMA3[1] ? color.new(#00ff00, 0) : color.new(#00ff00, 1), style=plot.style_linebr)
convPlot3 = plot(rth and rthMA3 == ethMA3 ? rthMA3 : na, "Convergence MA #3", color=color.new(#00ff00, 0), style=plot.style_linebr, display=display.none)
convBandU3 = plot(rth and rthMA3 == ethMA3 ? not partialBBLinesToggle ? bb3U : high >= rthMA3 ? bb3U : na : na, "Convergence Upper BB #3", color.new(#00ff00, 75), style=plot.style_linebr, display=display.none)
convBandL3 = plot(rth and rthMA3 == ethMA3 ? not partialBBLinesToggle ? bb3L : low < rthMA3 ? bb3L : na : na, "Convergence Lower BB #3", color.new(#00ff00, 75), style=plot.style_linebr, display=display.none)
rthPlot4 = plot(ni4 ? timeframe.isdwm ? rthMA4 : na : rth ? rthMA4 : na, "RTH MA #4", color=rthMA4 >= rthMA4[1] ? color.new(#3029ff, 0) : color.new(#3029ff, 1), style=plot.style_linebr, display=display.none)
ethPlot4 = plot(ni4 ? timeframe.isdwm ? ethMA4 : na : ethToggle ? rth ? na : ethMA4 : ethMA4, "ETH MA #4", ethMA4 >= ethMA4[1] ? color.new(#3029ff, 0) : color.new(#3029ff, 1), style=plot.style_linebr)
convPlot4 = plot(rth and rthMA4 == ethMA4 ? rthMA4 : na, "Convergence MA #4", color=color.new(#3029ff, 0), style=plot.style_linebr, display=display.none)
convBandU4 = plot(rth and rthMA4 == ethMA4 ? not partialBBLinesToggle ? bb4U : high >= rthMA4 ? bb4U : na : na, "Convergence Upper BB #4", color.new(#3029ff, 75), style=plot.style_linebr, display=display.none)
convBandL4 = plot(rth and rthMA4 == ethMA4 ? not partialBBLinesToggle ? bb4L : low < rthMA4 ? bb4L : na : na, "Convergence Lower BB #4", color.new(#3029ff, 75), style=plot.style_linebr, display=display.none)
rthPlot5 = plot(ni5 ? timeframe.isdwm ? rthMA5 : na : rth ? rthMA5 : na, "RTH MA #5", color=rthMA5 >= rthMA5[1] ? color.new(#8229ff, 0) : color.new(#8229ff, 1), style=plot.style_linebr, display=display.none)
ethPlot5 = plot(ni5 ? timeframe.isdwm ? ethMA5 : na : ethToggle ? rth ? na : ethMA5 : ethMA5, "ETH MA #5", ethMA5 >= ethMA5[1] ? color.new(#8229ff, 0) : color.new(#8229ff, 1), style=plot.style_linebr)
convPlot5 = plot(rth and rthMA5 == ethMA5 ? rthMA5 : na, "Convergence MA #5", color=color.new(#8229ff, 0), style=plot.style_linebr, display=display.none)
convBandU5 = plot(rth and rthMA5 == ethMA5 ? not partialBBLinesToggle ? bb5U : high >= rthMA5 ? bb5U : na : na, "Convergence Upper BB #5", color.new(#8229ff, 75), style=plot.style_linebr, display=display.none)
convBandL5 = plot(rth and rthMA5 == ethMA5 ? not partialBBLinesToggle ? bb5L : low < rthMA5 ? bb5L : na : na, "Convergence Lower BB #5", color.new(#8229ff, 75), style=plot.style_linebr, display=display.none)
rthPlot6 = plot(ni6 ? timeframe.isdwm ? rthMA6 : na : rth ? rthMA6 : na, "RTH MA #6", color=rthMA6 >= rthMA6[1] ? color.new(#ff00e8, 0) : color.new(#ff00e8, 1), style=plot.style_linebr, display=display.none)
ethPlot6 = plot(ni6 ? timeframe.isdwm ? ethMA6 : na : ethToggle ? rth ? na : ethMA6 : ethMA6, "ETH MA #6", ethMA6 >= ethMA6[1] ? color.new(#ff00e8, 0) : color.new(#ff00e8, 1), style=plot.style_linebr)
convPlot6 = plot(rth and rthMA6 == ethMA6 ? rthMA6 : na, "Convergence MA #6", color=color.new(#ff00e8, 0), style=plot.style_linebr, display=display.none)
convBandU6 = plot(rth and rthMA6 == ethMA6 ? not partialBBLinesToggle ? bb6U : high >= rthMA6 ? bb6U : na : na, "Convergence Upper BB #6", color.new(#ff00e8, 75), style=plot.style_linebr, display=display.none)
convBandL6 = plot(rth and rthMA6 == ethMA6 ? not partialBBLinesToggle ? bb6L: low < rthMA6 ? bb6L : na : na, "Convergence Lower BB #6", color.new(#ff00e8, 75), style=plot.style_linebr, display=display.none) |
Igniting Candles | https://www.tradingview.com/script/JrlQACnm-Igniting-Candles/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 111 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © syntaxgeek
//@version=5
indicator("Igniting Candles", shorttitle="Igniters", overlay=true, max_labels_count=500)
// <inputs>
i_strengthFilter = input.float(2.5, 'Strength Filter', minval=0.5, step=0.1, tooltip='Set to desired strength of ignition for display.', group='Basic')
i_avgVolumeMode = input.bool(false, 'Use average volume?', 'Sets current candle volume comparision against previous average or not.', inline='Average', group='Average Mode')
i_avgVolumeType = input.string('HMA', '', options=["SMA", "EMA", "SMMA (RMA)", "WMA", "HMA", "DEMA", "TEMA", "ZLEMA"])
i_avgVolumeModeBarPeriod = input.int(20, 'Lookback period', minval=2, step=1, group='Average Mode', tooltip='Only applies to average volume mode.')
i_icon = input.string('🚀', 'Icon', options=['🚀', '🧨', '🎆', '💥', '💣', '✨'], group='Style')
i_labelBgColor = input.color(color.white, title='Label Color', inline='Label', group='Style')
i_labelTextColor = input.color(color.black, title='Label Text Color', inline='Label', group='Style')
// </inputs>
// <consts>
v_y1 = low - (ta.atr(30) * 2)
v_y1B = low - ta.atr(30)
v_y2 = high + (ta.atr(30) * 2)
v_y2B = high + ta.atr(30)
// </consts>
// <funcs>
f_zlema(source, length) =>
v_lag = math.round((length - 1) / 2)
v_emaData = source + (source - source[v_lag])
ta.ema(v_emaData, length)
f_dema(source, length) =>
v_ema1 = ta.ema(source, length)
(2 * v_ema1) - ta.ema(v_ema1, length)
f_tema(source, length) =>
v_ema1 = ta.ema(source, length)
v_ema2 = ta.ema(v_ema1, length)
v_ema3 = ta.ema(v_ema2, length)
(3 * v_ema1) - (3 * v_ema2) + v_ema3
f_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)
"HMA" => ta.hma(source, length)
"DEMA" => f_dema(source, length)
"TEMA" => f_tema(source, length)
"ZLEMA" => f_zlema(source, length)
f_newLabel(_text, _bias) =>
v_labelColor = color.green
v_labelTextColor = color.white
v_labelPosition = v_y1
v_labelStyle = label.style_label_up
if _bias == 'bullish'
v_labelColor := color.green
v_labelPosition := v_y1
v_labelTextColor := color.white
v_labelStyle := label.style_label_up
else if _bias == 'bearish'
v_labelColor := color.red
v_labelPosition := v_y2
v_labelTextColor := color.white
v_labelStyle := label.style_label_down
else if _bias == 'neutral'
v_direction = close[1] > close
v_labelColor := color.white
v_labelPosition := v_direction ? v_y2 : v_y1
v_labelTextColor := color.black
v_labelStyle := v_direction ? label.style_label_down : label.style_label_up
label.new(bar_index, v_labelPosition, _text, xloc.bar_index, yloc.price, i_labelBgColor, v_labelStyle, i_labelTextColor)
// </funcs>
// <vars>
v_volDiff = 0.0
v_hasCandleIgnited = false
if not i_avgVolumeMode
v_volDiff := volume / volume[1]
v_hasCandleIgnited := v_volDiff >= i_strengthFilter
else
v_avgVolume = f_ma(volume, i_avgVolumeModeBarPeriod, i_avgVolumeType)
v_volDiff := volume / v_avgVolume
v_hasCandleIgnited := v_volDiff >= i_strengthFilter
// </vars>
// <plots>
plotchar(v_volDiff, 'Vol Diff', display=display.data_window, editable=false)
plotchar(v_hasCandleIgnited, 'Candle Ignited', display=display.data_window, editable=false)
if v_hasCandleIgnited
f_newLabel(i_icon + ' (' + str.tostring(v_volDiff, '#.#') + ')', 'neutral')
// </plots>
// <alerts>
if v_hasCandleIgnited
alert(i_icon + ' (' + str.tostring(v_volDiff, '#.#') + ')', alert.freq_once_per_bar_close)
// <alerts> |
VF-ST-EMA-CPR | https://www.tradingview.com/script/tv9PAzPc-VF-ST-EMA-CPR/ | deepphalke | https://www.tradingview.com/u/deepphalke/ | 90 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © deepphalke
//@version=5
indicator(title='VF-ST-EMA-CPR', overlay=true)
//supertend
factor = input.int(3, title="SuperTrend Factor")
atrP = input.int(10, title="SuperTrend atrPeriod")
[superTrend, direction] = ta.supertrend(factor, atrP)
sclr = direction > 0 ? color.red : color.green
plot(superTrend, title='SuperTrend', color=sclr)
//EMA
emaP = input.int(31, title="EMA length")
srcEma = input.source(high,"EMA source")
plot(ta.ema(srcEma,emaP))
//Volatality and Fibbonacci trade table
showTable=input(true, title="Show VF Table")
res = 'D'
test1=0
f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src, barmerge.gaps_off) // orignal code line
dc = f_secureSecurity(syminfo.tickerid, res, close[1+test1])
dc1 = f_secureSecurity(syminfo.tickerid, res, close[2+test1])
dc2 = f_secureSecurity(syminfo.tickerid, res, close[3+test1])
dc3 = f_secureSecurity(syminfo.tickerid, res, close[4+test1])
dc4 = f_secureSecurity(syminfo.tickerid, res, close[5+test1])
dc5 = f_secureSecurity(syminfo.tickerid, res, close[6+test1])
dc6 = f_secureSecurity(syminfo.tickerid, res, close[7+test1])
dc7 = f_secureSecurity(syminfo.tickerid, res, close[8+test1])
dc8 = f_secureSecurity(syminfo.tickerid, res, close[9+test1])
dc9 = f_secureSecurity(syminfo.tickerid, res, close[10+test1])
dc10 = f_secureSecurity(syminfo.tickerid, res, close[11+test1])
dop = f_secureSecurity(syminfo.tickerid, res, open)
logg00 = math.log(dc/dc1)
logg11 = math.log(dc1/dc2)
logg22 = math.log(dc2/dc3)
logg33 = math.log(dc3/dc4)
logg44 = math.log(dc4/dc5)
logg55 = math.log(dc5/dc6)
logg66 = math.log(dc6/dc7)
logg77 = math.log(dc7/dc8)
logg88 = math.log(dc8/dc9)
logg99 = math.log(dc9/dc10)
squrr00 = logg00*logg00
squrr11 = logg11*logg11
squrr22 = logg22*logg22
squrr33 = logg33*logg33
squrr44 = logg44*logg44
squrr55 = logg55*logg55
squrr66 = logg66*logg66
squrr77 = logg77*logg77
squrr88 = logg88*logg88
squrr99 = logg99*logg99
avg_logg0 = (logg00+logg11+logg22+logg33+logg44+logg55+logg66+logg77+logg88+logg99)/10
avg_squrr0 = (squrr00+squrr11+squrr22+squrr33+squrr44+squrr55+squrr66+squrr77+squrr88+squrr99)/10
variancee0 = avg_squrr0 - (avg_logg0*avg_logg0)
volatility0 = math.sqrt(variancee0)
round_preci=input.int(title="VF Decimal Scale", options=[0,1,2,3], defval=0)
range11=math.round(dc*volatility0,round_preci)
doKdc= math.abs(dop-dc)>(0.382*range11)? dop : dc
//re-do calc
logg = math.log(doKdc/dc1)
logg1 = math.log(dc1/dc2)
logg2 = math.log(dc2/dc3)
logg3 = math.log(dc3/dc4)
logg4 = math.log(dc4/dc5)
logg5 = math.log(dc5/dc6)
logg6 = math.log(dc6/dc7)
logg7 = math.log(dc7/dc8)
logg8 = math.log(dc8/dc9)
logg9 = math.log(dc9/dc10)
squrr = logg*logg
squrr1 = logg1*logg1
squrr2 = logg2*logg2
squrr3 = logg3*logg3
squrr4 = logg4*logg4
squrr5 = logg5*logg5
squrr6 = logg6*logg6
squrr7 = logg7*logg7
squrr8 = logg8*logg8
squrr9 = logg9*logg9
avg_logg = (logg+logg1+logg2+logg3+logg4+logg5+logg6+logg7+logg8+logg9)/10
avg_squrr = (squrr+squrr1+squrr2+squrr3+squrr4+squrr5+squrr6+squrr7+squrr8+squrr9)/10
variancee = avg_squrr - (avg_logg*avg_logg)
volatility = math.sqrt(variancee)
range1=math.round(doKdc*volatility,round_preci)
//doKdc=dc
buy_above=math.round(doKdc+(range1 * 0.236),round_preci)
buy_conf=math.round(doKdc+(range1 * 0.382),round_preci)
b_t1=math.round(doKdc+(range1 * 0.5),round_preci)
b_t2=math.round(doKdc+(range1 * 0.618),round_preci)
b_t3=math.round(doKdc+(range1 * 0.786),round_preci)
b_t4=math.round(doKdc+(range1 * 0.888),round_preci)
b_t5=math.round(doKdc+(range1 * 1.236),round_preci)
b_t6=math.round(doKdc+(range1 * 1.618),round_preci)
sell_below=math.round(doKdc-(range1 * 0.236),round_preci)
sell_conf=math.round(doKdc-(range1 * 0.382),round_preci)
s_t1=math.round(doKdc-(range1 * 0.5),round_preci)
s_t2=math.round(doKdc-(range1 * 0.618),round_preci)
s_t3=math.round(doKdc-(range1 * 0.786),round_preci)
s_t4=math.round(doKdc-(range1 * 0.888),round_preci)
s_t5=math.round(doKdc-(range1 * 1.236),round_preci)
s_t6=math.round(doKdc-(range1 * 1.618),round_preci)
sizeOption = input.string(title="VF Text Size",
options=["Normal", "Small"],
defval="Small")
txtSize= (sizeOption == "Small") ? size.small : size.normal
//BUY/Sell confirmation line
// Today's Session Start timestamp
y = year(timenow)
m = month(timenow)
d = dayofmonth(timenow)
// Start & End time for
showLineOnSameDay=input(true, title="Show VF Lines on same Day")
dd=showLineOnSameDay?d:d+1
start = timestamp(y, m, dd, 09, 15)
end = start + 86400000
tom_start = start
tom_end = end
colorLabl=input.color(color.black,"VF Label Text color")
var lbl1 = label.new(na, na, "Buy Conf", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl )
var lbl2 = label.new(na, na, "Sell Conf", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl3 = label.new(na, na, "T1", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl4 = label.new(na, na, "T2", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl5 = label.new(na, na, "T3", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl6 = label.new(na, na, "T4", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl7 = label.new(na, na, "T5", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl8 = label.new(na, na, "T6", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl9 = label.new(na, na, "T1", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl10 = label.new(na, na, "T2", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl11 = label.new(na, na, "T3", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl12 = label.new(na, na, "T4", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl13 = label.new(na, na, "T5", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl14 = label.new(na, na, "T6", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl15 = label.new(na, na, "Buy Above", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
var lbl16 = label.new(na, na, "Sell below", color = color(na), style = label.style_label_left,size = txtSize, textcolor = colorLabl)
colorBuy=input.color(color.green,"Buy Above Lines color")
colorSell=input.color(color.red,"Sell Below Lines color")
var lin1 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy, width = 2)
var lin2 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell, width = 2)
var lin3 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin4 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin5 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin6 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin7 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin8 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin9 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin10 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin11 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin12 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin13 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin14 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
var lin15 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorBuy)
var lin16 = line.new(na, na, na, na, xloc = xloc.bar_time, style = line.style_solid,color=colorSell)
//Buy_Conf_lvl
line.set_xy1(lin1, tom_start, buy_conf)
line.set_xy2(lin1, tom_end,buy_conf)
label.set_xy(lbl1, bar_index, buy_conf)
//Sell_Conf_lvl
line.set_xy1(lin2, tom_start, sell_conf)
line.set_xy2(lin2, tom_end,sell_conf)
label.set_xy(lbl2, bar_index, sell_conf)
//T1
line.set_xy1(lin3, tom_start, b_t1)
line.set_xy2(lin3, tom_end,b_t1)
label.set_xy(lbl3, bar_index, b_t1)
//T2
line.set_xy1(lin4, tom_start, b_t2)
line.set_xy2(lin4, tom_end,b_t2)
label.set_xy(lbl4, bar_index, b_t2)
//T3
line.set_xy1(lin5, tom_start, b_t3)
line.set_xy2(lin5, tom_end,b_t3)
label.set_xy(lbl5, bar_index, b_t3)
//T4
line.set_xy1(lin6, tom_start, b_t4)
line.set_xy2(lin6, tom_end,b_t4)
label.set_xy(lbl6, bar_index, b_t4)
//T5
line.set_xy1(lin7, tom_start, b_t5)
line.set_xy2(lin7, tom_end,b_t5)
label.set_xy(lbl7, bar_index, b_t5)
//T6
line.set_xy1(lin8, tom_start, b_t6)
line.set_xy2(lin8, tom_end,b_t6)
label.set_xy(lbl8, bar_index, b_t6)
//S1
line.set_xy1(lin9, tom_start, s_t1)
line.set_xy2(lin9, tom_end,s_t1)
label.set_xy(lbl9, bar_index, s_t1)
//S2
line.set_xy1(lin10, tom_start, s_t2)
line.set_xy2(lin10, tom_end,s_t2)
label.set_xy(lbl10, bar_index, s_t2)
//S3
line.set_xy1(lin11, tom_start, s_t3)
line.set_xy2(lin11, tom_end,s_t3)
label.set_xy(lbl11, bar_index, s_t3)
//S4
line.set_xy1(lin12, tom_start, s_t4)
line.set_xy2(lin12, tom_end,s_t4)
label.set_xy(lbl12, bar_index, s_t4)
//S5
line.set_xy1(lin13, tom_start, s_t5)
line.set_xy2(lin13, tom_end,s_t5)
label.set_xy(lbl13, bar_index, s_t5)
//S6
line.set_xy1(lin14, tom_start, s_t6)
line.set_xy2(lin14, tom_end,s_t6)
label.set_xy(lbl14, bar_index, s_t6)
//Buy Above
line.set_xy1(lin15, tom_start, buy_above)
line.set_xy2(lin15, tom_end,buy_above)
label.set_xy(lbl15, bar_index, buy_above)
//Sell Below
line.set_xy1(lin16, tom_start, sell_below)
line.set_xy2(lin16, tom_end,sell_below)
label.set_xy(lbl16, bar_index, sell_below)
color_g=#e6fce8
coor_r=#fce6ea
color_n=#bab8b8
color_rg=#ebe6ea
color_wh=color.white
txt_color_r=#f50a19
txt_color_g=#039458
plotVF = timeframe.period == 'D' or timeframe.period == '120'or timeframe.period == '120' or timeframe.period == '60' or timeframe.period == '15' or timeframe.period == '30'
or timeframe.period == '5' or timeframe.period == '3' or timeframe.period == '180'or timeframe.period == '240'
trendingTimes="T4,T5,T6: On trending Times"
NormalTargets="T2,T3: Normal Targets"
tableToolTip="This table works well in a Trending Markets; in sideways market use it as Support and Resistance"
var testTable = table.new(position = position.bottom_right, columns = 9, rows = 3, bgcolor = color.yellow, border_width = 1, border_color=color.white)
if barstate.islast and plotVF and showTable
table.cell(table_id = testTable, column = 1, row = 0, text = "^/v " ,text_size=txtSize,tooltip="Above/Below")
table.cell(table_id = testTable, column = 2, row = 0, text = "Conf ", bgcolor=color.green,text_size=txtSize,tooltip="Confirmation")
table.cell(table_id = testTable, column = 3, row = 0, text = "T1 ", bgcolor=color_wh,text_size=txtSize)
table.cell(table_id = testTable, column = 4, row = 0, text = "T2 ", bgcolor=color.gray,text_size=txtSize,tooltip=NormalTargets)
table.cell(table_id = testTable, column = 5, row = 0, text = "T3 ", bgcolor=color.gray,text_size=txtSize,tooltip=NormalTargets)
table.cell(table_id = testTable, column = 6, row = 0, text = "T4 ", bgcolor=color.green,text_size=txtSize,tooltip=trendingTimes)
table.cell(table_id = testTable, column = 7, row = 0, text = "T5 ", bgcolor=color.green,text_size=txtSize,tooltip=trendingTimes)
table.cell(table_id = testTable, column = 8, row = 0, text = "T6 ", bgcolor=color.green,text_size=txtSize,tooltip=trendingTimes)
table.cell(table_id = testTable, column = 0, row = 0, text = "VF Table", bgcolor=color.white, text_size=txtSize,tooltip=tableToolTip)
table.cell(table_id = testTable, column = 0, row = 1, text = "For Buy Above ", bgcolor=color.green ,text_size=txtSize)
table.cell(table_id = testTable, column = 0, row = 2, text = "For Sell Below ", bgcolor=color.orange ,text_size=txtSize)
table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(buy_above), bgcolor=color_g ,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 2, row = 1, text = str.tostring(buy_conf), bgcolor=color_g,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 3, row = 1, text = str.tostring(b_t1), bgcolor=color_wh,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 4, row = 1, text = str.tostring(b_t2), bgcolor=color_n,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 5, row = 1, text = str.tostring(b_t3), bgcolor=color_n,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 6, row = 1, text = str.tostring(b_t4), bgcolor=color_g,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 7, row = 1, text = str.tostring(b_t5), bgcolor=color_g,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 8, row = 1, text = str.tostring(b_t6), bgcolor=color_g,text_size=txtSize, text_color=txt_color_r)
table.cell(table_id = testTable, column = 1, row = 2, text = str.tostring(sell_below) , bgcolor=coor_r,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 2, row = 2, text = str.tostring(sell_conf), bgcolor=coor_r,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 3, row = 2, text = str.tostring(s_t1), bgcolor=color_wh,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 4, row = 2, text = str.tostring(s_t2), bgcolor=color_rg,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 5, row = 2, text = str.tostring(s_t3), bgcolor=color_rg,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 6, row = 2, text = str.tostring(s_t4), bgcolor=coor_r,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 7, row = 2, text = str.tostring(s_t5), bgcolor=coor_r,text_size=txtSize,text_color=txt_color_g)
table.cell(table_id = testTable, column = 8, row = 2, text = str.tostring(s_t6), bgcolor=coor_r,text_size=txtSize,text_color=txt_color_g)
tf = timeframe.isintraday ? "D" : "W"
d_high = f_secureSecurity(syminfo.tickerid, tf, high[1+test1])
d_low = f_secureSecurity(syminfo.tickerid, tf, low[1+test1])
d_close = f_secureSecurity(syminfo.tickerid, tf, close[1+test1])
pivot = (d_high + d_low + d_close)/3
BC = (d_high + d_low)/2
TC = (pivot - BC) + pivot
R1 = (pivot * 2) - d_low
R2 = pivot + (d_high-d_low)
S1 = (pivot * 2) - d_high
S2 = pivot - (d_high-d_low)
var testPTable = table.new(position = position.top_right, columns = 8, rows = 2, bgcolor = color.yellow, border_width = 1, border_color=color.white)
table.cell(table_id = testPTable, column = 0, row = 0, text = "S2 ",text_size=txtSize )
table.cell(table_id = testPTable, column = 1, row = 0, text = "S1 ",text_size=txtSize )
table.cell(table_id = testPTable, column = 2, row = 0, text = "Pivot" ,text_size=txtSize)
table.cell(table_id = testPTable, column = 3, row = 0, text = "R1 ",text_size=txtSize )
table.cell(table_id = testPTable, column = 4, row = 0, text = "R2",text_size=txtSize )
table.cell(table_id = testPTable, column = 5, row = 0, text = "BC",text_size=txtSize )
table.cell(table_id = testPTable, column = 6, row = 0, text = "TC",text_size=txtSize )
table.cell(table_id = testPTable, column = 7, row = 0, text = "Range",text_size=txtSize )
table.cell(table_id = testPTable, column = 0, row = 1, text = str.tostring(math.round(S2,round_preci)) ,bgcolor=color.green,text_size=txtSize)
table.cell(table_id = testPTable, column = 1, row = 1, text = str.tostring(math.round(S1,round_preci)), bgcolor=color.green,text_size=txtSize )
table.cell(table_id = testPTable, column = 2, row = 1, text = str.tostring(math.round(pivot,round_preci)) ,text_size=txtSize)
table.cell(table_id = testPTable, column = 3, row = 1, text = str.tostring(math.round(R1,round_preci)) , bgcolor=color.orange,text_size=txtSize )
table.cell(table_id = testPTable, column = 4, row = 1, text = str.tostring(math.round(R2,round_preci)) , bgcolor=color.orange,text_size=txtSize )
table.cell(table_id = testPTable, column = 5, row = 1, text = str.tostring(math.round(BC,round_preci)) , bgcolor=color.green,text_size=txtSize )
table.cell(table_id = testPTable, column = 6, row = 1, text = str.tostring(math.round(TC,round_preci)) , bgcolor=color.green,text_size=txtSize )
table.cell(table_id = testPTable, column = 7, row = 1, text = str.tostring(math.round((TC-BC),round_preci+1)) , bgcolor=color.orange,text_size=txtSize )
|
Regime Filter [CHE] | https://www.tradingview.com/script/YnD9Hh28/ | chervolino | https://www.tradingview.com/u/chervolino/ | 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/
// © chervolino
//@version=5
indicator("Regime Filter [CHE]", "Regime Filter [CHE]", timeframe="", overlay = true)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
length = input(50)
sig_length = input(9,'Signal Length')
//-----------------------------------------------------------------------------}
// Exponential Envelopes
//-----------------------------------------------------------------------------{
var a1 = 2/(length+1)
var u1_1 = 0.,var u1_2 = 0.
var d1_1 = 0.,var d1_2 = 0.
u1_1 := nz(math.max(close, open, u1_1[1] - (u1_1[1] - close) * a1), close)
u1_2 := nz(math.max(close * close, open * open, u1_2[1] - (u1_2[1] - close * close) * a1), close * close)
d1_1 := nz(math.min(close, open, d1_1[1] + (close - d1_1[1]) * a1), close)
d1_2 := nz(math.min(close * close, open * open, d1_2[1] + (close * close - d1_2[1]) * a1), close * close)
//Components
bl = math.sqrt(d1_2 - d1_1 * d1_1)
br = math.sqrt(u1_2 - u1_1 * u1_1)
signal = ta.ema(math.max(bl, br), sig_length)
osc_color = (100 * (bl - br) / br) > 0 ?color.yellow :color.blue
plotshape(true , 'line', shape.circle , location.bottom, osc_color, show_last=233, size=size.tiny) |
WR - BC Identifier | https://www.tradingview.com/script/dOmlAmFZ-WR-BC-Identifier/ | wrpteam2020 | https://www.tradingview.com/u/wrpteam2020/ | 58 | 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/
// © wrtech2020
//@version=4
study("BC Identifier", overlay = true)
C_Body = abs(close - open)
C_Bullish = close > open
C_Bearish = close < open
BC_Bull = C_Bullish and C_Body > C_Body[20] and C_Body > C_Body[19] and C_Body > C_Body[18] and C_Body > C_Body[17] and C_Body > C_Body[16] and C_Body > C_Body[15]and C_Body > C_Body[14] and C_Body > C_Body[13] and C_Body > C_Body[12] and C_Body > C_Body[11] and C_Body > C_Body[10] and C_Body > C_Body[9] and C_Body > C_Body[8] and C_Body > C_Body[7] and C_Body > C_Body[6] and C_Body > C_Body[5]and C_Body > C_Body[4] and C_Body > C_Body[3] and C_Body > C_Body[2] and C_Body > C_Body[1] and barstate.isconfirmed
BC_Bear = C_Bearish and C_Body > C_Body[20] and C_Body > C_Body[19] and C_Body > C_Body[18] and C_Body > C_Body[17] and C_Body > C_Body[16] and C_Body > C_Body[15]and C_Body > C_Body[14] and C_Body > C_Body[13] and C_Body > C_Body[12] and C_Body > C_Body[11] and C_Body > C_Body[10] and C_Body > C_Body[9] and C_Body > C_Body[8] and C_Body > C_Body[7] and C_Body > C_Body[6] and C_Body > C_Body[5]and C_Body > C_Body[4] and C_Body > C_Body[3] and C_Body > C_Body[2] and C_Body > C_Body[1] and barstate.isconfirmed
// Plot Bull Setup
plotshape(
BC_Bull,
title="BC Bull",
text=" BC ",
style=shape.labelup,
location=location.belowbar,
color=color.green,
textcolor=color.white
)
// Plot Bull Setup
plotshape(
BC_Bear,
title="BC Bear",
text=" BC ",
style=shape.labeldown,
location=location.abovebar,
color=color.red,
textcolor=color.white
) |
Volatility Adjusted EMA (VAEMA) | https://www.tradingview.com/script/V6vU98ia-Volatility-Adjusted-EMA-VAEMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Volatility Adjusted EMA", "VAEMA", overlay = true)
// function to calculate the exponential moving average
ema(src, len, a) => //{
alpha = a / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
// function to calculate the EMA with a variable alpha
ema_var_alpha(data, length, a, direction) =>
// calculate the volatility of the data
vol = ta.stdev(data, int(length))
// set the alpha value to be inversely proportional to the volatility
alpha = direction ? a / vol : a * vol
// calculate the EMA using the alpha value
ema(data, length, alpha)
source = input.source(close, "Source")
length = input.int(50, "Length")
alpha = input.float(1, "Alpha", 0.1, step = 0.05)
direction = input.bool(false, "Invert Alpha")
plot(ema_var_alpha(source, length, alpha, direction))
|
Portfolio Chart by fonoto | https://www.tradingview.com/script/GyFgZhmL-Portfolio-Chart-by-fonoto/ | copperneo | https://www.tradingview.com/u/copperneo/ | 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/
// © fonoto
//@version=5
indicator(title = "Portfolio Chart by fonoto", shorttitle = "Portfolio Chart", overlay=true)
paletteColor = close >= open ? color.rgb(33, 126, 103, 11) : color.rgb(250, 61, 67)
//Default stocks and quantities.
stock1Symbol = input("NSE:MARUTI", "1. Symbol", "", "Stock1", "Stocks")
stock1Quantity = input("2", "Quantity", "", "Stock1", "Stocks")
stock2Symbol = input("NSE:HDFCBANK", "2. Symbol", "", "Stock2", "Stocks")
stock2Quantity = input("11", "Quantity", "", "Stock2", "Stocks")
stock3Symbol = input("NSE:RELIANCE", "3. Symbol", "", "Stock3", "Stocks")
stock3Quantity = input("7", "Quantity", "", "Stock3", "Stocks")
stock4Symbol = input("NSE:INFY", "4. Symbol", "", "Stock4", "Stocks")
stock4Quantity = input("12", "Quantity", "", "Stock4", "Stocks")
stock5Symbol = input("NSE:HINDALCO", "5. Symbol", "", "Stock5", "Stocks")
stock5Quantity = input("40", "Quantity", "", "Stock5", "Stocks")
stock6Symbol = input("NSE:TITAN", "6. Symbol", "", "Stock6", "Stocks")
stock6Quantity = input("7", "Quantity", "", "Stock6", "Stocks")
stock7Symbol = input("NSE:HINDUNILVR", "7. Symbol", "", "Stock7", "Stocks")
stock7Quantity = input("6", "Quantity", "", "Stock7", "Stocks")
stock8Symbol = input("NSE:SUNPHARMA", "8. Symbol", "", "Stock8", "Stocks")
stock8Quantity = input("18", "Quantity", "", "Stock8", "Stocks")
stock9Symbol = input("NSE:DLF", "9. Symbol", "", "Stock9", "Stocks")
stock9Quantity = input("45", "Quantity", "", "Stock9", "Stocks")
stock10Symbol = input("NSE:ZEEL", "10. Symbol", "", "Stock10", "Stocks")
stock10Quantity = input("70", "Quantity", "", "Stock10", "Stocks")
//Divide the portfolio value by this factor so Y-Axis is offset with main chart to compare.
divideFactor = input("10", "Divide Factor", "", "DivideFactor", "Offset")
//Get Open, High, Low, Close prices of stocks.
stock1Open = request.security(stock1Symbol, "", open)
stock1High = request.security(stock1Symbol, "", high)
stock1Low = request.security(stock1Symbol, "", low)
stock1Close = request.security(stock1Symbol, "", close)
stock2Open = request.security(stock2Symbol, "", open)
stock2High = request.security(stock2Symbol, "", high)
stock2Low = request.security(stock2Symbol, "", low)
stock2Close = request.security(stock2Symbol, "", close)
stock3Open = request.security(stock3Symbol, "", open)
stock3High = request.security(stock3Symbol, "", high)
stock3Low = request.security(stock3Symbol, "", low)
stock3Close = request.security(stock3Symbol, "", close)
stock4Open = request.security(stock4Symbol, "", open)
stock4High = request.security(stock4Symbol, "", high)
stock4Low = request.security(stock4Symbol, "", low)
stock4Close = request.security(stock4Symbol, "", close)
stock5Open = request.security(stock5Symbol, "", open)
stock5High = request.security(stock5Symbol, "", high)
stock5Low = request.security(stock5Symbol, "", low)
stock5Close = request.security(stock5Symbol, "", close)
stock6Open = request.security(stock6Symbol, "", open)
stock6High = request.security(stock6Symbol, "", high)
stock6Low = request.security(stock6Symbol, "", low)
stock6Close = request.security(stock6Symbol, "", close)
stock7Open = request.security(stock7Symbol, "", open)
stock7High = request.security(stock7Symbol, "", high)
stock7Low = request.security(stock7Symbol, "", low)
stock7Close = request.security(stock7Symbol, "", close)
stock8Open = request.security(stock8Symbol, "", open)
stock8High = request.security(stock8Symbol, "", high)
stock8Low = request.security(stock8Symbol, "", low)
stock8Close = request.security(stock8Symbol, "", close)
stock9Open = request.security(stock9Symbol, "", open)
stock9High = request.security(stock9Symbol, "", high)
stock9Low = request.security(stock9Symbol, "", low)
stock9Close = request.security(stock9Symbol, "", close)
stock10Open = request.security(stock10Symbol, "", open)
stock10High = request.security(stock10Symbol, "", high)
stock10Low = request.security(stock10Symbol, "", low)
stock10Close = request.security(stock10Symbol, "", close)
//Calculate portfolio value for Open, High, Low, Close prices.
porfolioOpen = ((str.tonumber(stock1Quantity) * stock1Open) + (str.tonumber(stock2Quantity) * stock2Open) + (str.tonumber(stock3Quantity) * stock3Open) + (str.tonumber(stock4Quantity) * stock4Open) + (str.tonumber(stock5Quantity) * stock5Open) + (str.tonumber(stock6Quantity) * stock6Open) + (str.tonumber(stock7Quantity) * stock7Open) + (str.tonumber(stock8Quantity) * stock8Open) + (str.tonumber(stock9Quantity) * stock9Open) + (str.tonumber(stock10Quantity) * stock10Open)) / str.tonumber(divideFactor)
porfolioHigh = ((str.tonumber(stock1Quantity) * stock1High) + (str.tonumber(stock2Quantity) * stock2High) + (str.tonumber(stock3Quantity) * stock3High) + (str.tonumber(stock4Quantity) * stock4High) + (str.tonumber(stock5Quantity) * stock5High) + (str.tonumber(stock6Quantity) * stock6High) + (str.tonumber(stock7Quantity) * stock7High) + (str.tonumber(stock8Quantity) * stock8High) + (str.tonumber(stock9Quantity) * stock9High) + (str.tonumber(stock10Quantity) * stock10High)) / str.tonumber(divideFactor)
porfolioLow = ((str.tonumber(stock1Quantity) * stock1Low) + (str.tonumber(stock2Quantity) * stock2Low) + (str.tonumber(stock3Quantity) * stock3Low) + (str.tonumber(stock4Quantity) * stock4Low) + (str.tonumber(stock5Quantity) * stock5Low) + (str.tonumber(stock6Quantity) * stock6Low) + (str.tonumber(stock7Quantity) * stock7Low) + (str.tonumber(stock8Quantity) * stock8Low) + (str.tonumber(stock9Quantity) * stock9Low) + (str.tonumber(stock10Quantity) * stock10Low)) / str.tonumber(divideFactor)
porfolioClose = ((str.tonumber(stock1Quantity) * stock1Close) + (str.tonumber(stock2Quantity) * stock2Close) + (str.tonumber(stock3Quantity) * stock3Close) + (str.tonumber(stock4Quantity) * stock4Close) + (str.tonumber(stock5Quantity) * stock5Close) + (str.tonumber(stock6Quantity) * stock6Close) + (str.tonumber(stock7Quantity) * stock7Close) + (str.tonumber(stock8Quantity) * stock8Close) + (str.tonumber(stock9Quantity) * stock9Close) + (str.tonumber(stock10Quantity) * stock10Close)) / str.tonumber(divideFactor)
//Plot candles with the portolio values.
plotcandle(porfolioOpen, porfolioHigh, porfolioLow, porfolioClose, title="Candle", color = paletteColor, wickcolor = paletteColor, bordercolor = paletteColor)
//Plot exponential moving averages.
plot(ta.ema(porfolioClose, 21), color = color.green, title="21 EMA")
plot(ta.ema(porfolioClose, 50), color = color.orange, title="50 EMA")
plot(ta.ema(porfolioClose, 100), color = color.rgb(179, 182, 194), title="100 EMA")
plot(ta.ema(porfolioClose, 200), color = color.red, title="200 EMA")
plot(ta.ema(porfolioClose, 500), color = color.black, title="500 EMA")
|
Impulse Alerts - Riccardo Di Giacomo | https://www.tradingview.com/script/3Lk8lFbW-Impulse-Alerts-Riccardo-Di-Giacomo/ | riccardodigiacomo | https://www.tradingview.com/u/riccardodigiacomo/ | 71 | 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/
// © Riccardo Di Giacomo
//@version=5
indicator("Impulse Alerts - Riccardo Di Giacomo", "Impulse Alerts - Riccardo Di Giacomo", overlay=true)
ema260len = input.int(230, minval=1, title="Length")
ema260src = input(close, title="Source")
ema260offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
ema260out = ta.ema(ema260src, ema260len)
colorBasis = low >= ema260out ? color.blue : color.rgb(249, 27, 27)
plot(ema260out, title="EMA", color=colorBasis, offset=ema260offset)
ema(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)
typeEMA = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
ema260smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
ema260 = ema(ema260out, ema260smoothingLength, typeEMA)
//EMA9
ma9len = input.int(9, minval=1, title="Length")
ma9src = input(close, title="Source")
ma9offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
ma9out = ta.ema(ma9src, ma9len)
plot(ma9out, color=color.rgb(45, 162, 240), title="EMA9", offset=ma9offset)
ma9(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)
typeMA9 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
ma9smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
ma9smoothingLine = ma9(ma9out, ma9smoothingLength, typeMA9)
//EMA21
ema21len = input.int(21, minval=1, title="Length")
ema21src = input(close, title="Source")
ema21offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
ema21out = ta.ema(ema21src, ema21len)
plot(ema21out, color=color.rgb(245, 64, 64), title="MA", offset=ema21offset)
ema21(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)
typeMA21 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
ema21smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
ema21smoothingLine = ema21(ema21out, ema21smoothingLength, typeMA21)
//bollinger bands
bbsrc = input(close)
bblength = input.int(20, minval=1)
mult = input.float(2.0, minval=0.001, maxval=50)
basis = ta.sma(bbsrc, bblength)
dev = ta.stdev(bbsrc, bblength)
dev2 = mult*dev
upper1 = basis + dev
lower1 = basis - dev
upper2 = basis + dev2
lower2 = basis - dev2
pUpper1 = plot(upper1, color=color.rgb(127, 128, 133, 80), style=plot.style_line)
pUpper2 = plot(upper2, color=color.rgb(127, 128, 133, 80))
pLower1 = plot(lower1, color=color.rgb(127, 128, 133, 80), style=plot.style_line)
pLower2 = plot(lower2, color=color.rgb(127, 128, 133, 80))
fill(pUpper1, pUpper2, color=color.rgb(127, 128, 133, 80))
fill(pLower1, pLower2, color=color.rgb(127, 128, 133, 80))
//stoch
periodK = input.int(5, title="%K Length", minval=1)
smoothK = input.int(1, title="%K Smoothing", minval=1)
periodD = input.int(3, title="%D Smoothing", minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
upperbandstoch = 80.0
lowerbandstoch = 20.0
//RSI
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
isBB = maTypeInput == "Bollinger Bands"
//STOCASTICO RAGGIUNTO
buy_stoch = k <= lowerbandstoch
sell_stoch = k >= upperbandstoch
//SELL SETUP
sell_setup = false
if close < ema260 and close < ema21smoothingLine and ema21smoothingLine < ema260 and ma9smoothingLine < ema21smoothingLine and k > upperbandstoch and rsi < 50
alert("Impulse - Sell Setup", alert.freq_once_per_bar)
sell_setup := not sell_setup[1] and not sell_stoch[1] ? true : false
else
sell_setup := false
plotshape(sell_setup, style=shape.arrowdown, location=location.abovebar, color=color.red)
//BUY SETUP
buy_setup = false
if close > ema260 and close > ema21smoothingLine and ema21smoothingLine > ema260 and ma9smoothingLine > ema21smoothingLine and k < lowerbandstoch and rsi > 50
alert("Impulse - Buy Setup", alert.freq_once_per_bar)
buy_setup := not buy_setup[1] and not buy_stoch[1] ? true : false
else
buy_setup := false
plotshape(buy_setup, style=shape.arrowup, location=location.belowbar, color=color.blue) |
FBMA | https://www.tradingview.com/script/2lwYNmF2-fbma/ | FullTimeTradingRu | https://www.tradingview.com/u/FullTimeTradingRu/ | 1,797 | 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/
// Relese version: 22.0
// © Developer: tarasenko_
//@version=5
indicator("FBMA", overlay = true)
// Inputs
atr_period = input.int(14, "ATR Period", group = "Main Settings", minval = 1,display=display.none)
show_ma_labels = input(true, "Sign MAs?", group = "Settings of Moving Averages",display=display.none)
fix_overlapping = input(true, "Fix MAs' signatures overlapping?", group = "Settings of Moving Averages",display=display.none)
f = input.float(20, "Min distance between MAs' signatures (in % of 1 ATR)", group = "Settings of Moving Averages",display=display.none)/100.
ma1_src = input(close, "Source MA №1" , group = "MA №1 Settings",display=display.none)
ma1_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №1 Settings",display=display.none)
ma1_period = input.int(10, "МА №1 Period" , group = "MA №1 Settings", minval = 1,display=display.none)
show_ema1 = input(true, "EMA №1" , group = "MA №1 Settings", inline = "MA 1",display=display.none)
show_sma1 = input(false, "SMA №1" , group = "MA №1 Settings", inline = "MA 1",display=display.none)
ma1_signature_color = input.color(#000000, "Signature color for MA №1", group = "MA №1 Settings",display=display.none)
ma2_src = input(close, "Source MA №2" , group = "MA №2 Settings",display=display.none)
ma2_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №2 Settings",display=display.none)
ma2_period = input.int(20, "МА №2 Period" , group = "MA №2 Settings", minval = 1,display=display.none)
show_ema2 = input(true, "EMA №2" , group = "MA №2 Settings", inline = "MA 2",display=display.none)
show_sma2 = input(false, "SMA №2" , group = "MA №2 Settings", inline = "MA 2",display=display.none)
ma2_signature_color = input.color(#000000 , "Signature color for MA №2", group = "MA №2 Settings",display=display.none)
ma3_src = input(close, "Source MA №3" , group = "MA №3 Settings",display=display.none)
ma3_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №3 Settings",display=display.none)
ma3_period = input.int(50, "МА №3 Period" , group = "MA №3 Settings", minval = 1,display=display.none)
show_ema3 = input(true, "EMA №3" , group = "MA №3 Settings", inline = "MA 3",display=display.none)
show_sma3 = input(false, "SMA №3" , group = "MA №3 Settings", inline = "MA 3",display=display.none)
ma3_signature_color = input.color(#000000 , "Signature color for MA №3", group = "MA №3 Settings",display=display.none)
ma4_src = input(close, "Source MA №4" , group = "MA №4 Settings",display=display.none)
ma4_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №4 Settings",display=display.none)
ma4_period = input.int(100, "МА №4 Period" , group = "MA №4 Settings", minval = 1,display=display.none)
show_ema4 = input(true, "EMA №4" , group = "MA №4 Settings", inline = "MA 4",display=display.none)
show_sma4 = input(false, "SMA №4" , group = "MA №4 Settings", inline = "MA 4",display=display.none)
ma4_signature_color = input.color(#000eff , "Signature color for MA №4", group = "MA №4 Settings",display=display.none)
ma5_src = input(close, "Source MA №5" , group = "MA №5 Settings",display=display.none)
ma5_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №5 Settings",display=display.none)
ma5_period = input.int(200, "МА №5 Period" , group = "MA №5 Settings", minval = 1,display=display.none)
show_ema5 = input(true, "EMA №5" , group = "MA №5 Settings", inline = "MA 5",display=display.none)
show_sma5 = input(false, "SMA №5" , group = "MA №5 Settings", inline = "MA 5",display=display.none)
ma5_signature_color = input.color(#ff0000 , "Signature color for MA №5", group = "MA №5 Settings",display=display.none)
ma6_src = input(close, "Source MA №6" , group = "MA №6 Settings",display=display.none)
ma6_src_tf = input.timeframe('Current', "Source Timeframe", options = ['Current', '1', '3', '5', '10', '15', '30', '45', '60', '120', '180', '240', '360', '480', '720', '1D', '2D', '3D', '1W', '2W', '3W', '1M'], group = "MA №6 Settings",display=display.none)
ma6_period = input.int(5, "МА №6 Period" , group = "MA №6 Settings", minval = 1,display=display.none)
show_ema6 = input(false, "EMA №6" , group = "MA №6 Settings", inline = "MA 6",display=display.none)
show_sma6 = input(false, "SMA №6" , group = "MA №6 Settings", inline = "MA 6",display=display.none)
ma6_signature_color = input.color(#000000 , "Signature color for MA №6", group = "MA №6 Settings",display=display.none)
draw_cloud_ema12 = input(false, "Show cloud between 1st and 2nd EMA?", group = "Addons",display=display.none)
draw_cloud_sma12 = input(false, "Show cloud between 1st and 2nd SMA?", group = "Addons",display=display.none)
draw_lines_for_rp = input(true, "Draw lines for round prices?", group = "Addons", tooltip = "Draw two lines for nearest round price around current close price of the asset.\n\n* The more lines, the slower the script.",display=display.none)
pn_for_rp = input.int(2, "Number of pairs of round prices' lines", group = "Addons", minval = 1, maxval = 20, tooltip = "Max amount of pairs is 20, because after 20 pairs PineScript can't clean old drawings.\n\n* Too much lines slow the script.",display=display.none)
ul_col = input.color(#000eff, "Upper line colour", group = "Addons",display=display.none)
ll_col = input.color(#000eff, "Lower line colour", group = "Addons",display=display.none)
show_dashboard = input(true, "Show dashboard?", group = "Dashboard", inline = "Enables/disables dashboard with recommended ATR Take-Profit and Stop-Loss values.",display=display.none)
db_pos = input.string("Bottom right", "Dashboard position", options = ["Bottom right", "Bottom middle", "Bottom left", "Middle right", "Middle center", "Middle left", "Top right", "Top middle", "Top left"], group = "Dashboard",display=display.none)
db_sl_mult = input.float(1.0, "ATR Stop-Loss Multiplier (1.0 by default)", 0.1, step = 0.05, group = "Dashboard", inline = "Defines dashboard's ATR Stop-Loss multiplier (set to 1.0 by default).", tooltip = "Changes 1st row of dashboard.",display=display.none)
db_tp_mult = input.float(1.5, "ATR Take-Profit Multiplier (1.5 by default)", 0.1, step = 0.05, group = "Dashboard", inline = "Defines dashboard's ATR Take-Profit multiplier (set to 1.5 by default).", tooltip = "Changes 2nd row of dashboard.",display=display.none)
// Drumroll... Classes! Thanks to TradingView team for that, very useful in this particural situation!
// In the next update make recursion available, please.
//
// Moving Average class
//
// I am using classes in order to reduce amount of cycles for different
// operations and making process of plotting MAs' signatures a lot easier.
// Code itself also becomes cleaner and more comprehensive.
//
// BUT! Be careful while using classes in sorting algorithms,
// Because the size of the class affects the speed of your algorithm
// simply because when you do swapping objects, for example,
// all variables from one object will be transfered to another one by one,
// so such things will take time because of that.
type MovingAverage
float ma_value
string ma_type
int ma_period
color ma_colour
// Functions
// Get risk background color for dashboard
// Somewhat of gradient
get_risk_bgcol(r) =>
risk = r * 100
col = color.green
if risk <= 1
col := #00CC00
if risk <= 4 and risk > 1
col := #269401
if risk <= 5 and risk > 4
col := #33B900
if risk <= 10 and risk > 5
col := #695C00
if risk <= 15 and risk > 10
col := #C26100
if risk > 15
col := #C73601
col
// Get dashboard position
get_db_pos(p) =>
pos = position.bottom_right
if p == "Bottom middle"
pos := position.bottom_center
if p == "Bottom left"
pos := position.bottom_left
if p == "Middle right"
pos := position.middle_right
if p == "Middle center"
pos := position.middle_center
if p == "Middle left"
pos := position.middle_left
if p == "Top right"
pos := position.top_right
if p == "Top middle"
pos := position.top_center
if p == "Top left"
pos := position.top_left
pos
// get highest price
highest_price(int bars) =>
float max = 0
for i = 0 to bars
max := high[i] > max ? high[i] : max
max
// Get lowest price
lowest_price(int bars) =>
float min = open
for i = 0 to bars
min := low[i] < min ? low[i] : min
min
// Get MA source's tf's value
get_source_from_tf(string tf, float src) =>
float val = 0.0
val := request.security(syminfo.tickerid, tf == 'Current' ? timeframe.period : tf, src)
val
// Calculations
// ATR & risk
atr = ta.atr(atr_period)
risk = 1 - (close - atr) / close
risk_bgcol_sl = get_risk_bgcol(risk * db_sl_mult)
// Getting MAs' values if they are chosen to be plotted (show_ema should be true)
ema1 = show_ema1 ? get_source_from_tf(ma1_src_tf, ta.ema(ma1_src, ma1_period)) : na // EMAs
ema2 = show_ema2 ? get_source_from_tf(ma2_src_tf, ta.ema(ma2_src, ma2_period)) : na
ema3 = show_ema3 ? get_source_from_tf(ma3_src_tf, ta.ema(ma3_src, ma3_period)) : na
ema4 = show_ema4 ? get_source_from_tf(ma4_src_tf, ta.ema(ma4_src, ma4_period)) : na
ema5 = show_ema5 ? get_source_from_tf(ma5_src_tf, ta.ema(ma5_src, ma5_period)) : na
ema6 = show_ema6 ? get_source_from_tf(ma6_src_tf, ta.ema(ma6_src, ma6_period)) : na
sma1 = show_sma1 ? get_source_from_tf(ma1_src_tf, ta.sma(ma1_src, ma1_period)) : na // SMAs
sma2 = show_sma2 ? get_source_from_tf(ma2_src_tf, ta.sma(ma2_src, ma2_period)) : na
sma3 = show_sma3 ? get_source_from_tf(ma3_src_tf, ta.sma(ma3_src, ma3_period)) : na
sma4 = show_sma4 ? get_source_from_tf(ma4_src_tf, ta.sma(ma4_src, ma4_period)) : na
sma5 = show_sma5 ? get_source_from_tf(ma5_src_tf, ta.sma(ma5_src, ma5_period)) : na
sma6 = show_sma6 ? get_source_from_tf(ma6_src_tf, ta.sma(ma6_src, ma6_period)) : na
// MA ma_values array
ma_array = array.new<MovingAverage>(0) // Size is 0 because when you push elements size increases. Works like C++'s vector
// Filling MA Array
if show_ema1 and not na(ema1) // If MA value is NaN, it means that current bar index is less than MA's period so we don't need to push this element in array
array.push(ma_array, MovingAverage.new(ema1, "EMA", ma1_period, ma1_signature_color))
if show_ema2 and not na(ema2)
array.push(ma_array, MovingAverage.new(ema2, "EMA", ma2_period, ma2_signature_color))
if show_ema3 and not na(ema3)
array.push(ma_array, MovingAverage.new(ema3, "EMA", ma3_period, ma3_signature_color))
if show_ema4 and not na(ema4)
array.push(ma_array, MovingAverage.new(ema4, "EMA", ma4_period, ma4_signature_color))
if show_ema5 and not na(ema5)
array.push(ma_array, MovingAverage.new(ema5, "EMA", ma5_period, ma5_signature_color))
if show_ema6 and not na(ema6)
array.push(ma_array, MovingAverage.new(ema6, "EMA", ma6_period, ma6_signature_color))
if show_sma1 and not na(sma1)
array.push(ma_array, MovingAverage.new(sma1, "SMA", ma1_period, ma1_signature_color))
if show_sma2 and not na(sma2)
array.push(ma_array, MovingAverage.new(sma2, "SMA", ma2_period, ma2_signature_color))
if show_sma3 and not na(sma3)
array.push(ma_array, MovingAverage.new(sma3, "SMA", ma3_period, ma3_signature_color))
if show_sma4 and not na(sma4)
array.push(ma_array, MovingAverage.new(sma4, "SMA", ma4_period, ma4_signature_color))
if show_sma5 and not na(sma5)
array.push(ma_array, MovingAverage.new(sma5, "SMA", ma5_period, ma5_signature_color))
if show_sma6 and not na(sma6)
array.push(ma_array, MovingAverage.new(sma6, "SMA", ma6_period, ma6_signature_color))
// MA array size
size_ma_array = array.size(ma_array)
// If we don't sign MAs, then there is not need to do signature fixing
if show_ma_labels
if size_ma_array >= 2
// Fixing overlapping of MAs' signatures
overlapping_fix_array = array.new<float>(0)
for i = 0 to size_ma_array - 1
MovingAverage obj = array.get(ma_array, i)
array.push(overlapping_fix_array, obj.ma_value)
// Creating array for sorting MA array. It's values will be then used in creating labels
array<MovingAverage> sorted_ma_array = array.copy(ma_array)
if fix_overlapping
// Sorting overlapping_fix_array in descending order for purpose of fast overlapping fix
array.sort(overlapping_fix_array, order.descending)
// Fixing overlapping itself
for i = 0 to size_ma_array - 2
val1 = array.get(overlapping_fix_array, i)
val2 = array.get(overlapping_fix_array, i + 1)
if val1 < val2 or val1 - val2 < atr * f
array.set(overlapping_fix_array, i + 1, val1 - atr * f)
// Sorting MA array by value (Bubble sort *)
//
// * As it is impossible to do recursion in PineScript and there is no algo without recursion that could
// do sorting in O(n) or O(n*log(n)), bubble sort is the only way.
//
// But I think that even if I applied quick sort, the result still won't be much better, because
// there the maximum amount of elements in array is 12, not 10000, so it can't really affect the speed.
for i = 0 to size_ma_array - 2
for j = 0 to size_ma_array - 2 - i
curr_j = array.get(sorted_ma_array, j)
prev_j = array.get(sorted_ma_array, j + 1)
if curr_j.ma_value < prev_j.ma_value
array.set(sorted_ma_array, j, prev_j)
array.set(sorted_ma_array, j + 1, curr_j)
// MA labels
ma_labels = array.new<label>(size_ma_array)
for i = 0 to size_ma_array - 1
obj = array.get(sorted_ma_array, i) // Getting current MA object to plot
fixed_ma_value = array.get(overlapping_fix_array, i) // Obtained MA value after overlapping fix
ma_value = obj.ma_value // Original MA value
ma_type = obj.ma_type // Original MA type
ma_period = obj.ma_period // Original MA period
ma_colour = obj.ma_colour // Original MA colour
// Creating MA label, while pushing into MA labels array
// Using array for that makes this system more flexible,
// because now we don't care which MAs are enabled, we just
// push them in our MA array, make some math and plot them, that's it!
array.push(ma_labels, label.new(bar_index + 1, fixed_ma_value, str.tostring(ma_value, format.mintick) + " (" + ma_type + " " + str.tostring(ma_period) + ")", color = #ffffff01, style = label.style_label_left, textcolor = ma_colour) )
// Deleting old labels
while array.size(label.all) > size_ma_array
label.delete(array.shift(label.all))
else if size_ma_array == 1 // If there is only one MA in MA array, then there is no need to sort it and etc. Just plot it
obj = array.get(ma_array, 0)
ma_value = obj.ma_value
ma_type = obj.ma_type
ma_period = obj.ma_period
ma_colour = obj.ma_colour
MA_label = label.new(bar_index + 1, ma_value, str.tostring(ma_value, format.mintick) + " (" + ma_type + " " + str.tostring(ma_period) + ")", color = #ffffff01, style = label.style_label_left, textcolor = ma_colour)
label.delete(MA_label[1]) // Don't really care about the fact that I am deleting local object as long it works :) For safety purposes make MA_label global and use operator := to change it's value
// Round price's lines
if draw_lines_for_rp
array<line> rp_lines = array.new<line>(0)
array<label> rp_labels = array.new<label>(0)
// Cleaning previous lines
while array.size(line.all) != 0
line.delete(array.pop(line.all))
// Cleaning previous labels
// We add size_ma_array so we don't delete MA's signatures
while array.size(label.all) > (show_ma_labels ? size_ma_array : 0)
label.delete(array.shift(label.all))
if close >= 1 and close <= 10
for i = 0 to pn_for_rp - 1
ur_y = int(close) + (i + 1) // Upper Line y-coordinate
lr_y = close != int(close) - i ? int(close) - i : int(close) - (1 + i) // Lower line y-coordinate
array.push(rp_lines, line.new(bar_index, ur_y, bar_index + 20, ur_y, xloc.bar_index, extend.left, ul_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, ur_y, str.tostring(ur_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ul_col, style = label.style_label_left))
// If lower round price's y-coordinate is negative, then we don't plot it
if lr_y > 0
array.push(rp_lines, line.new(bar_index, lr_y, bar_index + 20, lr_y, xloc.bar_index, extend.left, ll_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, lr_y, str.tostring(lr_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ll_col, style = label.style_label_left))
if close > 10 and close < 1000
for i = 0 to pn_for_rp - 1
ur_y = close - (close % 10) + 10 * (i + 1)
lr_y = close != close - (close % 10) ? close - (close % 10) - 10 * i : close - 10 * (i + 1)
array.push(rp_lines, line.new(bar_index, ur_y, bar_index + 20, ur_y, xloc.bar_index, extend.left, ul_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, ur_y, str.tostring(ur_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ul_col, style = label.style_label_left))
if lr_y > 0
array.push(rp_lines, line.new(bar_index, lr_y, bar_index + 20, lr_y, xloc.bar_index, extend.left, ll_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, lr_y, str.tostring(lr_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ll_col, style = label.style_label_left))
if close >= 1000
for i = 0 to pn_for_rp - 1
ur_y = close - (close % 100) + 100 * (i + 1)
lr_y = close != close - (close % 100) ? close - (close % 100) - 100 * i : close - 100 * (i + 1)
array.push(rp_lines, line.new(bar_index, ur_y, bar_index + 20, ur_y, xloc.bar_index, extend.left, ul_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, ur_y, str.tostring(ur_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ul_col, style = label.style_label_left))
if lr_y > 0
array.push(rp_lines, line.new(bar_index, lr_y, bar_index + 20, lr_y, xloc.bar_index, extend.left, ll_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, lr_y, str.tostring(lr_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ll_col, style = label.style_label_left))
// For assets, whose current close is below 1$, we need to apply different calculation technique
if close < 1
price = close
float mult = 1
while price < 1
price *= 10
mult *= 10
for i = 0 to pn_for_rp - 1
ur_y = (int(price) + 1 + i) / mult
lr_y = price != int(price) ? (int(price) - i) / mult : (int(price) - 1 - i) / mult
array.push(rp_lines, line.new(bar_index, ur_y, bar_index + 20, ur_y, xloc.bar_index, extend.left, ul_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, ur_y, str.tostring(ur_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ul_col, style = label.style_label_left))
if lr_y > 0
array.push(rp_lines, line.new(bar_index, lr_y, bar_index + 20, lr_y, xloc.bar_index, extend.left, ll_col, width = 1))
array.push(rp_labels, label.new(bar_index + 20, lr_y, str.tostring(lr_y) + " " + syminfo.currency, color = #ffffff01, textcolor = ll_col, style = label.style_label_left))
PLOT_EMA1 = plot(show_ema1 ? ema1 : na, "EMA 1" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_EMA2 = plot(show_ema2 ? ema2 : na, "EMA 2" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_EMA3 = plot(show_ema3 ? ema3 : na, "EMA 3" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_EMA4 = plot(show_ema4 ? ema4 : na, "EMA 4" , #000eff, 2, plot.style_linebr,display = display.pane)
PLOT_EMA5 = plot(show_ema5 ? ema5 : na, "EMA 5" , #ff0000, 2, plot.style_linebr,display = display.pane)
PLOT_EMA6 = plot(show_ema6 ? ema6 : na, "EMA 6" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_SMA1 = plot(show_sma1 ? sma1 : na, "SMA 1" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_SMA2 = plot(show_sma2 ? sma2 : na, "SMA 2" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_SMA3 = plot(show_sma3 ? sma3 : na, "SMA 3" , #000000, 2, plot.style_linebr,display = display.pane)
PLOT_SMA4 = plot(show_sma4 ? sma4 : na, "SMA 4" , #000eff, 2, plot.style_linebr,display = display.pane)
PLOT_SMA5 = plot(show_sma5 ? sma5 : na, "SMA 5" , #ff0000, 2, plot.style_linebr,display = display.pane)
PLOT_SMA6 = plot(show_sma6 ? sma6 : na, "SMA 6" , #000000, 2, plot.style_linebr,display = display.pane)
// Clouds
fill(plot(ema1, "Cloud EMA №1", na,display = display.pane), plot(ema2, "Cloud EMA №2", na,display = display.pane), title = "Cloud of EMA №1 and EMA №2", color = draw_cloud_ema12 ? (ema1 > ema2 ? #00800059 : #ff000059) : na)
fill(plot(sma1, "Cloud SMA №1", na,display = display.pane), plot(sma2, "Cloud SMA №2", na,display = display.pane), title = "Cloud of SMA №1 and SMA №2", color = draw_cloud_sma12 ? (sma1 > sma2 ? #00800059 : #ff000059) : na)
// Dashboard
pos = get_db_pos(db_pos)
table db = table.new(pos, 2, 4, color.black, color.gray, 1, color.gray, 1)
if show_dashboard
table.cell(db, 0, 0, str.tostring(db_sl_mult) + " ATR" , text_color = color.white)
table.cell(db, 1, 0, str.tostring(db_sl_mult * atr, format.mintick) + " (" + str.tostring((db_sl_mult * atr) / close, '#####.##%') + ")" , text_color = color.white, bgcolor = risk_bgcol_sl)
table.cell(db, 0, 1, str.tostring(db_tp_mult) + " ATR" , text_color = color.white)
table.cell(db, 1, 1, str.tostring(db_tp_mult * atr, format.mintick) + " (" + str.tostring((db_tp_mult * atr) / close, '#####.##%') + ")" , text_color = color.white, bgcolor = color.gray)
// Alerts
alertcondition(ta.cross(close, ema1), "Price hit ЕМА №1" , "Price hit ЕМА №1.")
alertcondition(ta.cross(close, ema2), "Price hit ЕМА №2" , "Price hit ЕМА №2.")
alertcondition(ta.cross(close, ema3), "Price hit ЕМА №3" , "Price hit ЕМА №3.")
alertcondition(ta.cross(close, ema4), "Price hit ЕМА №4" , "Price hit ЕМА №4.")
alertcondition(ta.cross(close, ema5), "Price hit ЕМА №5" , "Price hit ЕМА №5.")
alertcondition(ta.cross(close, ema6), "Price hit ЕМА №6" , "Price hit ЕМА №6.")
alertcondition(ta.cross(close, sma1), "Price hit SМА №1" , "Price hit SМА №1.")
alertcondition(ta.cross(close, sma2), "Price hit SМА №2" , "Price hit SМА №2.")
alertcondition(ta.cross(close, sma3), "Price hit SМА №3" , "Price hit SМА №3.")
alertcondition(ta.cross(close, sma4), "Price hit SМА №4" , "Price hit SМА №4.")
alertcondition(ta.cross(close, sma5), "Price hit SМА №5" , "Price hit SМА №5.")
alertcondition(ta.cross(close, sma6), "Price hit SМА №6" , "Price hit SМА №6.")
// Originally developed by @ChrisMoody
// CM Price Action
period_ctP = input.int(66, "Percentage Input For Pin Bars, What % The Wick Of Candle Has To Be" , minval = 1, maxval = 99 , group = "Price Action",display=display.none)
period_blb = input.int(6, "Pin Bars Look Back Period To Define The Trend of Highs and Lows" , minval = 1, maxval = 100, group = "Price Action",display=display.none)
period_ctS = input.int(5, "Percentage Input For Shaved Bars, Percent of Range it Has To Close On The Lows or Highs" , minval = 1, maxval = 99 , group = "Price Action",display=display.none)
show_pin_bars = input(false, "Show Pin Bars?")
show_shaved_bars = input(false, "Show Shaved Bars?")
show_inside_bars = input(false, "Show Inside Bars?")
show_outside_bars = input(false, "Show Outside Bars?")
make_bars_gray = input(false, "Color bars in gray?", tooltip = "Helps better indentify price action bars.")
//Pin Bar Percentages
pctCp = period_ctP * .01
pctCPO = 1 - pctCp
//Shaved Bars Percentages
pctCs = period_ctS * .01
period_ctSPO = pctCs
// Price range
Range = high - low
///Pin Bars
pinBarUp = show_pin_bars and open > high - (Range * pctCPO) and close > high - (Range * pctCPO) and low <= ta.lowest(period_blb) ? 1 : 0
pinBarDn = show_pin_bars and open < high - (Range * pctCp) and close < high-(Range * pctCp) and high >= ta.highest(period_blb) ? 1 : 0
//Shaved Bars
shavedBarUp = show_shaved_bars and (close >= (high - (Range * pctCs)))
shavedBarDown = show_shaved_bars and close <= (low + (Range * pctCs))
//Inside Bars
insideBar = show_inside_bars and high <= high[1] and low >= low[1] ? 1 : 0
outsideBar = show_outside_bars and (high > high[1] and low < low[1]) ? 1 : 0
bar_colour = color(na)
if pinBarUp
bar_colour := color.lime
else if pinBarDn
bar_colour := color.red
else if shavedBarUp
bar_colour := color.fuchsia
else if shavedBarDown
bar_colour := color.aqua
else if insideBar
bar_colour := color.yellow
else if outsideBar
bar_colour := color.orange
else if make_bars_gray
bar_colour := color.gray
else
bar_colour := na
barcolor(bar_colour)
|
Trend Finder with Coefficient of Variation | https://www.tradingview.com/script/XseYRWFH-Trend-Finder-with-Coefficient-of-Variation/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 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/
// © DojiEmoji
//@version=5
indicator("Trend Finder w/ COV [DojiEmoji]", overlay=true)
//------------------------------
// Source data && Stats.
//------------------------------
var string GROUP_BASIS = "Source of data"
var int length_n = input.int(20, minval=1, group=GROUP_BASIS, title="Lookback (n)")
float src = input(close, title="Source", group=GROUP_BASIS)
float mean = ta.sma(src, length_n)
float stdev = ta.stdev(src, length_n)
float COV = stdev / mean // Coefficient of variation
//------------------------------
// Visualizations:
//------------------------------
var string GROUP_COV = "Comparing COV(source, n)"
var int length_m = input.int(50, minval=1, group=GROUP_COV, title="Lookback (m)")
var bool display_bg = input.bool(true, title="Display background with color scale:", group=GROUP_COV)
var color col_min =input.color(color.new(color.black,50), title="Low COV", group=GROUP_COV, inline="col")
var color col_max =input.color(color.new(color.yellow,50), title="High COV", group=GROUP_COV, inline="col")
bool is_ranging = COV < ta.median(COV, length_m)
bgcolor(display_bg ? color.from_gradient(COV, ta.lowest(COV,length_m), ta.highest(COV,length_m), col_min, col_max) : na)
//------------------------------
// Signals
//------------------------------
bool uptrend = close > mean and not is_ranging
bool downtrend = close < mean and not is_ranging
bool uptrend_begins = uptrend and is_ranging[1]
bool downtrend_begins = downtrend and is_ranging[1]
plotshape(uptrend_begins, style=shape.triangleup, location=location.belowbar, title="Uptrend", color=color.blue, size=size.small)
plotshape(downtrend_begins, style=shape.triangledown, location=location.abovebar, title="Uptrend", color=color.red, size=size.small)
alertcondition(uptrend_begins, title = "Uptrend", message = "Trend Finder with COV -> Uptrend")
alertcondition(downtrend_begins, title = "Downtrend", message = "Trend Finder with COV -> Downtrend")
|
Noise Gate | https://www.tradingview.com/script/MskozgXf-Noise-Gate/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 15 | 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/
// © peacefulLizard50262
//@version=5
indicator("Noise Gate")
// Define the input parameters for the script
alt = input.bool(false, "Use Source as Input")
source = input.source(close, "Source")
ratio = input.float(10, "Ratio", 0.00000001)
level = input.float(0, "Threshold", 0)
knee_type = input.string("soft", "Knee Type", ["soft", "hard"])
noise_gate(signal, ratio, level, knee_type) =>
// Calculate the absolute value of the signal
abs_signal = math.abs(signal)
// Check the value of the knee_type parameter
if knee_type == "hard"
// If the knee_type is "hard", apply a hard knee
if abs_signal > level
out = signal
else
out = signal / ratio
else
// If the knee_type is not "hard", apply a soft knee
if (abs_signal > level) or level == 0
// If the absolute value is above the threshold, return the signal as is
out = signal
else
// If the absolute value is below the threshold, calculate the soft knee ratio
soft_knee_ratio = 1 - (level - abs_signal) / level
// Reduce the amplitude of the signal by the soft knee ratio
out = signal * soft_knee_ratio
// Return the filtered signal
plot(noise_gate(alt ? source : volume, ratio, level, knee_type))
|
Sinusoidal Moving Average | https://www.tradingview.com/script/OZj1RM31-Sinusoidal-Moving-Average/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Sinusoidal Moving Average", "SMA", overlay = true)
// This function calculates the sinusoidal moving average of a given data series
// This function calculates the sine-weighted moving average of a given data series
sinusoidal_ma(data, length) =>
float sum = 0
float weight_sum = 0
for i = 0 to length - 1
a = math.sin((i + 1) * math.pi / (length + 1))
sum := sum + nz(data[i]) * a
weight_sum := weight_sum + a
// Calculate the sine-weighted average using the built-in sma function
// and the built-in sin function
sum/weight_sum
// Define the input parameters for the sine-weighted moving average
data = input.source(close, "Data")
length = input.int(20, "Length", 3)
// Plot the sine-weighted moving average on the chart
plot(sinusoidal_ma(data, length))
|
Brown's Exponential Smoothing (BES) | https://www.tradingview.com/script/hRHkSMKg-Brown-s-Exponential-Smoothing-BES/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 15 | 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/
// © peacefulLizard50262
//@version=5
indicator("Brown's Exponential Smoothing", "BES", overlay = true)
bes(float source = close, float alpha = 0.7)=>
var float smoothed = na
smoothed := na(smoothed) ? source : alpha * source + (1 - alpha) * nz(smoothed[1])
source = input.source(close, "Source")
alpha = input.float(0.01, "Alpha", 0.001, 1, 0.001)
plot(bes(source, alpha), "BES", color.orange)
|
Odd_mod Econ Calendar | https://www.tradingview.com/script/mEE1dDYA-Odd-mod-Econ-Calendar/ | OddLogic1618 | https://www.tradingview.com/u/OddLogic1618/ | 78 | 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/
// Orginal by © jdehorty
// Modified by OddLogicXYZ
// @version=5
indicator('Econ Calendar', overlay=true, scale=scale.none, max_lines_count=500)
//Library with the data
import jdehorty/EconomicCalendar/2 as calendar
//Unix time constants
u_minutes = 60000
u_hours = 3600000
u_days = 86400000
u_week = 604800000
// ==================
// ==== Inputs ====
// ==================
next_text = "Next meeting countdown"
next_tt = "Add a countdown to the next meeting on the legend."
alert_text = "Create Alert"
alert_tt = "Untested"
fomc_meet_group = "📅Federal Open Market Committee - Meeting"
fomc_meet_en = input.bool(defval = true, title = "Enable ", inline = "FOMC", group= fomc_meet_group, tooltip="The FOMC meets eight times a year to determine the course of monetary policy. The FOMC's decisions are announced in a press release at 2:15 p.m. ET on the day of the meeting. The press release is followed by a press conference at 2:30 p.m. ET. The FOMC's decisions are based on a review of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
fomc_meet_c = input.color(color.new(color.red, 50), title = "", group= fomc_meet_group, inline = "FOMC")
fomc_meet_next_en = input.bool(defval = false, title = next_text, inline = "FOMC2", group= fomc_meet_group, tooltip=next_tt)
fomc_meet_alert_en = input.bool(defval = false, title = alert_text, inline = "FOMC3", group= fomc_meet_group, tooltip=alert_tt)
fomc_min_group = "📅Federal Open Market Committee - Minutes"
fomc_min_en = input.bool(defval = true, title = "Enable", inline = "FOMCMinutes", group= fomc_min_group, tooltip="The FOMC minutes are released three weeks after each FOMC meeting. The minutes provide a detailed account of the FOMC's discussion of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
fomc_min_c = input.color(color.new(color.orange, 50), title = "", group= fomc_min_group, inline = "FOMCMinutes")
fomc_min_next_en = input.bool(defval = false, title = next_text, inline = "FOMCMinutes2", group= fomc_min_group, tooltip=next_tt)
fomc_min_alert_en = input.bool(defval = false, title = alert_text, inline = "FOMCMinutes3", group= fomc_min_group, tooltip=alert_tt)
ppi_group = "📅 Producer Price Index (PPI)"
ppi_en = input.bool(defval = true, title = "Enable", inline = "PPI", group= ppi_group, tooltip="The Producer Price Index (PPI) measures changes in the price level of goods and services sold by domestic producers. The PPI is a weighted average of prices of a basket of goods and services, such as transportation, food, and medical care. The PPI is a leading indicator of CPI.")
ppi_c = input.color(color.new(color.yellow, 50), title = "", group= ppi_group, inline = "PPI")
ppi_next_en = input.bool(defval = false, title = next_text, inline = "PPI2", group= ppi_group, tooltip=next_tt)
ppi_alert_en = input.bool(defval = false, title = alert_text, inline = "PPI3", group= ppi_group, tooltip=alert_tt)
cpi_group = "📅 Consumer Price Index (CPI)"
cpi_en = input.bool(defval = true, title = "Enable", inline = "CPI", group= cpi_group, tooltip="The Consumer Price Index (CPI) measures changes in the price level of goods and services purchased by households. The CPI is a weighted average of prices of a basket of consumer goods and services, such as transportation, food, and medical care. The CPI-U is the most widely used measure of inflation. The CPI-U is based on a sample of about 87,000 households and measures the change in the cost of a fixed market basket of goods and services purchased by urban consumers.")
cpi_c = input.color(color.new(color.lime, 50), title = "", group= cpi_group, inline = "CPI")
cpi_next_en = input.bool(defval = false, title = next_text, inline = "CPI2", group= cpi_group, tooltip=next_tt)
cpi_alert_en = input.bool(defval = false, title = alert_text, inline = "CPI3", group= cpi_group, tooltip=alert_tt)
csi_group = "📅 Consumer Sentiment Index (CSI)"
csi_en = input.bool(defval = true, title = "Enable", inline = "CSI", group= csi_group, tooltip="The University of Michigan's Consumer Sentiment Index (CSI) is a measure of consumer attitudes about the economy. The CSI is based on a monthly survey of 500 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CSI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
csi_c = input.color(color.new(color.aqua, 50), title = "", group= csi_group, inline = "CSI")
csi_next_en = input.bool(defval = false, title = next_text, inline = "CSI2", group= csi_group, tooltip=next_tt)
csi_alert_en = input.bool(defval = false, title = alert_text, inline = "CSI3", group= csi_group, tooltip=alert_tt)
cci_group = "📅 Consumer Confidence Index (CCI)"
cci_en = input.bool(defval = true, title = "Enable", inline = "CCI", group= cci_group, tooltip="The Conference Board's Consumer Confidence Index (CCI) is a measure of consumer attitudes about the economy. The CCI is based on a monthly survey of 5,000 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CCI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
cci_c = input.color(color.new(color.fuchsia, 50), title = "", group= cci_group, inline = "CCI")
cci_next_en = input.bool(defval = false, title = next_text, inline = "CCI2", group= cci_group, tooltip=next_tt)
cci_alert_en = input.bool(defval = false, title = alert_text, inline = "CCI3", group= cci_group, tooltip=alert_tt)
nfp_group = "📅 Non-Farm Payroll (NFP)"
nfp_en = input.bool(defval = true, title = "Enable", inline = "NFP", group= nfp_group, tooltip="The Non-Farm Payroll (NFP) is a measure of the change in the number of employed persons, excluding farm workers and government employees. The NFP is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
nfp_c = input.color(color.new(color.silver, 50), title = "", group= nfp_group, inline = "NFP")
nfp_next_en = input.bool(defval = false, title = next_text, inline = "NFP2", group= nfp_group, tooltip=next_tt)
nfp_alert_en = input.bool(defval = false, title = alert_text, inline = "NFP3", group= nfp_group, tooltip=alert_tt)
legend_group = "📊 Legend"
show_legend = input.bool(true, "Show Legend", group= legend_group, inline = "Legend", tooltip="Show the color legend for the economic calendar events.")
legend_loc = input.string("top_right", "Location", options=["top_left","top_center","top_right","middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"], group= legend_group, inline="Legend2")
add_top_margins = input.bool(true, "Top extra margins", group= legend_group, inline = "Legend3", tooltip="Adds extra spacers to the table when set to top locations")
short_names = input.bool(true, "Use Short Names", group= legend_group, inline = "Legend4", tooltip="Abbreviated names on the legend")
countdown_format = input.string("DAYS:HOURS:MINS", "Countdown time format", options=["DAYS:HOURS:MINS", "DAYS:HOURS", "DAYS"], group= legend_group, inline="Legend5")
alert_group = "⏰ Alerts"
alert_time = input.int(15, "Set alerts for", group= alert_group, inline="Alert")
alert_time_period = input.string("Mins", "", options=["Mins","Hours","Days"], group= alert_group, inline="Alert")
// =======================
// ==== Charting ====
// =======================
//column number placeholders
name_col = 0
next_col = 1
alert_col = 2
//row number placeholders
var int fomc_meet_r = na
var int fomc_min_r = na
var int ppi_r = na
var int cpi_r = na
var int csi_r = na
var int cci_r = na
var int nfp_r = na
//sortable arrays
var fomc_meet_ary = calendar.fomcMeetings()
var fomc_min_ary = calendar.fomcMinutes()
var ppi_ary = calendar.ppiReleases()
var cpi_ary = calendar.cpiReleases()
var csi_ary = calendar.csiReleases()
var cci_ary = calendar.cciReleases()
var nfp_ary = calendar.nfpReleases()
//Legend table
var tbl = table.new(position=legend_loc, columns=3, rows=12, frame_width=1, border_width=2, border_color=color.new(color.black, 100))
// function to find where to put the line in relation to the date due to the way lines are added in pine
lineTime (input) =>
int out = na
if timeframe.isintraday
if timeframe.multiplier >= 60
out := input - (timeframe.multiplier * u_minutes)
else
//Spelled out because its crazy complicated
//get minutes left in input
m_in_input = input - (int(input / u_days) * u_days)
//get minutes left in bar time to create 0 point
point_0 = time - (int(time / u_days) * u_days)
//take point 0 from minutes left in input
p_f_m = m_in_input - point_0
//find out if input time occours in a whole portion of the selected timeframe.multiplier
is_whole = (p_f_m % timeframe.multiplier == 0)
//If it is not a whole portion then move the timeframe back by one bar so the line is drawn on the bar with a start time before the input happens
out := is_whole ? input : input - (timeframe.multiplier * u_minutes)
else
out := timeframe.isdaily ? input - timeframe.multiplier*86400000 : timeframe.isweekly ? input - timeframe.multiplier*604800000 : timeframe.ismonthly ? input - timeframe.multiplier*2592000000 : input
out
// Things that don't change after initial lines are drawn
if barstate.isfirst
// Row counter
tbl_r = 0
//Creates margins for the table when set to top
if str.contains(legend_loc,"top") and add_top_margins
table.cell(tbl, 0, 1, '')
table.cell(tbl, 0, 2, '')
tbl_r := 2
//Extra for left side top
if str.contains(legend_loc,"left")
table.cell(tbl, 0, 3, '')
table.cell(tbl, 0, 4, '')
tbl_r := 4
//Per selection area
if fomc_meet_en
fomc_meet_r := tbl_r
array.sort(fomc_meet_ary)
for value in calendar.fomcMeetings()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=fomc_meet_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, fomc_meet_r, (short_names ? 'FEDMeet' : 'FOMC Meeting'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(fomc_meet_c, 10), text_size=size.small)
tbl_r += 1
if fomc_min_en
fomc_min_r := tbl_r
array.sort(fomc_min_ary)
for value in calendar.fomcMinutes()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=fomc_min_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, fomc_min_r, (short_names ? 'FEDMins' : 'FOMC Minutes'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(fomc_min_c, 10), text_size=size.small)
tbl_r += 1
if ppi_en
ppi_r := tbl_r
array.sort(ppi_ary)
for value in calendar.ppiReleases()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=ppi_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, ppi_r, (short_names ? 'PPI' : 'Producer Price Index (PPI)'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(ppi_c, 10), text_size=size.small)
tbl_r += 1
if cpi_en
cpi_r := tbl_r
array.sort(cpi_ary)
for value in calendar.cpiReleases()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=cpi_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, cpi_r, (short_names ? 'CPI' : 'Consumer Price Index (CPI)'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(cpi_c, 10), text_size=size.small)
tbl_r += 1
if csi_en
csi_r := tbl_r
array.sort(csi_ary)
for value in calendar.csiReleases()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=csi_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, csi_r, (short_names ? 'CSI' : 'Consumer Sentiment Index (CSI)'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(csi_c, 10), text_size=size.small)
tbl_r += 1
if cci_en
cci_r := tbl_r
array.sort(cci_ary)
for value in calendar.cciReleases()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=cci_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, cci_r, (short_names ? 'CCI' : 'Consumer Confidence Index (CCI)'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(cci_c, 10), text_size=size.small)
tbl_r += 1
if nfp_en
nfp_r := tbl_r
array.sort(nfp_ary)
for value in calendar.nfpReleases()
line_time = lineTime(value)
line.new(x1=line_time, y1=high, x2=line_time, y2=low, extend=extend.both,color=nfp_c, width=2, xloc=xloc.bar_time)
if show_legend
table.cell(tbl, name_col, nfp_r, (short_names ? 'NFP' : 'Non-Farm Payrolls (NFP)'), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(nfp_c, 10), text_size=size.small)
tbl_r += 1
formatCountdown (format, input) =>
time_left = input - timenow
days = int(time_left / u_days)
time_left := time_left - (days * u_days)
hours = int(time_left / u_hours)
time_left := time_left - (hours * u_hours)
mins = int(time_left / u_minutes)
switch format
"DAYS:HOURS:MINS" => "T-" + str.tostring(days) + ":" + (hours <= 9 ? '0' + str.tostring(hours) : str.tostring(hours)) + ":" + (mins <= 9 ? '0' + str.tostring(mins) : str.tostring(mins))
"DAYS:HOURS" => "T-" + str.tostring(days) + ":" + (hours <= 9 ? '0' + str.tostring(hours) : str.tostring(hours))
"DAYS" => "T-" + str.tostring(days)
//Things that only need to run on the last bar
if barstate.islast
//Next meeting section
if fomc_meet_en and fomc_meet_next_en and show_legend
int fomc_meet_next = na
array.sort(fomc_meet_ary)
for value in fomc_meet_ary
if value > timenow
fomc_meet_next := value
break
table.cell(tbl, next_col, fomc_meet_r, (na(fomc_meet_next) ? "No Data" : formatCountdown (countdown_format, fomc_meet_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(fomc_meet_c, 10), text_size=size.small)
if fomc_min_en and fomc_min_next_en and show_legend
int fomc_min_next = na
array.sort(fomc_min_ary)
for value in fomc_min_ary
if value > timenow
fomc_min_next := value
break
table.cell(tbl, next_col, fomc_min_r, (na(fomc_min_next) ? "No Data" : formatCountdown(countdown_format, fomc_min_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(fomc_min_c, 10), text_size=size.small)
if ppi_en and ppi_next_en and show_legend
int ppi_next = na
array.sort(ppi_ary)
for value in ppi_ary
if value > timenow
ppi_next := value
break
table.cell(tbl, next_col, ppi_r, (na(ppi_next) ? "No Data" : formatCountdown(countdown_format, ppi_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(ppi_c, 10), text_size=size.small)
if cpi_en and cpi_next_en and show_legend
int cpi_next = na
array.sort(cpi_ary)
for value in cpi_ary
if value > timenow
cpi_next := value
break
table.cell(tbl, next_col, cpi_r, (na(cpi_next) ? "No Data" : formatCountdown(countdown_format, cpi_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(cpi_c, 10), text_size=size.small)
if csi_en and csi_next_en and show_legend
int csi_next = na
array.sort(csi_ary)
for value in csi_ary
if value > timenow
csi_next := value
break
table.cell(tbl, next_col, csi_r, (na(csi_next) ? "No Data" : formatCountdown(countdown_format, csi_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(csi_c, 10), text_size=size.small)
if cci_en and cci_next_en and show_legend
int cci_next = na
array.sort(cci_ary)
for value in cci_ary
if value > timenow
cci_next := value
break
table.cell(tbl, next_col, cci_r, (na(cci_next) ? "No Data" : formatCountdown(countdown_format, cci_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(cci_c, 10), text_size=size.small)
if nfp_en and nfp_next_en and show_legend
int nfp_next = na
array.sort(nfp_ary)
for value in nfp_ary
if value > timenow
nfp_next := value
break
table.cell(tbl, next_col, nfp_r, (na(nfp_next) ? "No Data" : formatCountdown(countdown_format, nfp_next)), text_halign=text.align_center, bgcolor=color.black, text_color=color.new(nfp_c, 10), text_size=size.small)
//Table icon for alerts
if fomc_meet_en and fomc_meet_alert_en and show_legend
table.cell(tbl, alert_col, fomc_meet_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if fomc_min_en and fomc_min_alert_en and show_legend
table.cell(tbl, alert_col, fomc_min_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if ppi_en and ppi_alert_en and show_legend
table.cell(tbl, alert_col, ppi_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if cpi_en and cpi_alert_en and show_legend
table.cell(tbl, alert_col, cpi_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if csi_en and csi_alert_en and show_legend
table.cell(tbl, alert_col, csi_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if cci_en and cci_alert_en and show_legend
table.cell(tbl, alert_col, cci_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
if nfp_en and nfp_alert_en and show_legend
table.cell(tbl, alert_col, nfp_r, "⏰", text_halign=text.align_center, bgcolor=color.new(color.black, 100), text_size=size.small)
//Alerts, untested
if barstate.isrealtime
chk_time = switch alert_time_period
"Mins" => timenow - (alert_time * u_minutes)
"Hours" => timenow - (alert_time * u_hours)
"Days" => timenow - (alert_time * u_days)
if fomc_meet_en and fomc_meet_alert_en and array.includes(fomc_meet_ary, chk_time)
alert('FOMC Meeting in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if fomc_min_en and fomc_min_alert_en and array.includes(fomc_min_ary, chk_time)
alert('FOMC Minutes in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if ppi_en and ppi_alert_en and array.includes(ppi_ary, chk_time)
alert('Producer Price Index in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if cpi_en and cpi_alert_en and array.includes(cpi_ary, chk_time)
alert('Consumer Price Index in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if csi_en and csi_alert_en and array.includes(csi_ary, chk_time)
alert('Consumer Sentiment Index in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if cci_en and cci_alert_en and array.includes(cci_ary, chk_time)
alert('Consumer Confidence Index in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
if nfp_en and nfp_alert_en and array.includes(nfp_ary, chk_time)
alert('Non-Farm Payrolls in ' + str.tostring(alert_time) + ' ' + alert_time_period, alert.freq_once_per_bar)
|
Compare UVXY to its VIX futures basket | https://www.tradingview.com/script/92mKld6l-Compare-UVXY-to-its-VIX-futures-basket/ | mot_redat | https://www.tradingview.com/u/mot_redat/ | 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/
// © mot_redat
//@version=5
indicator("Compare UVXY to its VIX futures basket", "CMP-UVXY-FUT")
refcolor = input.color(color.white, "Reference value")
actcolorup = input.color(color.green, "Actual value (up)")
actcolordown = input.color(color.red, "Actual value (down)")
uvxy = request.security("UVXY", "", close)
fut = request.security("(2.2*CBOE:VX1!+8.8*CBOE:VX2!)/11", "", close)
diffUVXY = math.abs(uvxy[1] - uvxy[0]) / uvxy[1]
diffFut = math.abs(fut[1]-fut[0]) / fut[1]
actUp = (fut[0] - fut[1]) > 0
hline(1.5, title = "reference", color = refcolor, linestyle = hline.style_dashed)
plot(diffUVXY/diffFut, color = actUp ? actcolorup : actcolordown, linewidth = 2)
|
AutoLevels | https://www.tradingview.com/script/LlrDgKpB-AutoLevels/ | steven_eth | https://www.tradingview.com/u/steven_eth/ | 260 | 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/
// © steven_eth
//@version=5
indicator('ATR FibLevels', overlay=true,explicit_plot_zorder = true)
length = input.int(14, minval=1, title='ATR Length')
atr = ta.atr(length)
TF = input.timeframe(title='Timeframe', defval='D')
current_day_open = request.security(syminfo.tickerid, TF, open[0],lookahead=barmerge.lookahead_on )
atr_value_at_current_day_open = request.security(syminfo.tickerid, TF, atr[1], lookahead=barmerge.lookahead_on)
mult1 = (.236)
mult2 = (.382)
mult3 = (.618)
mult5 = (1)
u_mult1 = current_day_open + atr_value_at_current_day_open / 2 * mult1
u_mult2 = current_day_open + atr_value_at_current_day_open / 2 * mult2
u_mult3 = current_day_open + atr_value_at_current_day_open / 2 * mult3
u_mult5 = current_day_open + atr_value_at_current_day_open / 2 * mult5
l_mult1 = current_day_open - atr_value_at_current_day_open / 2 * mult1
l_mult2 = current_day_open - atr_value_at_current_day_open / 2 * mult2
l_mult3 = current_day_open - atr_value_at_current_day_open / 2 * mult3
l_mult5 = current_day_open - atr_value_at_current_day_open / 2 * mult5
line1 = plot(u_mult1,color=u_mult1 != u_mult1[1] ? na : color.rgb(76, 175, 79, 10), linewidth=1)
line2 = plot(u_mult2, color=u_mult2 != u_mult2[1] ? na : color.rgb(76, 175, 79, 10), linewidth=1)
plot(u_mult3, color=u_mult3 != u_mult3[1] ? na : color.rgb(175, 147, 76))
line4 = plot(u_mult5, color=u_mult5 != u_mult5[1] ? na : color.rgb(175, 147, 76))
line9 = plot(l_mult1, color=l_mult1 != l_mult1[1] ? na : color.rgb(221, 48, 48, 10), linewidth=1)
line10 = plot( l_mult2, color=l_mult2 != l_mult2[1] ? na : color.rgb(221, 48, 48, 10), linewidth=1)
plot(l_mult3, color=l_mult3 != l_mult3[1] ? na : color.rgb(175, 147, 76))
line12 = plot(l_mult5, color=l_mult5 != l_mult5[1] ? na : color.rgb(175, 147, 76))
|
Relative Strength/Weakness Arrows | https://www.tradingview.com/script/FSvaNV1v-Relative-Strength-Weakness-Arrows/ | IsWhatItIs1 | https://www.tradingview.com/u/IsWhatItIs1/ | 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/
// © seaneholmes
//@version=5
indicator(shorttitle='RRS/S', title='Real Relative Sector Strength Arrows', overlay=true)
var CURRENT_COLOR = #d1d4dc
var BASELINE_COLOR = #b2b5be
colorCurrent = input.color(CURRENT_COLOR, title='Current')
baseline = input.symbol('SPY', title='Baseline', inline='baseline')
colorBaseline = input.color(BASELINE_COLOR, title='', inline='baseline')
src = input(close, title='Source')
periodPC= input.int(12, minval=1, title='Price Chg. Period')
periodATR = input.int(12, minval=1, title='ATR Period')
// ===== Sector Symbol Definitions =====
// Note:
// - As of 2022-08-29
// - A symbol may belong in multiple sectors
// Communication Services
var sectorName1 = 'Comms'
var sector1 = 'XLC'
var sectorSymbols1 = 'ATVI, CHTR, CMCSA, DIS, DISH, EA, META, FOX, FOXA, GOOG, GOOGL, IPG, LUMN, LYV, MTCH, NFLX, NWS, NWSA, OMC, PARA, T, TMUS, TTWO, TWTR, VZ, WBD'
var color1 = #ffc000
// ===== Sector Inputs =====
var SECTOR_GROUP_NAME = 'Sectors (Check Each to Always Show)'
var SECTOR_SHOW_NAME = ''
showAll = input.bool(false, title='Show All', group=SECTOR_GROUP_NAME)
c1 = input.color(color1, title='1', group=SECTOR_GROUP_NAME, inline='S1A')
n1 = input.string(sectorName1, title='', group=SECTOR_GROUP_NAME, inline='S1A')
s1 = input.symbol(sector1 , title='', group=SECTOR_GROUP_NAME, inline='S1B')
symbols1 = input.string(sectorSymbols1, title='', group=SECTOR_GROUP_NAME, inline='S1B')
show1 = input.bool(false, title=SECTOR_SHOW_NAME, group=SECTOR_GROUP_NAME, inline='S1B')
// ===== Utility Functions =====
isSymbolInSector(string sectorSymbols) =>
// replace all commas, pluses and minuses with whitespace then split by whitespace
symbols = str.split(str.replace_all(str.replace_all(str.replace_all(sectorSymbols, ',', ' '), '+', ' '), '-', ' '), ' ')
array.indexof(symbols, syminfo.ticker) >= 0
// ===== RRS =====
// NOTE:
// - RRS is the powerIndex of the current symbol minus the powerIndex of the baseline/sector
// - A higher (lower) powerIndex to the baseline/sector means relative strength (weakness)
// - Because we're plotting the symbol, baseline and sector together, we show each powerIndex instead of RRS
calcPowerIndex(series float src, series float atr) =>
symbolRollingMove = src - src[periodPC]
symbolPowerIndex = symbolRollingMove / atr[1]
// current + baseline
powerIndex = calcPowerIndex(close, ta.atr(periodATR))
[src0, atr0] = request.security(symbol=baseline, timeframe="", expression=[src, ta.atr(periodATR)])
powerIndex0 = calcPowerIndex(src0, atr0)
// sectors
var plot1 = str.length(s1) > 0 and (showAll or show1 or isSymbolInSector(symbols1))
[src1, atr1 ] = request.security(symbol=s1, timeframe="", expression=[src, ta.atr(periodATR)])
powerIndex1 = calcPowerIndex(plot1 ? src1 : na, plot1 ? atr1 : na)
// ===== Visuals (Sector Tags) =====
// sectors
var string[] activeSectors = array.new_string()
var color[] activeColors = array.new_color()
if barstate.isfirst
if plot1
array.push(activeSectors, str.length(n1) > 0 ? n1 : syminfo.ticker(s1))
array.push(activeColors, c1)
var sectorTag = table.new(position=position.bottom_right, columns=array.size(activeSectors), rows=1, border_width=0)
if barstate.isfirst
int i = 0
while i < array.size(activeSectors)
table.cell(sectorTag, column=i, row=0, text=array.get(activeSectors, i), text_color=array.get(activeColors, i))
i := i+1
//BarColor Plot:
long1 = powerIndex > powerIndex0 and powerIndex1 > powerIndex0 and powerIndex > powerIndex1 and isSymbolInSector(symbols1)
short1 = powerIndex < powerIndex0 and powerIndex1 < powerIndex0 and powerIndex < powerIndex1 and isSymbolInSector(symbols1)
vwap = ta.vwap
vwapup = close > ta.vwap
vwapdown = close < ta.vwap
plotshape((long1) and vwapup, "Long", shape.triangleup, location.belowbar, color.green)
plotshape((short1) and vwapdown, "Short", shape.triangledown, location.abovebar, color.red)
|
Center Weighted Moving Average (CWMA) | https://www.tradingview.com/script/oYT7miIC-Center-Weighted-Moving-Average-CWMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("CWMA", overlay = true)
// Define the weighted moving average function
wma(src, weights, int len) =>
// Compute the weighted sum of the source data
weightedSum = math.sum(src * weights, len)
// Compute the sum of the weights
sumWeights = math.sum(weights, len)
// Divide the weighted sum by the sum of the weights to calculate the weighted average
weightedSum / sumWeights
cwma(src, len) =>
// Compute the weights for each value in the moving average
weights = (len + 1) / 2 - math.abs(len - src)
// Calculate the weighted moving average
wma(src, weights, len)
source = input.source(close, 'Source')
length = input.int(20, "Length", 1)
plot(cwma(source, length))
|
Immediate Trend - VHX | https://www.tradingview.com/script/yLBWQPpa-Immediate-Trend-VHX/ | Vulnerable_human_x | https://www.tradingview.com/u/Vulnerable_human_x/ | 208 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Vulnerable_human_x
//@version=5
indicator("Immediate Trend - VHX", format=format.price, precision=0, overlay=true, max_lines_count=500)
breakType = input.string("Body",title="Fractal Break Type:",options=["Wick+Body","Body"])
n = input.int(title="Periods", defval=1, minval=1)
bubreakline = input.color(color.lime,title="Bullish Break", inline="1")
bebreakline = input.color(color.red,title="Bullish Break", inline="1")
sthcolor = input.color(color.rgb(255, 255, 255, 47),title="STH", inline="2")
stlcolor = input.color(color.rgb(255, 255, 255, 47),title="STL", inline="2")
showstructure = input.bool(true,"Show Structure Table")
string i_tableYpos = input.string("bottom", "Table Position", inline = "12", options = ["top", "middle", "bottom"])
string i_tableXpos = input.string("right", "", inline = "12", options = ["left", "center", "right"])
var table table1 = table.new(i_tableYpos + "_" + i_tableXpos , 1, 2, frame_color = color.rgb(165, 165, 165, 66), frame_width = 2, border_width=1, border_color=color.rgb(255, 255, 255, 79))
size1 = input.string("small", "Text Size", options = ["tiny", "small", "normal", "large", "huge", "auto"])
var int x = 0
// STH
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
STH = (upflagDownFrontier and flagUpFrontier)
//STL
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
STL = (downflagDownFrontier and flagDownFrontier)
var float topValue = na, var float bottomValue = na
var int lastRedIndex = na, var float lastRedLow = na, var float lastRedHigh = na
var int lastGreenIndex = na, var float lastGreenLow = na, var float lastGreenHigh = na
var line topLine = na, var line bottomLine = na
var box demandBox = na, var box supplyBox = na
var topBreakBlock = false, var bottomBreakBlock = false
var isLongBreak = false, var isShortBreak = false
topBreakCheckSource = breakType == "Wick+Body" ? high : close
bottomBreakCheckSource = breakType == "Wick+Body" ? low : close
//Last red check
if close < open
lastRedIndex := bar_index
lastRedLow := low
lastRedHigh := high
//Last green check
if close > open
lastGreenIndex := bar_index
lastGreenLow := low
lastGreenHigh := high
//Top break
if ta.crossover(topBreakCheckSource,topValue) and topBreakBlock == false
topBreakBlock := true
isLongBreak := true
x := 1
line.set_x2(topLine,bar_index)
line.set_color(topLine,bubreakline)
//Bottom break
if ta.crossunder(bottomBreakCheckSource,bottomValue) and bottomBreakBlock == false
bottomBreakBlock := true
isShortBreak := true
x := 0
line.set_x2(bottomLine,bar_index)
line.set_color(bottomLine,bebreakline)
//New up fractal
if STH
topBreakBlock := false
isLongBreak := false
topValue := high[n]
topLine := line.new(bar_index[n],topValue,bar_index,topValue, color=color.teal, style=line.style_dotted, width=3)
//New down fractal
if STL
bottomBreakBlock := false
isShortBreak := false
bottomValue := low[n]
bottomLine := line.new(bar_index[n],bottomValue,bar_index,bottomValue, color=color.maroon, style=line.style_dotted, width=3)
//PLOTS
plotshape(STL ,style=shape.triangleup, location=location.belowbar,title="STL", offset=-n, color=stlcolor, size = size.tiny)
plotshape(STH, style=shape.triangledown, location=location.abovebar,title="STH", offset=-n, color=sthcolor, size = size.tiny)
//table
if barstate.islast and showstructure
table.cell(table1, 0, 0, "STRUCTURE", width=0,text_valign=text.align_center , text_color = color.white, text_size=size1, text_halign=text.align_center)
table.cell(table1, 0, 1, x==1?"Bullish":"Bearish", width=0,text_valign=text.align_center , text_color = x==1?color.green:color.red, text_size=size1, text_halign=text.align_center)
//IMBALANCE
show_IMB = input.bool(true, "Imbalance", group='IMBALANCE')
imbalancecolor = input.color(color.yellow, title="Imbalance Color", group='IMBALANCE')
fvgTransparency = input(title="Transparency", defval=60, group='IMBALANCE')
fvgboxLength = input.int(title='Length', defval=0, group='IMBALANCE')
fvgisUp(index) =>
close[index] > open[index]
fvgisDown(index) =>
close[index] < open[index]
fvgisObUp(index) =>
fvgisDown(index + 1) and fvgisUp(index) and close[index] > high[index + 1]
fvgisObDown(index) =>
fvgisUp(index + 1) and fvgisDown(index) and close[index] < low[index + 1]
bullishFvg = low[0] > high[2]
bearishFvg = high[0] < low[2]
if bullishFvg and show_IMB
box.new(left=bar_index - 1, top=low[0], right=bar_index + fvgboxLength, bottom=high[2], bgcolor=color.new(imbalancecolor, fvgTransparency), border_color=color.new(imbalancecolor, fvgTransparency))
if bearishFvg and show_IMB
box.new(left=bar_index - 1, top=low[2], right=bar_index + fvgboxLength, bottom=high[0], bgcolor=color.new(imbalancecolor, fvgTransparency), border_color=color.new(imbalancecolor, fvgTransparency))
//////////////////// FVG //////////////////
|
Cumulative Weighted Exponential Moving Average (CWEMA) | https://www.tradingview.com/script/TIFzkWJ0-Cumulative-Weighted-Exponential-Moving-Average-CWEMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © peacefulLizard50262
//@version=5
indicator("CWEEMA", overlay = true)
// Define the exponential moving average function
ema(src, len) => //{
alpha = 2 / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
// Define the weighted moving average function
wma(src, weights, int len) =>
// Compute the weighted sum of the source data
weightedSum = math.sum(src * weights, len)
// Compute the sum of the weights
sumWeights = math.sum(weights, len)
// Divide the weighted sum by the sum of the weights to calculate the weighted average
weightedSum / sumWeights
cweema(src, len) =>
// Compute the weights for each value in the moving average
weights = (len + 1) / 2 - math.abs(len - src)
// Calculate the weighted moving average
wma(ema(src, len), weights, len)
source = input.source(close, 'Source')
length = input.int(5, "Length", 1)
plot(cweema(source, length))
|
10 pips | https://www.tradingview.com/script/nzI0gTmy-10-pips/ | DECODEDMAN | https://www.tradingview.com/u/DECODEDMAN/ | 80 | 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/
// © d3cod3dman
//@version=5
indicator("10 pips", overlay = true)
pips = input.float(10, "How many pips to offset?", group = "First range")
color color1 = input.color(color.rgb(0, 55, 255), "Color for range 1", group = "First range")
use2 = input.bool(true, "Show second range?", group = "Second range")
pips2 = input.float(20, "How many pips to offset?", group = "Second range")
color color2 = input.color(color.rgb(78, 199, 255), "Color for range 2", group = "Second range")
lineLenght = input.int(2, "Length of the lines", 1, 10, 1,group = "Properties of the lines")
lineWidth = input.int(2, "Width of the lines", 1, 3,group = "Properties of the lines")
var lup = line.new(0,0,0,0)
var ldown = line.new(0,0,0,0)
var lup2 = line.new(0,0,0,0)
var ldown2 = line.new(0,0,0,0)
if syminfo.mintick == 0.00001
pips := pips*10*syminfo.mintick
pips2 := pips2*10*syminfo.mintick
if syminfo.mintick == 0.001
pips := pips*10*syminfo.mintick
pips2 := pips2*10*syminfo.mintick
if syminfo.mintick == 0.01
pips := pips*10*syminfo.mintick
pips2 := pips2*10*syminfo.mintick
if syminfo.mintick > 0.2
pips := pips
pips2 := pips2
if timeframe.isintraday
line.delete(lup)
line.delete(ldown)
lup := line.new(bar_index, close + pips, bar_index[lineLenght], close + pips, color=color1, style=line.style_solid, width=lineWidth)
ldown := line.new(bar_index, close - pips, bar_index[lineLenght], close - pips, color=color1, style=line.style_solid, width=lineWidth)
if use2
line.delete(lup2)
line.delete(ldown2)
lup2 := line.new(bar_index, close + pips2, bar_index[lineLenght], close + pips2, color=color2, style=line.style_solid, width=lineWidth)
ldown2 := line.new(bar_index, close - pips2, bar_index[lineLenght], close - pips2, color=color2, style=line.style_solid, width=lineWidth) |
Prime, E & PI Superiority Cycles | https://www.tradingview.com/script/6xQjPl78-Prime-E-PI-Superiority-Cycles/ | Eliza123123 | https://www.tradingview.com/u/Eliza123123/ | 133 | 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/
// © Eliza123123 & david4342
//@version=5
indicator("Prime, E & PI Superiority Cycles", overlay = true, max_lines_count = 200)
// Inputs
Prime = input.bool(true, "On/Off", "", inline = "Colour", group = "Prime Frame")
PrimeCol = input.color(color.new(color.olive,0), "", inline = "Colour", group = "Prime Frame")
Euler = input.bool(true, "On/Off", "", inline = "Colour", group = "E Frame")
EulerCol = input.color(color.new(color.green,0), "", inline = "Colour", group = "E frame")
Pi = input.bool(true, "On/Off", "", inline = "Colour", group = "Pi Frame")
PiCol = input.color(color.new(color.maroon,0), "", inline = "Colour", group = "Pi Frame")
//---------------------FRAME CREATION CODE-------------------//
// Define constants
pi = 3.14159
e = 2.71828
// Initialises and assigns values to the Prime Frame, E frame and Pi Frame.
float[] primes = array.from(2.0,3.0,5.0,7.0,11.0,13.0,17.0,19.0,23.0,27.0,29.0,31.0,37.0,41.0,43.0,47.0,53.0,59.0,61.0,67.0,71.0,73.0,79.0,83.0,89.0,97.0)
float[] eLevels = array.from(2.71828, 5.43656, 8.15484, 10.87312, 13.5914, 16.30968, 19.02796, 21.74624, 24.46452, 27.1828, 29.90108, 32.61936, 35.33764,
38.05592, 40.7742, 43.49248, 46.21076, 48.92904, 51.64732, 54.3656, 57.08388, 59.80216, 62.52044, 65.23872, 67.957, 70.67528, 73.39356000000001, 76.11184,
78.83012, 81.5484, 84.26668000000001, 86.98496, 89.70324, 92.42152, 95.13980000000001, 97.85808)
float[] piLevels = array.from(3.14159, 6.28318, 9.424769999999999, 12.56636, 15.70795, 18.849539999999998, 21.99113, 25.13272, 28.27431, 31.4159, 34.55749,
37.699079999999995, 40.840669999999996, 43.98226, 47.12385, 50.26544, 53.40703, 56.54862, 59.69021, 62.8318, 65.97339, 69.11498, 72.25657, 75.39815999999999,
78.53975, 81.68133999999999, 84.82293, 87.96452, 91.10611, 94.2477, 97.38929)
// Function gets scaling for the asset. This is important as the elements from primes, eLevels and piLevels array need to mutiplied by scale to ensure indicator works on all assets
get_scale_func() =>
get_scale = 0.0
if (close >= 10 and close < 100)
get_scale := 1
if (close >= 100 and close < 1000)
get_scale := 10
if (close >= 1000 and close < 10000)
get_scale := 100
if (close >= 1 and close < 10)
get_scale := 0.1
if (close >= 0.1 and close < 1)
get_scale := 0.01
if (close >= 0.01 and close < 0.1)
get_scale := 0.001
if (close >= 0.001 and close < 0.01)
get_scale := 0.0001
if (close >= 0.0001 and close < 0.001)
get_scale := 0.00001
if (close >= 0.00001 and close < 0.0001)
get_scale := 0.000001
if (close > 10000)
get_scale := 1000
get_scale
// Calls and assings cale from get_scale_func()
scale = get_scale_func()
// Color switch for on/off switches
if Pi
PiCol
else
PiCol := na
if Euler
EulerCol
else
EulerCol := na
if Prime
PrimeCol
else
PrimeCol := na
// Function to create frames defined by a constant to be iterated up the chart
create_frame_func(fFrame, showLines, frameCol) =>
a = 1
lw = a % 10 == 0 ? 4 : 1
while a <= (100.0 / (fFrame / scale))
if barstate.islast and showLines
line.new(bar_index[4999], fFrame * a, bar_index, fFrame * a, color = frameCol, width = lw, extend = extend.both)
a += 1
// Generates e and pi frame
closest_pi_percent = create_frame_func(3.14159 * scale, true, PiCol) // Pi
closest_e_percent = create_frame_func(2.71828 * scale, true, EulerCol) // Euler's Constant
// Generates prime frame
i = 0
while i < array.size(primes)
a = array.get(primes, i)
v = a * scale
line = line.new (bar_index[1], v, bar_index, v, color = PrimeCol, width = 1, extend = extend.both)
i += 1
//---------------------END OF FRAME CREATION CODE-------------------//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//---------------------SUPERIORITY CYCLE CODE-------------------//
// Initialise high and low arrays
float [] highsArray = array.new_float(0)
float [] lowsArray = array.new_float(0)
// Add last 11 highs/lows to arrays
for j = 0 to 10
array.push(highsArray, high[j])
array.push(lowsArray, low[j])
// Boolean condition to ensure five highs to the left and five highs to the right are all lower than the central high in the array high[5] & counter logic for lows
bool highPiv = array.max(highsArray) == high[5]
bool lowPiv = array.min(lowsArray) == low[5]
// Assigns most recent high pivot and low pivot float values
float lastHighPivPrice = ta.valuewhen(highPiv, high[5], 0)
float lastLowPivPrice = ta.valuewhen(lowPiv, low[5], 0)
// Function to determine the distance from the last high or low pivot to the nearest level in a given frame
distanceFromStructureToPiv(taFloatValue, float[] y) =>
thisScale = get_scale_func()
get_dist = array.new_float(0)
float minimisedValue = 0.0
float arrayex_var = array.get(y, 0) * thisScale
for k = 1 to array.size(y) - 2
float arrayex_var2 = array.get(y, k) * thisScale
if (math.abs(taFloatValue - arrayex_var2) < math.abs(taFloatValue - arrayex_var))
arrayex_var := arrayex_var2
array.push(get_dist, math.abs(taFloatValue - arrayex_var))
minimisedValue := array.get(get_dist, 0)
minimisedValue
// Creates six float values for data comparison each containing 1 minimised value
float highPiv_primeFrame = distanceFromStructureToPiv(lastHighPivPrice, primes), float lowPiv_primeFrame = distanceFromStructureToPiv(lastLowPivPrice, primes)
float highPiv_eFrame = distanceFromStructureToPiv(lastHighPivPrice, eLevels), float lowPiv_eFrame = distanceFromStructureToPiv(lastLowPivPrice, eLevels)
float highPiv_piFrame = distanceFromStructureToPiv(lastHighPivPrice, piLevels), float lowPiv_piFrame = distanceFromStructureToPiv(lastLowPivPrice, piLevels)
// Creates array of each frames performance
superiorityFunction(xHigh, xLow, xArray, yHigh, yLow, yArray, zHigh, zLow, zArray) =>
results = array.new_float(0)
xSuperiority = (xHigh + xLow < yHigh + yLow) and (xHigh + xLow < zHigh + zLow)
var xSuperiorityCount = 0
if xSuperiority
xSuperiorityCount := (xSuperiorityCount + 1)
ySuperiority = (yHigh + yLow < xHigh + xLow) and (yHigh + yLow < zHigh + zLow)
var ySuperiorityCount = 0
if ySuperiority
ySuperiorityCount := (ySuperiorityCount + 1)
zSuperiority = (zHigh + zLow < xHigh + xLow) and (zHigh + zLow < yHigh + yLow)
var zSuperiorityCount = 0
if zSuperiority
zSuperiorityCount := (zSuperiorityCount + 1)
array.push(results, xSuperiorityCount / array.size(xArray))
array.push(results, ySuperiorityCount / array.size(yArray))
array.push(results, zSuperiorityCount / array.size(zArray))
results
//superiorityFunction() call to create array of frame performances
float [] sfArray = superiorityFunction(highPiv_primeFrame, lowPiv_primeFrame, primes, highPiv_eFrame, lowPiv_eFrame, eLevels, highPiv_piFrame, lowPiv_piFrame, piLevels)
// Finds worst performing frame and retrieves index from array
lowest = array.max(sfArray, 0)
index = array.indexof(sfArray, lowest)
// bgcolors correspond to which frame to target trades at next.
// ----> if bgcolor is olive target prime frame reversals
// ----> if bgcolor is green target e frame reversals
// ----> if bgcolor is maroon target pi frame reversals
bgcolor(color = index == 0 ? color.new(color.olive, 80) : na)
bgcolor(color = index == 1 ? color.new(color.green, 80) : na)
bgcolor(color = index == 2 ? color.new(color.maroon, 80) : na)
// Table showing which frame to target reversals on and the respective scores of each frame.
var dataTable = table.new(position = position.bottom_right, columns = 2, rows = 5, bgcolor = color.black, border_width = 1)
table.cell(table_id = dataTable, column = 0, row = 1, text = "Next target: Prime Superiority (Olive lines on chart)", bgcolor = index == 0 ? color.olive : color.white, text_color = index == 0 ? color.white : #000000)
table.cell(table_id = dataTable, column = 0, row = 2, text = "Next target: E Superiority (Green lines on chart)", bgcolor = index == 1 ? color.green : color.white, text_color = index == 1 ? color.white : #000000)
table.cell(table_id = dataTable, column = 0, row = 3, text = "Next target: Pi Superiority (Maroon Lines on chart)", bgcolor = index == 2 ? color.maroon : color.white, text_color = index == 2 ? color.white : #000000)
table.cell(table_id = dataTable, column = 0, row = 4, text = "[Prime Score, E Score, Pi Score]: " + str.tostring(sfArray), bgcolor = color.white, text_color = #000000)
//---------------------END OF SUPERIORITY CYCLE CODE-------------------// |
Cumulative Weighted Triple Exponential Moving Average (CWTEMA) | https://www.tradingview.com/script/cVA8QEco-Cumulative-Weighted-Triple-Exponential-Moving-Average-CWTEMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 81 | 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/
// © peacefulLizard50262
//@version=5
indicator("CWTEMA", overlay = true)
// Define the triple exponential moving average function
tema(src, len) =>
// Compute the weights for each value in the moving average
weights = (len + 1) / 2 - math.abs(len - src)
// Calculate the triple exponential moving average
tema = 3 * ta.ema(src, len) - 3 * ta.ema(ta.ema(src, len), len) + ta.ema(ta.ema(ta.ema(src, len), len), len)
// Define the weighted moving average function
wma(src, weights, int len) =>
// Compute the weighted sum of the source data
weightedSum = math.sum(src * weights, len)
// Compute the sum of the weights
sumWeights = math.sum(weights, len)
// Divide the weighted sum by the sum of the weights to calculate the weighted average
weightedSum / sumWeights
cweema(src, len) =>
// Compute the weights for each value in the moving average
weights = (len + 1) / 2 - math.abs(len - src)
// Calculate the weighted moving average
wma(tema(src, len), weights, len)
source = input.source(close, 'Source')
length = input.int(100, "Length", 1)
plot(cweema(source, length))
|
Oscillator Extremes | https://www.tradingview.com/script/kUevXr7J-Oscillator-Extremes/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 59 | 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('Oscillator Extremes', shorttitle = 'OSC EXTREME', overlay= false)
//Inputs//
src = input.source(close)
LengthInput = input.int(14, minval=1, title='Oscillator Length')
type = input.string('RSI', title='Oscillator', options=['RSI', 'MOM','CCI','CMO','ROC'])
//Oscillator Selection//
Multi_OSC(type, src, LengthInput) =>
float result = 0
if type == "RSI"
result := ta.rsi(src, LengthInput)
if type == "MOM"
result := ta.mom(src, LengthInput)
if type == "CCI"
result := ta.cci(src, LengthInput)
if type == 'CMO'
result := ta.cmo(src,LengthInput)
if type == 'ROC'
result := ta.roc(src,LengthInput)
result
//BB//
OscMax = ta.max(Multi_OSC(type,src, LengthInput))
OscMin= ta.min(Multi_OSC(type,src, LengthInput))
BBsrc = (((Multi_OSC(type,src, LengthInput))-OscMin)/(OscMax-OscMin))*100
length = input.int(20, minval=1, title='BB Length')
mult = input.float(2.0, minval=0.001, maxval=50, title='BB Mult')
float basis = ta.sma(BBsrc, length)
float dev = mult * ta.stdev(BBsrc, length)
upper = basis + dev
lower = basis - dev
//Fplus/Fminus//
Fplus = upper - BBsrc
Fminus= BBsrc-lower
hline=(0)
//ADX//
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sigmax = ta.max(adx(dilen,adxlen))
sigmin= ta.min(adx(dilen, adxlen))
sig = ((adx(dilen, adxlen)-sigmin)/(sigmax-sigmin))*100
//Plots//
AdxSig= plot(sig, title='ADX', color= sig >= sig[1] ? color.rgb(57, 16, 65): color.white, linewidth=2)
Upper = plot(Fplus, title='Bullish', color= Fplus < Fminus ? color.rgb(16, 49, 17) : color.gray, linewidth= 3)
Lower = plot(Fminus, title= 'Bearish', color= Fminus < Fplus ? color.rgb(59, 16, 16) : color.gray, linewidth= 3)
ZeroLine= plot(hline, title='Zero Line', color=color.white) |
Vector Magnitude | https://www.tradingview.com/script/K6HDVEU7-Vector-Magnitude/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Vector Magnitude")
// Define the getVectorDirection() function
getVectorDirection(src, len) =>
// Calculate the average of the vector
avg = ta.sma(src, len)
// Determine the direction of the vector
direction = src[0] > avg[0] ? 1 : (src[0] < avg[0] ? -1 : 0)
// Calculate the magnitude of the vector
magnitude = math.sqrt((src[0] - avg[0]) * (src[0] - avg[0]) + (src[1] - avg[1]) * (src[1] - avg[1]) + (src[2] - avg[2]) * (src[2] - avg[2]))
// Return the direction and magnitude of the vector
out = direction == 1 ? magnitude : direction == -1 ? -magnitude : 0
out
len = input.int(30, "Length", 1)
plot(getVectorDirection(close, len))
|
Gedhusek TrendFibonacci | https://www.tradingview.com/script/JhZujkH3-Gedhusek-TrendFibonacci/ | Gedhusek | https://www.tradingview.com/u/Gedhusek/ | 324 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gedhusek
//@version=5
indicator("Gedhusek TrendFibonacci",shorttitle="G FiboTrend",scale=scale.left)
BackStep = input.int(50,"Analysis Period")
lowerValue = input.float(0.382,"Lower Fibonacci Level",options=[0.236, 0.382, 0.50, 0.618, 0.786])
upperValue = input.float(0.618,"Upper Fibonacci Level",options=[0.236, 0.382, 0.50, 0.618, 0.786])
showFill = input.bool(true,"Show Filling")
changeCandle = input.bool(true,"Change Candle Color")
atr = ta.atr(200)
max = ta.highest(close,BackStep)
min = ta.lowest(close,BackStep)
lowerFib = min + (max-min)*lowerValue
upperFib = min + (max-min)*upperValue
ma = ta.wma(close,6)
float closeVal = ma
float openVal = ma
color clrToUse = closeVal>upperFib and openVal>upperFib?color.green:closeVal<lowerFib and openVal<lowerFib?color.red:color.yellow
maxLine = plot(max,color=color.green)
minLine = plot(min,color=color.red)
LowerFibLine = plot(lowerFib,color=color.rgb(228, 255, 75, 20))
UpperFibLine = plot(upperFib,color=color.rgb(228, 255, 75, 20))
fill(maxLine,UpperFibLine,color=showFill?color.rgb(0,255,0,changeCandle?95:70):na)
fill(UpperFibLine,LowerFibLine,color=showFill?color.rgb(228, 255, 75, changeCandle?95:70):na)
fill(LowerFibLine,minLine,color=showFill?color.rgb(255,0,0,changeCandle?95:70):na)
plotcandle(open,high,low,close,"Bar",color=changeCandle?clrToUse:na,wickcolor=changeCandle?clrToUse:na,bordercolor=changeCandle?clrToUse:na)
float LowerRetracement = (max-min)*0.318
float UpperRetracement = (max-min)*0.618
|
Buyer to Seller Volume (BSV) Indicator | https://www.tradingview.com/script/v7LTDK4s-Buyer-to-Seller-Volume-BSV-Indicator/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 511 | 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("Buyer to Seller Volume (BSV)")
BackgroundData(symbol, timeframe, data) =>
isLive = barstate.isrealtime
request.security(symbol, timeframe, data[isLive ? 1 : 0])[isLive ? 0 : 1]
InSession(sessionTimes, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTimes, sessionTimeZone))
higherTimeFrame = input.timeframe("D", title="Time Frame")
AvgLength = input.int(14, title="Average Length")
greencandle = (close > open)
redcandle = (open > close)
greencandlevolume = if greencandle
volume
redcandlevolume = if redcandle
volume
// Vol Over time
BuyAverage = BackgroundData(syminfo.tickerid, higherTimeFrame, math.sum(greencandlevolume, AvgLength))
SellAverage = BackgroundData(syminfo.tickerid, higherTimeFrame, math.sum(redcandlevolume, AvgLength))
buyvolmax = ta.highest(BuyAverage, AvgLength)
buyvolmin = ta.lowest(BuyAverage, AvgLength)
sellvolmax = ta.highest(SellAverage, AvgLength)
sellvolmin = ta.lowest(SellAverage, AvgLength)
bool buyvolmaxatmax = BuyAverage >= buyvolmax
bool buyvolminatmin = BuyAverage <= buyvolmin
bool sellvolmax2 = SellAverage >= sellvolmax
bool sellvolmin2 = SellAverage >= sellvolmin
// Color
color volBullColorInput = input.color(color.green, "Bull")
color volBearColorInput = input.color(color.red, "Bear")
color neutralinput = input.color(color.gray, "Neutral")
color maxbuyers = input.color(color.fuchsia, "Max Buyers")
color minbuyers = input.color(color.black, "Max Sellers")
color buyerneutral = input.color(color.black, "Buyers Neutral")
color buyavgcolor = buyvolmaxatmax ? minbuyers : volBullColorInput
color sellavgcolor = sellvolmax2 ? neutralinput : volBearColorInput
// SMA Vol
volavg = (BuyAverage + SellAverage) / 2
sma = ta.sma(volavg, AvgLength)
plot(sma, "SMA", color=color.yellow)
//plot(br, style=plot.style_histogram, color = pallette)
plot(BuyAverage, "Buyer Volume", color = volBullColorInput, linewidth=2)
plot(SellAverage, "Seller Volume", color = volBearColorInput, linewidth=2) |
Triple Exponential Hull Moving Average THMA | https://www.tradingview.com/script/FMqiXARS-Triple-Exponential-Hull-Moving-Average-THMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 31 | 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/
// © peacefulLizard50262
//@version=5
indicator("THMA", overlay = true)
gaussianma(values, length) =>
// Define the standard deviation of the Gaussian distribution
stddev = length / 4
// Generate an array of indices from 1 to length
indices = ta.range(1, length)
// Calculate the Gaussian weights for each value in the array
weights = math.exp(-0.5 * (math.pow((indices - length), 2) / math.pow(stddev, 2)))
// Calculate the weighted sum of the values
sum = math.sum(values * weights, length)
// Return the moving average
sum / math.sum(weights, length)
ema(src, len, a) => //{
alpha = a / (len + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
thma(src, len, a, smoothing) =>
gaussianma(ema(ema(ema(src, int(len/2), a), int(math.sqrt(len/2)), a), int(math.sqrt(len/2)), a), smoothing)
Source = input.source(close)
Length = input.int(200, minval = 2)
alpha = input.float(10, "Alpha", 0.01, step = 0.5)
smoothing = input.int(1, "Smoothing", 1)
thma = thma(Source, Length, alpha, smoothing)
hma_dif = (thma - thma[2])/2
colour = math.sign(hma_dif) == 1 ? color.green : color.red
plot(thma, "EHMA", colour)
|
Daily Reset CWEMA/CWTEMA | https://www.tradingview.com/script/StuKjTWo-Daily-Reset-CWEMA-CWTEMA/ | peacefulLizard50262 | https://www.tradingview.com/u/peacefulLizard50262/ | 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/
// © peacefulLizard50262
//@version=5
indicator("Daily Reset CWEMA", overlay = true)
source = input.source(close, 'Source')
length = input.int(20, "Length", 1)
style = input.string("CWTEMA", "Style", ["CWEMA","CWTEMA"])
newday = timeframe.change("D")
bs_nd = ta.barssince(newday) + 1
v_len = (timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly) ? length : bs_nd < length ? bs_nd : length
ema(src) => //{
alpha = 2 / (bs_nd + 1)
sum = 0.0
sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
// Define the triple exponential moving average function
tema(src) =>
// Compute the weights for each value in the moving average
weights = (v_len + 1) / 2 - math.abs(v_len - src)
// Calculate the triple exponential moving average
tema = 3 * ema(src) - 3 * ema(ema(src)) + ema(ema(ema(src)))
// Define the weighted moving average function
wma(src, weights) =>
// Compute the weighted sum of the source data
weightedSum = math.sum(src * weights, v_len)
// Compute the sum of the weights
sumWeights = math.sum(weights, v_len)
// Divide the weighted sum by the sum of the weights to calculate the weighted average
weightedSum / sumWeights
cwema(src) =>
// Compute the weights for each value in the moving average
weights = (v_len + 1) / 2 - math.abs(v_len - src)
// Calculate the weighted moving average
wma(ema(src), weights)
cwtema(src) =>
// Compute the weights for each value in the moving average
weights = (v_len + 1) / 2 - math.abs(v_len - src)
// Calculate the weighted moving average
wma(tema(src), weights)
ma(src, len, style)=>
switch style
"CWEMA" => cwema(src)
"CWTEMA" => cwtema(src)
plot(ma(source, length, style))
|
Key Points of Adjoining Median (KPAM) | https://www.tradingview.com/script/bXXk4gXL-Key-Points-of-Adjoining-Median-KPAM/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 70 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © More-Than-Enough
//@version=5
indicator(title = "Key Points of Adjoining Median", shorttitle = "KPAM", precision = 3)
RSI = ta.rsi(close, 14) * 0.1 - 5
float Stoch = ta.sma(ta.stoch(close, high, low, 14) * 0.1 - 5, 1)
float Stoch_RSI = ta.sma(ta.stoch(RSI, RSI, RSI, 14) * 0.1 - 5, 3)
float KPAM = 0.0
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch < 0
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI < 0 and Stoch >= 0
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
Smoothing_Amount = input(5, "KPAM Smoothing")
Smooth_KPAM = ta.ema(KPAM, Smoothing_Amount)
/////////////// Thresholds ///////////////
SOLID = "Solid"
DASHED = "Dashed"
DOTTED = "Dotted"
Top_Color = input.color(color.rgb(255, 245, 157, 50), "", inline = "Top Line", group = "Top Line")
Top_Style = input.string(DOTTED, "", [SOLID, DASHED, DOTTED], inline = "Top Line", group = "Top Line")
Top_Width = input.int(1, "", [1, 2, 3, 4], inline = "Top Line", group = "Top Line")
Top = input.float(4.0, "", minval = 0.0, step = 0.1, inline = "Top Line", group = "Top Line")
High_Color = input.color(color.rgb(187, 217, 251, 30), "", inline = "High Line", group = "High Line")
High_Style = input.string(DOTTED, "", [SOLID, DASHED, DOTTED], inline = "High Line", group = "High Line")
High_Width = input.int(1, "", [1, 2, 3, 4], inline = "High Line", group = "High Line")
Mid = 0
Mid_Color = input.color(color.rgb(255, 245, 157, 70), "", inline = "Middle Line", group = "Middle Line")
Mid_Style = input.string(SOLID, "", [SOLID, DASHED, DOTTED], inline = "Middle Line", group = "Middle Line")
Mid_Width = input.int(1, "", [1, 2, 3, 4], inline = "Middle Line", group = "Middle Line")
Low_Color = input.color(color.rgb(187, 217, 251, 30), "", inline = "Low Line", group = "Low Line")
Low_Style = input.string(DOTTED, "", [SOLID, DASHED, DOTTED], inline = "Low Line", group = "Low Line")
Low_Width = input.int(1, "", [1, 2, 3, 4], inline = "Low Line", group = "Low Line")
Bottom_Color = input.color(color.rgb(255, 245, 157, 50), "", inline = "Bottom Line", group = "Bottom Line")
Bottom_Style = input.string(DOTTED, "", [SOLID, DASHED, DOTTED], inline = "Bottom Line", group = "Bottom Line")
Bottom_Width = input.int(1, "", [1, 2, 3, 4], inline = "Bottom Line", group = "Bottom Line")
Bottom = input.float(-4.0, "", maxval = 0.0, step = 0.1, inline = "Bottom Line", group = "Bottom Line")
Set_Style(style) =>
Output = switch style
SOLID => hline.style_solid
DASHED => hline.style_dashed
DOTTED => hline.style_dotted
Set_Width(width) =>
Output = switch width
1 => 1
2 => 2
3 => 3
4 => 4
/////////////// Plots ///////////////
Top_Line = hline(Top, "Top Line", Top_Color, Set_Style(Top_Style), Set_Width(Top_Width), false)
High_Line = hline(Mid + ((math.abs(Top) - math.abs(Mid)) / 2), "High Line", High_Color, Set_Style(High_Style), Set_Width(High_Width), false)
Mid_Line = hline(Mid, "Middle Line", Mid_Color, Set_Style(Mid_Style), Set_Width(Mid_Width), false)
Low_Line = hline(Mid - ((math.abs(Mid) + math.abs(Bottom)) / 2), "Low Line", Low_Color, Set_Style(Low_Style), Set_Width(Low_Width), false)
Bottom_Line = hline(Bottom, "Bottom Line", Bottom_Color, Set_Style(Bottom_Style), Set_Width(Bottom_Width), false)
fill(High_Line, Top_Line, color.new(color.aqua, 85), "Top Zone")
fill(Mid_Line, High_Line, color.rgb(33, 150, 243, 90), "High Zone")
fill(Mid_Line, Low_Line, color.rgb(33, 150, 243, 90), "Low Zone")
fill(Low_Line, Bottom_Line, color.new(color.aqua, 85), "Bottom Zone")
plot(RSI, "RSI", color = color.rgb(206, 147, 216), linewidth = 2)
S = plot(Stoch, "Stoch", color = color.aqua, display = display.none)
SR = plot(Stoch_RSI, "Stoch RSI", color = color.orange, display = display.none)
plot(KPAM, "KPAM", color.rgb(255, 249, 196))
plot(Smooth_KPAM, "Smooth KPAM", color.white, 2, display = display.none)
fill(S, SR, color.rgb(255, 249, 196, 75), title = "Discordance") |
Midnight Open NY Time | https://www.tradingview.com/script/ahysJP0t-Midnight-Open-NY-Time/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 244 | 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/
// ©ALPHAICTRADER
//@version=5
indicator("Midnight Open", "Midnight Open", true, max_lines_count=500)
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(#58A2B0,52), "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)
//===========================
|
Bands Bands (BanB) | https://www.tradingview.com/script/qrweXGiv-Bands-Bands-BanB/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 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/
// © More-Than-Enough
//@version=5
indicator("Bands Bands", "BanB", true)
Spikes_On = input.bool(false, "Spike Bands")
Arls_On = input.bool(true, "ARL Bands")
Plunges_On = input.bool(false, "Plunge Bands")
Middle = 0.0
A = 0.5
B = 1.2
C = 1.8
D = 2.3
E = 3.15
F = 4.0
G = 5.0
H = 8.0
I = 11.0
/// ARL Bands ///
Length = 14
Exponent = 0
Source = hlc3
Secondary_Source = low
ARL = (ta.ema(Secondary_Source, Length)[1] + (Source - ta.ema(Secondary_Source, Length)[1]) / (Length * math.pow(Source / ta.ema(close, Length)[1], Exponent)))
Arl_Peak = ARL * (1.00 + (F * 0.01))
Arl_Top = ARL * (1.00 + (E * 0.01))
Arl_High = ARL * (1.00 + (D * 0.01))
Arl_Mid_Peak = ARL * (1.00 + (C * 0.01))
Arl_Mid_Top = ARL * (1.00 + (B * 0.01))
Arl_Mid_High = ARL * (1.00 + (A * 0.01))
Arl_Middle = ARL * (1.00 + (Middle * 0.01))
Arl_Mid_Low = ARL * (1.00 + (-A * 0.01))
Arl_Mid_Bottom = ARL * (1.00 + (-B * 0.01))
Arl_Mid_Dip = ARL * (1.00 + (-C * 0.01))
Arl_Low = ARL * (1.00 + (-D * 0.01))
Arl_Bottom = ARL * (1.00 + (-E * 0.01))
Arl_Dip = ARL * (1.00 + (-F * 0.01))
/// Spike Bands ///
Top_Spike_Line = ta.sma(low - (ta.atr(20) * -I), 75)
Middle_Spike_Line = ta.sma(low - (ta.atr(20) * -H), 75)
Bottom_Spike_Line = ta.sma(low - (ta.atr(20) * -G), 75)
/// Plunge Bands ///
Top_Plunge_Line = ta.sma(low - (ta.atr(20) * G), 75)
Middle_Plunge_Line = ta.sma(low - (ta.atr(20) * H), 75)
Bottom_Plunge_Line = ta.sma(low - (ta.atr(20) * I), 75)
/// Plots ///
plot(Spikes_On ? Top_Spike_Line : na, "Spike Top Line", color.rgb(34, 171, 148), linewidth = 3)
plot(Spikes_On ? Middle_Spike_Line: na, "Spike Middle Line", color.rgb(102, 187, 106), linewidth = 3)
plot(Spikes_On ? Bottom_Spike_Line: na, "Spike Bottom Line", color.rgb(165, 214, 167), linewidth = 3)
plot(Plunges_On ? Top_Plunge_Line : na, "Plunge Top Line", color.rgb(250, 161, 164), linewidth = 3)
plot(Plunges_On ? Middle_Plunge_Line : na, "Plunge Middle Line", color.rgb(247, 82, 95), linewidth = 3)
plot(Plunges_On ? Bottom_Plunge_Line : na, "Plunge Bottom Line", color.rgb(178, 40, 51), linewidth = 3)
Peak_Line = plot(Arls_On ? Arl_Peak : na, "Peak", color.rgb(178, 235, 242), linewidth = 2)
Top_Line = plot(Arls_On ? Arl_Top : na, "Top", color.rgb(77, 208, 225), linewidth = 2)
High_Line = plot(Arls_On ? Arl_High : na, "High", color.rgb(0, 151, 167), linewidth = 2)
Mid_Peak_Line = plot(Arls_On ? Arl_Mid_Peak : na, "Middle Peak", color.rgb(0, 151, 167))
Mid_Top_Line = plot(Arls_On ? Arl_Mid_Top : na, "Middle Top", color.gray)
Mid_High_Line = plot(Arls_On ? Arl_Mid_High : na, "Middle High", color.gray)
Middle_Line = plot(Arls_On ? Arl_Middle : na, "Middle", color.white, display = display.none)
Mid_Low_Line = plot(Arls_On ? Arl_Mid_Low : na, "Middle Low", color.gray)
Mid_Bottom_Line = plot(Arls_On ? Arl_Mid_Bottom : na, "Middle Bottom", color.gray)
Mid_Dip_Line = plot(Arls_On ? Arl_Mid_Dip : na, "Middle Dip", color.rgb(0, 151, 167))
Low_Line = plot(Arls_On ? Arl_Low : na, "Low", color.rgb(0, 151, 167), linewidth = 2)
Bottom_Line = plot(Arls_On ? Arl_Bottom : na, "Bottom", color.rgb(77, 208, 225), linewidth = 2)
Dip_Line = plot(Arls_On ? Arl_Dip : na, "Dip", color.rgb(178, 235, 242), linewidth = 2)
fill(Top_Line, Peak_Line, color.rgb(0, 151, 167, 85), "Peak Zone")
fill(High_Line, Top_Line, color.rgb(77, 208, 225, 85), "Top Zone")
fill(Mid_High_Line, High_Line, color.rgb(178, 235, 242, 85), "High Zone")
fill(Mid_Low_Line, Mid_High_Line, color.rgb(91, 156, 246, 85), "Middle Zone")
fill(Mid_Low_Line, Low_Line, color.rgb(178, 235, 242, 85), "Low Zone")
fill(Low_Line, Bottom_Line, color.rgb(77, 208, 225, 85), "Bottom Zone")
fill(Bottom_Line, Dip_Line, color.rgb(0, 151, 167, 85), "Dip Zone")
/// Alerts ///
Opportunity = ta.crossunder(low, Arl_Mid_Dip) or ta.crossover(high, Arl_Mid_Peak)
alertcondition(Opportunity, "Opportunity Zone", "Opportunity reached!") |
Sessions [LuxAlgo] | https://www.tradingview.com/script/bkb6vZDz-Sessions-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 4,186 | 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("Sessions [LuxAlgo]", "LuxAlgo - Sessions", overlay = true, max_bars_back = 500, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
//Session A
show_sesa = input(true, '', inline = 'sesa', group = 'Session A')
sesa_txt = input('New York', '', inline = 'sesa', group = 'Session A')
sesa_ses = input.session('1300-2200', '', inline = 'sesa', group = 'Session A')
sesa_css = input.color(#ff5d00, '', inline = 'sesa', group = 'Session A')
sesa_range = input(true, 'Range', inline = 'sesa_overlays', group = 'Session A')
sesa_tl = input(false, 'Trendline', inline = 'sesa_overlays', group = 'Session A')
sesa_avg = input(false, 'Mean', inline = 'sesa_overlays', group = 'Session A')
sesa_vwap = input(false, 'VWAP', inline = 'sesa_overlays', group = 'Session A')
sesa_maxmin = input(false, 'Max/Min', inline = 'sesa_overlays', group = 'Session A')
//Session B
show_sesb = input(true, '', inline = 'sesb', group = 'Session B')
sesb_txt = input('London', '', inline = 'sesb', group = 'Session B')
sesb_ses = input.session('0700-1600', '', inline = 'sesb', group = 'Session B')
sesb_css = input.color(#2157f3, '', inline = 'sesb', group = 'Session B')
sesb_range = input(true, 'Range', inline = 'sesb_overlays', group = 'Session B')
sesb_tl = input(false, 'Trendline', inline = 'sesb_overlays', group = 'Session B')
sesb_avg = input(false, 'Mean', inline = 'sesb_overlays', group = 'Session B')
sesb_vwap = input(false, 'VWAP', inline = 'sesb_overlays', group = 'Session B')
sesb_maxmin = input(false, 'Max/Min', inline = 'sesb_overlays', group = 'Session B')
//Session C
show_sesc = input(true, '', inline = 'sesc', group = 'Session C')
sesc_txt = input('Tokyo', '', inline = 'sesc', group = 'Session C')
sesc_ses = input.session('0000-0900', '', inline = 'sesc', group = 'Session C')
sesc_css = input.color(#e91e63, '', inline = 'sesc', group = 'Session C')
sesc_range = input(true, 'Range', inline = 'sesc_overlays', group = 'Session C')
sesc_tl = input(false, 'Trendline', inline = 'sesc_overlays', group = 'Session C')
sesc_avg = input(false, 'Mean', inline = 'sesc_overlays', group = 'Session C')
sesc_vwap = input(false, 'VWAP', inline = 'sesc_overlays', group = 'Session C')
sesc_maxmin = input(false, 'Max/Min', inline = 'sesc_overlays', group = 'Session C')
//Session D
show_sesd = input(true, '', inline = 'sesd', group = 'Session D')
sesd_txt = input('Sydney', '', inline = 'sesd', group = 'Session D')
sesd_ses = input.session('2100-0600', '', inline = 'sesd', group = 'Session D')
sesd_css = input.color(#ffeb3b, '', inline = 'sesd', group = 'Session D')
sesd_range = input(true, 'Range', inline = 'sesd_overlays', group = 'Session D')
sesd_tl = input(false, 'Trendline', inline = 'sesd_overlays', group = 'Session D')
sesd_avg = input(false, 'Mean', inline = 'sesd_overlays', group = 'Session D')
sesd_vwap = input(false, 'VWAP', inline = 'sesd_overlays', group = 'Session D')
sesd_maxmin = input(false, 'Max/Min', inline = 'sesd_overlays', group = 'Session D')
//Timezones
tz_incr = input.int(0, 'UTC (+/-)', group = 'Timezone')
use_exchange = input(false, 'Use Exchange Timezone', group = 'Timezone')
//Ranges Options
bg_transp = input.float(90, 'Range Area Transparency', group = 'Ranges Settings')
show_outline = input(true, 'Range Outline', group = 'Ranges Settings')
show_txt = input(true, 'Range Label', group = 'Ranges Settings')
//Dashboard
show_dash = input(false, 'Show Dashboard', group = 'Dashboard')
advanced_dash = input(false, 'Advanced Dashboard', group = 'Dashboard')
dash_loc = input.string('Top Right', 'Dashboard Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
text_size = input.string('Small', 'Dashboard Size', options = ['Tiny', 'Small', 'Normal'], group = 'Dashboard')
//Divider
show_ses_div = input(false, 'Show Sessions Divider', group = 'Dividers')
show_day_div = input(true, 'Show Daily Divider', group = 'Dividers')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index
//Get session average
get_avg(session)=>
var len = 1
var float csma = na
var float sma = na
if session > session[1]
len := 1
csma := close
if session and session == session[1]
len += 1
csma += close
sma := csma / len
sma
//Get trendline coordinates
get_linreg(session)=>
var len = 1
var float cwma = na
var float csma = na
var float csma2 = na
var float y1 = na
var float y2 = na
var float stdev = na
var float r2 = na
if session > session[1]
len := 1
cwma := close
csma := close
csma2 := close * close
if session and session == session[1]
len += 1
csma += close
csma2 += close * close
cwma += close * len
sma = csma / len
wma = cwma / (len * (len + 1) / 2)
cov = (wma - sma) * (len+1)/2
stdev := math.sqrt(csma2 / len - sma * sma)
r2 := cov / (stdev * (math.sqrt(len*len - 1) / (2 * math.sqrt(3))))
y1 := 4 * sma - 3 * wma
y2 := 3 * wma - 2 * sma
[y1 , y2, stdev, r2]
//Session Vwap
get_vwap(session) =>
var float num = na
var float den = na
if session > session[1]
num := close * volume
den := volume
else if session and session == session[1]
num += close * volume
den += volume
else
num := na
[num, den]
//Set line
set_line(session, y1, y2, session_css)=>
var line tl = na
if session > session[1]
tl := line.new(n, close, n, close, color = session_css)
if session and session == session[1]
line.set_y1(tl, y1)
line.set_xy2(tl, n, y2)
//Set session range
get_range(session, session_name, session_css)=>
var t = 0
var max = high
var min = low
var box bx = na
var label lbl = na
if session > session[1]
t := time
max := high
min := low
bx := box.new(n, max, n, min
, bgcolor = color.new(session_css, bg_transp)
, border_color = show_outline ? session_css : na
, border_style = line.style_dotted)
if show_txt
lbl := label.new(t, max, session_name
, xloc = xloc.bar_time
, textcolor = session_css
, style = label.style_label_down
, color = color.new(color.white, 100)
, size = size.tiny)
if session and session == session[1]
max := math.max(high, max)
min := math.min(low, min)
box.set_top(bx, max)
box.set_rightbottom(bx, n, min)
if show_txt
label.set_xy(lbl, int(math.avg(t, time)), max)
[session ? na : max, session ? na : min]
//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period
var tz = use_exchange ? syminfo.timezone :
str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))
is_sesa = math.sign(nz(time(tf, sesa_ses, tz)))
is_sesb = math.sign(nz(time(tf, sesb_ses, tz)))
is_sesc = math.sign(nz(time(tf, sesc_ses, tz)))
is_sesd = math.sign(nz(time(tf, sesd_ses, tz)))
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dash_loc == 'Bottom Left' ? position.bottom_left
: dash_loc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = text_size == 'Tiny' ? size.tiny
: text_size == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 5, 6
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if barstate.isfirst and show_dash
table.cell(tb, 0, 0, 'LuxAlgo', text_color = color.white, text_size = table_size)
table.merge_cells(tb, 0, 0, 4, 0)
table.cell(tb, 0, 2, sesa_txt, text_color = sesa_css, text_size = table_size)
table.cell(tb, 0, 3, sesb_txt, text_color = sesb_css, text_size = table_size)
table.cell(tb, 0, 4, sesc_txt, text_color = sesc_css, text_size = table_size)
table.cell(tb, 0, 5, sesd_txt, text_color = sesd_css, text_size = table_size)
if advanced_dash
table.cell(tb, 0, 1, 'Session', text_color = color.white
, text_size = table_size)
table.cell(tb, 1, 1, 'Status', text_color = color.white
, text_size = table_size)
table.cell(tb, 2, 1, 'Trend', text_color = color.white
, text_size = table_size)
table.cell(tb, 3, 1, 'Volume', text_color = color.white
, text_size = table_size)
table.cell(tb, 4, 1, 'σ', text_color = color.white
, text_size = table_size)
if barstate.islast and show_dash
table.cell(tb, 1, 2, is_sesa ? 'Active' : 'Innactive'
, bgcolor = is_sesa ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 1, 3, is_sesb ? 'Active' : 'Innactive'
, bgcolor = is_sesb ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 1, 4, is_sesc ? 'Active' : 'Innactive'
, bgcolor = is_sesc ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 1, 5, is_sesd ? 'Active' : 'Innactive'
, bgcolor = is_sesd ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
//-----------------------------------------------------------------------------}
//Overlays
//-----------------------------------------------------------------------------{
var float max_sesa = na
var float min_sesa = na
var float max_sesb = na
var float min_sesb = na
var float max_sesc = na
var float min_sesc = na
var float max_sesd = na
var float min_sesd = na
//Ranges
if show_sesa and sesa_range
[max, min] = get_range(is_sesa, sesa_txt, sesa_css)
max_sesa := max
min_sesa := min
if show_sesb and sesb_range
[max, min] = get_range(is_sesb, sesb_txt, sesb_css)
max_sesb := max
min_sesb := min
if show_sesc and sesc_range
[max, min] = get_range(is_sesc, sesc_txt, sesc_css)
max_sesc := max
min_sesc := min
if show_sesd and sesd_range
[max, min] = get_range(is_sesd, sesd_txt, sesd_css)
max_sesd := max
min_sesd := min
//Trendlines
if show_sesa and (sesa_tl or advanced_dash)
[y1, y2, stdev, r2] = get_linreg(is_sesa)
if advanced_dash
table.cell(tb, 2, 2, str.tostring(r2, '#.##')
, bgcolor = r2 > 0 ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 4, 2, str.tostring(stdev, '#.####')
, text_color = color.white
, text_size = table_size)
if sesa_tl
set_line(is_sesa, y1, y2, sesa_css)
if show_sesb and (sesb_tl or advanced_dash)
[y1, y2, stdev, r2] = get_linreg(is_sesb)
if advanced_dash
table.cell(tb, 2, 3, str.tostring(r2, '#.##')
, bgcolor = r2 > 0 ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 4, 3, str.tostring(stdev, '#.####')
, text_color = color.white
, text_size = table_size)
if sesb_tl
set_line(is_sesb, y1, y2, sesb_css)
if show_sesc and (sesc_tl or advanced_dash)
[y1, y2, stdev, r2] = get_linreg(is_sesc)
if advanced_dash
table.cell(tb, 2, 4, str.tostring(r2, '#.##')
, bgcolor = r2 > 0 ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 4, 4, str.tostring(stdev, '#.####')
, text_color = color.white
, text_size = table_size)
if sesc_tl
set_line(is_sesc, y1, y2, sesc_css)
if show_sesd and (sesd_tl or advanced_dash)
[y1, y2, stdev, r2] = get_linreg(is_sesd)
if advanced_dash
table.cell(tb, 2, 5, str.tostring(r2, '#.##')
, bgcolor = r2 > 0 ? #089981 : #f23645
, text_color = color.white
, text_size = table_size)
table.cell(tb, 4, 5, str.tostring(stdev, '#.####')
, text_color = color.white
, text_size = table_size)
if sesd_tl
set_line(is_sesd, y1, y2, sesd_css)
//Mean
if show_sesa and sesa_avg
avg = get_avg(is_sesa)
set_line(is_sesa, avg, avg, sesa_css)
if show_sesb and sesb_avg
avg = get_avg(is_sesb)
set_line(is_sesb, avg, avg, sesb_css)
if show_sesc and sesc_avg
avg = get_avg(is_sesc)
set_line(is_sesc, avg, avg, sesc_css)
if show_sesd and sesd_avg
avg = get_avg(is_sesd)
set_line(is_sesd, avg, avg, sesd_css)
//VWAP
var float vwap_a = na
var float vwap_b = na
var float vwap_c = na
var float vwap_d = na
if show_sesa and (sesa_vwap or advanced_dash)
[num, den] = get_vwap(is_sesa)
if sesa_vwap
vwap_a := num / den
if advanced_dash
table.cell(tb, 3, 2, str.tostring(den, format.volume)
, text_color = color.white
, text_size = table_size)
if show_sesb and (sesb_vwap or advanced_dash)
[num, den] = get_vwap(is_sesb)
if sesb_vwap
vwap_b := num / den
if advanced_dash
table.cell(tb, 3, 3, str.tostring(den, format.volume)
, text_color = color.white
, text_size = table_size)
if show_sesc and (sesc_vwap or advanced_dash)
[num, den] = get_vwap(is_sesc)
if sesc_vwap
vwap_c := num / den
if advanced_dash
table.cell(tb, 3, 4, str.tostring(den, format.volume)
, text_color = color.white
, text_size = table_size)
if show_sesd and (sesd_vwap or advanced_dash)
[num, den] = get_vwap(is_sesd)
if sesd_vwap
vwap_d := num / den
if advanced_dash
table.cell(tb, 3, 5, str.tostring(den, format.volume)
, text_color = color.white
, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Plot max/min
plot(sesa_maxmin ? max_sesa : na, 'Session A Maximum', sesa_css, 1, plot.style_linebr)
plot(sesa_maxmin ? min_sesa : na, 'Session A Minimum', sesa_css, 1, plot.style_linebr)
plot(sesb_maxmin ? max_sesb : na, 'Session B Maximum', sesb_css, 1, plot.style_linebr)
plot(sesb_maxmin ? min_sesb : na, 'Session B Minimum', sesb_css, 1, plot.style_linebr)
plot(sesc_maxmin ? max_sesc : na, 'Session C Maximum', sesc_css, 1, plot.style_linebr)
plot(sesc_maxmin ? min_sesc : na, 'Session C Minimum', sesc_css, 1, plot.style_linebr)
plot(sesd_maxmin ? max_sesd : na, 'Session D Maximum', sesd_css, 1, plot.style_linebr)
plot(sesd_maxmin ? min_sesd : na, 'Session D Minimum', sesd_css, 1, plot.style_linebr)
//Plot vwaps
plot(vwap_a, 'Session A VWAP', sesa_css, 1, plot.style_linebr)
plot(vwap_b, 'Session B VWAP', sesb_css, 1, plot.style_linebr)
plot(vwap_c, 'Session C VWAP', sesc_css, 1, plot.style_linebr)
plot(vwap_d, 'Session D VWAP', sesd_css, 1, plot.style_linebr)
//Plot Divider A
plotshape(is_sesa and show_ses_div and show_sesa, "·"
, shape.square
, location.bottom
, na
, text = "."
, textcolor = sesa_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(is_sesa != is_sesa[1] and show_ses_div and show_sesa, "NYE"
, shape.labelup
, location.bottom
, na
, text = "❚"
, textcolor = sesa_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
//Plot Divider B
plotshape(is_sesb and show_ses_div and show_sesb, "·"
, shape.labelup
, location.bottom
, na
, text = "."
, textcolor = sesb_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(is_sesb != is_sesb[1] and show_ses_div and show_sesb, "LDN"
, shape.labelup
, location.bottom
, na
, text = "❚"
, textcolor = sesb_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
//Plot Divider C
plotshape(is_sesc and show_ses_div and show_sesc, "·"
, shape.square
, location.bottom
, na
, text = "."
, textcolor = sesc_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(is_sesc != is_sesc[1] and show_ses_div and show_sesc, "TYO"
, shape.labelup
, location.bottom
, na
, text = "❚"
, textcolor = sesc_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
//Plot Divider D
plotshape(is_sesd and show_ses_div and show_sesd, "·"
, shape.labelup
, location.bottom
, na
, text = "."
, textcolor = sesd_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(is_sesd != is_sesd[1] and show_ses_div and show_sesd, "SYD"
, shape.labelup
, location.bottom
, na
, text = "❚"
, textcolor = sesd_css
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
//-----------------------------------------------------------------------------}
//Plots daily dividers
//-----------------------------------------------------------------------------{
day = dayofweek
if day != day[1] and show_day_div
line.new(n, close + syminfo.mintick, n, close - syminfo.mintick
, color = color.gray
, extend = extend.both
, style = line.style_dashed)
plotshape(day != day[1] and day == 1 and show_day_div, "Sunday"
, shape.labeldown
, location.top
, na
, text = "Sunday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 2 and show_day_div, "Monday"
, shape.labeldown
, location.top
, na
, text = "Monday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 3 and show_day_div, "Tuesday"
, shape.labeldown
, location.top
, na
, text = "Tuesday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 4 and show_day_div, "Wednesay"
, shape.labeldown
, location.top
, na
, text = "Wednesday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 5 and show_day_div, "Thursday"
, shape.labeldown
, location.top
, na
, text = "Thursday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 6 and show_day_div, "Friday"
, shape.labeldown
, location.top
, na
, text = "Friday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
plotshape(day != day[1] and day == 7 and show_day_div, "Saturday"
, shape.labeldown
, location.top
, na
, text = "Saturday"
, textcolor = color.gray
, size = size.tiny
, display = display.all - display.status_line
, editable = false)
//-----------------------------------------------------------------------------} |
Correlated ATR MA | Adulari | https://www.tradingview.com/script/GisfirS2-Correlated-ATR-MA-Adulari/ | Adulari | https://www.tradingview.com/u/Adulari/ | 61 | 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/
// ©Adulari
// @version=5
indicator("Correlated ATR MA | Adulari", overlay = true)
// Inputs
weight = input.int(1, title='Weight', minval=1, group='General Settings')
length = input.int(200, title='Length', minval=1, group='General Settings')
atrlength = input.int(14, title='ATR Length', minval=1, group='General Settings')
smoothing = input.int(50, title='Smoothing', minval=1, group='General Settings')
source = input(close, title='Source', group='General Settings')
tfAdaptive = input.bool(true, title='Timeframe Adaptive', group='Advanced Settings')
tfMultiplier = input.int(15, title='Multiplier', inline='Timeframe Adaptive', group='Advanced Settings')
// Adaptive Weight
tfStrength = if tfAdaptive
if timeframe.in_seconds(timeframe.period)/60>=60
0.0
else
tfMultiplier/timeframe.in_seconds(timeframe.period)/60
else
0.0
// Calculations
var value = 0.
atr = ta.atr(atrlength)
correlation = ta.correlation(atr, source, length)
value := correlation * atr + (1 - correlation) * nz(atr[1], atr)
flength = int(math.max(length/smoothing,1))
normalMA = ta.hma(source,smoothing)
ma = (ta.hma((1-(correlation/100*(1+weight/10)))*(ta.sma(source+value, smoothing)+ta.sma(source-value,smoothing))/2,flength)+normalMA*tfStrength)/(1+tfStrength)
// Colors
beColor = #675F76
buColor = #a472ff
raColor = #b4a7d6
// Plots
plot(ma, title='Moving Average', color=ma>ma[2] ? buColor : beColor, linewidth=2) |
Session Zones | https://www.tradingview.com/script/hkGIezOJ-Session-Zones/ | syntaxgeek | https://www.tradingview.com/u/syntaxgeek/ | 49 | 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/
// © syntaxgeek
//@version=5
indicator("Session Zones", "SZ", overlay=true, scale=scale.none)
// <inputs>
i_timezone = input.string("America/New_York", title="Timezone")
// session 1
i_session1Name = input.string("US Session", title="Identifier", group="Session 1")
i_session1 = input.session("0930-1600", title="Range", group="Session 1")
i_session1BgColor = input.color(color.new(color.gray, 80), title="Background", group="Session 1", inline="color")
i_session1Enabled = input.bool(true, "Display?", group="Session 1")
i_session1Alerts = input.bool(true, "Alert Entry/Exit?", group="Session 1")
// session 2
i_session2Name = input.string("EU Session", title="Identifier", group="Session 2")
i_session2 = input.session("0300-1230", title="Range", group="Session 2")
i_session2BgColor = input.color(color.new(color.aqua, 80), title="Background", group="Session 2", inline="color")
i_session2Enabled = input.bool(true, "Display?", group="Session 2")
i_session2Alerts = input.bool(true, "Alert Entry/Exit?", group="Session 2")
// session 3
i_session3Name = input.string("HK Session", title="Identifier", group="Session 3")
i_session3 = input.session("2130-0400", title="Range", group="Session 3")
i_session3BgColor = input.color(color.new(color.fuchsia, 80), title="Background", group="Session 3", inline="color")
i_session3Enabled = input.bool(true, "Display?", group="Session 3")
i_session3Alerts = input.bool(true, "Alert Entry/Exit?", group="Session 3")
// session 4
i_session4Name = input.string("JP Session", title="Identifier", group="Session 4")
i_session4 = input.session("2000-0200", title="Range", group="Session 4")
i_session4BgColor = input.color(color.new(color.blue, 80), title="Background", group="Session 4", inline="color")
i_session4Enabled = input.bool(true, "Display?", group="Session 4")
i_session4Alerts = input.bool(true, "Alert Entry/Exit?", group="Session 4")
// session 5
i_session5Name = input.string("US ORB", title="Identifier", group="Session 5")
i_session5 = input.session("0930-0945", title="Range", group="Session 5")
i_session5BgColor = input.color(color.new(color.lime, 80), title="Background", group="Session 5", inline="color")
i_session5Enabled = input.bool(true, "Display?", group="Session 5")
i_session5Alerts = input.bool(true, "Alert Entry/Exit?", group="Session 5")
i_hideSessionTable = input.bool(false, "Hide Session Table?")
// </inputs>
// <funcs>
f_timeInRange(_session) => not na(time(timeframe.period, _session + ":23456", i_timezone)) ? 1 : 0
f_isNewTimeframeBar(_res) =>
t = time(_res)
not na(t) and (na(t[1]) or t > t[1])
f_calculateSessionTableRows() =>
count = 0
if i_session1Enabled
count := count + 1
if i_session2Enabled
count := count + 1
if i_session3Enabled
count := count + 1
if i_session4Enabled
count := count + 1
if i_session5Enabled
count := count + 1
count
f_isSessionEnabled(_session) =>
switch _session
1 => i_session1Enabled
2 => i_session2Enabled
3 => i_session3Enabled
4 => i_session4Enabled
5 => i_session5Enabled
=> false
f_sessionName(_session) =>
switch _session
1 => i_session1Name
2 => i_session2Name
3 => i_session3Name
4 => i_session4Name
5 => i_session5Name
=> ''
f_sessionBgColor(_session) =>
switch _session
1 => i_session1BgColor
2 => i_session2BgColor
3 => i_session3BgColor
4 => i_session4BgColor
5 => i_session5BgColor
=> color.new(color.white, 100)
f_addSessionTableRow(_sessionTable, _sessionTableRows, _session, _inSession) =>
if f_isSessionEnabled(_session)
v_row = _sessionTableRows + 1
table.cell(_sessionTable, row=v_row, column=0, text=f_sessionName(_session), text_color=color.black, bgcolor=color.white)
table.cell(_sessionTable, row=v_row, column=1, text=" ", bgcolor=color.new(f_sessionBgColor(_session), 0))
table.cell(_sessionTable, row=v_row, column=2, text=_inSession ? "In" : "Out", bgcolor=color.white)
v_row
else
_sessionTableRows
// </funcs>
// <vars>
var v_sessionTableTotalRows = f_calculateSessionTableRows()
var v_sessionTableRowsCreated = -1
var v_sessionTable = table.new(position=position.top_right, rows=v_sessionTableTotalRows, columns=3, border_width=1)
var v_in_session1 = false
var v_in_session2 = false
var v_in_session3 = false
var v_in_session4 = false
var v_in_session5 = false
v_in_session1 := f_timeInRange(i_session1)
v_in_session2 := f_timeInRange(i_session2)
v_in_session3 := f_timeInRange(i_session3)
v_in_session4 := f_timeInRange(i_session4)
v_in_session5 := f_timeInRange(i_session5)
if not i_hideSessionTable
v_sessionTableRowsCreated := f_addSessionTableRow(v_sessionTable, v_sessionTableRowsCreated, 1, v_in_session1)
v_sessionTableRowsCreated := f_addSessionTableRow(v_sessionTable, v_sessionTableRowsCreated, 2, v_in_session2)
v_sessionTableRowsCreated := f_addSessionTableRow(v_sessionTable, v_sessionTableRowsCreated, 3, v_in_session3)
v_sessionTableRowsCreated := f_addSessionTableRow(v_sessionTable, v_sessionTableRowsCreated, 4, v_in_session4)
v_sessionTableRowsCreated := f_addSessionTableRow(v_sessionTable, v_sessionTableRowsCreated, 5, v_in_session5)
if v_sessionTableRowsCreated == v_sessionTableTotalRows - 1
v_sessionTableRowsCreated := -1
// </vars>
// <plots>
bgcolor(i_session1Enabled and (v_in_session1 or v_in_session1[1]) ? i_session1BgColor : na, editable=false)
bgcolor(i_session2Enabled and (v_in_session2 or v_in_session2[1]) ? i_session2BgColor : na, editable=false)
bgcolor(i_session3Enabled and (v_in_session3 or v_in_session3[1]) ? i_session3BgColor : na, editable=false)
bgcolor(i_session4Enabled and (v_in_session4 or v_in_session4[1]) ? i_session4BgColor : na, editable=false)
bgcolor(i_session5Enabled and (v_in_session5 or v_in_session5[1]) ? i_session5BgColor : na, editable=false)
// </plots>
// <alerts>
if i_session1Enabled and i_session1Alerts and v_in_session1 and not v_in_session1[1]
alert("Entering " + i_session1Name, alert.freq_once_per_bar_close)
if i_session1Enabled and i_session1Alerts and v_in_session1[1] and not v_in_session1
alert("Exiting " + i_session1Name, alert.freq_once_per_bar_close)
if i_session2Enabled and i_session2Alerts and v_in_session2 and not v_in_session2[1]
alert("Entering " + i_session2Name, alert.freq_once_per_bar_close)
if i_session2Enabled and i_session2Alerts and v_in_session2[1] and not v_in_session2
alert("Exiting " + i_session2Name, alert.freq_once_per_bar_close)
if i_session3Enabled and i_session3Alerts and v_in_session3 and not v_in_session3[1]
alert("Entering " + i_session3Name, alert.freq_once_per_bar_close)
if i_session3Enabled and i_session3Alerts and v_in_session3[1] and not v_in_session3
alert("Exiting " + i_session3Name, alert.freq_once_per_bar_close)
if i_session4Enabled and i_session4Alerts and v_in_session4 and not v_in_session4[1]
alert("Entering " + i_session4Name, alert.freq_once_per_bar_close)
if i_session4Enabled and i_session4Alerts and v_in_session4[1] and not v_in_session4
alert("Exiting " + i_session4Name, alert.freq_once_per_bar_close)
if i_session5Enabled and i_session5Alerts and v_in_session5 and not v_in_session5[1]
alert("Entering " + i_session5Name, alert.freq_once_per_bar_close)
if i_session5Enabled and i_session5Alerts and v_in_session5[1] and not v_in_session5
alert("Exiting " + i_session5Name, alert.freq_once_per_bar_close)
// </alerts> |
Correlated ATR Bands | Adulari | https://www.tradingview.com/script/duBwXylJ-Correlated-ATR-Bands-Adulari/ | Adulari | https://www.tradingview.com/u/Adulari/ | 102 | 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/
// ©Adulari
// @version=5
indicator("Correlated ATR Bands | Adulari", overlay = true)
// Inputs
weight = input.int(5, title='Weight', minval=1, group='General Settings')
length = input.int(200, title='Length', minval=1, group='General Settings')
atrlength = input.int(14, title='ATR Length', minval=1, group='General Settings')
smoothing = input.int(50, title='Smoothing', minval=1, group='General Settings')
source = input(close, title='Source', group='General Settings')
multiplier = input.float(3, title='Multiplier', minval=0.1, step=0.1, group='General Settings')
inverse = input.bool(true, title='Inverse', group='Advanced Settings')
tfAdaptive = input.bool(true, title='Timeframe Adaptive', group='Advanced Settings')
tfMultiplier = input.int(15, title='Multiplier', inline='Timeframe Adaptive', group='Advanced Settings')
// Adaptive Strength
tfStrength = if tfAdaptive
if timeframe.in_seconds(timeframe.period)/60>=60
0.0
else
tfMultiplier/timeframe.in_seconds(timeframe.period)/60
else
0.0
// Calculations
var value = 0.
atr = ta.atr(atrlength)
correlation = ta.correlation(atr, source, length)
value := correlation * atr + (1 - correlation) * nz(atr[1], atr)
flength = int(math.max(length/smoothing,2))
ma = (ta.hma((1-(correlation/100*(1+weight/10)))*(ta.sma(source+value, smoothing)+ta.sma(source-value,smoothing))/2,flength)+ta.hma(source,length)*tfStrength)/(1+tfStrength)
if inverse
value := value/(value/multiplier/100)
svalue = ta.hma(value,length)/(math.max(tfStrength,1))
upperBand = ma+svalue*multiplier //old calculation: ta.hma(atr*multiplier+source, smoothing)
lowerBand = ma-svalue*multiplier //old calculation: ta.hma(source-atr*multiplier, smoothing)
// Colors
beColor = #675F76
buColor = #a472ff
raColor = #b4a7d6
// Plots
pMA = plot(ma, title='Moving Average', color=ma>ma[2] ? buColor : beColor, linewidth=2)
pUB = plot(upperBand, title='Upper Band', color=upperBand>upperBand[2] ? buColor : beColor, linewidth=2)
pLB = plot(lowerBand, title='Lower Band', color=lowerBand>lowerBand[2] ? buColor : beColor, linewidth=2)
fill(pMA,pLB,color=lowerBand>lowerBand[2] ? color.new(buColor,95) : color.new(beColor,95))
fill(pMA,pUB,color=upperBand>upperBand[2] ? color.new(buColor,95) : color.new(beColor,95)) |
Fixed Fibonacci Support Resistance | https://www.tradingview.com/script/BDC6umPC-Fixed-Fibonacci-Support-Resistance/ | F_rank_01 | https://www.tradingview.com/u/F_rank_01/ | 142 | 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/
// Source code is from Fibonacci levels MTF from © LonesomeTheBlue
// F_rank_01
//@version=5
indicator("Fixed Fibonacci Support Resistance", overlay = true, max_bars_back = 2000)
startTime = input.time(title="Start Time Selection", defval=timestamp("8 Dec 2022 14:30 0001"), confirm = true)
endTime = input.time(title="End Time Selection",defval=timestamp("9 Dec 2022 7:30 0001"), confirm = true)
extendFibo = input.bool(false, "extend fibonacci?")
showStartEnd = input.bool(true, "Show start/end white line?")
enable1 = input.bool(defval = true, title = "Level 1", inline = "1", group = "Fibonacci Levels")
level1 = input.float(defval = 0.66, title = "", minval = 0, inline = "1", group = "Fibonacci Levels")
color1 = input.color(defval = #4caf50, title = "Support color", inline = "1", group = "Fibonacci Levels")
color6 = input.color(defval = #f23645, title = "Resistance color", inline = "1", group = "Fibonacci Levels")
enable2 = input.bool(defval = true, title = "Level 2", inline = "2", group = "Fibonacci Levels")
level2 = input.float(defval = 1, title = "", minval = 0, inline = "2", group = "Fibonacci Levels")
color2 = input.color(defval = #787b86, title = "Support color", inline = "2", group = "Fibonacci Levels")
color7 = input.color(defval = #787b86, title = "Resistance color", inline = "2", group = "Fibonacci Levels")
enable3 = input.bool(defval = true, title = "Level 3", inline = "3", group = "Fibonacci Levels")
level3 = input.float(defval = 0.616, title = "", minval = 0, inline = "3", group = "Fibonacci Levels")
color3 = input.color(defval = #4caf50, title = "Support color", inline = "3", group = "Fibonacci Levels")
color8 = input.color(defval = #f23645, title = "Resistance color", inline = "3", group = "Fibonacci Levels")
enable4 = input.bool(defval = true, title = "Level 4", inline = "4", group = "Fibonacci Levels")
level4 = input.float(defval = 0.919, title = "", minval = 0, inline = "4", group = "Fibonacci Levels")
color4 = input.color(defval = #e91e63, title = "Support color", inline = "4", group = "Fibonacci Levels")
color9 = input.color(defval = #9c27b0, title = "Resistance color", inline = "4", group = "Fibonacci Levels")
enable5 = input.bool(defval = true, title = "Level 5", inline = "5", group = "Fibonacci Levels")
level5 = input.float(defval = 0.818, title = "", minval = 0, inline = "5", group = "Fibonacci Levels")
color5 = input.color(defval = #3179f5, title = "Support color", inline = "5", group = "Fibonacci Levels")
color10 = input.color(defval = #c2185b, title = "Resistance color", inline = "5", group = "Fibonacci Levels")
enable100 = input.bool(defval = true, title = "Level 6", inline = "100", group = "Fibonacci Levels")
level100 = input.float(defval = 0.786, title = "", minval = 0, inline = "100", group = "Fibonacci Levels")
color100 = input.color(defval = #3179f5, title = "Support color", inline = "100", group = "Fibonacci Levels")
color11 = input.color(defval = #c2185b, title = "Resistance color", inline = "100", group = "Fibonacci Levels")
_barForTime(_t) =>
var int _bar = na
if time == _t
_bar := last_bar_index - bar_index
_bar
int firstTime = _barForTime(startTime)
int secondTime = _barForTime(endTime)
int timeLength = firstTime - secondTime
highest(source, length) =>
float highest = na
array_high = array.new_float(length, na)
for i = 0 to length -1
array.set(array_high, i, source[i])
highest := array.max(array_high, 0)
highest
lowest(source, length) =>
float lowest = na
array_low = array.new_float(length, na)
for i = 0 to length -1
array.set(array_low, i, source[i])
lowest := array.min(array_low, 0)
lowest
high_ = ta.valuewhen(time == endTime, highest(high, timeLength), 0)
low_ = ta.valuewhen(time == endTime, lowest(low, timeLength), 0)
var enabled = array.from(enable100, enable5, enable4, enable3, enable2, enable1)
var levels = array.from(level100, level5, level4, level3, level2, level1)
var colors = array.from(color100, color5, color4, color3, color2, color1, color11, color10, color9, color8, color7, color6)
mlevelsSupport = array.new_float(7, na)
mlevelsResistance = array.new_float(7, na)
for x = 0 to array.size(levels) - 1
array.set(mlevelsSupport, x, array.get(enabled, x) ? (high_ - (high_ - low_) * array.get(levels, x)) : na)
array.set(mlevelsResistance, x, array.get(enabled, x) ? (low_ + (high_ - low_) * array.get(levels, x)) : na)
if barstate.ishistory and showStartEnd
startLine = line.new(bar_index[firstTime -1], close, bar_index[firstTime -1], open, extend = extend.both, color = color.white)
line.delete(startLine[1])
endLine = line.new(bar_index[secondTime -1], close, bar_index[secondTime -1], open, extend = extend.both, color = color.white)
line.delete(endLine[1])
// fibonacci levels
line1 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 0), bar_index[secondTime - 1], array.get(mlevelsSupport, 0), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 0))
line2 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 1), bar_index[secondTime - 1], array.get(mlevelsSupport, 1), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 1))
line3 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 2), bar_index[secondTime - 1], array.get(mlevelsSupport, 2), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 2))
line4 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 3), bar_index[secondTime - 1], array.get(mlevelsSupport, 3), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 3))
line5 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 4), bar_index[secondTime - 1], array.get(mlevelsSupport, 4), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 4))
line6 = line.new(bar_index[firstTime], array.get(mlevelsSupport, 5), bar_index[secondTime - 1], array.get(mlevelsSupport, 5), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 5))
line7 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 0), bar_index[secondTime - 1], array.get(mlevelsResistance, 0), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 6))
line8 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 1), bar_index[secondTime - 1], array.get(mlevelsResistance, 1), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 7))
line9 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 2), bar_index[secondTime - 1], array.get(mlevelsResistance, 2), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 8))
line10 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 3), bar_index[secondTime - 1], array.get(mlevelsResistance, 3), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 9))
line11 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 4), bar_index[secondTime - 1], array.get(mlevelsResistance, 4), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 10))
line12 = line.new(bar_index[firstTime], array.get(mlevelsResistance, 5), bar_index[secondTime - 1], array.get(mlevelsResistance, 5), extend = extendFibo ? extend.right : extend.none, color = array.get(colors, 11))
label1 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 0), str.tostring(level100), color = na, textcolor = array.get(colors, 0))
label2 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 1), str.tostring(level5), color = na, textcolor = array.get(colors, 1))
label3 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 2), str.tostring(level4), color = na, textcolor = array.get(colors, 2))
label4 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 3), str.tostring(level3), color = na, textcolor = array.get(colors, 3))
label5 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 4), str.tostring(level2), color = na, textcolor = array.get(colors, 4))
label6 = label.new(bar_index[firstTime + 10], array.get(mlevelsSupport, 5), str.tostring(level1), color = na, textcolor = array.get(colors, 5))
label7 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 0), str.tostring(level100), color = na, textcolor = array.get(colors, 6))
label8 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 1), str.tostring(level5), color = na, textcolor = array.get(colors, 7))
label9 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 2), str.tostring(level4), color = na, textcolor = array.get(colors, 8))
label10 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 3), str.tostring(level3), color = na, textcolor = array.get(colors, 9))
label11 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 4), str.tostring(level2), color = na, textcolor = array.get(colors, 10))
label12 = label.new(bar_index[firstTime + 10], array.get(mlevelsResistance, 5), str.tostring(level1), color = na, textcolor = array.get(colors, 11))
line.delete(line1[1])
line.delete(line2[1])
line.delete(line3[1])
line.delete(line4[1])
line.delete(line5[1])
line.delete(line6[1])
line.delete(line7[1])
line.delete(line8[1])
line.delete(line9[1])
line.delete(line10[1])
line.delete(line11[1])
line.delete(line12[1])
label.delete(label1[1])
label.delete(label2[1])
label.delete(label3[1])
label.delete(label4[1])
label.delete(label5[1])
label.delete(label6[1])
label.delete(label7[1])
label.delete(label8[1])
label.delete(label9[1])
label.delete(label10[1])
label.delete(label11[1])
label.delete(label12[1]) |
DollarVolume/MarketCap_Ratio (DVMC) | https://www.tradingview.com/script/KUzHIkYn-DollarVolume-MarketCap-Ratio-DVMC/ | polarbearking | https://www.tradingview.com/u/polarbearking/ | 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/
// © polarbearking
//@version=5
indicator(title = "DollarVolume/MarketCap_Ratio", shorttitle = "DVMC", overlay = false)
DVMC_MA_ON = input.bool(true, "SHOW DVMC__MOVING_AVERAGE (Default: True)")
DVMC_MA_LEN = input.int(50, "LENGTH: DVMC__MOVING_AVERAGE")
TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
MarketCap = TSO * close
DollarVolume = volume * close
DVMC = (DollarVolume / MarketCap) * 100
DVMC_MA = DVMC_MA_ON ? ta.sma(DVMC, DVMC_MA_LEN) : na
plot(DVMC, color = color.orange)
plot(DVMC_MA, color = color.blue) |
Gann Spiral / Square of 9 | https://www.tradingview.com/script/o6k0pyoU-Gann-Spiral-Square-of-9/ | S4M44R | https://www.tradingview.com/u/S4M44R/ | 230 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © S4M44R
//@version=5
indicator(title="Gann Spiral / Square of 9", shorttitle="Spiral / Sq9", overlay=true, max_lines_count=500)
// ----------------------
// -- Tips --
// ----------------------
modeTip = "Set which direction to draw price lines based on whether the input price is considered to be low, high, or both"
fTimeTip = "Set whether time lines are plotted in the future or the past."
priceTip = "Set the price value to use to draw price levels"
dateTip = "Set the time to use to draw time levels"
timeTip = "Set the timeframe to use to draw time levels"
denomTip = "ONLY USE IF YOU KNOW WHAT YOU'RE DOING! \n \nThis changes the value used to determine what constitutes as a full revolution. \n \nInputting 2π or ~ 6.28 will allow you to base your calculations on radians"
pLenTip = "Set the number of price levels to plot."
tLenTip = "Set the number of time levels to plot"
priceDegreeTip = "Set the degrees to rotate around a spiral to draw price levels. 1 Revolution = 360° \n \nThis is influenced by the Full Revolution Value"
timeDegreeTip = "Set the degrees to rotate around a spiral to draw time levels. 1 Revolution = 360° \n \nThis is influenced by the Full Revolution Value"
// ---------------------------
// -- User Inputs --
// ---------------------------
var iMode = input.string("Low", "Price Direction", options = ["Low", "High", "Both"], tooltip = modeTip, group = "Modes")
var fTime = input.string("Future", "Time Flip", options = ["Future", "Past"], tooltip = fTimeTip, group = "Modes")
var iPrice = input.price(1, "Price", confirm = true, tooltip = priceTip, group = "Price & Time")
var iDate = input.time(timestamp("20 Jul 2021 00:00 +0300"), "Date", confirm = true, tooltip = dateTip, group = "Price & Time")
var iTime = input.timeframe("D", "Timeframe", tooltip = timeTip, group = "Price & Time")
var iFullRev = input.float(360, "Full Revolution Value", tooltip = denomTip, group = "Price & Time")
pLen = input.int(16, "Price Lines", maxval = 500, minval = 1, tooltip = pLenTip, group = "Lines")
tLen = input.int(4, "Time Lines", maxval = 500, minval = 1, tooltip = tLenTip, group = "Lines")
var iPriceDegree = input.float(45, "Price Rotation Degree", tooltip = priceDegreeTip, group = "Degrees")
var iTimeDegree = input.float(45, "Time Rotation Degree", tooltip = timeDegreeTip, group = "Degrees")
var tPrice = input.bool(true, "Toggle Price", group = "Customization")
var tTime = input.bool(true, "Toggle Time", group = "Customization")
var cPrice = input.color(color.purple, "Price Color", group = "Customization")
var cTime = input.color(color.teal, "Time Color", group = "Customization")
var cMidLine = input.color(color.yellow, "Midline Color", group = "Customization")
var iPriceStyle = input.string("Dotted", "Price Line Style", options = ["Dotted", "Solid", "Dashed"], group = "Customization")
var iTimeStyle = input.string("Dotted", "Time Line Style", options = ["Dotted", "Solid", "Dashed"], group = "Customization")
var iTableLocation = input.string("Top Right", "Table Position", options = ["Top Right", "Top Center", "Middle Right"])
// ----------------------------
// -- Time to Unix --
// ----------------------------
// Borrow some code from TV docs to convert input timeframe to Unix
var float inputTf =
timeframe.multiplier * (
timeframe.isseconds ? 1. / 60 :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 60. * 24 :
timeframe.isweekly ? 60. * 24 * 7 :
timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
float unixTF = 60000 * request.security(syminfo.tickerid, iTime, inputTf)
// ---------------------------
// -- Initializer --
// ---------------------------
// Convert price to degrees for future use
initializer = iFullRev * math.sqrt(iPrice)
// Initialize arrays
var pLowValues = array.new_float()
var pHighValues = array.new_float()
var tValues = array.new_float()
// Calculate key levels for price and time to store in arrays
if barstate.islastconfirmedhistory
array.clear(pLowValues)
array.clear(pHighValues)
array.clear(tValues)
if tPrice
if iMode == "Low" or iMode == "Both"
for i = iMode == "Both" ? 1 : 0 to pLen
array.push(pLowValues, math.pow(((initializer + (iPriceDegree * i))/iFullRev), 2))
if iMode == "High" or iMode == "Both"
for i = iMode == "Both" ? 1 : 0 to iMode == "Both" ? pLen : pLen-1
dInc = (initializer - (iPriceDegree * i))
if dInc < 0
break
array.push(pHighValues, math.pow((dInc/iFullRev), 2))
if tTime
if fTime == "Future"
for i = 0 to tLen
array.push(tValues, math.pow((((iTimeDegree * i))/iFullRev), 2) * unixTF + iDate)
else
for i = 0 to tLen
array.push(tValues, iDate - math.pow((((iTimeDegree * i))/iFullRev), 2) * unixTF)
// ------------------------------
// -- Plotting Lines --
// ------------------------------
// Variables to track # of lines plotted
pLowLineNum = 0
pHighLineNum = 0
tLineNum = 0
// Arrays to hold lines
var iLine = array.new_line()
var pLine = array.new_line()
var tLine = array.new_line()
// Determine style from user input
var pStyle = iPriceStyle == "Dotted" ? line.style_dotted : iPriceStyle == "Solid" ? line.style_solid : iPriceStyle == "Dashed" ? line.style_dashed : na
var tStyle = iTimeStyle == "Dotted" ? line.style_dotted : iTimeStyle == "Solid" ? line.style_solid : iTimeStyle == "Dashed" ? line.style_dashed : na
// Draw mid line if "Both" is selected
if barstate.islastconfirmedhistory and iMode == "Both" and tPrice
array.push(iLine, line.new(0, iPrice, bar_index, iPrice, xloc=xloc.bar_time, color=cMidLine, extend=extend.both, style=pStyle))
// Loop to draw price lines
if barstate.islastconfirmedhistory and tPrice
pLowLineNum := 0
pHighLineNum := 0
if iMode == "Low" or iMode == "Both"
for i = 0 to pLen-1
if pLowLineNum >= 500 and iMode != "Both"
break
else if pLowLineNum >=250
break
array.push(pLine, line.new(0, array.get(pLowValues, i), bar_index, array.get(pLowValues, i), xloc=xloc.bar_time, color=cPrice, extend=extend.both, style=pStyle))
pLowLineNum += 1
if iMode == "High" or iMode == "Both"
for i = 0 to array.size(pHighValues)-1
if pHighLineNum >= 500 and iMode != "Both"
break
else if pHighLineNum >= 250
break
array.push(pLine, line.new(0, array.get(pHighValues, i), bar_index, array.get(pHighValues, i), xloc=xloc.bar_time, color=cPrice, extend=extend.both, style=pStyle))
pHighLineNum += 1
// Loop to draw time lines
if barstate.islastconfirmedhistory and tTime
array.clear(tLine)
tLineNum := 0
for i = 0 to tLen-1
if (pLowLineNum + pHighLineNum) >= 500 or tLineNum >= 500
break
array.push(tLine, line.new(int(array.get(tValues, i)), high, int(array.get(tValues, i)), low, xloc=xloc.bar_time, color=cTime, extend=extend.both, style=tStyle))
tLineNum += 1
// -----------------------------------
// -- Information Display --
// -----------------------------------
tableLocation = iTableLocation == "Top Right" ? position.top_right : iTableLocation == "Middle Right" ? position.middle_right : position.top_center
var squareNine = table.new(tableLocation, 3, 5, frame_width = 2, frame_color = color.black)
table.cell(squareNine, 1, 0, "Price", text_color = #5C87FF)
table.cell(squareNine, 2, 0, "Time", text_color = #5C87FF)
table.cell(squareNine, 0, 1, "Plotted Lines:", text_color = #D55D48)
table.cell(squareNine, 1, 1, str.tostring(pLowLineNum + pHighLineNum), text_color = #D55D48)
table.cell(squareNine, 2, 1, str.tostring(tLineNum), text_color = #D55D48)
table.cell(squareNine, 0, 2, "Degree:", text_color = color.green)
table.cell(squareNine, 1, 2, str.tostring(iPriceDegree, '#.###'), text_color = color.green)
table.cell(squareNine, 2, 2, str.tostring(iTimeDegree, '#.###'), text_color = color.green)
table.cell(squareNine, 0, 3, "Starting Degree:", text_color = color.teal)
table.cell(squareNine, 1, 3, str.tostring(initializer, '#.##'), text_color = color.teal)
table.cell(squareNine, 0, 4, "Price:", text_color = color.orange)
table.cell(squareNine, 1, 4, str.tostring(iPrice), text_color = color.orange) |
Recent Distance Dynamic Average | https://www.tradingview.com/script/CTXeY2nW-Recent-Distance-Dynamic-Average/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 19 | study | 5 | CC-BY-NC-SA-4.0 | // https://creativecommons.org/licenses/by-nc-sa/4.0/
// © kaigouthro
//@version=5
// experimental, checks highest distance from source to output
// and adjusts source input feed accordingly
// Recent Distance Dynamic Average
indicator("rdda" , 'rdda' , true )
varip src = float(na)
varip out = src
src := input.source ( close , 'Source' )
length = input.float ( 2 , 'Length' , 1 , 50 , step = 0.25 )
dynamic = input.float ( 1 , 'dynamic' , 1 , 50 , step = 0.25 )
out := nz ( out [1] , src )
dist = input.int ( 2 , 'Strain Distance' , 2 , 50 )
dif = nz (out[dist],src )
len = ( math.pow(ta.highest(math.max ( dif , src ) / math.min ( dif , src ),dist), dynamic ) ) / length
out += src * len
out /= 1 + len
plot(out,'ed',out>out[1]?input.color(#00ffff,'Rising'):input.color(#ff9001,'Falling'),input.bool(true,'Show')?2:na)
|
Average Daily Range Expansion Remaindeer for Daytrading | https://www.tradingview.com/script/GXwWs6Q7-Average-Daily-Range-Expansion-Remaindeer-for-Daytrading/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © greenmask9
//@version=5
indicator(title = "Average Daily Range Remaindeer", shorttitle = "ADRR", overlay = true)
i_full_style = input.string("Solid", title = "Line Style", options = ["Solid", "Dotted", "Dashed"], group="Full Expansion")
full_style = i_full_style == "Solid" ? line.style_solid : i_full_style == "Dotted" ? line.style_dotted : line.style_dashed
i_full_colour = input.color(color.new(#00bcd4,0), title = "Color", group="Full Expansion")
i_full_width = input.int(1, title = "Line Width", minval=1, group="Full Expansion")
i_full_enable = input.bool(true, "Enable", group="Full Expansion")
i_rem_style = input.string("Solid", title = "Line Style", options = ["Solid", "Dotted", "Dashed"], group="Remaining Expansion")
rem_style = i_rem_style == "Solid" ? line.style_solid : i_rem_style == "Dotted" ? line.style_dotted : line.style_dashed
i_rem_colour = input.color(color.new(#00bcd4,0), title = "Color", group="Remaining Expansion")
i_rem_width = input.int(1, title = "Line Width", minval=1, group="Remaining Expansion")
i_rem_enable = input.bool(true, "Enable", group="Remaining Expansion")
d_1 = request.security(syminfo.tickerid, "D", high[1]-low[1], lookahead=barmerge.lookahead_on)
d_2 = request.security(syminfo.tickerid, "D", high[2]-low[2], lookahead=barmerge.lookahead_on)
d_3 = request.security(syminfo.tickerid, "D", high[3]-low[3], lookahead=barmerge.lookahead_on)
d_4 = request.security(syminfo.tickerid, "D", high[4]-low[4], lookahead=barmerge.lookahead_on)
d_5 = request.security(syminfo.tickerid, "D", high[5]-low[5], lookahead=barmerge.lookahead_on)
ADR = (d_1 + d_2 + d_3 + d_4 + d_5) / 5
var new_day_x1 = 0
new_day = ADR != ADR[1]
if new_day
new_day_x1 := time
var full_expansion_upwards = line.new(na,na,na,na, xloc = xloc.bar_time, style = full_style, color = i_full_colour,width = i_full_width)
var full_expansion_downwards = line.new(na,na,na,na, xloc = xloc.bar_time, style = full_style, color = i_full_colour,width = i_full_width)
var remaining_expansion_upwards = line.new(na,na,na,na, xloc = xloc.bar_time, style = rem_style, color = i_rem_colour,width = i_rem_width)
var remaining_expansion_downwards = line.new(na,na,na,na, xloc = xloc.bar_time, style = rem_style, color = i_rem_colour,width = i_rem_width)
var float intra_high = na
var float intra_low = na
if new_day
if i_full_enable
line.set_xy1(full_expansion_upwards, new_day_x1, open + ADR)
line.set_xy2(full_expansion_upwards, time_close("1D"), open + ADR)
line.set_xy1(full_expansion_downwards, new_day_x1, open - ADR)
line.set_xy2(full_expansion_downwards, time_close("1D"), open - ADR)
intra_high := high
intra_low := low
if high > intra_high[1]
intra_high := high
if low < intra_low[1]
intra_low := low
remaining_adr = ADR - (intra_high - intra_low)
if i_rem_enable
line.set_xy1(remaining_expansion_upwards, time[1], intra_high + remaining_adr)
line.set_xy2(remaining_expansion_upwards, time_close("1D"), intra_high + remaining_adr)
line.set_xy1(remaining_expansion_downwards, time[1], intra_low - remaining_adr)
line.set_xy2(remaining_expansion_downwards, time_close("1D"), intra_low - remaining_adr) |
USTS Yield Curve Inversions | https://www.tradingview.com/script/W2QZsrc9-USTS-Yield-Curve-Inversions/ | dharmatech | https://www.tradingview.com/u/dharmatech/ | 128 | 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/
// © dharmatech
//@version=5
indicator("Yield Curve Inversion", overlay = false)
DGS30 = request.security("DGS30", "D", close)
DGS20 = request.security("DGS20", "D", close)
DGS10 = request.security("DGS10", "D", close)
DGS7 = request.security("DGS7", "D", close)
DGS5 = request.security("DGS5", "D", close)
DGS3 = request.security("DGS3", "D", close)
DGS2 = request.security("DGS2", "D", close)
DGS1 = request.security("DGS1", "D", close)
DGS6MO = request.security("DGS6MO", "D", close)
DGS3MO = request.security("DGS3MO", "D", close)
DGS1MO = request.security("DGS1MO", "D", close)
RRP = request.security("RRPONTSYAWARD", "D", close)
get_color(a, b) =>
if (b < a)
color.red
else if (b >= a)
color.green
else
color.black
plot(1.0, linewidth = 11, color = get_color(DGS20, DGS30))
plot(0.9, linewidth = 11, color = get_color(DGS10, DGS20))
plot(0.8, linewidth = 11, color = get_color(DGS7, DGS10))
plot(0.7, linewidth = 11, color = get_color(DGS5, DGS7))
plot(0.6, linewidth = 11, color = get_color(DGS3, DGS5))
plot(0.5, linewidth = 11, color = get_color(DGS2, DGS3))
plot(0.4, linewidth = 11, color = get_color(DGS1, DGS2))
plot(0.3, linewidth = 11, color = get_color(DGS6MO, DGS1))
plot(0.2, linewidth = 11, color = get_color(DGS3MO, DGS6MO))
plot(0.1, linewidth = 11, color = get_color(DGS1MO, DGS3MO))
plot(0.0, linewidth = 11, color = get_color(RRP, DGS1MO))
if barstate.islast
label.new(bar_index + 5, 1.0 - 0.03, "30Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.9 - 0.03, "20Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.8 - 0.03, "10Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.7 - 0.03, "7Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.6 - 0.03, "5Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.5 - 0.03, "3Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.4 - 0.03, "2Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.3 - 0.03, "1Y", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.2 - 0.03, "6M", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.1 - 0.03, "3M", style = label.style_none, textcolor = color.yellow)
label.new(bar_index + 5, 0.0 - 0.03, "1M", style = label.style_none, textcolor = color.yellow) |
Time Zone / Market Sessions | https://www.tradingview.com/script/CtTSZvGy-Time-Zone-Market-Sessions/ | traderharikrishna | https://www.tradingview.com/u/traderharikrishna/ | 334 | 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/
// © traderharikrishna
//@version=5
indicator("Time/Sessions",overlay=true)
/////////////////////////////////////////
showtime=input(true,'Show Time Sessions',group='TIME/SESSION')
var show_newyork_session = true and showtime
var newyork_color = input(title='New York Session Color', defval=color.rgb(10, 141, 242, 20),group='TIME/SESSION')
var newyork_text_color = input(title='New York Session Label Color', defval=color.rgb(10, 141, 242, 0),group='TIME/SESSION')
var newyork_position = input.string(title='New York Session Position', options=['Top', 'Bottom'], defval='Top',group='TIME/SESSION')
var show_london_session = true and showtime
var london_color = input(title='London Session Color', defval=color.rgb(80, 204, 27, 20),group='TIME/SESSION')
var london_text_color = input(title='London Session Label Color', defval=color.rgb(80, 204, 27, 0),group='TIME/SESSION')
var london_position = input.string(title='London Session Position', options=['Top', 'Bottom'], defval='Bottom',group='TIME/SESSION')
var show_tokyo_session = true and showtime
var tokyo_color = input(title='Tokyo Session Color', defval=color.rgb(252, 223, 3, 20),group='TIME/SESSION')
var tokyo_text_color = input(title='Tokyo Session Label Color', defval=color.rgb(252, 223, 3, 0),group='TIME/SESSION')
var tokyo_position = input.string(title='Tokyo Session Position', options=['Top', 'Bottom'], defval='Top',group='TIME/SESSION')
var show_sydney_session = true and showtime
var sydney_color = input(title='Sydney Session Color', defval=color.rgb(247, 72, 238, 20),group='TIME/SESSION')
var sydney_text_color = input(title='Sydney Session Label Color', defval=color.rgb(253, 75, 215),group='TIME/SESSION')
var sydney_position = input.string(title='Sydney Session Position', options=['Top', 'Bottom'], defval='Bottom',group='TIME/SESSION')
// sessions
newyork_session = time(timeframe.period, '0800-1600:1234567', 'America/New_York')
newyork_session_start = time(timeframe.period, '0800-0801:1234567', 'America/New_York')
plotshape(show_newyork_session ? newyork_session : na, style=shape.square, color=newyork_color, location=newyork_position == 'Top' ? location.top : location.bottom, size=size.auto)
plotshape(show_newyork_session ? newyork_session_start : na, style=shape.square, color=color.rgb(255, 255, 255, 255), textcolor=newyork_text_color, location=newyork_position == 'Top' ? location.top : location.bottom, size=size.auto, text='Newyork')
london_session = time(timeframe.period, '0300-1100:1234567', 'America/New_York')
london_session_start = time(timeframe.period, '0300-0301:1234567', 'America/New_York')
plotshape(show_london_session ? london_session : na, style=shape.square, color=london_color, location=london_position == 'Top' ? location.top : location.bottom, size=size.auto)
plotshape(show_london_session ? london_session_start : na, style=shape.square, color=color.rgb(0, 0, 0, 255), textcolor=london_text_color, location=london_position == 'Top' ? location.top : location.bottom, size=size.auto, text='London')
tokyo_session = time(timeframe.period, '1900-0300:1234567', 'America/New_York')
tokyo_session_start = time(timeframe.period, '1900-1901:1234567', 'America/New_York')
plotshape(show_tokyo_session ? tokyo_session : na, style=shape.square, color=tokyo_color, location=tokyo_position == 'Top' ? location.top : location.bottom, size=size.auto)
plotshape(show_tokyo_session ? tokyo_session_start : na, style=shape.square, color=color.rgb(0, 0, 0, 255), textcolor=tokyo_text_color, location=tokyo_position == 'Top' ? location.top : location.bottom, size=size.auto, text='Tokyo')
sydney_session = time(timeframe.period, '1700-0100:1234567', 'America/New_York')
sydney_session_start = time(timeframe.period, '1700-1701:1234567', 'America/New_York')
plotshape(show_sydney_session ? sydney_session : na, style=shape.square, color=sydney_color, location=sydney_position == 'Top' ? location.top : location.bottom, size=size.auto)
plotshape(show_sydney_session ? sydney_session_start : na, style=shape.square, color=color.rgb(0, 0, 0, 255), textcolor=sydney_text_color, location=sydney_position == 'Top' ? location.top : location.bottom, size=size.auto, text='Sydney')
// alerts
alertcondition(newyork_session_start, title='New York Session Open', message='New York Session Open')
alertcondition(london_session_start, title='London Session Open', message='London Session Open')
alertcondition(tokyo_session_start, title='Tokyo Session Open', message='Tokyo Session Open')
alertcondition(sydney_session_start, title='Sydney Session Open', message='Sydney Session Open')
markets = table.new(position.top_right, 4, 9, border_width=1)
if not showtime
table.cell(markets, 0, 0, text='OPEN', bgcolor=color.rgb(39, 133, 42),text_color=color.new(#ffffff, 0), text_size=size.small,text_halign=text.align_left)
table.cell(markets, 0, 1, text='NewYork ' + str.tostring(hour(timenow,"America/New_York"), "00:") + str.tostring(minute(timenow,"America/New_York"), "00:") + str.tostring(second(timenow,"America/New_York"), "00") + "", bgcolor=newyork_session?newyork_color:color.gray,text_color=color.new(#ffffff, 0), text_size=size.small,text_halign=text.align_left)
table.cell(markets, 0, 2, text='London '+ str.tostring(hour(timenow,"Europe/London"), "00:") + str.tostring(minute(timenow,"Europe/London"), "00:") + str.tostring(second(timenow,"Europe/London"), "00") + "", bgcolor=london_session?london_color:color.gray, text_color=color.new(#ffffff, 0), text_size=size.small,text_halign=text.align_left)
table.cell(markets, 0, 3, text='Tokyo '+ str.tostring(hour(timenow,"Asia/Tokyo"), "00:") + str.tostring(minute(timenow,"Asia/Tokyo"), "00:") + str.tostring(second(timenow,"Asia/Tokyo"), "00") + "", bgcolor=tokyo_session?tokyo_color:color.gray,text_color=color.new(#ffffff, 0), text_size=size.small,text_halign=text.align_left)
table.cell(markets, 0, 4, text='Sydney '+ str.tostring(hour(timenow,"Australia/Sydney"), "00:") + str.tostring(minute(timenow,"Australia/Sydney"), "00:") + str.tostring(second(timenow,"Australia/Sydney"), "00") + "", bgcolor= sydney_session?sydney_color:color.gray, text_color=color.new(#ffffff, 0), text_size=size.small,text_halign=text.align_left)
|
BIAS Notes | https://www.tradingview.com/script/qbBm0ak6-BIAS-Notes/ | UnknownUnicorn44422730 | https://www.tradingview.com/u/UnknownUnicorn44422730/ | 131 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Robthhh
//@version=5
indicator("BIAS Notes", overlay = true)
textSize = input.string(size.normal, 'Text Size', [size.tiny, size.small, size.normal, size.large, size.huge], inline='txt')
txt_1=input('','1.HTF',inline='first')
txt_2=input('','2.LTF', inline='second')
txt_3=input('','3.TF' , inline='third')
first = input.string("None", "Bias", options = ["None", "Bullish", "Bearish",'Wait'], inline='first')
secondary = input.string("None", "Bias", options = ["None", "Bullish", "Bearish",'Wait'], inline='second')
third = input.string('None', 'Bias', options = ["None", "Bullish", "Bearish",'Wait'], inline='third')
show_icons=input(false,'Show Icons under table?')
first_color = color.rgb(161, 161, 161)
secondary_color = color.rgb(161, 161, 161)
third_color = color.rgb(161, 161, 161)
if first == 'Bullish'
first_color := color.rgb(0, 152, 68)
if first == 'Bearish'
first_color := color.rgb(176, 48, 48)
if secondary == 'Bullish'
secondary_color := color.rgb(52, 172, 114, 20)
if secondary == 'Bearish'
secondary_color := color.rgb(206, 62, 62)
if third == 'Bullish'
third_color := color.rgb(121, 187, 30, 23)
if third == 'Bearish'
third_color := color.rgb(184, 53, 53, 39)
var table = table.new(position=position.top_right, columns=3, rows=3, border_color = color.black, border_width = 1)
table.cell(table, 0, 0, text = txt_1, bgcolor = first_color, text_color = color.white, text_size = textSize)
table.cell(table, 1, 0, text = txt_2, bgcolor = secondary_color, text_color = color.white, text_size = textSize)
table.cell(table, 2, 0, text = txt_3, bgcolor = third_color, text_color = color.white, text_size = textSize)
txt_4=input.string('','Icon',options=['','🟡','🟢','🔴','Wait'],inline='first')
txt_5=input.string('','Icon',options=['','🟡','🟢','🔴','Wait'],inline='second')
txt_6=input.string('','Icon',options=['','🟡','🟢','🔴','Wait'],inline='third')
if show_icons==true
table.cell(table, 0, 1, text = txt_4, bgcolor = color.white, text_color = color.black, text_size = textSize)
table.cell(table, 1, 1, text = txt_5, bgcolor = color.white, text_color = color.black, text_size = textSize)
table.cell(table, 2, 1, text = txt_6, bgcolor = color.white, text_color = color.black, text_size = textSize) |
True Momentum Oscillator | https://www.tradingview.com/script/VRwDppqd-True-Momentum-Oscillator/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 176 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo
//@version=5
indicator("True Momentum Oscillator", shorttitle = 'TMO', overlay=false)
//Inputs//
tmoleng= input.int(14,title='TMO Length')
calcLeng = input(5, title='Calcuated Length')
smoothLeng = input(3, title='Smooth Line Length')
lengType = input.string('EMA', title='TMO length moving average selection', options=['EMA', 'SMA', 'RMA','WVMA', 'VWAP','HULL'])
calcLengType = input.string('EMA', title='Calcalculated length moving average selection', options=['EMA', 'SMA', 'RMA','WVMA','VWAP','HULL'])
smoothLengType = input.string('EMA', title='Smooth length moving average selection', options=['EMA', 'SMA', 'RMA', 'WVMA', 'VWAP','HULL'])
//Moving Average Selection//
Multi_ma(type, src, len) =>
float result = 0
if type == "EMA"
result := ta.ema(src, len)
if type == "SMA"
result := ta.sma(src, len)
if type == "RMA"
result := ta.rma(src, len)
if type == 'WVMA'
result := ta.vwma(src,len)
if type == 'VWAP'
result := ta.vwap(src, len)
if type == 'HULL'
result := ta.hma(src, len)
result
//TMO//
OS=open
CS= close
dataset = 0
for i1 = 1 to tmoleng -1
if CS > OS[i1]
dataset := dataset + 1
if CS < OS[i1]
dataset := dataset - 1
MA = Multi_ma(lengType, dataset, calcLeng)
MainSignal = Multi_ma(calcLengType, MA, smoothLeng)
SmoothSignal =Multi_ma(smoothLengType, MainSignal, smoothLeng)
Hist=MainSignal-SmoothSignal
mom_len = input.int(14, minval=1, title='Momentum Length')
tmo_mom_main = MainSignal - MainSignal[mom_len]
tmo_mom_smooth = SmoothSignal - SmoothSignal[mom_len]
//PLots//
ob = hline(math.round(tmoleng * .7), title='overbought line', color=color.gray, linestyle=hline.style_solid)
os = hline(-math.round(tmoleng * .7), title='oversold line', color=color.gray, linestyle=hline.style_solid)
upper = hline(tmoleng, title='upper line', color=color.red, linestyle=hline.style_solid)
lower = hline(-tmoleng, title='lower line', color=color.green, linestyle=hline.style_solid)
zero = hline(0, title='zero line', color=color.gray, linestyle=hline.style_solid)
main = plot(MainSignal, title='main line', color=MainSignal>SmoothSignal?color.green:color.red, linewidth=2)
signal = plot(SmoothSignal, title='signal line', color=color.gray, linewidth=2)
cross = plot(ta.cross(MainSignal,SmoothSignal)?MainSignal:na, title="crossover dot", color=MainSignal>SmoothSignal?color.green:color.red, style=plot.style_circles, linewidth=3)
histogram = plot(Hist, title='histogram', color=MainSignal>SmoothSignal?color.green:color.red, style=plot.style_histogram)
fill(main, signal, title='main and signal fill', color=MainSignal>SmoothSignal?color.green:color.red)
fill(ob, upper, title='overbought fill', color=color.new(color.gray,20) )
fill(os, lower, title='oversold fill', color=color.new(color.gray,20))
mommain = plot(tmo_mom_main, color=color.orange, title='TMO Main Momentum')
momsignal= plot(tmo_mom_smooth, color=color.yellow, title='TMO Smooth Momentum')
bc= MainSignal > SmoothSignal ? color.green : MainSignal < SmoothSignal ? color.red : color.gray
barcolor(bc) |
RSItrend | https://www.tradingview.com/script/ZE7BiZH0-rsitrend/ | AHgpeu | https://www.tradingview.com/u/AHgpeu/ | 73 | 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/
// © AHgpeu
//@version=5
indicator("RSItrend", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
//RSI
rsiLengthInput = input.int(4, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
plot(rsi, "RSI", color=#7E57C2)
hline(80,editable =false)
hline (20,editable =false)
//RSI channel
max=rsi
max := rsi[2]<rsi[1] and rsi[1]>rsi ? rsi[1]: max[1]
min=rsi
min := rsi[2]>rsi[1] and rsi[1]<rsi ? rsi[1]:min[1]
plot(max, "max", linewidth = 2,color=color.rgb(44, 168, 81))
plot(min, "min", linewidth = 2,color=color.rgb(216, 48, 48))
//Bar Color
col =color.blue
col := rsi < min or rsi < 20 ? color.blue: rsi> max or rsi > 80 ? color.orange:col[1]
barcolor(col)
|
Average Daily Range% for Daytrading | https://www.tradingview.com/script/PDV3uJhy-Average-Daily-Range-for-Daytrading/ | OrcChieftain | https://www.tradingview.com/u/OrcChieftain/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © greenmask9
//@version=5
indicator(title = "Average Daily Range%", shorttitle = "ADR%", overlay = false, format = format.percent)
i_comparative_stats_max = input.int(240, title = "Max for Comparative Statistics", group = "Tables")
i_comparative_stats_min = input.int(10, title = "Max for Comparative Statistics", group = "Tables")
i_hline_w = input.int(1, title = "Hline Width")
i_position = input.string("Top-Right", "Table position", options = ["Top-Right", "Center-Right", "Bottom-Right"], group = "Text")
table_position = i_position == "Top-Right" ? position.top_right : i_position == "Tiny" ? position.middle_right : position.bottom_right
i_its = input.string("Auto", "Axis text size", options = ["Auto", "Tiny", "Small", "Normal"], group = "Text")
axis_ts = i_its == "Auto" ? size.auto : i_its == "Tiny" ? size.tiny : i_its == "Small" ? size.small : size.normal
i_header_width = input.int(16, title = "Width for table statistics description", group = "Text", tooltip = "You don't need to edit any settings in this group, unless the tables are malfunctioning when you use multiple charts per tab")
i_content_width = input.int(4, title = "Width for table values box", group = "Text")
i_box_height = input.int(8, title = "Height for table boxes", group = "Text")
c_hlines = input.color(color.new(color.gray, 80), title = "Hline", group = "Colour")
c_tabletext = input.color(color.new(color.yellow, 0), title = "Table Text", group = "Colour")
c_indicator = input.color(color.new(color.fuchsia, 0), title = "Indicator", group = "Colour")
d_0 = request.security(syminfo.tickerid, "D", high[0]-low[0], lookahead=barmerge.lookahead_on)
d_1 = request.security(syminfo.tickerid, "D", high[1]-low[1], lookahead=barmerge.lookahead_on)
d_2 = request.security(syminfo.tickerid, "D", high[2]-low[2], lookahead=barmerge.lookahead_on)
d_3 = request.security(syminfo.tickerid, "D", high[3]-low[3], lookahead=barmerge.lookahead_on)
d_4 = request.security(syminfo.tickerid, "D", high[4]-low[4], lookahead=barmerge.lookahead_on)
d_5 = request.security(syminfo.tickerid, "D", high[5]-low[5], lookahead=barmerge.lookahead_on)
ADR = (d_1 + d_2 + d_3 + d_4 + d_5) / 5
ADR_normalized = d_0 / ADR * 100
plot(ADR_normalized, title = "Average Daily Range", color = c_indicator, linewidth = 1)
hline(100,title="100", color = c_hlines, linewidth = i_hline_w)
hline(80,title="80", color = c_hlines, linewidth = i_hline_w)
hline(50,title="50", color = c_hlines, linewidth = i_hline_w)
hline(0,title="100", color = c_hlines, linewidth = i_hline_w)
statistics = table.new(table_position, 3, 32, bgcolor = na, frame_color = na, frame_width = 0, border_color = na, border_width = 0)
fill_table(row,txt_header,txt_content) =>
table.cell(statistics,0,row,text = txt_header, text_color = c_tabletext, height = i_box_height, width = i_header_width, text_size = axis_ts, bgcolor = na)
table.cell(statistics,1,row,text = txt_content, text_color = c_tabletext, height = i_box_height, width = i_content_width, text_size = axis_ts, bgcolor = na)
//90 day stats
//Number of Days Over 100
above_100_total(min,max) =>
int above_100_total = 0
for counter = min to max
if ADR_normalized[counter] > 100
above_100_total += 1
above_100_total
fill_table(0,"Above 100 Ratio",str.tostring(above_100_total(i_comparative_stats_min,i_comparative_stats_max)/i_comparative_stats_max, format.percent))
//plotshape(ADR_normalized > 100, location = location.top)
//Max Days In a Row under 100
under_100_inrow(min,max) =>
int below_100_inrow = 0, int below_100_current = 0, int continuous_cycle = max
for counter = min to max
if ADR_normalized[counter] < 100 and counter < max
below_100_current += 1
else if counter == max and ADR_normalized[counter] < 100
while ADR_normalized[continuous_cycle] < 100
below_100_current += 1
continuous_cycle += 1
else
below_100_current := 0
if below_100_current > below_100_inrow
below_100_inrow := below_100_current
below_100_inrow
fill_table(1,"Under 100 In a Row",str.tostring(under_100_inrow(i_comparative_stats_min,i_comparative_stats_max)))
//Remaining
fill_table(2,"Today Move",str.tostring(ADR_normalized/100, format.percent)) |
LowHighFinder | https://www.tradingview.com/script/Vsy9nl4f-LowHighFinder/ | xjtlumedia | https://www.tradingview.com/u/xjtlumedia/ | 104 | 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/
// © xjtlumedia
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © xjtlumedia
//@version=5
indicator("LowHighFinder v2")
//inputs
emaline = input.int( 5, "EMA control line", minval = 3,maxval = 20, group = "EMA conntrol line" )
leng2 = input.int( 5, "Output line length", minval = 1,maxval = 20, group = "output line" )
multiplierv = input.int( 1, "Vol Multiplier", minval = 1,maxval = 20 , group = "Cotrol vol multipler" )
multipliero = input.int( 1, "Open Multiplier", minval = 1,maxval = 20 , group = "Cotrol open multipler" )
multiplierl = input.int( 1, "Low Multiplier", minval = 1,maxval = 20 , group = "Cotrol low multipler" )
multiplierh = input.int( 1, "High Multiplier", minval = 1,maxval = 20 , group = "Cotrol high multipler" )
multiplierc = input.int( 1, "Close Multiplier", minval = 1,maxval = 20 , group = "Cotrol close multipler" )
emamultipler = input.int( 1, "EMA Multipler", minval = 1,maxval = 15 , group = "Cotrol EMA multipler" )
percentchange = input.int( 100, "Percent change(in 1/1000)", minval = 1,maxval = 1000 , group = "Cotrol percentchange" )
compares = input.int( 10, "Comparison line length", minval = 1,maxval = 100 , group = "Cotrol Comparison line length" )
linediff= input.int( 15, "Comparison line differences(in 1/1000)", minval = 1,maxval = 1000 , group = "Cotrol Comparison line differences" )
//calculation of K lines
src1=high
src2=low
src3=open
src4=close
voldiff=(volume-nz(volume[1]))/nz(volume[1])
odiff=(src3-nz(src3[1]))/nz(src3[1])
cdiff=(src4-nz(src4[1]))/nz(src4[1])
hdiff=(src1-nz(src1[1]))/nz(src1[1])
ldiff=(src2-nz(src2[1]))/nz(src2[1])
emadiff=(src4-nz(ta.ema(src4,emaline)))/ta.ema(src4,emaline)
volsignal=0.0
osignal=0.0
csignal=0.0
hsignal=0.0
lsignal=0.0
smoothsignal=0.0
//signal calculation
volsignal:=voldiff>(percentchange/1000) ? 2*multiplierv : voldiff>0 and voldiff<(percentchange/1000) ? 1*multiplierv :voldiff<0 and voldiff>-(percentchange/1000) ? -1*multiplierv : -2*multiplierv
osignal:=odiff>(percentchange/1000) ? 2*multipliero: odiff>0 and odiff<(percentchange/1000) ? 1*multipliero :odiff<0 and odiff>-(percentchange/1000) ? -1*multipliero : -2*multipliero
lsignal:=ldiff>(percentchange/1000) ? 2*multiplierl: ldiff>0 and ldiff<(percentchange/1000) ? 1*multiplierl :ldiff<0 and voldiff>-(percentchange/1000) ? -1*multiplierl : -2*multiplierl
hsignal:=hdiff>(percentchange/1000) ? 2*multiplierh: hdiff>0 and hdiff<(percentchange/1000) ? 1*multiplierh :hdiff<0 and voldiff>-(percentchange/1000) ? -1*multiplierh : -2*multiplierh
csignal:=cdiff>(percentchange/1000) ? 2*multiplierc: cdiff>0 and cdiff<(percentchange/1000) ? 1*multiplierc :cdiff<0 and voldiff>-(percentchange/1000) ? -1*multiplierc : -2*multiplierc
smoothsignal:=emadiff>(percentchange/1000) ? 2*emamultipler: emadiff>0 and emadiff<(percentchange/1000) ? 1*emamultipler :emadiff<0 and emadiff>-(percentchange/1000) ? -1*emamultipler : -2*emamultipler
cvols=0.0
copens=0.0
ccloses=0.0
chighs=0.0
clows=0.0
cemas=0.0
cvols:=volsignal+cvols
copens:=osignal+copens
ccloses:=csignal+ccloses
chighs:=hsignal+chighs
clows:=lsignal+clows
cemas:=smoothsignal+cemas
compareup=0.0
comparedown=0.0
if ta.ema(src4,compares)>=src4 and (ta.ema(src4,compares)-src4)/ta.ema(src4,compares)>(linediff/1000)
comparedown:=1
else
comparedown:=0
if ta.ema(src4,compares)<src4 and (src4-ta.ema(src4,compares))/ta.ema(src4,compares)>(linediff/1000)
compareup:=1
else
compareup:=0
rsv=0.0
nrsv=0.0
rsv:=(cvols+ccloses+copens+chighs+clows-cemas)
nrsv:=ta.sma(rsv,leng2)
plot(0,color = color.gray)
p1=plot(2.5,color = color.green)
p2=plot(-2.5,color = color.red)
p3=plot(nrsv,color = color.rgb(189, 243, 81))
plotshape(nrsv<-2.5 and comparedown==1, title="Long Entry Point Warning", location=location.bottom, style=shape.circle, size=size.tiny, color=color.lime)
plotshape(nrsv>2.5 and compareup==1, title="Short Entry Point Warning", location=location.top, style=shape.circle, size=size.tiny, color=color.red) |
Index_and_Commodity_Prices | https://www.tradingview.com/script/8bw1pi0P/ | volkankocabas | https://www.tradingview.com/u/volkankocabas/ | 746 | 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/
// © volkankocabas
//@version=5
indicator("Endeks ve Emtia Fiyatları", overlay = true)
dow= request.security("DJI", "D",close, ignore_invalid_symbol=true)
dow1=request.security("DJI", "D",close[1], ignore_invalid_symbol=true)
dax= request.security("DAX", "D",close, ignore_invalid_symbol=true)
dax1= request.security("DAX", "D",close[1], ignore_invalid_symbol=true)
vix= request.security("VIX", "D",close, ignore_invalid_symbol=true)
vix1= request.security("VIX", "D",close[1], ignore_invalid_symbol=true)
eurusd= request.security("EURUSD", "D",close, ignore_invalid_symbol=true)
eurusd1= request.security("EURUSD", "D",close[1], ignore_invalid_symbol=true)
btcusd= request.security("BTCUSD","D",close, ignore_invalid_symbol=true)
btcusd1= request.security("BTCUSD","D",close[1], ignore_invalid_symbol=true)
xauusd= request.security("XAUUSD1!","D",close, ignore_invalid_symbol=true)
xauusd1= request.security("XAUUSD1!","D",close[1], ignore_invalid_symbol=true)
xagusd= request.security("XAGUSD1!","D",close, ignore_invalid_symbol=true)
xagusd1= request.security("XAGUSD1!","D",close[1], ignore_invalid_symbol=true)
us10y= request.security("US10Y","D",close, ignore_invalid_symbol=true)
us10y1= request.security("US10Y","D",close[1], ignore_invalid_symbol=true)
brent= request.security("BR1!","D",close, ignore_invalid_symbol=true)
brent1= request.security("BR1!","D",close[1], ignore_invalid_symbol=true)
dgaz= request.security("NG1!","D",close, ignore_invalid_symbol=true)
dgaz1= request.security("NG1!","D",close[1], ignore_invalid_symbol=true)
hrc= request.security("HRC1!","D",close, ignore_invalid_symbol=true)
hrc1= request.security("HRC1!","D",close[1], ignore_invalid_symbol=true)
dxy= request.security("DXY","D",close, ignore_invalid_symbol=true)
dxy1= request.security("DXY","D",close[1], ignore_invalid_symbol=true)
bugday= request.security("ZW1!","D",close, ignore_invalid_symbol=true)
bugday1= request.security("ZW1!","D",close[1], ignore_invalid_symbol=true)
bakir= request.security("HG1!","D",close, ignore_invalid_symbol=true)
bakir1= request.security("HG1!","D",close[1], ignore_invalid_symbol=true)
komur= request.security("DJUSCL","D",close, ignore_invalid_symbol=true)
komur1= request.security("DJUSCL","D",close[1], ignore_invalid_symbol=true)
b100= request.security("XU100","D",close, ignore_invalid_symbol=true)
b1001= request.security("XU100","D",close[1], ignore_invalid_symbol=true)
b30= request.security("XU030","D",close, ignore_invalid_symbol=true)
b301= request.security("XU030","D",close[1], ignore_invalid_symbol=true)
vip30= request.security("XU030D1!","D",close, ignore_invalid_symbol=true)
vip301= request.security("XU030D1!","D",close[1], ignore_invalid_symbol=true)
//PANEL FEATURES
/////////////////////////////////////////////
f_draw_infopanel(_x, _y, _line, _text, _color)=>
_rep_text = ""
for _l = 0 to _line
_rep_text := _rep_text + "\n"
_rep_text := _rep_text + _text
var label _la = na
label.delete(_la)
_la := label.new(style = label.style_label_up,x=_x, y=_y,
text=_rep_text, xloc=xloc.bar_time, yloc=yloc.price,
color=color.yellow, textcolor=_color, size=size.normal)
//PANEL LOCATION
/////////////////////////////////////////////
PanelLocation = input(50, title="Panel Lokasyon Ayar")
//Recommended Settings for 4Hour (50)
//PANEL LOCATION
/////////////////////////////////////////////
posx = timenow + math.round(ta.change(time)*PanelLocation)
posy = ta.highest(50)
//PANEL PARTS
/////////////////////////////////////////////
f_draw_infopanel(posx, posy, 34, "BUĞDAY: "+str.tostring(bugday)+" "+ "%" +str.tostring(math.round((bugday-bugday1)/bugday*100,2)), (bugday-bugday1)/bugday*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 32, "KÖMÜR: "+str.tostring(komur)+" "+ "%" +str.tostring(math.round((komur-komur1)/komur*100,2)), (komur-komur1)/komur*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 30, "BAKIR: "+str.tostring(bakir)+" "+ "%" +str.tostring(math.round((bakir-bakir1)/hrc*100,2)), (bakir-bakir1)/bakir*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 28, "HRC: "+str.tostring(hrc)+" "+ "%" +str.tostring(math.round((hrc-hrc1)/hrc*100,2)), (hrc-hrc1)/hrc*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 26, "DOĞAL GAZ: "+str.tostring(dgaz)+" "+ "%" +str.tostring(math.round((dgaz-dgaz1)/dgaz*100,2)), (dgaz-dgaz1)/dgaz*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 24, "BRENT: "+str.tostring(brent)+" "+ "%" +str.tostring(math.round((brent-brent1)/brent*100,2)), (brent-brent1)/brent*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 22, "US10Y: "+str.tostring(us10y)+" "+ "%" +str.tostring(math.round((us10y-us10y1)/us10y*100,2)), (us10y-us10y1)/us10y*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 20, "XAGUSD: "+str.tostring(xagusd)+" "+ "%" +str.tostring(math.round((xagusd-xagusd1)/xagusd*100,2)), (xagusd-xagusd1)/xagusd*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 18, "XAUUSD: "+str.tostring(xauusd)+" "+ "%" +str.tostring(math.round((xauusd-xauusd1)/xauusd*100,2)), (xauusd-xauusd1)/xauusd*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 16, "BTCUSD: "+str.tostring(btcusd)+" "+ "%" +str.tostring(math.round((btcusd-btcusd1)/btcusd*100,2)), (btcusd-btcusd1)/btcusd*100 > 0 ?color.green : color.red)
f_draw_infopanel(posx, posy, 14, "EURUSD: "+str.tostring(eurusd)+" "+ "%" +str.tostring(math.round((eurusd-eurusd1)/eurusd*100,2)), (eurusd-eurusd1)/eurusd*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 12, "VIX: "+str.tostring(vix)+" "+ "%" +str.tostring(math.round((vix-vix1)/vix*100,2)), (vix-vix1)/vix*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 10, "DXY: "+str.tostring(dxy)+" "+ "%" +str.tostring(math.round((dxy-dxy1)/dxy*100,2)), (dxy-dxy1)/dxy*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 8, "DAX: "+str.tostring(dax)+" "+ "%" +str.tostring(math.round((dax-dax1)/dax*100,2)), (dax-dax1)/dax*100 > 0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 6, "DJI: "+str.tostring(dow)+" "+ "%" +str.tostring(math.round((dow-dow1)/dow*100,2)), (dow-dow1)/dow*100 >0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 4, "VİP-30: "+str.tostring(math.round(vip30,2))+" "+ "%" +str.tostring(math.round((vip30-vip301)/vip30*100,2)), (vip30-vip301)/vip30*100 >0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 2, "BİST-30: "+str.tostring(math.round(b30,2))+" "+ "%" +str.tostring(math.round((b30-b301)/b30*100,2)), (b30-b301)/b30*100 >0 ? color.green : color.red)
f_draw_infopanel(posx, posy, 0, "BİST-100: "+str.tostring(math.round(b100,2))+" "+ "%" +str.tostring(math.round((b100-b1001)/b100*100,2)), (b100-b1001)/b100*100 >0 ? color.green : color.red)
|
[EDU] RSI Momentum Bands | https://www.tradingview.com/script/6ikLZjbk-edu-rsi-momentum-bands/ | tarasenko_ | https://www.tradingview.com/u/tarasenko_/ | 174 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tarasenko_
//@version=5
indicator("RSI Momentum Bands")
// Inputs
p = input(14, "RSI Period")
mp = input(4, "1st RSI MA Period")
ma_p = input(50, "2nd RSI MA Period")
bm = input.float(1.0, "Band Mult", step = 0.1)
// Calculations
rsi = ta.ema(ta.rsi(close, p), mp)
ma_rsi = ta.wma(rsi, ma_p)
std = ta.stdev(ma_rsi, ma_p)
ub = ma_rsi + bm * std
lb = ma_rsi - bm * std
col = rsi > ub ? color.lime : rsi < lb ? color.red : color.black
// Plottings
RSI = plot(rsi, "RSI", col, 3)
plot(ma_rsi, "MA RSI", color.white)
U = plot(ub, "UB", color.gray)
L = plot(lb, "LB", color.gray)
fill(RSI, U, rsi > ub ? #00e67675 : na)
fill(RSI, L, rsi < lb ? #ff525275 : na)
barcolor(col)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.