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
|
---|---|---|---|---|---|---|---|---|
Dynamic Trend Fusion (DTF) | https://www.tradingview.com/script/gRpNvFa3-Dynamic-Trend-Fusion-DTF/ | TheRealDrip2Rip | https://www.tradingview.com/u/TheRealDrip2Rip/ | 37 | 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/
// © TheRealDrip2Rip
//@version=5
indicator("Dynamic Trend Fusion", shorttitle="DTF", overlay=false)
// Define input options
option = input.string("Standard", title="Select Option", options=["Standard","Short-term Trading","Long-term Trading","Aggressive Short-term","Conservative Long-term","Balanced Approach","High Sensitivity","Low Sensitivity","Day Trading","Swing Trading"])
// Initialize variables for MACD and RSI settings
var fastLength = 12
var slowLength = 26
var signalSmoothing = 9
var rsiLength = 14
// Update variables based on the selected option
if option == "Short-term Trading"
fastLength := 8
slowLength := 17
signalSmoothing := 9
rsiLength := 8
else if option == "Long-term Trading"
fastLength := 19
slowLength := 39
signalSmoothing := 9
rsiLength := 21
else if option == "Aggressive Short-term"
fastLength := 5
slowLength := 13
signalSmoothing := 8
rsiLength := 5
else if option == "Conservative Long-term"
fastLength := 24
slowLength := 52
signalSmoothing := 18
rsiLength := 28
else if option == "Balanced Approach"
fastLength := 10
slowLength := 22
signalSmoothing := 7
rsiLength := 12
else if option == "High Sensitivity"
fastLength := 4
slowLength := 8
signalSmoothing := 5
rsiLength := 3
else if option == "Low Sensitivity"
fastLength := 30
slowLength := 60
signalSmoothing := 12
rsiLength := 50
else if option == "Day Trading"
fastLength := 6
slowLength := 19
signalSmoothing := 9
rsiLength := 6
else if option == "Swing Trading"
fastLength := 12
slowLength := 26
signalSmoothing := 12
rsiLength := 14
// MACD
[macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalSmoothing)
macdHist = macdLine - signalLine
// RSI
rsi = ta.rsi(close, rsiLength)
// Normalizing MACD and RSI to a similar scale
normMacd = (macdHist - ta.lowest(macdHist, 100)) / (ta.highest(macdHist, 100) - ta.lowest(macdHist, 100))
normRsi = (rsi - 30) / 40 // RSI typically moves between 30 and 70
// Combining normalized values
comboValue = (normMacd + normRsi) / 2
// Smoothing the combined value with a moving average
smoothingLength = input(10, title="Smoothing Length")
smoothedComboValue = ta.sma(comboValue, smoothingLength)
// Determine whether the indicator is bullish or bearish
isBullish = smoothedComboValue > 0.5
isBearish = smoothedComboValue < 0.5
// Plotting with color based on bullish or bearish state
plot(smoothedComboValue, title="Custom RSI-MACD Combo", color=isBullish ? color.rgb(76, 175, 79, 50) : color.rgb(255, 82, 82, 50), linewidth = 2)
hline(0.5, title="Midline", color=color.gray, linestyle=hline.style_dashed)
// Alert conditions
alertcondition(isBullish, title="Bullish Alert", message="DTF is Bullish")
alertcondition(not isBullish, title="Bearish Alert", message="DTF is Bearish")
|
Position_control | https://www.tradingview.com/script/6VJrjoc7-Position-control/ | djmad | https://www.tradingview.com/u/djmad/ | 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/
// © djmad
//@version=5
// @description This is a library for defining positions and working with them. Additionally i added here my standardblocks which i use in other scripts
library("Position_control")
import djmad/Mad_Standardparts/1 as STDP
// Definition of the type Position and its subtypes
// defining the aviable trailstops
export type t_TP_Variant
string TP_Type //Trailstop, Direktsell, Fractal Trail,...
int TP_Parameter_1
int TP_Parameter_2
float TP_Parameter_3
float TP_Parameter_4
// defining how a Takeprofit is handled
export type t_TPs
float TP_Price
float TP_Lot
t_TP_Variant TP_Variant
bool TP_Active
// defining how a Takeprofit is handled
export type t_SLs
float SL_Price
float SL_Lot
bool SL_Active
// defining the complete position
export type t_Position_type
float Lot
float Leverage
float Maintenance
int Starttime
float Entry_Start
int Stoptime
float Entry_Stop
float Entryprice
array<t_TPs> TPs
array<t_SLs> SLs
// drawout parameters
export type t_drawing_parameters
bool ShowPos
bool ShowLIQ
array<color> A_Colors
bool Prolong_lines
string Str_fontsize
int Textshift
int Decimals_contracts
int Decimals_price
int Decimals_percent
int bartime
//}
// @function Calculate the leverage used in a trade.
// @description This function calculates the leverage used in a trade, based on the value of the trade, the maintenance margin, and the direction of the trade.
// @param _Leverage The leverage used in the trade, as a floating point number.
// @param _maintenance The maintenance margin percentage, as a floating point number.
// @param _value The value of the trade, as a floating point number.
// @param _direction The direction of the trade, either "long" or "short".
// @returns The leverage used in the trade, as a floating point number.
export f_calculateLeverage(float _Leverage, float _maintenance, float _value, string _direction) =>
if _direction == "short"
(_Leverage * _value)/(_Leverage - 1 + (_maintenance * _Leverage))
else if _direction == "long"
(_Leverage * _value)/(_Leverage + 1 - (_maintenance * _Leverage))
// @function Calculate the profit or loss for a given trade.
// @description This function calculates the profit or loss for a given trade, based on the position type, maximum take profit, position index, and whether to show the profit as a percentage or a value.
// @param _Position An array of position types for the trade.
// @param _max_TP The maximum take profit for the trade, as an integer value.
// @param _Position_index The index of the position in the array, as an integer value.
// @param _show_profit A boolean value indicating whether to show the profit as a percentage or a value.
// @returns The profit or loss for the trade, as a floating point number.
export f_calculate_PL(t_Position_type [] _Position, int _max_TP, int _Position_index, bool _show_profit, int _i_decimals_contracts = 2, int _i_decimals_prercent = 2) =>
var float profit = na
var float loss = na
var float getTPs_1i = na
var float tpsum = 0
var _getA_RW = array.get(_Position, _Position_index)
var entry_price = math.avg(_getA_RW.Entry_Start,_getA_RW.Entry_Stop)
tpsum := 0
for i = 0 to _getA_RW.TPs.size()-1
tpsum := tpsum + _getA_RW.TPs.get(i).TP_Lot
if math.round(tpsum,2) != 1
for i1 = 0 to _getA_RW.TPs.size()-1
temp_TP = _getA_RW.TPs.get(i1)
temp_TP.TP_Lot /= tpsum
_getA_RW.TPs.set(i1, temp_TP)
profit := 0
loss := 0
//calculation verified by Crader_Florians Excel calculation, 2 approaches, same result, fine one check at least from not me ;-)
for i2 = 0 to math.min(_getA_RW.TPs.size()-1,_max_TP-1)
profit += (_getA_RW.TPs.get(i2).TP_Price - entry_price) * _getA_RW.TPs.get(i2).TP_Lot
loss := (entry_price - _getA_RW.SLs.get(0).SL_Price)
result = _show_profit?
(STDP.roundTo(math.abs(profit*_getA_RW.Lot/10000),_i_decimals_contracts)):
(STDP.roundTo(math.abs(profit/loss),_i_decimals_prercent))
result
// @function draws a position on the chart
// @description via sending in a typo of Position this function is able to drawout Stoploss, Entrybox, Takeprofits and the required labels with information
// @param _Position array of type t_Position_type containing the position information.
// @param _max_TP maximum number of take-profit levels.
// @param _Position_index the index of the current position.
// @param _i_decimals_contracts the number of decimal places to display for the contract size. Default is 2.
// @param _i_decimals_percent the number of decimal places to display for the percentage values. Default is 2.
// @returns None but boxes / lines / labels on the chart itself
export f_drawposition(t_Position_type [] _Position, t_drawing_parameters _Parameters, int _Position_index = 0) =>
if not na(_Position)
if _Position.size() > 0
var box [] pos_boxes = array.new_box()
var label [] pos_label = array.new_label()
var line [] pos_lines = array.new_line()
var line [] TP_lines = array.new_line()
var label [] TP_label = array.new_label()
var line [] SL_lines = array.new_line()
var label [] SL_label = array.new_label()
var line [] LIQ_lines = array.new_line()
var label [] LIQ_label = array.new_label()
var string TP_text = na
var string TP_text_contracts_1 = na
var string TP_text_contracts_2 = na
_getA_RO = array.get(_Position, _Position_index)
entry_price = math.avg(_getA_RO.Entry_Start,_getA_RO.Entry_Stop)
////////////}
// Print Liquidation Line{
// This block creates a liquidation line on the chart based on the user's input, represented by the ShowLIQ, Prolong_lines, A_Colors, and LIQ_lines variables.
// The f_calculateLeverage function calculates the leverage based on the direction (short or long) provided and returns the result.
// If ShowLIQ is true, two new lines are created to represent the liquidation line on the chart.
// If Prolong_lines is also true, a third line is created to extend the liquidation line to the left of the chart.
// The lines are then added to the LIQ_lines array and the oldest line is removed if the array has more than 40 lines.
if _Parameters.ShowLIQ
array.unshift(LIQ_lines,
line.new(
x1 = _getA_RO.Starttime ,
y1 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
x2 = _getA_RO.Stoptime ,
y2 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,0) ,
style = line.style_solid ,
width = 1
)
)
array.unshift(LIQ_lines,
line.new(
x1 = _getA_RO.Stoptime ,
y1 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
x2 = time ,
y2 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,1) ,
style = line.style_dotted ,
width = 1
)
)
if _Parameters.Prolong_lines
array.unshift(LIQ_lines,
line.new(
x1 = _getA_RO.Starttime - _Parameters.bartime*3 ,
y1 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
x2 = _getA_RO.Starttime ,
y2 = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
xloc = xloc.bar_time ,
extend = extend.left ,
color = array.get(_Parameters.A_Colors,1) ,
style = line.style_dotted ,
width = 1
)
)
if array.size(LIQ_lines) > 40
line.delete(array.pop(LIQ_lines))
// }
// Print Liquidation Labels {
array.unshift(LIQ_label,
label.new(
// x = _getA_RO.Stoptime ,
x = time ,
y = f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short") ,
text = STDP.shifting(_Parameters.Textshift) + "LIQ L= x"+ str.tostring(_getA_RO.Leverage) + " M=" + str.tostring(_getA_RO.Maintenance*10000) + "% =" + str.tostring(STDP.roundTo(f_calculateLeverage(_getA_RO.Leverage, _getA_RO.Maintenance, entry_price, _getA_RO.SLs.get(0).SL_Price < entry_price? "long":"short"),_Parameters.Decimals_price)) ,
xloc = xloc.bar_time ,
textcolor = array.get(_Parameters.A_Colors,8) ,
style = label.style_none ,
textalign = text.align_left,
size = _Parameters.Str_fontsize
)
)
if array.size(LIQ_label) > 20
label.delete(array.pop(LIQ_label))
// }
// Print SL Line{
// This block of code adds stop-loss lines to the chart using the line.new() function.
// The stop-loss lines are created based on the values of _getA_RO, which is a user-defined input.
// The lines are added to the SL_lines array using the array.unshift() function.
// The first line.new() function call creates a solid line that represents the initial stop-loss level.
// The line starts at the beginning of the trade (_getA_RO.Starttime) and ends at the stop-loss level (_getA_RO.SLs.get(0).SL_Price).
// The line's color and width are also set using the A_Colors array and a fixed value, respectively.
// The second line.new() function call creates a dotted line that represents the updated stop-loss level.
// The line starts at the stop-loss level (_getA_RO.SLs.get(0).SL_Price) and ends at the current time.
// The line's color and style are also set using the A_Colors array and a fixed value, respectively.
// The Prolong_lines variable determines whether to add an extra dotted line to the left of the initial stop-loss line.
// If Prolong_lines is true, the third line.new() function call creates a dotted line that extends to the left of the initial stop-loss line.
// The if statement checks whether the SL_lines array has more than 40 elements.
// If so, it removes the oldest line using array.pop() and deletes it from the chart using line.delete().
array.unshift(SL_lines,
line.new(
x1 = _getA_RO.Starttime ,
y1 = _getA_RO.SLs.get(0).SL_Price ,
x2 = _getA_RO.Stoptime ,
y2 = _getA_RO.SLs.get(0).SL_Price ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,2) ,
style = line.style_solid ,
width = 2
)
)
array.unshift(SL_lines,
line.new(
x1 = _getA_RO.Stoptime ,
y1 = _getA_RO.SLs.get(0).SL_Price ,
x2 = time ,
y2 = _getA_RO.SLs.get(0).SL_Price ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,3) ,
style = line.style_dotted ,
width = 1
)
)
if _Parameters.Prolong_lines
array.unshift(SL_lines,
line.new(
x1 = _getA_RO.Starttime - _Parameters.bartime*3 ,
y1 = _getA_RO.SLs.get(0).SL_Price ,
x2 = _getA_RO.Starttime ,
y2 = _getA_RO.SLs.get(0).SL_Price ,
xloc = xloc.bar_time ,
extend = extend.left ,
color = array.get(_Parameters.A_Colors,3) ,
style = line.style_dotted ,
width = 1
)
)
if array.size(SL_lines) > 40
line.delete(array.pop(SL_lines))
// }
// Print SL Labels {
// This block of code creates a label that displays the stop-loss information for the current trade.
// The TP_text variable is used to construct the label text, which includes the stop-loss price and the percentage change from the entry price.
// The TP_text_contracts_1 variable is used to display the contract size if ShowPos is true.
// The label is created using the label.new() function and added to the SL_label array using the array.unshift() function.
// The if statement checks whether the SL_label array has more than 20 elements.
// If so, it removes the oldest label using array.pop() and deletes it from the chart using label.delete().
// This block of code creates a rectangle that highlights the entry price range for the current trade.
// The rectangle is created using the box.new() function and added to the pos_boxes array using the array.unshift() function.
// The if statement checks whether the pos_boxes array has more than 400 elements.
// If so, it removes the oldest rectangle using array.pop() and deletes it from the chart using box.delete().
if _Parameters.ShowPos
TP_text_contracts_1 :=
" / " +
str.tostring( -1 * math.abs( STDP.roundTo( _getA_RO.Lot * ( ( entry_price/ _getA_RO.SLs.get(0).SL_Price ) -1) , _Parameters.Decimals_contracts ) ) ) +
"C"
else
TP_text_contracts_1 := ""
TP_text := STDP.shifting(_Parameters.Textshift) +
"SL @ " + str.tostring( STDP.roundTo(_getA_RO.SLs.get(0).SL_Price,_Parameters.Decimals_price)) +
" = " + str.tostring( STDP.roundTo( (math.abs((entry_price > _getA_RO.SLs.get(0).SL_Price) ? ((_getA_RO.SLs.get(0).SL_Price - entry_price)/_getA_RO.SLs.get(0).SL_Price) :((entry_price - _getA_RO.SLs.get(0).SL_Price)/entry_price ))) * -100,_Parameters.Decimals_percent) ) +
"%" +
TP_text_contracts_1
array.unshift(SL_label,
label.new(
x = time ,
y = _getA_RO.SLs.get(0).SL_Price ,
text = TP_text ,
xloc = xloc.bar_time ,
textcolor = array.get(_Parameters.A_Colors,8) ,
style = label.style_none ,
textalign = text.align_left,
size = _Parameters.Str_fontsize
)
)
if array.size(SL_label) > 20
label.delete(array.pop(SL_label))
// }
// Print Entry Box {
// Print Entry Box - This section of the code is responsible for creating and displaying the entry box on the chart
// First, it creates a new box using the values from the _getB object, including the start and stop times, and the entry start and stop prices
// It then adds this box to the "pos_boxes" array.
// If the size of the "pos_boxes" array is greater than 60, it removes the last element from the array.
// If "Prolong_lines" is true, it creates two new lines and adds them to the "pos_lines" array.
// These lines extend from the start time of the entry period 3 times the length of a bar time to the start time of the entry period.
// If the size of the "pos_lines" array is greater than 40, it removes the last element from the array.
array.unshift(pos_boxes,
box.new(
left = _getA_RO.Starttime ,
bottom = _getA_RO.Entry_Start ,
right = _getA_RO.Stoptime ,
top = _getA_RO.Entry_Stop ,
xloc = xloc.bar_time ,
extend = extend.none ,
bgcolor = array.get(_Parameters.A_Colors,4) ,
border_style = line.style_solid ,
border_width = 1
)
)
if array.size(pos_boxes) > 60
box.delete(array.pop(pos_boxes))
//}
// Print Entry Lines {
// This block of code adds two dotted lines to the chart to mark the entry price range for the current trade.
// The lines are created using the line.new() function and added to the pos_lines array using the array.unshift() function.
// The first line marks the upper limit of the range, and the second line marks the lower limit of the range.
// The lines start at the stop time of the current trade (_getA_RO.Stoptime) and extend to the current time.
// The color of the lines is set using the A_Colors array.
// The Prolong_lines variable determines whether to add an extra set of dotted lines to the left of the entry price range.
// If Prolong_lines is true, the second if statement adds two more dotted lines to the chart to extend the entry price range to the left.
// The if statement checks whether the pos_lines array has more than 40 elements.
// If so, it removes the oldest line using array.pop() and deletes it from the chart using line.delete().
//Right side
array.unshift(pos_lines,
line.new(
x1 = _getA_RO.Stoptime ,
y1 = _getA_RO.Entry_Start ,
x2 = time ,
y2 = _getA_RO.Entry_Start ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,5) ,
style = line.style_dotted ,
width = 1
)
)
array.unshift(pos_lines,
line.new(
x1 = _getA_RO.Stoptime ,
y1 = _getA_RO.Entry_Stop ,
x2 = time ,
y2 = _getA_RO.Entry_Stop ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,5) ,
style = line.style_dotted ,
width = 1
)
)
if _Parameters.Prolong_lines
//Left side
array.unshift(pos_lines,
line.new(
x1 = _getA_RO.Starttime - _Parameters.bartime*3 ,
y1 = _getA_RO.Entry_Start ,
x2 = _getA_RO.Starttime ,
y2 = _getA_RO.Entry_Start ,
xloc = xloc.bar_time ,
extend = extend.left ,
color = array.get(_Parameters.A_Colors,5) ,
style = line.style_dotted ,
width = 1
)
)
array.unshift(pos_lines,
line.new(
x1 = _getA_RO.Starttime - _Parameters.bartime*3 ,
y1 = _getA_RO.Entry_Stop ,
x2 = _getA_RO.Starttime ,
y2 = _getA_RO.Entry_Stop ,
xloc = xloc.bar_time ,
extend = extend.left ,
color = array.get(_Parameters.A_Colors,5) ,
style = line.style_dotted ,
width = 1
)
)
if array.size(pos_lines) > 40
line.delete(array.pop(pos_lines))
// }
// Print Entry Labels {
// This block of code creates a label that displays the entry price information for the current trade.
// The EP_text_contracts variable is used to display the contract size if ShowPos is true.
// The label text is constructed using the STDP.shifting() function to shift the text to the left, and STDP.roundTo() function to round the price and contract size to the desired decimal places.
// The label is created using the label.new() function and added to the pos_label array using the array.unshift() function.
// The if statement checks whether the pos_label array has more than 20 elements.
// If so, it removes the oldest label using array.pop() and deletes it from the chart using label.delete().
var string EP_text_contracts = na
if _Parameters.ShowPos
EP_text_contracts := " = " + str.tostring(STDP.roundTo(_getA_RO.Lot,_Parameters.Decimals_contracts))
else
EP_text_contracts := ""
array.unshift(pos_label,
label.new(
x = time ,
y = entry_price ,
text =
STDP.shifting(_Parameters.Textshift) + "Entry " + str.tostring(STDP.roundTo(_getA_RO.Entry_Start,_Parameters.Decimals_price)) + " - " + str.tostring(STDP.roundTo(_getA_RO.Entry_Stop,_Parameters.Decimals_price)) + "\n" +
STDP.shifting(_Parameters.Textshift) + "Avg. @ "+str.tostring(STDP.roundTo(entry_price,_Parameters.Decimals_price)) + EP_text_contracts + "C" ,
xloc = xloc.bar_time ,
textcolor = array.get(_Parameters.A_Colors,8) ,
style = label.style_none ,
textalign = text.align_left,
size = _Parameters.Str_fontsize
)
)
if array.size(pos_label) > 20
label.delete(array.pop(pos_label))
// }
// Print TPs Lines{
// This block of code creates a solid line for each take profit (TP) level that has a non-zero lot size.
// The lines are created using the line.new() function and added to the TP_lines array using the array.unshift() function.
// The lines start at the start time of the current trade (_getA_RO.Starttime) and extend to the current time.
// The color of the lines is set using the A_Colors array.
// The Prolong_lines variable determines whether to add an extra set of dotted lines to the left of each TP level.
// If Prolong_lines is true, the second if statement adds a dotted line to the chart to extend each TP level to the left.
// The if statement checks whether the TP_lines array has more than 300 elements.
// If so, it removes the oldest line using array.pop() and deletes it from the chart using line.delete().
for i = 0 to _getA_RO.TPs.size()-1
if _getA_RO.TPs.get(i).TP_Lot != 0
array.unshift(TP_lines,
line.new(
x1 = _getA_RO.Starttime ,
y1 = _getA_RO.TPs.get(i).TP_Price ,
x2 = time ,
y2 = _getA_RO.TPs.get(i).TP_Price ,
xloc = xloc.bar_time ,
extend = extend.none ,
color = array.get(_Parameters.A_Colors,6) ,
style = line.style_solid ,
width = 1
)
)
if _Parameters.Prolong_lines
array.unshift(TP_lines,
line.new(
x1 = _getA_RO.Starttime - _Parameters.bartime*3 ,
y1 = _getA_RO.TPs.get(i).TP_Price ,
x2 = _getA_RO.Starttime ,
y2 = _getA_RO.TPs.get(i).TP_Price ,
xloc = xloc.bar_time ,
extend = extend.left ,
color = array.get(_Parameters.A_Colors,6) ,
style = line.style_dotted ,
width = 1
)
)
if array.size(TP_lines) > 300
line.delete(array.pop(TP_lines))
// }
// Print TP Labels {
// Print TP Labels - This section of the code is responsible for creating and displaying the Take Profit (TP) labels on the chart
// It loops through the "TPs" matrix from the _getB object and for each non-zero value in the matrix, it does the following:
// First, it creates two string variables "TP_text" and "TP_text_contracts_1" and assigns them the value "na"
// Then, it checks the value of the "ShowPos" variable. If it is true, it assigns the value of "TP_text_contracts_1" to a string that concatenates "= "
// with the rounded value of _getA_RO.Lot multiplied by the value in the matrix, and "i_decimals_contracts" and "C"
// Else, it assigns the value of "TP_text_contracts_1" to an empty string.
// Then it assigns the value of "TP_text" to a string that concatenates several pieces of information such as the TP number, sell percentage, and P/L and Gain.
// It creates a new label using the values from the _getB object and the "TP_text" variable and adds this label to the "TP_label" array.
// If the size of the "TP_label" array is greater than 400, it removes the last element from the array.
for ia = 0 to _getA_RO.TPs.size()-1
if _getA_RO.TPs.get(ia).TP_Lot != 0
if _Parameters.ShowPos
TP_text_contracts_1 := "= " + (str.tostring(STDP.roundTo(_getA_RO.Lot*_getA_RO.TPs.get(ia).TP_Lot,_Parameters.Decimals_contracts))) + "C"
TP_text_contracts_2 := " / " + str.tostring(f_calculate_PL(_Position = _Position,
_max_TP = ia+1,
_Position_index = 0,
_show_profit = true,
_i_decimals_contracts = _Parameters.Decimals_contracts,
_i_decimals_prercent = _Parameters.Decimals_percent)) + "C"
else
TP_text_contracts_1 := ""
TP_text_contracts_2 := ""
shortperc=((_getA_RO.TPs.get(ia).TP_Price - entry_price )/ entry_price*100)
longperc=((entry_price - _getA_RO.TPs.get(ia).TP_Price )/ entry_price*100)
TP_text :=
STDP.shifting(_Parameters.Textshift) + "TP "+str.tostring(ia+1) + " - @ " + str.tostring(STDP.roundTo(_getA_RO.TPs.get(ia).TP_Price,_Parameters.Decimals_price)) +
" / Sell " + str.tostring(STDP.roundTo(_getA_RO.TPs.get(ia).TP_Lot*100,_Parameters.Decimals_percent)) + "% " + TP_text_contracts_1 + "\n" +
STDP.shifting(_Parameters.Textshift) + "P/L=" + str.tostring(STDP.roundTo(f_calculate_PL(_Position = _Position, _max_TP = ia+1, _Position_index = 0, _show_profit = false, _i_decimals_contracts = _Parameters.Decimals_contracts, _i_decimals_prercent = _Parameters.Decimals_percent),_Parameters.Decimals_percent)) +
" / Move = " +
str.tostring( STDP.roundTo( (entry_price > _getA_RO.TPs.get(ia).TP_Price ? longperc:shortperc) , _Parameters.Decimals_percent ) ) +
"%" + TP_text_contracts_2,
array.unshift(TP_label,
label.new(
x = time ,
y = _getA_RO.TPs.get(ia).TP_Price ,
text = TP_text,
xloc = xloc.bar_time ,
textcolor = array.get(_Parameters.A_Colors,8) ,
style = label.style_none ,
textalign = text.align_left,
size = _Parameters.Str_fontsize
)
)
if array.size(TP_label) > 400
label.delete(array.pop(TP_label))
// }
|
logger | https://www.tradingview.com/script/66H1hx00-logger/ | GETpacman | https://www.tradingview.com/u/GETpacman/ | 2 | 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/
// © GETpacman
//@version=5
// @description A dual logging library for developers.
library("logger")
GETpacman =
"\n
logger Library
Import the Library and Call docs(), and hover mouse over docs() to see Docs in Editor!
import GETpacman/logger/3 as logger
logger.usage() => Sample Code Usage
logger.fields() => For listing all fields
logger.methods() => For listing of all methods
logger.docs() => All documentation in one go
Code demo => 'https://www.tradingview.com/script/wITCQP6R-libhs-log-DEMO/'
"
// Credits
// QuantNomad - For his idea on logging messages as Error/Warnings and displaying the color based on the type of the message. This got me started on my own private logging library.
// RicardoSantos - When I was new to pine and looked up some of his code on how to pass arrays created within function as init.
// Tradingview - For implementing UDTs. This single feature has made it possible for me to migrate my library for public use, leading to less complex code.
// HoanGhetti - For markdown explanation. This explanation has helped me provide an exhaustive help lookup/markup for all methods, right within the code editor window
// FFriZz - For the concept of having a docs() method, just to show the documentation, using markdown.
// kaigouthro - Cast Improvements - Some of the exports I had come up independently as part of my own quick logging requirement. Then I discovered kaigouthro's conversions and copied some here (float with decimals, rounding float to float, rounding string when converting to float, and converting string to int)
export type log
color HeaderColor
color HeaderColorBG
color StatusColor
color StatusColorBG
color TextColor
color TextColorBG
color FrameColor
int FrameSize = 1
int CellBorderSize = 0
color CellBorderColor
color SeparatorColor = color.gray
bool iq = false
bool IsConsole = true
bool ShowHeader = true
bool HeaderAtTop = true
bool ShowStatusBar = true
bool StatusBarAtBottom = true
bool ShowMetaStatus = true
string HeaderQbarIndex = 'Bar#'
string HeaderQdateTime = 'Date'
string HeaderQLevelCode = 'Code'
string HeaderQLogLevel = 'LvL'
string HeaderQ1 = '[.q1]'
string HeaderQ2 = '<.q2>'
string HeaderQ3 = '(.q3)'
string HeaderQ4 = ''
string HeaderQ5 = ''
string HeaderQ6 = ''
string Status = ''
string HeaderTooltip = 'Header'
string StatusTooltip = 'Status'
string MetaStatusTooltip= 'Meta Info'
bool ShowBarIndex = false
bool ShowDateTime = false
bool ShowLogLevels = false //Shows the debug log level as a column in Logx or as meta tab in Console
bool ShowQ1 = true
bool ShowQ2 = true
bool ShowQ3 = true
bool ShowQ4 = false
bool ShowQ5 = false
bool ShowQ6 = false
int TabSizeQ1 = 0
int TabSizeQ2 = 0
int TabSizeQ3 = 0
int TabSizeQ4 = 0
int TabSizeQ5 = 0
int TabSizeQ6 = 0
int PageHistory = 0
bool PageOnEveryBar = false
bool MoveLogUp = true
bool ColorText = true
bool HighlightText = false
bool ReplaceWithCodes=false
bool RestrictLevelsToKey7 = false
bool MarkNewBar = true
int MinWidth = 40
bool AutoMerge = true
bool PrefixLogLevel = false
int ShowMinimumLevel = 0
matrix<string> mqx
matrix<int> hqx
matrix<color> cqx
matrix<bool> bqx
array<int> intDB
array<bool> boolDB
array<string> stringDB
matrix<color> colorDB
array<string> levelDB
array<string> fontDB
matrix<color> cfgx
matrix<color> cbgx
table tbx
table cbx
// @function
// convert to upper string\
// convert to upper string from bool
export method upper(string this) => str.upper(this)
// @function
// convert to lower string\
// convert to lower string from bool
export method lower(string this) => str.lower(this)
// @function convert bool to string upper
export method upper(bool this) => str.upper(str.tostring(this))
// @function convert bool to string lower
export method lower(bool this) => str.lower(str.tostring(this))
// @function
// convert to float from bool\
// convert to float from string\
// convert to float from int
// rounds float to specified decimals `.f(int deciimals=6)`
export method f(bool this) => this ? 1.0 : 0.0
export method f(string this, int decimals=6) =>
// export method f(string this) => str.tonumber(this)
math.round(str.tonumber(this), decimals)
export method f(int this) => float(this)
export method f(float this, int decimals = 6 ) => math.round(this, decimals)
// @function
// convert to int from bool\
// convert to int from string\
// convert to int from float
export method i(bool this) => this ? 1 : 0
export method i(string this) =>
// export method i(string this) => int(str.tonumber(this))
switch
na(str.match(this,'[^\\d]')) => int(str.tonumber(this))
=> int(na)
export method i(float this) => int(this)
// @function
// convert to string from bool\
// convert to string from int\
// convert to string from float
export method s(bool this) => str.tostring(this)
export method s(int this) => str.tostring(this)
export method s(float this) => str.tostring(this)
// @function
// convert to bool from int\
// convert to bool from float\
// convert to bool from string
export method b(int this) => this!=0?true:false
export method b(float this) => this!=0.0?true:false
export method b(string this) =>
// export method b(string this) => str.upper(this)=='TRUE' ? true : false
varip _false = array.from('n','no','nan','0','0.0','f','false','fail','failed','x')
varip _true = array.from('y','yes','1','1.0','t','true','pass','passed','p')
float snum=str.tonumber(this)
if na(snum)
switch
array.includes(_false,str.lower(this)) => false
array.includes(_true ,str.lower(this)) => true
=> bool(na)
else
snum!=0.0
// @function Returns TV compliant Text Alignment, that can be used in TV functions
// @param align, string: alignment in human readable form. Deafult is left
// @returns text alignment
export method getTextAlign(string name) =>
var _style = switch str.lower(name)
'left' => text.align_left
'right' => text.align_right
'top' => text.align_top
'bottom' => text.align_bottom
'center' => text.align_center
_style
// @function Returns TV compliant Text size, that can be used in TV functions
// @param size, string: size in human readable form. Deafult is auto
// @returns text alignment
export method getTextSize(string name) =>
var _style = switch str.lower(name)
'auto' => size.auto
'tiny' => size.tiny
'small' => size.small
'normal' => size.normal
'large' => size.large
'huge' => size.huge
_style
// @function Returns TV compliant Table position, that can be used in TV functions
// @param position, string: position in human readable form. Deafult is top left
// @returns Table position
export method getTablePosition(string name) =>
var _position= switch str.lower(name)
'top right' => position.top_right
'top center' => position.top_center
'top left' => position.top_left
'middle right' => position.middle_right
'middle center' => position.middle_center
'middle left' => position.middle_left
'bottom right' => position.bottom_right
'bottom center' => position.bottom_center
'bottom left' => position.bottom_left
_position
//====================
__consolePosition(int position) =>
_position=switch position
1 => 'top'
2 => 'right'
4 => 'left'
=> 'bottom'
__consolePosition(string position='anywhere') =>
_position = switch str.lower(position)
'top' => 1
'right' => 2
'left' => 4
=> 3
_position
method __resetLocations(log this) =>
this.intDB.set(17,0), this.intDB.set(18,0), this.intDB.set(19,1), this.intDB.set(20,8)
this.intDB.set(13,0), this.intDB.set(14,10), this.intDB.set(15,this.intDB.get(1)-1+(this.ShowHeader?1:0) + (this.ShowStatusBar?1:0)), this.intDB.set(16,18)
this.intDB.set(11,3)
method __switchMode(log this)=>
if this.boolDB.get(1) and not this.IsConsole
string _metaLog='', string _toLog='', int oldm1Len=0, int m1Len=0, int lvl=0
for x=0 to this.mqx.rows()>0 ? (this.mqx.rows()-1) : na
oldm1Len:=str.length(this.mqx.get(x,1))
if str.contains(this.mqx.get(x,8),'New Bar')
_metaLog:=''
_toLog:=this.mqx.get(x,1)
m1Len:=this.hqx.get(x,3)
else
lvl:=this.hqx.get(x,0)
_metaLog:=(this.ShowBarIndex ? (str.tostring(bar_index)+', ') : '') +
(this.ShowDateTime ? (str.format('{0,date,'+this.stringDB.get(4)+'}',this.hqx.get(x,2))+' ') : '') +
((this.TabSizeQ1>0 and lvl>1 and lvl<=7)? str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ1)):'') +
( (this.PrefixLogLevel and lvl>=0 and lvl<=this.levelDB.size())? (this.levelDB.get(lvl) +': ' ):'')
_toLog:=str.substring(this.mqx.get(x,1),0,4096-str.length(_metaLog))
m1Len:=str.length(_metaLog)+str.length(_toLog)
this.hqx.set(x,3,m1Len), this.mqx.set(x,0,_metaLog), this.mqx.set(x,1,_toLog)
this.boolDB.set(1, this.IsConsole)
method __MarkNewBar(log this, int lvl=0, int ccode=0, string font=na, int tv=time, int q=0)=>
if (this.MarkNewBar and this.intDB.get(4)!=bar_index)
int _txn = (q>=1 and q<=6)?this.intDB.get(25+q):math.max(this.intDB.get(0),this.intDB.get(26),this.intDB.get(27),this.intDB.get(28),this.intDB.get(29),this.intDB.get(30),this.intDB.get(31))
// int _qsize = this.intDB.get(1)
int _qn = ((_txn+1)%this.intDB.get(1))
_logMark='#.'+str.tostring(bar_index)+' '+this.stringDB.get(1)
_markLen=str.length(_logMark)
this.hqx.set(_qn,0, lvl),this.hqx.set(_qn,1, bar_index),this.hqx.set(_qn,2, tv),this.hqx.set(_qn,3, _markLen),this.hqx.set(_qn,4, _markLen),this.hqx.set(_qn,5, this.intDB.get(6)),this.hqx.set(_qn,6, font==font.family_monospace?1:0)
this.mqx.set(_qn,0, ''),this.mqx.set(_qn,1, _logMark),this.mqx.set(_qn,2, ''),this.mqx.set(_qn,3, ''),this.mqx.set(_qn,4, ''),this.mqx.set(_qn,5, ''),this.mqx.set(_qn,6, ''),this.mqx.set(_qn,7, '')
this.mqx.set(_qn,8,'New Bar #.'+str.tostring(bar_index))
this.cqx.set(_qn,0,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cqx.set(_qn,1,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cfgx.set(_qn,0,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cfgx.set(_qn,1,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cfgx.set(_qn,2,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cfgx.set(_qn,3,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cfgx.set(_qn,4,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cfgx.set(_qn,5,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(ccode,0) : this.HighlightText ? this.colorDB.get(ccode, 2) : this.TextColor)
this.cbgx.set(_qn,0,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cbgx.set(_qn,1,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cbgx.set(_qn,2,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cbgx.set(_qn,3,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cbgx.set(_qn,4,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.cbgx.set(_qn,5,(ccode<0 or ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(ccode,1) : this.HighlightText ? this.colorDB.get(ccode, 0) : this.TextColorBG)
this.bqx.set(_qn,0,true), this.bqx.set(_qn,1,true)
if q>=1 and q<=6
this.intDB.set(25+q,this.intDB.get(25+q)+1)
else
this.intDB.set(0,this.intDB.get(0)+1)
// @function
// Clears all the queue, including bar_index and time queues, of existing messages
//```
// method clear()
//```
//___
export method clear (log this)=>
this.mqx.fill( '', 0, this.mqx.rows(), 0, this.mqx.columns())
this.hqx.fill( -1, 0, this.hqx.rows(), 0, this.hqx.columns())
this.bqx.fill(true,0, this.bqx.rows(), 0, this.bqx.columns())
this.hqx.fill( 0, 0, this.hqx.rows(), 6,7)
this.hqx.fill( 0, 0, this.hqx.rows(), 3,5)
this.hqx.fill( this.intDB.get(6), 0, this.hqx.rows(), 5,6)
this.cfgx.fill(chart.fg_color,0,this.cfgx.rows(),0,this.cfgx.columns())
this.cbgx.fill(chart.bg_color,0,this.cbgx.rows(),0,this.cbgx.columns())
this.intDB.set(7,0),this.intDB.set(0,-1),this.intDB.set(26,-1),this.intDB.set(27,-1),this.intDB.set(28,-1),this.intDB.set(29,-1),this.intDB.set(30,-1),this.intDB.set(31,-1),this.intDB.set(12,-1)
// @function
// Resizes the message queues. If size is decreased then removes the oldest message.
//```
// method resize (int rows=40)
//```
// #### *Parameters*
//> int `rows`=*40* Number of rows to be resized to
//___
// @param rows The new size needed for the queues. Default value is 40.
export method resize (log this, int rows=40) =>
int _txn = this.intDB.get(0)
int _qsize = this.intDB.get(1)
int _qc = (_txn<=-1 or _qsize<1) ? na : (_txn%_qsize)
int _qn = (_txn<=-1 or _qsize<1) ? na : ((_txn+1)%_qsize)
int _rows = math.min(1000,rows)
if _rows<=0
this.clear()
else
if _qsize > _rows and _qsize != _rows
for x = 1 to (_qsize - _rows)
this.mqx.remove_row(_qn),this.hqx.remove_row(_qn),this.cqx.remove_row(_qn),this.bqx.remove_row(_qn)
_qn := (_txn<=-1) ? na : ((_txn+1)%_qsize)
if _qn>_qc
_qn := (_qc+1 > (_qsize-1-x)) ? 0 : _qn
else
_qc -= 1
if _qsize < _rows and _qsize != _rows
for x =1 to (_rows - _qsize)
this.mqx.add_row(_qn,array.new_string(this.mqx.columns(),'')),this.hqx.add_row(_qn,array.new_int(this.hqx.columns(),-1)),this.cqx.add_row(_qn,array.new_color(this.cqx.columns(),na)),this.bqx.add_row(_qn,array.new_bool(this.bqx.columns(),true)),this.cfgx.add_row(_qn,array.new_color(this.cfgx.columns(),na)),this.cbgx.add_row(_qn,array.new_color(this.cbgx.columns(),na))
this.hqx.set(_qn+1,3,0),this.hqx.set(_qn+1,4,0),this.hqx.set(_qn+1,6,0),this.hqx.set(_qn+1,5,this.intDB.get(6))
this.intDB.set(1, _rows)
_txn := (_txn+1) < _qsize ? _txn : (_rows-1+_qn)
this.intDB.set(0, _txn),this.intDB.set(12, _txn),this.intDB.set(26, _txn),this.intDB.set(27, _txn),this.intDB.set(28, _txn),this.intDB.set(29, _txn),this.intDB.set(30, _txn),this.intDB.set(31, _txn)
this.intDB.set(15, _rows-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0) + (this.intDB.get(11)==1 ? 2 : 0))
// @function
// Undo messages logged. Will not undo when messages have been logged asynchronously
//```
// method undo (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo(log this, int rows=1) =>
int _txn = this.intDB.get(0)
int _rows = math.min(this.intDB.get(1),math.max(0,rows))
_rows := (_txn+1)>=_rows ? _rows : this.intDB.get(1)
if _rows==this.intDB.get(1)
this.clear()
else if _rows>0
int wx=0
int del=0
while wx<=(_rows-1)
_qu=(_txn-wx)%this.intDB.get(1)
if this.bqx.get(_qu,0)!=this.bqx.get(_qu,1)
break
this.hqx.set(_qu,1,-1),this.hqx.set(_qu,3,0),this.hqx.set(_qu,4,0),this.hqx.set(_qu,6,0),this.hqx.set(_qu,5,this.intDB.get(6))
wx+=1
del+=1
this.intDB.set(7,this.intDB.get(7)-del),this.intDB.set(0,this.intDB.get(0)-del)
this.intDB.set(26,this.intDB.get(26)-del),this.intDB.set(27,this.intDB.get(27)-del),this.intDB.set(28,this.intDB.get(28)-del),this.intDB.set(29,this.intDB.get(29)-del),this.intDB.set(30,this.intDB.get(30)-del),this.intDB.set(31,this.intDB.get(31)-del),this.intDB.set(12,this.intDB.get(12)-del)
// @function
// Undo asynchronously logged messages. Will not undo normally logged messages.
//```
// method undoq (int q, int rows=1)
//```
// #### *Parameters*
//> int `q` Q number whose messages are to be reverted\
//> int `rows`*=1* Number of rows to be reverted
//___
// @param q The Q number to remove messages from
// @param rows Default is 1
export method undoq(log this, int q, int rows=1) =>
bool _undo=(q<1 or q>6)?false:this.intDB.get(25+q)>this.intDB.get(12)?true:false
if _undo
int _txn = this.intDB.get(12)
int _txnQ = this.intDB.get(25+q)
// int _qsize = this.intDB.get(1)
int _rows = math.min(this.intDB.get(1),math.max(0,rows),this.intDB.get(25+q)-this.intDB.get(12))
if _rows>0
int wx=0
int _qu=_txnQ%this.intDB.get(1)
while wx<=(_rows-1) and _txnQ>_txn and this.bqx.get(_qu,0)!=this.bqx.get(_qu,1)
this.mqx.set(_qu,q,'')
this.cfgx.set(_qu,q-1,na)
this.cbgx.set(_qu,q-1,chart.bg_color)
_txnQ-=1
this.intDB.set(25+q,_txnQ)
if _txnQ == math.max(this.intDB.get(26),this.intDB.get(27),this.intDB.get(28),this.intDB.get(29),this.intDB.get(30),this.intDB.get(31))
this.hqx.set(_qu,1,-1)
this.bqx.set(_qu,0,true)
this.bqx.set(_qu,1,true)
wx+=1
_qu:=_txnQ%this.intDB.get(1)
this.intDB.set(0,math.max(this.intDB.get(26),this.intDB.get(27),this.intDB.get(28),this.intDB.get(29),this.intDB.get(30),this.intDB.get(31)))
// @function
// Undo asynchronously logged messages from Q1. Will not undo normally logged messages.
//```
// method undo1 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo1(log this, int rows=1) => this.undoq(1,rows)
// @function
// Undo asynchronously logged messages from Q2. Will not undo normally logged messages.
//```
// method undo2 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo2(log this, int rows=1) => this.undoq(2,rows)
// @function
// Undo asynchronously logged messages from Q3. Will not undo normally logged messages.
//```
// method undo3 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo3(log this, int rows=1) => this.undoq(3,rows)
// @function
// Undo asynchronously logged messages from Q4. Will not undo normally logged messages.
//```
// method undo4 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo4(log this, int rows=1) => this.undoq(4,rows)
// @function
// Undo asynchronously logged messages from Q5. Will not undo normally logged messages.
//```
// method undo5 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo5(log this, int rows=1) => this.undoq(5,rows)
// @function
// Undo asynchronously logged messages from Q6. Will not undo normally logged messages.
//```
// method undo6 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// @param rows Default is 1
export method undo6(log this, int rows=1) => this.undoq(6,rows)
__getFont(string font=na)=>font==font.family_monospace?font.family_monospace:font.family_default
// @function
// Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm\
//```
// method dateTimeFormat(string format='')
//```
// #### *Parameters*
//> string `format`*=''* Date time format. If passed as empty (not as na) then resets teh format to d.MMM.yy H:mm, which would look as 9.Aug.23 9:01
//___
// @param format time format to be used for displaying the date. If empty then reverts to dd.MMM.yy HH:mm
export method dateTimeFormat(log this, string format='') =>this.stringDB.set(4, format==''?'d.MMM.yy H:mm':format)
// @function
// Sets up font to be used for Header (only on Logx)\
//```
// method setFontHeader(string font=na)
//```
// #### *Parameters*
//> string `font`*=na* Font to be used for Logx header. If it is not font.family_monospace then it is set to font.family_default
//___
// @param font Font to be used for Header. If nothing is specified then defaults to font.family_default
export method setFontHeader(log this, string font=na)=>this.stringDB.set(6,__getFont(font))
// @function
// Sets up font to be used for Status\
//```
// method setFontStatus(string font=na)
//```
// #### *Parameters*
//> string `font`*=na* Font to be used for Console/Logx status bar. If it is not font.family_monospace then it is set to font.family_default
//___
// @param font Font to be used for Status. If nothing is specified then defaults to font.family_default
export method setFontStatus(log this, string font=na)=>this.stringDB.set(7,__getFont(font))
// @function
// Sets up font to be used for meta info in Status\
//```
// method setFontMetaStatus(string font=na)
//```
// #### *Parameters*
//> string `font`*=na* Font to be used for Console/Logx status bar. If it is not font.family_monospace then it is set to font.family_default
//___
// @param font Font to be used for Meta Status. If nothing is specified then defaults to font.family_default
export method setFontMetaStatus(log this, string font=na)=>this.stringDB.set(8,__getFont(font))
// @function
// Resets the text color of the log to library default.
//```
// method resetTextColor()
//```
//___
export method resetTextColor(log this) =>this.TextColor := color.new(chart.fg_color,60)
// @function
// Resets the background color of the log to library default.
//```
// method resetTextColorBG()
//```
//___
export method resetTextColorBG(log this) =>this.TextColorBG := chart.bg_color
// @function
// Resets the color used for Headers, to library default.
//```
// method resetHeaderColor()
//```
//___
export method resetHeaderColor(log this) =>this.TextColor := color.new(chart.fg_color,30)
// @function
// Resets the background color used for Headers, to library default.
//```
// method resetHeaderColorBG()
//```
//___
export method resetHeaderColorBG(log this) =>this.HeaderColorBG := color.new(#434651,80)
// @function
// Resets the text color of the status row, to library default.
//```
// method resetStatusColor()
//```
//___
export method resetStatusColor(log this) =>this.StatusColor := color.new(#9598a1,50)
// @function
// Resets the background color of the status row, to library default.
//```
// method resetStatusColorBG()
//```
//___
export method resetStatusColorBG(log this) =>this.StatusColorBG := color.new(#434651,70)
// @function
// Resets the color used for the frame around the log table, to library default.
//```
// method resetFrameColor()
//```
//___
export method resetFrameColor(log this) =>this.FrameColor := chart.bg_color
// @function
// Resets the color used for the highlighting when Highlight Text option is used, to library default
//```
// method resetColorsHC()
//```
//___
export method resetColorsHC(log this) =>
if this.colorDB.rows()<37
for x=1 to 37-this.colorDB.rows()
this.colorDB.add_row(0)
this.colorDB.fill(color.new(color.white,10),0,this.colorDB.rows(),2,3)
this.colorDB.set(5, 2,color.new(color.black,10)),this.colorDB.set(6, 2,color.new(color.black,10)),this.colorDB.set(14,2,color.new(color.black,10)),this.colorDB.set(21,2,color.new(color.black,10)),this.colorDB.set(22,2,color.new(color.black,10)),this.colorDB.set(26,2,color.new(color.black,10)),this.colorDB.set(34,2,color.new(color.black,10)),this.colorDB.set(35,2,color.new(color.black,10))
this.intDB.set(21,this.colorDB.rows())
// @function
// Resets the background color used for setting the background color, when the Color Text option is used, to library default
//```
// method resetColorsBG()
//```
//___
export method resetColorsBG(log this) =>
if this.colorDB.rows()<37
for x=1 to 37-this.colorDB.rows()
this.colorDB.add_row(0)
for x=0 to this.colorDB.rows()-1
this.colorDB.set(x,1,chart.bg_color)
this.intDB.set(21,this.colorDB.rows())
// @function
// Resets the color used for respective color code, when the ColorText option is used, to library default
//```
// method resetColors()
//```
//___
export method resetColors(log this) =>
if this.colorDB.rows()<37
for x=1 to 37-this.colorDB.rows()
this.colorDB.add_row(0)
this.colorDB.set(3, 0, color.new(#2196f3,10)),this.colorDB.set(2, 0, color.new(#4caf50,10)),this.colorDB.set(1, 0, color.new(#9598a1,20)),this.colorDB.set(4, 0, color.new(#c29857,20)),this.colorDB.set(5, 0, color.new(#fbc02d,10)),this.colorDB.set(6, 0, color.new(#f57f17,00)),this.colorDB.set(7, 0, color.new(#f44336,10))
this.colorDB.set(8, 0, color.new(color.aqua,10)),this.colorDB.set(9, 0, color.new(color.blue,10)),this.colorDB.set(10,0, color.new(color.red,10)),this.colorDB.set(11,0, color.new(color.fuchsia,10)),this.colorDB.set(12,0, color.new(color.gray,10)),this.colorDB.set(13,0, color.new(color.green,10)),this.colorDB.set(14,0, color.new(color.lime,10))
this.colorDB.set(15,0, color.new(color.maroon,10)),this.colorDB.set(16,0, color.new(color.navy,10)),this.colorDB.set(17,0, color.new(color.olive,10)),this.colorDB.set(18,0, color.new(color.purple,10)),this.colorDB.set(19,0, color.new(color.silver,10)),this.colorDB.set(20,0, color.new(color.teal,10)),this.colorDB.set(21,0, color.new(color.white,10))
this.colorDB.set(22,0, color.new(color.yellow,10)),this.colorDB.set(23,0, color.new(#9C6E1B,00)),this.colorDB.set(24,0, color.new(#AA00FF,10)),this.colorDB.set(25,0, color.new(#673ab7,10)),this.colorDB.set(26,0, color.new(#CCCC00,10)),this.colorDB.set(27,0, color.new(#c29857,10)),this.colorDB.set(28,0, color.new(#5d606b,00))
this.colorDB.set(29,0, color.new(#fc5d07,10)),this.colorDB.set(30,0, color.new(#004d40,10)),this.colorDB.set(31,0, color.new(#b71c1c,10)),this.colorDB.set(32,0, color.new(#7e57c2,50)),this.colorDB.set(33,0, color.new(#388e3c,20)),this.colorDB.set(34,0, color.new(#ffeb3b,00)),this.colorDB.set(35,0, color.new(#fbc02d,00))
this.colorDB.set(36,0, color.new(#ff9850,10))
this.resetColorsHC(),this.resetColorsBG()
// @function
// Sets the colors corresponding to color codes. Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
//```
// method setColors(color[] c)
//```
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color is used
//___
// @param c Array of colors to be used for corresponding color codes. If the corresponding code is not found, then text color is used
export method setColors(log this, color[] c) =>
sc=c.size()
sq=this.colorDB.rows()
if sq<sc
trow=this.colorDB.row(0)
for x=1 to sc-sq
this.colorDB.add_row(0)
if sq>sc and sc>0
for x=1 to sq-sc
this.colorDB.remove_row(0)
for x=0 to (sc > 0 ? sc-1 : na)
this.colorDB.set(x,0,c.get(x))
this.intDB.set(21,this.colorDB.rows())
// @function
// Sets the highlight colors corresponding to color codes. Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
//```
// method setColorsHC(color[] c)
//```
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
//___
// @param c Array of highlight colors to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
export method setColorsHC(log this, color[] c) =>
sc=c.size()
sq=this.colorDB.rows()
if sq<sc
trow=this.colorDB.row(0)
for x=1 to sc-sq
this.colorDB.add_row(0)
if sq>sc and sc>0
for x=1 to sq-sc
this.colorDB.remove_row(0)
for x=0 to (sc > 0 ? sc-1 : na)
this.colorDB.set(x,2,c.get(x))
this.intDB.set(21,this.colorDB.rows())
// @function
// Sets the background colors corresponding to color codes. Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
//```
// method setColorsBG(color[] c)
//```
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
//___
// @param c Array of background colors to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
export method setColorsBG(log this, color[] c) =>
sc=c.size()
sq=this.colorDB.rows()
if sq<sc
trow=this.colorDB.row(0)
for x=1 to sc-sq
this.colorDB.add_row(0)
if sq>sc and sc>0
for x=1 to sq-sc
this.colorDB.remove_row(0)
for x=0 to (sc > 0 ? sc-1 : na)
this.colorDB.set(x,1,c.get(x))
this.intDB.set(21,this.colorDB.rows())
// @function
// Sets the color corresponding to color code
//```
// method setColor(int e, color c)
// method setColor(int e, color fg, color bg, color hc)
//```
// #### *Parameters*
//> int `e` Color code whose color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
// #### *Parameters*
//> color `fg` Foreground Color corresponding to code supplied\
//> color `bg` Background Color corresponding to code supplied\
//> color `hc` Highlight Color corresponding to code supplied.
//___
// @param e Color code number whose color needs to be changed. If this code is not found, then color array will be expanded.
// @param c Color corresponding to code supplied.
export method setColor(log this, int e, color c) =>
if e>=0
if e>(this.colorDB.rows()-1)
ca=array.from(this.TextColor,this.TextColorBG,color.white)
while e>(this.colorDB.rows()-1)
this.colorDB.add_row(this.intDB.get(21)-1,ca)
this.intDB.set(21,this.colorDB.rows())
this.colorDB.set(e,0,c)
// @function Sets the color corresponding to error code
// @param e Error code whose color needs to be changed. If this error code is not found, then error color array will be expanded.
// @param fg Foreground Color corresponding to error code supplied.
// @param bg Background Color corresponding to error code supplied.
// @param hc Highlight Color corresponding to error code supplied.
export method setColor(log this, int e, color fg, color bg, color hc) =>
if e>=0
if e>(this.colorDB.rows()-1)
ca=array.from(this.TextColor,this.TextColorBG,color.white)
while e>(this.colorDB.rows()-1)
this.colorDB.add_row(this.intDB.get(21),ca)
this.intDB.set(21,this.colorDB.rows())
this.colorDB.set(e,0,fg)
this.colorDB.set(e,1,bg)
this.colorDB.set(e,2,hc)
// @function
// Sets the highlight color corresponding to error code
//```
// method setColorHC(int e, color c)
//```
// #### *Parameters*
//> int `e` Color code whose highlight color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
//___
// @param e Color code number whose highlight color needs to be changed. If this code is not found, then color array will be expanded.
// @param c Color corresponding to code supplied.
export method setColorHC(log this, int e, color c) =>
if e>=0
if e>(this.colorDB.rows()-1)
ca=array.from(this.TextColor,this.TextColorBG,color.white)
while e>(this.colorDB.rows()-1)
this.colorDB.add_row(this.intDB.get(21),ca)
this.intDB.set(21,this.colorDB.rows())
this.colorDB.set(e,2,c)
// @function
// Sets the background color corresponding to error code
//```
// method setColorBG(int e, color c)
//```
// #### *Parameters*
//> int `e` Color code whose background color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
//___
// @param e Color code number whose background color needs to be changed. If this code is not found, then color array will be expanded.
// @param c Color corresponding to code supplied.
export method setColorBG(log this, int e, color c) =>
if e>=0
if e>(this.colorDB.rows()-1)
ca=array.from(this.TextColor,this.TextColorBG,color.white)
while e>(this.colorDB.rows()-1)
this.colorDB.add_row(this.intDB.get(21),ca)
this.intDB.set(21,this.colorDB.rows())
this.colorDB.set(e,1,c)
// @function
// Returns the color corresponding to color code
//```
// method getColor(int e)
//```
// #### *Parameters*
//> int `e` Color Code whose color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// @param e Code whose color needs to be extracted. If this code is not found, then na will be returned.
export method getColor(log this, int e) =>
if e>=0 and e<this.intDB.get(21)
this.colorDB.get(e,0)
// @function
// Returns the highlight color corresponding to color code
//```
// method getColorHC(int e)
//```
// #### *Parameters*
//> int `e` Color Code whose highlight color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The highlight color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// @param e Code whose highlight color needs to be extracted. If this code is not found, then na will be returned.
export method getColorHC(log this, int e) =>
if e>=0 and e<this.intDB.get(21)
this.colorDB.get(e,2)
// @function
// Returns the background color corresponding to color code
//```
// method getColorBG(int e)
//```
// #### *Parameters*
//> int `e` Color Code whose background color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The background color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// @param e Code whose background color needs to be extracted. If this code is not found, then na will be returned.
export method getColorBG(log this, int e) =>
if e>=0 and e<this.intDB.get(21)
this.colorDB.get(e,1)
// @function
// Resets the log level names used for corresponding level codes\
// With prefix/suffix, the default Level name will be like => prefix + Code + suffix
//```
// method resetLevelNames(string prefix='Level ', string suffix='')
//```
// #### *Parameters*
//> string `prefix`=*'Level'* Prefix to use when resetting level names\
//> string `suffix`=*''* Suffix to use when resetting level names
//___
// @param prefix Prefix to use when resetting level names
// @param suffix Suffix to use when resetting level names
export method resetLevelNames(log this, string prefix='Level ', string suffix='') =>
this.levelDB.clear()
this.levelDB:=array.new_string(this.colorDB.rows()<8 ? 8 : (this.colorDB.rows()))
this.levelDB.set(0,''),this.levelDB.set(1,'TRACE'),this.levelDB.set(2,'DEBUG'),this.levelDB.set(3,'INFO'),this.levelDB.set(4,'WARNING'),this.levelDB.set(5,'ERROR'),this.levelDB.set(6,'CRITICAL'),this.levelDB.set(7,'FATAL')
for x=8 to this.levelDB.size() > 8 ? (this.levelDB.size()-1) : na
this.levelDB.set(x,prefix+str.tostring(x)+suffix)
// @function
// Resets the log level names used for corresponding level codes\
// Index 0 of input array names is reserved for future use\
// Index 1 of input array names is name used for level code 1.\
// Index 2 of input array names is name used for level code 2 and so on.
//```
// method setLevelNames(string[] names)
//```
// #### *Parameters*
//> string[ ] `names` Array of log level names be used for corresponding level odes. If the corresponding code is not found, then an empty string is used
//___
// @param names Array of log level names be used for corresponding level odes. If the corresponding code is not found, then an empty string is used
export method setLevelNames(log this, string[] names) =>
if names.size()>0
this.levelDB.clear()
this.levelDB:=array.new_string(names.size()<8 ? 8 : names.size())
this.levelDB.set(0,''),this.levelDB.set(1,''),this.levelDB.set(2,''),this.levelDB.set(3,''),this.levelDB.set(4,''),this.levelDB.set(5,''),this.levelDB.set(6,''),this.levelDB.set(7,'')
for x=0 to names.size()-1
this.levelDB.set(x+1,names.get(x))
// @function
// Sets the Log level name corresponding to code supplied.
//```
// method setLevelName(int e, string levelName)
//```
// #### *Parameters*
//> int `e` Code whose log level name needs to be changed. If this code is not found, then log level names array will be expanded.\
//> string `levelName` Level name corresponding to code supplied.
//___
// @param e Error code whose log level name needs to be changed. If this code is not found, then log level names array will be expanded.
// @param levelName Log level name corresponding to code supplied.
export method setLevelName(log this, int e, string levelName) =>
if e>=0
while e>(this.levelDB.size()-1)
this.levelDB.push('LVL <'+str.tostring(this.levelDB.size())+'>')
this.levelDB.set(e,levelName)
// @function
// Gets the Log level name corresponding to error code supplied.
//```
// method getLevelName(int e)
//```
// #### *Parameters*
//> int `e` Code whose log level name needs to be extracted. If this error code is not found, then na will be returned.\
// #### Returns
//> **`string`** The log level name corresponding to code supplied. If this code is not found, then na will be returned.
//___
// @param e Code whose log level name needs to be extracted. If this error code is not found, then na will be returned.
export method getLevelName(log this, int e) =>
if e>=0 and e<this.levelDB.size()
this.levelDB.get(e)
// @function
// Sets up data for logging. It consists of 6 separate message queues, and 3 additional queues for bar index, time and log level/error code. Do not directly alter the contents, as library could break.
//```
// method init (int rows=50, isConsole=true)
//```
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with\
//> bool `isConsole`*=true* Whether to initialise as Console or Logx. If true will setup as Console.
//___
// @param rows Log size, excluding the header/status. Default value is 50.
// @param isConsole Whether to init the log as console or logx. True= as console, False = as Logx. Default is true, hence init as console.
export method init(log this, int rows=50, bool isConsole=true) =>
var bool _init = false
if not _init and barstate.isfirst
_rows=math.max(1,math.min(1000,rows))
this.IsConsole:=isConsole
this.mqx:= matrix.new<string> (_rows,9,'')
this.hqx:= matrix.new<int> (_rows,7,-1)
this.bqx:= matrix.new<bool> (_rows,2,true)
this.cqx:= matrix.new<color> (_rows,2)
this.cfgx:= matrix.new<color> (_rows,6)
this.cbgx:= matrix.new<color> (_rows,6)
this.intDB := array.new<int> (40,0)
this.boolDB := array.new<bool> (10,false)
this.stringDB := array.new<string> (10,'')
this.colorDB := matrix.new<color> (37,3)
this.levelDB := array.new<string> (37,'')
this.fontDB := array.from(font.family_default,font.family_monospace)
this.intDB.set(21,this.colorDB.rows())
this.resetColors()
this.dateTimeFormat()
this.resetLevelNames('LVL <','>')
this.HeaderColor := color.new(chart.fg_color,30)
this.HeaderColorBG := color.new(#434651,80)
this.StatusColor := color.new(#9598a1,50)
this.StatusColorBG := color.new(#434651,70)
this.TextColor := color.new(chart.fg_color,60)
this.TextColorBG := chart.bg_color
this.FrameColor := chart.bg_color
this.CellBorderColor:= chart.bg_color
this.stringDB.set(0,' ')
this.stringDB.set(1,'______________')
this.intDB.set(22,str.length(this.stringDB.get(0))),this.intDB.set(23,str.length(this.stringDB.get(1)) )
this.stringDB.set(3,' ')
this.stringDB.set(6,font.family_default),this.stringDB.set(7,font.family_default),this.stringDB.set(8,font.family_default)
this.intDB.set(1, math.max(0,rows)),this.intDB.set(6,0),this.intDB.set(5,0),this.intDB.set(7,0)
// this.hqx.fill(0,0, this.hqx.rows(), 6,7),this.hqx.fill(0,0, this.hqx.rows(), 3,5),this.hqx.fill(0,0, this.hqx.rows(), 5,6)
this.hqx.fill(0,0, this.hqx.rows(), 3,7)
this.boolDB.set(1,this.IsConsole)
this.stringDB.set(4, 'dd.MMM.yy HH:mm'),this.stringDB.set(5, position.top_right)
this.intDB.set(24,80),this.intDB.set(25,40)
this.__resetLocations(),this.setFontHeader(),this.setFontStatus(),this.setFontMetaStatus()
_init:=true
this.boolDB.set(0,_init)
this.SeparatorColor:=color.new(#c29857,20)
this.MarkNewBar:=this.IsConsole?true:false
this.ShowBarIndex:=this.IsConsole?false:true
// @function
// Sets up logger as Console. It consists of one message queue, and 3 additional queues for bar index, time and log level/error code.
//```
// method initConsole (int rows=50)
//```
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with
// #### Override default settings with following
//> `MarkNewBar` =*true*\
//> `ShowBarIndex`= *false*
//___
// @param rows Log size, excluding status. Default value is 50.
export method initConsole(log this, int rows=50)=>
this.init(rows,isConsole=true)
this.MarkNewBar := true
this.ShowBarIndex := false
// @function
// Sets up logger as Logx. It consists of six message queues, and 3 additional queues for bar index, time and log level/error code.
//```
// method initLogx (int rows=50)
//```
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with
// #### Override default settings with following
//> `MarkNewBar` =*false*\
//> `ShowBarIndex` =*true*
//___
// @param rows Log size, excluding status. Default value is 50.
export method initLogx(log this, int rows=50)=>
this.init(rows,isConsole=false)
this.MarkNewBar := false
this.ShowBarIndex := true
// @function
// Logs messages asyncronously to the queue, including, time/date, bar_index, and error code
//```
// method alog ( string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, int c, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message.If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `q`*=1* Q number the message to be logged to\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
// #### *Note 1:*
// When logging to a console, color code parameter `c` is ignored and color coding of messages is via c1. This is due to Console not having multiple cells, and all data being fit into single table cell.\
// Hence, to keep logging behaviour consistent with Logx logging, the message colouring is via `c1` - `c6`, however for Console, the row color parameter `c` is not used for coloring.
// #### *Note 2:*
// When logging to console, the colour is picked from the last message logged\
// Sometimes, this can get confusing when (empty) messages are logged with a different colour and one would expect console to show a different color.
//___
// @param lvl (Optional) Log Level to be assigned.
// @param c (Optional) Color code of the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If not specified, uses lvl as color code
// @param m Message needed to be logged to Q.
// @param q Which Q should this message be logged to. Default is 1. If not in between 1 and 6, this message will not be logged.
// @param cq (Optional) Color code to be used for the message being logged. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param font Font to be used for this message row, when its displayed in the table. Accepts either font.family_default or font.family_monospace
// @param tooltip Tooltip to display over each row when mouse hovers over it
// @param tv Time to be used. Default value is time, which logs the start time of bar.
// @param log Whether to log the message or not. Default is true.
export method alog (log this, int lvl, int c, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)=>
_mq='',_metaC='',_m1Len=0,_tabSize=0, _ccode=c<0?lvl:c, _ccodeq=na(cq)?_ccode:cq<0?lvl:cq>this.colorDB.rows()?lvl:cq
this.PageHistory:=this.PageHistory < 0 ? 0 : this.PageHistory
if this.PageOnEveryBar and bar_index-this.intDB.get(3) > this.PageHistory
if this.PageHistory==0
this.clear()
else if this.intDB.get(1)>0
for x=0 to this.intDB.get(1)-1
this.hqx.set(x,1,(bar_index-this.hqx.get(x,1)) > this.PageHistory ? -1 : this.hqx.get(x,1))
this.hqx.set(x,3,(bar_index-this.hqx.get(x,1)) > this.PageHistory ? 0 : this.hqx.get(x,3))
this.intDB.set(3, bar_index - this.PageHistory)
if this.IsConsole!=this.boolDB.get(1)
this.__switchMode()
if log and q>0 and q<7
int _txnLeader = math.max(this.intDB.get(26),this.intDB.get(27),this.intDB.get(28),this.intDB.get(29),this.intDB.get(30),this.intDB.get(31))
int _txn = this.intDB.get(12)
// int _qsize = this.intDB.get(1)
int _qn = ((_txn+1)%this.intDB.get(1))
int _txnQ = this.intDB.get(25+q)
int _qnQ = ((_txnQ+1)%this.intDB.get(1))
// _qnQ+=str.contains(this.mqx.get(_qnQ,8),'New Bar')?1:0
if _txnQ==_txnLeader
_gap=(_txnQ+1)-(_txn+1)
_itn=((_gap-(_gap%this.intDB.get(1)))/this.intDB.get(1))%2
if this.bqx.get(_qnQ,_itn)
this.bqx.set(_qnQ,_itn,false),this.bqx.set(_qnQ,1-_itn,true)
this.mqx.set(_qnQ,1,''),this.mqx.set(_qnQ,2,''),this.mqx.set(_qnQ,3,''),this.mqx.set(_qnQ,4,''),this.mqx.set(_qnQ,5,''),this.mqx.set(_qnQ,6,'')
if (_txnLeader+1)-(_txnQ+1)<=this.intDB.get(1) and _txnLeader>=_txnQ
if not this.IsConsole
_tabSize:=switch q
1 => this.TabSizeQ1
2 => this.TabSizeQ2
3 => this.TabSizeQ3
4 => this.TabSizeQ4
5 => this.TabSizeQ5
6 => this.TabSizeQ6
=> 0
_mq := (lvl>1 and lvl<=7 and str.length(msg)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,_tabSize)):''
_mq += str.substring(msg,0,4096-str.length(_mq))
_metaC:=''
if this.IsConsole
_metaC:= (this.ShowBarIndex ? (str.tostring(bar_index)+', ') : '') +
(this.ShowDateTime ? (str.format('{0,date,'+this.stringDB.get(4)+'}',tv)+' ') : '') +
((this.TabSizeQ1>0 and lvl>1 and lvl<=7)? str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ1)):'') +
( (this.PrefixLogLevel and lvl>=0 and lvl<=this.levelDB.size())? (this.levelDB.get(lvl) +': ' ):'')
_storedLen=str.length(_metaC)+str.length(this.mqx.get(_qnQ,1))+str.length(this.mqx.get(_qnQ,2))+str.length(this.mqx.get(_qnQ,3))+str.length(this.mqx.get(_qnQ,4))+str.length(this.mqx.get(_qnQ,5))+str.length(this.mqx.get(_qnQ,6))
_mq:= _storedLen<4096?str.substring(msg,0,4096-_storedLen):''
this.mqx.set(_qnQ,0, _metaC),this.mqx.set(_qnQ,q, _mq)
this.hqx.set(_qnQ,3, str.length(_metaC)+str.length(this.mqx.get(_qnQ,1))+str.length(this.mqx.get(_qnQ,2))+str.length(this.mqx.get(_qnQ,3))+str.length(this.mqx.get(_qnQ,4))+str.length(this.mqx.get(_qnQ,5))+str.length(this.mqx.get(_qnQ,6)))
this.hqx.set(_qnQ,0, lvl),this.hqx.set(_qnQ,1, bar_index),this.hqx.set(_qnQ,2, tv),this.hqx.set(_qnQ,5, this.intDB.get(6)),this.hqx.set(_qnQ,6,font==font.family_monospace?1:0)
this.mqx.set(_qnQ,7, (lvl<0 or lvl>this.levelDB.size())?'':this.levelDB.get(lvl)),this.mqx.set(_qnQ,8,tooltip)
this.cqx.set(_qnQ,0,(_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode,0) : this.HighlightText ? this.colorDB.get(_ccode, 2) : this.TextColor)
this.cqx.set(_qnQ,1,(_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode,1) : this.HighlightText ? this.colorDB.get(_ccode, 0) : this.TextColorBG)
this.cfgx.set(_qnQ,q-1,(_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccodeq,0) : this.HighlightText ? this.colorDB.get(_ccodeq, 2) : this.TextColor)
this.cbgx.set(_qnQ,q-1,(_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccodeq,1) : this.HighlightText ? this.colorDB.get(_ccodeq, 0) : this.TextColorBG)
// this.cqx.set(_qnQ,0,this.ColorText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode,0)) : this.HighlightText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode, 2)) : this.TextColor )
// this.cqx.set(_qnQ,1,this.ColorText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode,1)) : this.HighlightText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode, 0)) : this.TextColorBG)
// this.cfgx.set(_qnQ,q-1,this.ColorText ? ((_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccodeq,0)) : this.HighlightText ? ((_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccodeq, 2)) : this.TextColor )
// this.cbgx.set(_qnQ,q-1,this.ColorText ? ((_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccodeq,1)) : this.HighlightText ? ((_ccodeq<0 or _ccodeq>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccodeq, 0)) : this.TextColorBG)
this.intDB.set(4,bar_index)
this.intDB.set(25+q, _txnQ+1),this.intDB.set(0,math.max(this.intDB.get(26),this.intDB.get(27),this.intDB.get(28),this.intDB.get(29),this.intDB.get(30),this.intDB.get(31)))
else if this.IsConsole
this.stringDB.set(2, ' +'+str.tostring(4096-this.intDB.get(5)) + (this.PageOnEveryBar ? ' ● ' : ' ') + '◼︎' )
// @function
// Logs messages to the queues , including, time/date, bar_index, and error code
//```
// method log ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.AutoMerge` Automatically merges the right most columns into left if there is no text logged.\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7
// #### *Properties used*
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `m1` Message needed to be logged to Q1, or for console\
//> string `m2` - `m6` Message needed to be logged to Q2 to Q6. Not used/ignored when in console mode\
//> int `c1` - `c6` (Optional) Color Code to be used for the messages being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
// #### *Note 1:*
// When logging to a console, color code parameter `c` is ignored and color coding of messages is via c1. This is due to Console not having multiple cells, and all data being fit into single table cell.\
// Hence, to keep logging behaviour consistent with Logx logging, the message colouring is via `c1` - `c6`, however for Console, the row color parameter `c` is not used for coloring.
// #### *Note 2:*
// When logging to console, the colour is picked from the last message logged\
// Sometimes, this can get confusing when (empty) messages are logged with a different colour and one would expect console to show a different color.
//___
// @param lvl (Optional) Log Level to be assigned.
// @param c (Optional) Color code of the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If not specified, uses lvl as color code
// @param m1 Message needed to be logged to Q1, or for console.
// @param m2 Message needed to be logged to Q2. Not used/ignored when in console mode
// @param m3 Message needed to be logged to Q3. Not used/ignored when in console mode
// @param m4 Message needed to be logged to Q4. Not used/ignored when in console mode
// @param m5 Message needed to be logged to Q5. Not used/ignored when in console mode
// @param m6 Message needed to be logged to Q6. Not used/ignored when in console mode
// @param c1 (Optional) Color code to be used for the message being logged to Q1. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c2 (Optional) Color code to be used for the message being logged to Q2. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c3 (Optional) Color code to be used for the message being logged to Q3. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c4 (Optional) Color code to be used for the message being logged to Q4. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c5 (Optional) Color code to be used for the message being logged to Q5. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c6 (Optional) Color code to be used for the message being logged to Q6. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param tooltip Tooltip to display over each row when mouse hovers over it
// @param font Font to be used for this message row, when its displayed in the table. Accepts either font.family_default or font.family_monospace
// @param tv Time to be used. Default value is time, which logs the start time of bar.
// @param log Whether to log the message or not. Default is true.
export method log (log this, int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)=>
_mq1='',_mq2='',_mq3='',_mq4='',_mq5='',_mq6='',_m1Len=0,_metaC='', _ccode=c<0?lvl:c
cdb=this.colorDB.rows()
_ccode1=na(c1)?_ccode:c1<0?lvl:c1>cdb?lvl:c1
_ccode2=na(c2)?_ccode:c2<0?lvl:c2>cdb?lvl:c2
_ccode3=na(c3)?_ccode:c3<0?lvl:c3>cdb?lvl:c3
_ccode4=na(c4)?_ccode:c4<0?lvl:c4>cdb?lvl:c4
_ccode5=na(c5)?_ccode:c5<0?lvl:c5>cdb?lvl:c5
_ccode6=na(c6)?_ccode:c6<0?lvl:c6>cdb?lvl:c6
this.PageHistory:=this.PageHistory < 0 ? 0 : this.PageHistory
if this.PageOnEveryBar and bar_index-this.intDB.get(3) > this.PageHistory
if this.PageHistory==0
this.clear()
else if this.intDB.get(1)>0
for x=0 to this.intDB.get(1)-1
this.hqx.set(x,1, (bar_index-this.hqx.get(x,1)) > this.PageHistory ? -1 : this.hqx.get(x,1))
this.hqx.set(x,3, (bar_index-this.hqx.get(x,1)) > this.PageHistory ? 0 : this.hqx.get(x,3))
this.intDB.set(3, bar_index - this.PageHistory)
if this.IsConsole!=this.boolDB.get(1)
this.__switchMode()
if log
this.__MarkNewBar(lvl,_ccode,font,tv,0)
int _txn = this.intDB.get(0)
// int _qsize = this.intDB.get(1)
int _qn = ((_txn+1)%this.intDB.get(1))
if not this.IsConsole
_mq1 := ( (lvl>1 and lvl<=7 and str.length(m1)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ1)):'')
_mq2 := ( (lvl>1 and lvl<=7 and str.length(m2)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ2)):'')
_mq3 := ( (lvl>1 and lvl<=7 and str.length(m3)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ3)):'')
_mq4 := ( (lvl>1 and lvl<=7 and str.length(m4)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ4)):'')
_mq5 := ( (lvl>1 and lvl<=7 and str.length(m5)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ5)):'')
_mq6 := ( (lvl>1 and lvl<=7 and str.length(m6)>0)?str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ6)):'')
_mq1+=str.substring(m1,0,4096-str.length(_mq1))
_mq2+=str.substring(m2,0,4096-str.length(_mq2))
_mq3+=str.substring(m3,0,4096-str.length(_mq3))
_mq4+=str.substring(m4,0,4096-str.length(_mq4))
_mq5+=str.substring(m5,0,4096-str.length(_mq5))
_mq6+=str.substring(m6,0,4096-str.length(_mq6))
_m1Len:=0
_metaC:=''
if this.IsConsole
_totalLen=array.sum(this.hqx.col(3))
_metaC:= (this.ShowBarIndex ? (str.tostring(bar_index)+', ') : '') +
(this.ShowDateTime ? (str.format('{0,date,'+this.stringDB.get(4)+'}',tv)+' ') : '') +
((this.TabSizeQ1>0 and lvl>1 and lvl<=7)? str.substring(this.stringDB.get(3),0,(math.min(7,lvl)-1)*math.min(4,this.TabSizeQ1)):'') +
( (this.PrefixLogLevel and lvl>=0 and lvl<=this.levelDB.size())? (this.levelDB.get(lvl) +': ' ):'')
_mq1:=str.substring(m1,0,4096-str.length(_metaC))
_m1Len:=str.length(_metaC)+str.length(_mq1)
this.hqx.set(_qn,0, lvl),this.hqx.set(_qn,1, bar_index),this.hqx.set(_qn,2, tv),this.hqx.set(_qn,3, _m1Len),this.hqx.set(_qn,5, this.intDB.get(6)),this.hqx.set(_qn,6,font==font.family_monospace?1:0)
this.cqx.set(_qn,0,(_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode,0) : this.HighlightText ? this.colorDB.get(_ccode, 2) : this.TextColor)
this.cqx.set(_qn,1,(_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode,1) : this.HighlightText ? this.colorDB.get(_ccode, 0) : this.TextColorBG)
this.cfgx.set(_qn,0,(_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode1,0) : this.HighlightText ? this.colorDB.get(_ccode1, 2) : this.TextColor)
this.cfgx.set(_qn,1,(_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode2,0) : this.HighlightText ? this.colorDB.get(_ccode2, 2) : this.TextColor)
this.cfgx.set(_qn,2,(_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode3,0) : this.HighlightText ? this.colorDB.get(_ccode3, 2) : this.TextColor)
this.cfgx.set(_qn,3,(_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode4,0) : this.HighlightText ? this.colorDB.get(_ccode4, 2) : this.TextColor)
this.cfgx.set(_qn,4,(_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode5,0) : this.HighlightText ? this.colorDB.get(_ccode5, 2) : this.TextColor)
this.cfgx.set(_qn,5,(_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColor : this.ColorText ? this.colorDB.get(_ccode6,0) : this.HighlightText ? this.colorDB.get(_ccode6, 2) : this.TextColor)
this.cbgx.set(_qn,0,(_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode1,1) : this.HighlightText ? this.colorDB.get(_ccode1, 0) : this.TextColorBG)
this.cbgx.set(_qn,1,(_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode2,1) : this.HighlightText ? this.colorDB.get(_ccode2, 0) : this.TextColorBG)
this.cbgx.set(_qn,2,(_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode3,1) : this.HighlightText ? this.colorDB.get(_ccode3, 0) : this.TextColorBG)
this.cbgx.set(_qn,3,(_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode4,1) : this.HighlightText ? this.colorDB.get(_ccode4, 0) : this.TextColorBG)
this.cbgx.set(_qn,4,(_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode5,1) : this.HighlightText ? this.colorDB.get(_ccode5, 0) : this.TextColorBG)
this.cbgx.set(_qn,5,(_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColorBG : this.ColorText ? this.colorDB.get(_ccode6,1) : this.HighlightText ? this.colorDB.get(_ccode6, 0) : this.TextColorBG)
// this.cqx.set(_qn,0,this.ColorText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode,0)) : this.HighlightText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode, 2)) : this.TextColor )
// this.cqx.set(_qn,1,this.ColorText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode,1)) : this.HighlightText ? ((_ccode<0 or _ccode>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode, 0)) : this.TextColorBG)
// this.cfgx.set(_qn,0,this.ColorText ? ((_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode1,0)) : this.HighlightText ? ((_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode1, 2)) : this.TextColor )
// this.cfgx.set(_qn,1,this.ColorText ? ((_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode2,0)) : this.HighlightText ? ((_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode2, 2)) : this.TextColor )
// this.cfgx.set(_qn,2,this.ColorText ? ((_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode3,0)) : this.HighlightText ? ((_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode3, 2)) : this.TextColor )
// this.cfgx.set(_qn,3,this.ColorText ? ((_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode4,0)) : this.HighlightText ? ((_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode4, 2)) : this.TextColor )
// this.cfgx.set(_qn,4,this.ColorText ? ((_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode5,0)) : this.HighlightText ? ((_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode5, 2)) : this.TextColor )
// this.cfgx.set(_qn,5,this.ColorText ? ((_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode6,0)) : this.HighlightText ? ((_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode6, 2)) : this.TextColor )
// this.cbgx.set(_qn,0,this.ColorText ? ((_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode1,1)) : this.HighlightText ? ((_ccode1<0 or _ccode1>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode1, 0)) : this.TextColorBG)
// this.cbgx.set(_qn,1,this.ColorText ? ((_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode2,1)) : this.HighlightText ? ((_ccode2<0 or _ccode2>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode2, 0)) : this.TextColorBG)
// this.cbgx.set(_qn,2,this.ColorText ? ((_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode3,1)) : this.HighlightText ? ((_ccode3<0 or _ccode3>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode3, 0)) : this.TextColorBG)
// this.cbgx.set(_qn,3,this.ColorText ? ((_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode4,1)) : this.HighlightText ? ((_ccode4<0 or _ccode4>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode4, 0)) : this.TextColorBG)
// this.cbgx.set(_qn,4,this.ColorText ? ((_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode5,1)) : this.HighlightText ? ((_ccode5<0 or _ccode5>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode5, 0)) : this.TextColorBG)
// this.cbgx.set(_qn,5,this.ColorText ? ((_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColorBG : this.colorDB.get(_ccode6,1)) : this.HighlightText ? ((_ccode6<0 or _ccode6>this.colorDB.rows() ) ? this.TextColor : this.colorDB.get(_ccode6, 0)) : this.TextColorBG)
this.mqx.set(_qn,0, _metaC),this.mqx.set(_qn,1, _mq1),this.mqx.set(_qn,2, _mq2),this.mqx.set(_qn,3, _mq3),this.mqx.set(_qn,4, _mq4),this.mqx.set(_qn,5, _mq5),this.mqx.set(_qn,6, _mq6),this.mqx.set(_qn,7, (lvl<0 or lvl>this.levelDB.size())?'':this.levelDB.get(lvl)),this.mqx.set(_qn,8,tooltip)
this.bqx.set(_qn,0,true),this.bqx.set(_qn,1,true)
this.intDB.set(4,bar_index)
_txn+=1
this.intDB.set(0, _txn),this.intDB.set(12, _txn),this.intDB.set(26, _txn),this.intDB.set(27, _txn),this.intDB.set(28, _txn),this.intDB.set(29, _txn),this.intDB.set(30, _txn),this.intDB.set(31, _txn)
else if this.IsConsole
this.stringDB.set(2, ' +'+str.tostring(4096-this.intDB.get(5)) + (this.PageOnEveryBar ? ' ● ' : ' ') + '◼︎' )
// @function
// Logs messages to the queues , including, time/date, bar_index, and error code. All messages from previous bars are cleared
//```
// method page ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` `not used`\
//> `.PageHistory` `not used`\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.AutoMerge` Automatically merges the right most columns into left if there is no text logged.\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7
// #### *Properties used*
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `m1` Message needed to be logged to Q1, or for console\
//> string `m2` - `m6` Message needed to be logged to Q2 to Q6. Not used/ignored when in console mode\
//> int `c1` - `c6` (Optional) Color Code to be used for the messages being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `page`*=true* Whether to page the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
// #### *Note 1:*
// When logging to a console, color code parameter `c` is ignored and color coding of messages is via c1. This is due to Console not having multiple cells, and all data being fit into single table cell.\
// Hence, to keep logging behaviour consistent with Logx logging, the message colouring is via `c1` - `c6`, however for Console, the row color parameter `c` is not used for coloring.
// #### *Note 2:*
// When logging to console, the colour is picked from the last message logged\
// Sometimes, this can get confusing when (empty) messages are logged with a different colour and one would expect console to show a different color.
//___
// @param lvl (Optional) Log Level to be assigned.
// @param c (Optional) Color code to be used for logging. If not specified, uses lvl as color code
// @param m1 Message needed to be logged to Q1, or for console.
// @param m2 Message needed to be logged to Q2. Not used/ignored when in console mode
// @param m3 Message needed to be logged to Q3. Not used/ignored when in console mode
// @param m4 Message needed to be logged to Q4. Not used/ignored when in console mode
// @param m5 Message needed to be logged to Q5. Not used/ignored when in console mode
// @param m6 Message needed to be logged to Q6. Not used/ignored when in console mode
// @param c1 (Optional) Color code to be used for the message being logged to Q1. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c2 (Optional) Color code to be used for the message being logged to Q2. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c3 (Optional) Color code to be used for the message being logged to Q3. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c4 (Optional) Color code to be used for the message being logged to Q4. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c5 (Optional) Color code to be used for the message being logged to Q5. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param c6 (Optional) Color code to be used for the message being logged to Q6. If negative, uses lvl to determine color code. If omitted, uses row color code (parameter c).
// @param tooltip Tooltip to display over each row when mouse hovers over it
// @param font Font to be used for this message row, when its displayed in the table. Accepts either font.family_default or font.family_monospace
// @param tv Time to be used. Default value is time, which logs the start time of bar.
// @param page Whether to log the message or not. Default is true.
export method page (log this, int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)=>
if this.intDB.get(3)!=bar_index and page
this.clear()
this.intDB.set(3, bar_index )
this.log(lvl,c,m1,m2,m3,m4,m5,m6,c1,c2,c3,c4,c5,c6,font,tooltip,tv,log=page)
// @function
// Set the messages to be on a new page, clearing messages from previous page.
// This is not dependent on PageHistory option, as this export method simply just clears all the messages, like turning old pages onto a new page.
//```
// method turnPage (bool turn=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` `not used`\
//> `.PageHistory` `not used`
// #### *Parameters*
//> bool `turn`=*true* //> bool `turn`=*true* Whether to turn the page or not
//___
//@param turn default is true. If set then will turn the page when called.
export method turnPage (log this, bool turn=true)=>
this.intDB.set(6, this.intDB.get(6)+1)
for x=0 to (turn and this.intDB.get(1)>0)?(this.intDB.get(1)-1):na
this.hqx.set(x,1, (this.intDB.get(6)-this.hqx.get(x,5)) > this.PageHistory ? -1 : this.hqx.get(x,1))
export method alog(log this, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)=> this.alog(3,1,msg,q,cq,tooltip,font,tv,log)
export method alog(log this, int lvl, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)=> this.alog(lvl,-1,msg,q,cq,tooltip,font,tv,log)
export method log (log this, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.log(3,1,m1,m2,m3,m4,m5,m6,c1,c2,c3,c4,c5,c6,tooltip,font,tv,log)
export method log (log this, int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.log(lvl,-1,m1,m2,m3,m4,m5,m6,c1,c2,c3,c4,c5,c6,tooltip,font,tv,log)
export method page(log this, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true) => this.page(3,3,m1,m2,m3,m4,m5,m6,c1,c2,c3,c4,c5,c6,tooltip,font,tv,page)
export method page(log this, int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true) => this.page(lvl,-1,m1,m2,m3,m4,m5,m6,c1,c2,c3,c4,c5,c6,tooltip,font,tv,page)
// @function
// Logs messages asyncronously to the queue 1, including, time/date, bar_index, and error code
//```
// method log1( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log1(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log1(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log1(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,1,cq,tooltip,font,tv,log)
export method log1(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,1,cq,tooltip,font,tv,log)
export method log1(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,1,cq,tooltip,font,tv,log)
// @function
// Logs messages asyncronously to the queue 2, including, time/date, bar_index, and error code
//```
// method log2( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log2(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,2,cq,tooltip,font,tv,log)
export method log2(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,2,cq,tooltip,font,tv,log)
export method log2(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,2,cq,tooltip,font,tv,log)
// @function
// Logs messages asyncronously to the queue 3, including, time/date, bar_index, and error code
//```
// method log3( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log3(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,3,cq,tooltip,font,tv,log)
export method log3(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,3,cq,tooltip,font,tv,log)
export method log3(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,3,cq,tooltip,font,tv,log)
// @function
// Logs messages asyncronously to the queue 4, including, time/date, bar_index, and error code
//```
// method log4( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log4(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,4,cq,tooltip,font,tv,log)
export method log4(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,4,cq,tooltip,font,tv,log)
export method log4(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,4,cq,tooltip,font,tv,log)
// @function
// Logs messages asyncronously to the queue 5, including, time/date, bar_index, and error code
//```
// method log5( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log5(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,5,cq,tooltip,font,tv,log)
export method log5(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,5,cq,tooltip,font,tv,log)
export method log5(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,5,cq,tooltip,font,tv,log)
// @function
// Logs messages asyncronously to the queue 6, including, time/date, bar_index, and error code
//```
// method log6( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
export method log6(log this, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(3,0,msg,6,cq,tooltip,font,tv,log)
export method log6(log this, int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,-1,msg,6,cq,tooltip,font,tv,log)
export method log6(log this, int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true) => this.alog(lvl,c,msg,6,cq,tooltip,font,tv,log)
__display (table tt, log this, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto) =>
if barstate.islast
int _txn = this.intDB.get(0)
// int _qsize = this.intDB.get(1)
int _txnS = (_txn<=-1 or this.intDB.get(1)<1) ? na : _txn<this.intDB.get(1) ? 0 : (_txn - this.intDB.get(1) + 1)
int _txnLen = (_txn<=-1 or this.intDB.get(1)<1) ? na : _txn<this.intDB.get(1) ? _txn : (this.intDB.get(1) - 1)
int _qS = this.MoveLogUp ? _txnS :_txn
int _dx = this.MoveLogUp ? 1 : -1
int _qc = (_qS%this.intDB.get(1))
int _qn=na
int _hqcolBar = this.intDB.get(14)-1+(this.ShowBarIndex?1:0)
int _hqcolDateTime = _hqcolBar+(this.ShowDateTime?1:0)
int _hqcolEC = _hqcolDateTime+(this.ShowLogLevels?1:0)
int _mqcolQ1 = _hqcolEC+(this.ShowQ1?1:0)
int _mqcolQ2 = _mqcolQ1+(this.ShowQ2?1:0)
int _mqcolQ3 = _mqcolQ2+(this.ShowQ3?1:0)
int _mqcolQ4 = _mqcolQ3+(this.ShowQ4?1:0)
int _mqcolQ5 = _mqcolQ4+(this.ShowQ5?1:0)
int _mqcolQ6 = _mqcolQ5+(this.ShowQ6?1:0)
int _logx_headerRowDelta = this.intDB.get(13) + ((this.ShowHeader and this.HeaderAtTop) ? 1 : 0) + ((this.ShowStatusBar and not this.StatusBarAtBottom) ? 1 : 0)
int _hrow = 0
string _toShow=''
if this.ShowHeader and not this.IsConsole
_hrow := this.intDB.get(13) + (this.HeaderAtTop ? (this.ShowStatusBar ? (this.StatusBarAtBottom ? 0 : 1) : 0) : (this.intDB.get(1) + (this.ShowStatusBar ? (this.StatusBarAtBottom ? 0 : 1 ) : 0)))
if this.ShowBarIndex
tt.cell(column=_hqcolBar, row=_hrow, text=this.HeaderQbarIndex, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowDateTime
tt.cell(column=_hqcolDateTime, row=_hrow, text=this.HeaderQdateTime, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowLogLevels and this.ReplaceWithCodes
tt.cell(column=_hqcolEC, row=_hrow, text=this.HeaderQLevelCode, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowLogLevels and not this.ReplaceWithCodes
tt.cell(column=_hqcolEC, row=_hrow, text=this.HeaderQLogLevel, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ1
tt.cell(column=_mqcolQ1, row=_hrow, text=this.HeaderQ1, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ2
tt.cell(column=_mqcolQ2, row=_hrow, text=this.HeaderQ2, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ3
tt.cell(column=_mqcolQ3, row=_hrow, text=this.HeaderQ3, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ4
tt.cell(column=_mqcolQ4, row=_hrow, text=this.HeaderQ4, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ5
tt.cell(column=_mqcolQ5, row=_hrow, text=this.HeaderQ5, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if this.ShowQ6
tt.cell(column=_mqcolQ6, row=_hrow, text=this.HeaderQ6, text_halign=hhalign, text_valign=hvalign, text_size=hsize, text_color=this.HeaderColor , bgcolor=this.HeaderColorBG, text_font_family = this.stringDB.get(6), tooltip=this.HeaderTooltip)
if _mqcolQ6<this.intDB.get(16)
tt.merge_cells(start_column=_mqcolQ6, start_row=_hrow, end_column=this.intDB.get(16), end_row=_hrow)
if not this.IsConsole
for x=0 to _txnLen
_qc := (_qS%this.intDB.get(1))
_qS += _dx
if this.hqx.get(_qc,1) >=0 and not this.IsConsole and this.hqx.get(_qc,0)>=this.ShowMinimumLevel
if this.ShowBarIndex
tt.cell(column=_hqcolBar, row=x+_logx_headerRowDelta, text=str.tostring( this.hqx.get(_qc,1)), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowDateTime
tt.cell(column=_hqcolDateTime, row=x+_logx_headerRowDelta, text=str.format('{0,date,'+this.stringDB.get(4)+'}',this.hqx.get(_qc,2)),
text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowLogLevels and this.ReplaceWithCodes
tt.cell(column=_hqcolEC, row=x+_logx_headerRowDelta, text=str.tostring(this.hqx.get(_qc,0)), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowLogLevels and not this.ReplaceWithCodes
tt.cell(column=_hqcolEC, row=x+_logx_headerRowDelta, text=((this.RestrictLevelsToKey7 and this.hqx.get(_qc,0) >=0 and this.hqx.get(_qc,0) <=7) or not this.RestrictLevelsToKey7)? this.mqx.get(_qc,7) : '' ,
text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ1
// tt.cell(column=_mqcolQ1, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,1), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ1, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,1), text_color=this.cfgx.get(_qc,0), bgcolor=this.cbgx.get(_qc,0), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ2
// tt.cell(column=_mqcolQ2, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,2), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ2, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,2), text_color=this.cfgx.get(_qc,1), bgcolor=this.cbgx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ3
// tt.cell(column=_mqcolQ3, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,3), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ3, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,3), text_color=this.cfgx.get(_qc,2), bgcolor=this.cbgx.get(_qc,2), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ4
// tt.cell(column=_mqcolQ4, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,4), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ4, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,4), text_color=this.cfgx.get(_qc,3), bgcolor=this.cbgx.get(_qc,3), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ5
// tt.cell(column=_mqcolQ5, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,5), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ5, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,5), text_color=this.cfgx.get(_qc,4), bgcolor=this.cbgx.get(_qc,4), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.ShowQ6
// tt.cell(column=_mqcolQ6, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,6), text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
tt.cell(column=_mqcolQ6, row=x+_logx_headerRowDelta, text=this.mqx.get(_qc,6), text_color=this.cfgx.get(_qc,5), bgcolor=this.cbgx.get(_qc,5), text_halign=thalign, text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8) )
if this.AutoMerge
if str.length(this.mqx.get(_qc,6))==0
if str.length(this.mqx.get(_qc,5))==0
if str.length(this.mqx.get(_qc,4))==0
if str.length(this.mqx.get(_qc,3))==0
if str.length(this.mqx.get(_qc,2))==0
tt.merge_cells( start_column = _mqcolQ1, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else
tt.merge_cells( start_column = _mqcolQ2, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else
tt.merge_cells( start_column = _mqcolQ3, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else
tt.merge_cells( start_column = _mqcolQ4, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else
tt.merge_cells( start_column = _mqcolQ5, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else if _mqcolQ6<this.intDB.get(16)
tt.merge_cells( start_column = _mqcolQ6, end_column = this.intDB.get(16), start_row = x+_logx_headerRowDelta, end_row = x+_logx_headerRowDelta)
else if _mqcolQ6<this.intDB.get(16)
tt.merge_cells(start_column=_mqcolQ6, start_row=x+_logx_headerRowDelta, end_column=this.intDB.get(16), end_row=x+_logx_headerRowDelta)
if this.IsConsole
_totalLen=array.sum(this.hqx.col(3))
_overflow= (_totalLen+this.intDB.get(1)-1) > 4096 ? true : false
_freeup = _overflow ?( _totalLen + this.intDB.get(1) - 1 - 4096): 0
_rowsout=1
while _freeup > 0 and _rowsout <= this.intDB.get(1)
_qn:=((_txn+_rowsout)%this.intDB.get(1))
_freeup -= this.hqx.get(_qn,3)
this.hqx.set(_qn,0,0),this.hqx.set(_qn,1, -1),this.hqx.set(_qn,2, 0),this.hqx.set(_qn,3,0),this.hqx.set(_qn,4,0)
this.mqx.set(_qn,1,''),this.mqx.set(_qn,2,''),this.mqx.set(_qn,3,''),this.mqx.set(_qn,4,''),this.mqx.set(_qn,5,''),this.mqx.set(_qn,6,'')
_rowsout+=1
_totalLen:=array.sum(this.hqx.col(3))
this.intDB.set(5, _totalLen)
this.stringDB.set(2, ' +'+str.tostring(4096-_totalLen)+(this.PageOnEveryBar ? ' ● ' : ' ')+(_overflow ? 'x' : '') )
for x=0 to _txnLen
_qc := (_qS%this.intDB.get(1))
_qS += _dx
_toShow+=((this.hqx.get(_qc,1) >=0 and this.hqx.get(_qc,0)>=this.ShowMinimumLevel)? (this.mqx.get(_qc,0)+this.mqx.get(_qc,1) +
((not(this.bqx.get(_qc,0) and this.bqx.get(_qc,1)))?(this.mqx.get(_qc,2)+this.mqx.get(_qc,3)+this.mqx.get(_qc,4)+this.mqx.get(_qc,5)+this.mqx.get(_qc,6)):'') +
(x==_txnLen ? '' : '\n') ): '')
int _crowUP = this.intDB.get(17) + (this.ShowStatusBar ? (this.StatusBarAtBottom? 0 : 1) : 0)
int _crowDN = this.intDB.get(19) - (this.ShowStatusBar ? (this.StatusBarAtBottom? 1 : 0) : 0)
string _font=this.hqx.get(_qc,1) >=0 ? this.fontDB.get(this.hqx.get(_qc,6)) : __getFont()
tt.merge_cells(start_column=this.intDB.get(18), end_column=this.intDB.get(20),
start_row=_crowUP,
end_row =_crowDN)
// tt.cell(column=this.intDB.get(18), row=_crowUP, text=_toShow, text_color=this.cqx.get(_qc,0), bgcolor=this.cqx.get(_qc,1), text_halign=thalign,text_valign=tvalign, text_size=tsize, text_font_family=this.fontDB.get(this.hqx.get(_qc,6)), tooltip=this.mqx.get(_qc,8))
tt.cell(column=this.intDB.get(18), row=_crowUP, text=_toShow, text_color=this.cfgx.get(_qc,0), bgcolor=this.cbgx.get(_qc,0), text_halign=thalign,text_valign=tvalign, text_size=tsize, text_font_family=_font, tooltip=this.mqx.get(_qc,8))
if this.ShowStatusBar and not this.IsConsole
int _srow = this.intDB.get(13) + (this.StatusBarAtBottom ? (this.intDB.get(1) + (this.ShowHeader?1:0)) : 0)
int _endMerge=this.ShowMetaStatus ? ((this.ShowBarIndex?1:0) + (this.ShowDateTime?1:0) + (this.ShowLogLevels?1:0) ) : 0
_minStatusLen=math.max(this.intDB.get(24),this.MinWidth)-(this.ShowMetaStatus?11:0)
_status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status)))
if _endMerge >1
tt.merge_cells(start_column=this.intDB.get(14), start_row=_srow, end_column=this.intDB.get(14)+_endMerge-1, end_row=_srow)
tt.merge_cells(start_column=this.intDB.get(14)+_endMerge, start_row=_srow, end_column=this.intDB.get(16), end_row=_srow)
tt.cell(column=this.intDB.get(14), row=_srow, text=(this.PageOnEveryBar?'●':'')+' @'+str.tostring(bar_index)+(this.StatusBarAtBottom?' ▲':' ▼'), text_halign=text.align_left, text_valign=text.align_center, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(8), tooltip=this.MetaStatusTooltip)
tt.cell(column=this.intDB.get(14)+_endMerge, row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(7), tooltip=this.StatusTooltip)
else
tt.merge_cells(start_column=this.intDB.get(14)+(this.ShowMetaStatus?1:0), start_row=_srow, end_column=this.intDB.get(16), end_row=_srow)
if this.ShowMetaStatus
tt.cell(column=this.intDB.get(14), row=_srow, text=(this.PageOnEveryBar?'●':'')+' @'+str.tostring(bar_index)+(this.StatusBarAtBottom?' ▲':' ▼'), text_halign=text.align_left, text_valign=text.align_center, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(8), tooltip=this.MetaStatusTooltip)
tt.cell(column=this.intDB.get(14)+(this.ShowMetaStatus?1:0), row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor , bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(7), tooltip=this.StatusTooltip)
if this.ShowStatusBar and this.IsConsole
int _srow = this.StatusBarAtBottom? this.intDB.get(19) : this.intDB.get(17)
_hideECmeta= (this.hqx.get(_qc,0)<=0 or (not this.ShowLogLevels) or (this.ShowLogLevels and this.hqx.get(_qc,0)>this.levelDB.size()) or (this.ShowLogLevels and this.RestrictLevelsToKey7 and this.hqx.get(_qc,0)>7))
_minStatusLen=math.max(this.intDB.get(25),this.MinWidth)-(this.ShowMetaStatus?20:0)
if _hideECmeta
_status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status)))
tt.merge_cells(start_column=this.intDB.get(18),start_row=_srow, end_column=this.intDB.get(20)-(this.ShowMetaStatus?1:0),end_row=_srow)
if this.ShowMetaStatus
tt.cell(column=this.intDB.get(20), row=_srow, text=(this.StatusBarAtBottom?'▲':'▼')+' @'+str.tostring(bar_index)+this.stringDB.get(2) , text_halign=text.align_right, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(8), tooltip=this.MetaStatusTooltip)
tt.cell(column=this.intDB.get(18), row=_srow, text=_status , text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(7), tooltip=this.StatusTooltip)
else
string _lvlText = this.levelDB.get(this.hqx.get(_qc,0))
color _lvlColor = (this.hqx.get(_qc,0)>0 and this.hqx.get(_qc,0)<=this.levelDB.size())? this.colorDB.get(this.hqx.get(_qc,0),0) : this.StatusColorBG
color _lvlColorHC = (this.hqx.get(_qc,0)>0 and this.hqx.get(_qc,0)<=this.levelDB.size())? this.colorDB.get(this.hqx.get(_qc,0),2) : this.StatusColor
// color _lvlColor = (this.hqx.get(_qc,0)>0 and this.hqx.get(_qc,0)<=this.levelDB.size())? this.cqx.get(_qc,1) : this.StatusColorBG
// color _lvlColorHC = (this.hqx.get(_qc,0)>0 and this.hqx.get(_qc,0)<=this.levelDB.size())? this.cqx.get(_qc,0) : this.StatusColor
_minStatusLen-=str.length(_lvlText)
_status=this.Status + (str.length(this.Status)>_minStatusLen ? '': str.substring(this.stringDB.get(0),0,_minStatusLen-str.length(this.Status)))
tt.cell(column=this.intDB.get(18), row=_srow, text=_lvlText, text_halign=text.align_center, text_valign=text.align_top, text_size=tsize, text_color=_lvlColorHC, bgcolor=_lvlColor, text_font_family = this.stringDB.get(8))
tt.merge_cells(start_column=this.intDB.get(18)+1,start_row=_srow, end_column=this.intDB.get(20)-(this.ShowMetaStatus?1:0),end_row=_srow)
if this.ShowMetaStatus
tt.cell(column=this.intDB.get(20), row=_srow, text=(this.StatusBarAtBottom?'▲':'▼')+' @'+str.tostring(bar_index)+this.stringDB.get(2) , text_halign=text.align_right, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG,text_font_family = this.stringDB.get(8), tooltip=this.MetaStatusTooltip)
tt.cell(column=this.intDB.get(18)+1, row=_srow, text=_status, text_halign=text.align_left, text_valign=text.align_top, text_size=tsize, text_color=this.StatusColor, bgcolor=this.StatusColorBG, text_font_family = this.stringDB.get(7), tooltip=this.StatusTooltip)
// @function
// Display Message Q, Index Q, Time Q, and Log Levels
//```
// method show (string position=position.bottom_right, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto, bool show=true, log attach=na)
//```
// #### *Note*
//> All options for postion/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc.\
//> Use getTablePosition() / getTextAlign() / getTextSize() methods to get the TV accepted names.
// #### *Example:*
//```
// ip_TablePosition = input.string('Top Right', 'Position', options=['Top Left','Top Center','Top Right','Middle Left','Middle Center','Middle Right','Bottom Left','Bottom Center','Bottom Right'])
// ip_TextSize = input.string('Small', 'Size', options=['Auto','Tiny','Small','Normal','Large','Huge'])
// ip_Align = input.string('Left', 'Alignment', options=['Left','Center','Right'])
// .show(position=ip_TablePosition.getTablePosition(), thalign=ip_Align.getTextAlign(), tsize=ip_TextSize.getTextSize() )
//```
// #### *Properties impacting how log is displayed*
//> `ColorText` Color Code will be used only if ColorText has been set to true\
//> `HighlightText` Color Code will be used only if HighlightText has been set to true\
//> `MoveLogUp` Reverse the direction of the log scrolling. The usual direction is scrolling up. False will scroll down\
//> `ShowMinimumLevel` The Log level upto which the messages will be shown. All messages below this level will not be displayed, even if logged\
//> `MinWidth` Sometimes the text displayed goes over table edges. Setting this property ensures a minumum width is always displayed
// #### *Properties impacting how log is displayed*
//> `ReplaceWithCodes` (Logx Only) When displaying the Q with Log Level names, you can display Log level codes instead\
//> `RestrictLevelsToKey7` When displaying Log Level names, only first seven (TRACE to CRITICAL) will be displayed and rest ignored
// #### *Parameters*
//> string `position`=*position.bottom_right* Position of the logger table.\
//> string `hhalign`=*text.align_left* Header text's horizontal alignment\
//> string `hvalign`=*text.align_top* Header text's vertical alignment\
//> string `hhsize`=*size.auto* Header text size
// #### *Parameters*
//> string `thalign`=*text.align_left* Text's horizontal alignment of each cell within the log table\
//> string `tvalign`=*text.align_top* Text's vertical alignment of each cell within the log table\
//> string `thsize`=*size.auto* Logger cell's text size
// #### *Parameters*
//> bool `show`=*true* Whether to show the log table or not\
//> log `attach` (Optional) Console that has been attached before using logger.attach() method
//___
// @param position Position of the table used for displaying the messages. Default is Bottom Right.
// @param hhalign Horizontal alignment of Header columns
// @param hvalign Vertical alignment of Header columns
// @param hsize Size of Header text Options
// @param thalign Horizontal alignment of all messages
// @param tvalign Vertical alignment of all messages
// @param tsize Size of text across the table
// @param show Whether to display the logs or not. Default is true.
export method show (log this, string position=position.bottom_right, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto, bool show=true, log attach=na) =>
this.stringDB.set(5,position)
if barstate.islast
if this.IsConsole!=this.boolDB.get(1)
this.__switchMode()
if barstate.islast and not show and not na(this.tbx)
this.tbx.delete()
if barstate.islast and show and not this.boolDB.get(3)
this.__resetLocations()
if barstate.islast and show and not this.boolDB.get(2)
this.tbx := table.new(frame_color=this.FrameColor, border_color=this.CellBorderColor, position=position, columns=19, rows= 2 + 2+this.intDB.get(1)+1, frame_width=this.FrameSize, border_width=this.CellBorderSize)
if not na(attach)
if attach.intDB.get(2)!=-1
attach.resize(this.intDB.get(1))
if this.boolDB.get(3) and not na(this.SeparatorColor)
this.tbx.merge_cells(start_column= this.intDB.get(11)==1? this.intDB.get(14) :this.intDB.get(11)==2?(this.intDB.get(16)+1):this.intDB.get(11)==4?(this.intDB.get(14)-1): this.intDB.get(14),
start_row= this.intDB.get(11)==1?(this.intDB.get(13)-1):this.intDB.get(11)==2? this.intDB.get(13) :this.intDB.get(11)==4? this.intDB.get(13) :(this.intDB.get(15)+1),
end_column= this.intDB.get(11)==1? this.intDB.get(16) :this.intDB.get(11)==2?(this.intDB.get(16)+1):this.intDB.get(11)==4?(this.intDB.get(14)-1):this.intDB.get(16),
end_row= this.intDB.get(11)==1?(this.intDB.get(13)-1):this.intDB.get(11)==2? this.intDB.get(15) :this.intDB.get(11)==4? this.intDB.get(15) :(this.intDB.get(15)+1))
this.tbx.cell(text=' ',bgcolor=this.SeparatorColor, text_color=this.SeparatorColor,
row= this.intDB.get(11)==1?(this.intDB.get(13)-1):this.intDB.get(11)==2? this.intDB.get(13) :this.intDB.get(11)==4? this.intDB.get(13) :(this.intDB.get(15)+1),
column=this.intDB.get(11)==1? this.intDB.get(14) :this.intDB.get(11)==2?(this.intDB.get(16)+1):this.intDB.get(11)==4?(this.intDB.get(14)-1):this.intDB.get(14))
if attach.boolDB.get(2)
__display(this.tbx, attach, hhalign=hhalign, hvalign=hvalign, hsize=hsize, thalign=thalign, tvalign=tvalign, tsize=tsize)
__display(this.tbx, this, hhalign=hhalign, hvalign=hvalign, hsize=hsize, thalign=thalign, tvalign=tvalign, tsize=tsize)
// @function
// Attaches a console to Logx, or moves already attached console around Logx
//```
// method attach(log attach, string position='anywhere')
//```
// #### *Parameters*
//> log `attach` Console object that to be attached.\
//> string `position`=*anywhere* Position of Console relative to Logx. Can be Top, Right, Bottom, Left. Default is Bottom. If unknown specified then defaults to Bottom
//___
// @param attach Console object that has been previously attached.
// @param position Position of Console in relation to Logx. Can be Top, Right, Bottom, Left. Default is Bottom. If unknown specified then defaults to bottom.
export method attach(log this,log attach, string position='anywhere')=>
if not this.boolDB.get(3)
if (this.intDB.get(11)%2==0)
attach.intDB.set(2,attach.intDB.get(1)),attach.resize(this.intDB.get(1))
else
attach.intDB.set(2,-1)
if this.boolDB.get(3)
if __consolePosition(position)%2!=this.intDB.get(11)%2
if attach.intDB.get(2)==-1
attach.intDB.set(2,attach.intDB.get(1)), attach.resize(this.intDB.get(1))
else
attach.resize(attach.intDB.get(2)),attach.intDB.set(2,-1)
attach.tbx.delete()
this.intDB.set(11,__consolePosition(position))
this.IsConsole:=false
attach.IsConsole:=true
this.boolDB.set(2,false),this.boolDB.set(3,true),attach.boolDB.set(2,true),attach.boolDB.set(3,false)
_ate=not(na(this.SeparatorColor))
int _czeroRow = this.intDB.get(11)==3 ? (this.intDB.get(1)+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0) + (_ate?1:0) ) : 0
int _czeroCol = this.intDB.get(11)==2 ? (9 + (_ate?1:0)) : 0
int _clastCol = _czeroCol + 8
int _clastRow = _czeroRow + (this.intDB.get(11)%2==1 ? 1 : (this.intDB.get(1)-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0)))
int _lzeroRow = this.intDB.get(11)==1 ? (_clastRow+1+(_ate?1:0)) : 0
int _lzeroCol = this.intDB.get(11)==4? (_clastCol+1+(_ate?1:0)): 0
int _llastRow = _lzeroRow + this.intDB.get(1)-1+(this.ShowHeader?1:0)+(this.ShowStatusBar?1:0)
int _llastCol = _lzeroCol + 8
this.intDB.set(14,_lzeroCol),this.intDB.set(16,_llastCol),this.intDB.set(13,_lzeroRow),this.intDB.set(15,_llastRow)
attach.intDB.set(14,_lzeroCol),attach.intDB.set(16,_llastCol),attach.intDB.set(13,_lzeroRow),attach.intDB.set(15,_llastRow)
attach.intDB.set(18,_czeroCol),attach.intDB.set(20,_clastCol),attach.intDB.set(17,_czeroRow),attach.intDB.set(19,_clastRow)
// @function
// Detaches the attached console from Logx.
//```
// method detach(log attachment)
//```
// #### *Parameters*
//> log `attachment` Console object to be detached.
//___
// @param attachment Console object that has been previously attached.
export method detach(log this,log attachment)=>
this.boolDB.set(2,false),this.boolDB.set(3,false),attachment.boolDB.set(2,false),attachment.boolDB.set(3,false)
this.__resetLocations(),attachment.__resetLocations()
if attachment.intDB.get(2)!=-1
attachment.resize(attachment.intDB.get(2))
// @function
// Displays a separate table, showing what Error Colors (maximum 200 colors)
//```
// method showColors (string position=position.bottom_left,bool showColors=true)
//```
// #### *Parameters*
//> string `position`=*position.bottom_left* Position of the logger table.\
//> bool `showColors`=*true* Whether to show Colors table or not. Default is true.\
//___
// @param position Position of the table used for displaying the messages. Default is Bottom Left. Accepts TV string for position.
// @param showColors Whether to show Colors table or not. Default is true.
export method showColors (log this,string position=position.bottom_left,bool showColors=true) =>
var int dataCols=3
var int dataRows=206
if barstate.islast and not showColors and not na(this.cbx)
this.cbx.delete()
if barstate.islast and showColors
this.cbx := table.new(columns=dataCols,rows=dataRows,position=position)
this.cbx.merge_cells(start_column=dataCols-2, start_row=0, end_column=dataCols-1, end_row=0)
this.cbx.cell(column=dataCols-2, row=0, text='Frame =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=0, text='Frame Color', text_halign=text.align_left, text_size=size.small, text_color=this.FrameColor, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-2, row=1, text='Header =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=1, text='Header Color + BG', text_halign=text.align_left, text_size=size.small, text_color=this.HeaderColor, bgcolor=this.HeaderColorBG)
this.cbx.cell(column=dataCols-2, row=2, text='Status =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=2, text='Status Color + BG', text_halign=text.align_left, text_size=size.small, text_color=this.StatusColor, bgcolor=this.StatusColorBG)
this.cbx.cell(column=dataCols-2, row=3, text='Text =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=3, text='Text Color + BG', text_halign=text.align_left, text_size=size.small, text_color=this.TextColor, bgcolor=this.TextColorBG)
this.cbx.cell(column=dataCols-2, row=4, text='Cell Border =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=4, text='Cell Border Color', text_halign=text.align_left, text_size=size.small, text_color=this.CellBorderColor, bgcolor=this.CellBorderColor)
this.cbx.cell(column=dataCols-2, row=5, text='Separator =>', text_halign=text.align_right, text_size=size.small, text_color=chart.fg_color, bgcolor=chart.bg_color)
this.cbx.cell(column=dataCols-1, row=5, text='Separator Color', text_halign=text.align_left, text_size=size.small, text_color=this.SeparatorColor, bgcolor=this.SeparatorColor)
for x=0 to math.min(this.colorDB.rows(),200)-1
this.cbx.cell(column=dataCols-2, row=x+6, text='Color #' +str.tostring(x)+' '+(x<this.levelDB.size()?this.levelDB.get(x):'No Level Name')+' ', text_halign=text.align_left, text_size=size.small, text_color=this.colorDB.get(x,0), bgcolor=this.colorDB.get(x,1))
this.cbx.cell(column=dataCols-1, row=x+6, text='Highlight '+str.tostring(x)+' '+(x<this.levelDB.size()?this.levelDB.get(x):'No Level Name')+' ', text_halign=text.align_left, text_size=size.small, text_color=this.colorDB.get(x,2), bgcolor=this.colorDB.get(x,0))
// @function
// Library demo link => https://www.tradingview.com/script/wITCQP6R-libhs-log-DEMO/
//___
// ### **init**()
// Sets up data for logging. It consists of 6 separate message queues, and 3 additional queues for bar index, time and log level/error code. Do not directly alter the contents, as library could break.
//```
// method init (int rows=50, isConsole=true)
//```
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with\
//> bool `isConsole`*=true* Whether to initialise as Console or Logx. If true will setup as Console.
//___
// ### **initConsole**()
//```
// method initConsole (int rows=50)
//```
// Sets up logger as Console. It consists of one message queue, and 3 additional queues for bar index, time and log level/error code.
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with
// #### Override default settings with following
//> `MarkNewBar` =*true*\
//> `ShowBarIndex`= *false*
//___
// ### **initLogx**()
//```
// method initLogx (int rows=50)
//```
// Sets up logger as Logx. It consists of six message queues, and 3 additional queues for bar index, time and log level/error code.
// #### *Parameters*
//> int `rows`*=50* Number of rows to start with
// #### Override default settings with following
//> `MarkNewBar` =*false*\
//> `ShowBarIndex` =*true*
//___
// ### **clear**()
//```
// method clear()
//```
// Clears all the queue, including bar_index and time queues, of existing messages
//___
// ### **resize**()
//```
// method resize (int rows=40)
//```
// Resizes the message queues. If size is decreased then removes the oldest message.
// #### *Parameters*
//> int `rows`=*40* Number of rows to be resized to
//___
// ### **undo**()
//```
// method undo (int rows=1)
//```
// Undo messages logged. Will not undo when messages have been logged asynchronously
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// ### **undoq**()
//```
// method undoq (int q, int rows=1)
//```
// Undo asynchronously logged messages. Will not undo normally logged messages.
// #### *Parameters*
//> int `q` Q number whose messages are to be reverted\
//> int `rows`*=1* Number of rows to be reverted
//___
// ### **undo1**(), **undo2**(), **undo3**(), **undo4**(), **undo5**(), **undo6**()
// Undo asynchronously logged messages from Q1/2/3/4/5/6. Will not undo normally logged messages.
//```
// method undo1 (int rows=1)
// method undo2 (int rows=1)
// method undo3 (int rows=1)
// method undo4 (int rows=1)
// method undo5 (int rows=1)
// method undo6 (int rows=1)
//```
// #### *Parameters*
//> int `rows`*=1* Number of rows to be reverted
//___
// ### **log**()
// Logs messages to the queues , including, time/date, bar_index, and error code
//```
// method log ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.AutoMerge` Automatically merges the right most columns into left if there is no text logged.\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7
// #### *Properties used*
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `m1` Message needed to be logged to Q1, or for console\
//> string `m2` - `m6` Message needed to be logged to Q2 to Q6. Not used/ignored when in console mode\
//> int `c1` - `c6` (Optional) Color Code to be used for the messages being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
// ### **page**()
// Logs messages to the queues , including, time/date, bar_index, and error code. All messages from previous bars are cleared
//```
// method page ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` `not used`\
//> `.PageHistory` `not used`\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.AutoMerge` Automatically merges the right most columns into left if there is no text logged.\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7
// #### *Properties used*
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the row being logged. Not used for messages, but for other fields such as Bar Index, if they are displayed. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `m1` Message needed to be logged to Q1, or for console\
//> string `m2` - `m6` Message needed to be logged to Q2 to Q6. Not used/ignored when in console mode\
//> int `c1` - `c6` (Optional) Color Code to be used for the messages being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `page`*=true* Whether to page the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
// ### **turnPage**()
//```
// method turnPage (bool turn=true)
//```
// Set the messages to be on a new page, clearing messages from previous page.
// This is not dependent on PageHistory option, as this export method simply just clears all the messages, like turning old pages onto a new page.
// #### *Properties used*
//> `.PageOnEveryBar` `not used`\
//> `.PageHistory` `not used`
// #### *Parameters*
//> bool `turn`=*true* Whether to turn the page or not
//___
// ### **alog**()
// Logs messages asyncronously to the queue, including, time/date, bar_index, and error code
//```
// method alog ( string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, int c, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message.If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `q`*=1* Q number the message to be logged to\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
// ### **log1**(), **log2**(), **log3**(), **log4**(), **log5**(), **log6**()
// Logs messages asyncronously to the queue 1/2/3/4/5/6, including, time/date, bar_index, and error code
//```
// method log1( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log1(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log1(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log2( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log3( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log4( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log5( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log6( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
// #### *Properties used*
//> `.PageOnEveryBar` Paging will be done on each bar only if this property has been set to true\
//> `.PageHistory` Number of bars that will be retained, if paging is on. Defalut is 0, which mean only messages from current bar will be retained\
//> `.MarkNewBar` First on each new bar will be marked, only if this property has been set to true\
//> `.TabSizeQ1-6` Adds a tab of the size specified to start of each message in each cell, if using log levels 1 - 7\
//> `.PrefixLogLevel` (Console Only) Prefix the log level name before the messages (in Q1, when logging asynchronously)
// #### *Parameters*
//> int `lvl` (Optional) Log Level of the message. If omitted, defaults to Level 3 = Info / Color Code = 1/Off White. Refer to levels/colors below\
//> int `c` (Optional) Color Code to be used for the message. If omitted or negative, uses lvl to determine color code. Color code 0 will hide the message\
//> string `msg` Message to be logged\
//> int `cq` (Optional) Color Code to be used for the message being logged. If negative, uses `lvl` to determine color code. If omitted, uses row color code (parameter `c`). Color code 0 will hide the message
// #### *Parameters*
//> string `tooltip`*=na* Tooltip for the row\
//> string `font`*=na* Font to be used for the row\
//> int `tv`*=time* Time value to be logged\
//> bool `log`*=true* Whether to log the message or not
// #### *Log Levels*
// `1 = TRACE Off White`
// `2 = DEBUG Green`
// `3 = INFO Blue`
// `4 = WARNING Cream`
// `5 = ERROR Yellow`
// `6 = CRITICAL Orange`
// `7 = FATAL Red`
//___
// ### **show**()
//```
// method show (string position=position.bottom_right, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto, bool show=true, log attach=na)
//```
// Display Message Q, Index Q, Time Q, and Log Levels
// #### *Note*
//> All options for postion/alignment accept TV values, such as position.bottom_right, text.align_left, size.auto etc.\
//> Use getTablePosition() / getTextAlign() / getTextSize() methods to get the TV accepted names.
// #### *Example:*
//```
// ip_TablePosition = input.string('Top Right', 'Position', options=['Top Left','Top Center','Top Right','Middle Left','Middle Center','Middle Right','Bottom Left','Bottom Center','Bottom Right'])
// ip_TextSize = input.string('Small', 'Size', options=['Auto','Tiny','Small','Normal','Large','Huge'])
// ip_Align = input.string('Left', 'Alignment', options=['Left','Center','Right'])
// .show(position=ip_TablePosition.getTablePosition(), thalign=ip_Align.getTextAlign(), tsize=ip_TextSize.getTextSize() )
//```
// #### *Properties impacting how log is displayed*
//> `.ColorText` Color Code will be used only if ColorText has been set to true\
//> `.HighlightText` Color Code will be used only if HighlightText has been set to true\
//> `.MoveLogUp` Reverse the direction of the log scrolling. The usual direction is scrolling up. False will scroll down\
//> `.ShowMinimumLevel` The Log level upto which the messages will be shown. All messages below this level will not be displayed, even if logged\
//> `.MinWidth` Sometimes the text displayed goes over table edges. Setting this property ensures a minumum width is always displayed
// #### *Properties impacting how log is displayed*
//> `.ReplaceWithCodes` (Logx Only) When displaying the Q with Log Level names, you can display Log level codes instead\
//> `.RestrictLevelsToKey7` When displaying Log Level names, only first seven (TRACE to CRITICAL) will be displayed and rest ignored
// #### *Parameters*
//> string `position`=*position.bottom_right* Position of the logger table.\
//> string `hhalign`=*text.align_left* Header text's horizontal alignment\
//> string `hvalign`=*text.align_top* Header text's vertical alignment\
//> string `hhsize`=*size.auto* Header text size
// #### *Parameters*
//> string `thalign`=*text.align_left* Text's horizontal alignment of each cell within the log table\
//> string `tvalign`=*text.align_top* Text's vertical alignment of each cell within the log table\
//> string `thsize`=*size.auto* Logger cell's text size
// #### *Parameters*
//> bool `show`=*true* Whether to show the log table or not\
//> log `attach` (Optional) Console that has been attached before using logger.attach() method
//___
// ### **attach**()
//```
// method attach(log attach, string position='anywhere')
//```
// Attaches a console to Logx, or moves already attached console around Logx
// #### *Parameters*
//> log `attach` Console object that to be attached.\
//> string `position`=*anywhere* Position of Console relative to Logx. Can be Top, Right, Bottom, Left. Default is Bottom. If unknown specified then defaults to Bottom
//___
// ### **detach**()
//```
// method detach(log attachment)
//```
// Detaches the attached console from Logx.
// #### *Parameters*
//> log `attachment` Console object to be detached.
//___
// ### **showColors**()
//```
// method showColors (string position=position.bottom_left,bool showColors=true)
//```
// Displays a separate table, showing what Error Colors (maximum 200 colors)
// #### *Parameters*
//> string `position`=*position.bottom_left* Position of the logger table.\
//> bool `showColors`=*true* Whether to show Colors table or not. Default is true.
//___
// ### **dateTimeFormat**()
//```
// method dateTimeFormat(string format='')
//```
// Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm\
// #### *Parameters*
//> string `format`*=''* Date time format. If passed as empty (not as na) then resets teh format to d.MMM.yy H:mm, which would look as 9.Aug.23 9:01
//___
// ### **setFontHeader**()
//```
// method setFontHeader(string font=na)
//```
// Sets up font to be used for Header (only on Logx)
// #### *Parameters*
//> string `font`*=na* Font to be used for Logx header. If it is not font.family_monospace then it is set to font.family_default
//___
// ### **setFontStatus**()
//```
// method setFontStatus(string font=na)
//```
// Sets up font to be used for Status
// #### *Parameters*
//> string `font`*=na* Font to be used for Console/Logx status bar. If it is not font.family_monospace then it is set to font.family_default
//___
// ### **setFontMetaStatus**()
//```
// method setFontMetaStatus(string font=na)
//```
// Sets up font to be used for meta info in Status
// #### *Parameters*
//> string `font`*=na* Font to be used for Console/Logx status bar. If it is not font.family_monospace then it is set to font.family_default
//___
// ### **resetXX**()
//```
// method resetTextColor() => // Resets the text color of the log to library default.
// method resetTextColorBG() => // Resets the background color of the log to library default.
// method resetHeaderColor() => // Resets the color used for Headers, to library default.
// method resetHeaderColorBG() => // Resets the background color used for Headers, to library default.
// method resetStatusColor() => // Resets the text color of the status row, to library default.
// method resetStatusColorBG() => // Resets the background color of the status row, to library default.
// method resetFrameColor() => // Resets the color used for the frame around the log table, to library default.
// method resetColorsHC() => // Resets the color used for the highlighting when Highlight Text option is used, to library default
// method resetColorsBG() => // Resets the background color used for setting the background color, when the Color Text option is used, to library default
// method resetColors() => // Resets the color used for respective color code, when the Color Text option is used, to library default
//```
//___
// ### **setColors**()
// Sets the colors corresponding to color codes.
//```
// method setColors(color[] c)
//```
// Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color is used
//___
// ### **setColorsHC**()
// Sets the highlight colors corresponding to color codes.
//```
// method setColorsHC(color[] c)
//```
// Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
//___
// ### **setColorsBG**()
//```
// method setColorsBG(color[] c)
//```
// Sets the background colors corresponding to color codes. Index 0 of input array c is color is reserved for future use\
// Index 1 of input array c is color for color code 1\
// Index 2 of input array c is color for color code 2 and so on.\
// There are 2 modes of coloring
// 1. Using the Foreground color
// 2. Using the Foreground color as background color and a white/black/gray color as foreground color
// - This is denoting or highlighting. Which effectively puts the foreground color as background color
// #### *Parameters*
//> color[ ] `c` Color Array to be used for corresponding color codes. If the corresponding code is not found, then text color BG is used
//___
// ### **setColor**()
// Sets the color corresponding to color code
//```
// method setColor(int e, color c)
// method setColor(int e, color fg, color bg, color hc)
//```
// #### *Parameters*
//> int `e` Color code whose color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
// #### *Parameters*
//> color `fg` Foreground Color corresponding to code supplied\
//> color `bg` Background Color corresponding to code supplied\
//> color `hc` Highlight Color corresponding to code supplied.
//___
// ### **setColorHC**()
// Sets the highlight color corresponding to error code
//```
// method setColorHC(int e, color c)
//```
// #### *Parameters*
//> int `e` Color code whose highlight color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
//___
// ### **setColorBG**()
//```
// method setColorBG(int e, color c)
//```
// Sets the background color corresponding to error code
// #### *Parameters*
//> int `e` Color code whose background color needs to be changed. If this code is not found, then color array will be expanded\
//> color `c` Color corresponding to code supplied.
//___
// ### **getColor**()
//```
// method getColor(int e)
//```
// Returns the color corresponding to color code
// #### *Parameters*
//> int `e` Color Code whose color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// ### **getColorHC**()
//```
// method getColorHC(int e)
//```
// Returns the highlight color corresponding to color code
// #### *Parameters*
//> int `e` Color Code whose highlight color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The highlight color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// ### **getColorBG**()
//```
// method getColorBG(int e)
//```
// Returns the background color corresponding to color code
// #### *Parameters*
//> int `e` Color Code whose background color needs to be extracted. If this code is not found, then na will be returned.\
// #### Returns
//> **`color`** The background color corresponding to color code supplied. If this code is not found, then na will be returned.
//___
// ### **resetLevelNames**()
//```
// method resetLevelNames(string prefix='Level ', string suffix='')
//```
// Resets the log level names used for corresponding level codes\
// With prefix/suffix, the default Level name will be like => prefix + Code + suffix
// #### *Parameters*
//> string `prefix`=*'Level'* Prefix to use when resetting level names\
//> string `suffix`=*''* Suffix to use when resetting level names
//___
// ### **setLevelNames**()
//```
// method setLevelNames(string[] names)
//```
// Resets the log level names used for corresponding level codes\
// Index 0 of input array names is reserved for future use\
// Index 1 of input array names is name used for level code 1.\
// Index 2 of input array names is name used for level code 2 and so on.
// #### *Parameters*
//> string[ ] `names` Array of log level names be used for corresponding level odes. If the corresponding code is not found, then an empty string is used
//___
// ### **setLevelName**()
//```
// method setLevelName(int e, string levelName)
//```
// Sets the Log level name corresponding to code supplied.
// #### *Parameters*
//> int `e` Code whose log level name needs to be changed. If this code is not found, then log level names array will be expanded.\
//> string `levelName` Level name corresponding to code supplied.
//___
// ### **getLevelName**()
//```
// method getLevelName(int e)
//```
// Gets the Log level name corresponding to error code supplied.
// #### *Parameters*
//> int `e` Code whose log level name needs to be extracted. If this error code is not found, then na will be returned.\
// #### Returns
//> **`string`** The log level name corresponding to code supplied. If this code is not found, then na will be returned.
//___
//> import GETpacman/logger/3 as logger\
//> `logger.usage()`\
//> `logger.fields()`\
//> `logger.methods()`\
//> `logger.docs()`
//___
export docs()=>
''
// @function
// `Color Settings`
// ```
// color HeaderColor
// color HeaderColorBG
// color StatusColor
// color StatusColorBG
// color TextColor
// color TextColorBG
// color FrameColor
// int FrameSize = 1
// int CellBorderSize = 0
// color CellBorderColor
// color SeparatorColor = color.gray
// ```
// `Header/Status Bar settings`
// ```
// bool IsConsole = true
// bool ShowHeader = true
// bool HeaderAtTop = true
// string HeaderTooltip = 'Header'
// bool ShowStatusBar = true
// bool StatusBarAtBottom= true
// string Status = ''
// string StatusTooltip = 'Status'
// bool ShowMetaStatus = true
// string MetaStatusTooltip= 'Meta Info'
// ```
// `Columns settings`
// ```
// bool ShowBarIndex = false
// bool ShowDateTime = false
// bool ShowLogLevels = false //Shows the debug log level as a column in Logx or as meta tab in Console
// bool ShowQ1 = true
// bool ShowQ2 = true
// bool ShowQ3 = true
// bool ShowQ4 = false
// bool ShowQ5 = false
// bool ShowQ6 = false
// string HeaderQbarIndex = 'Bar#'
// string HeaderQdateTime = 'Date'
// string HeaderQLevelCode= 'Code'
// string HeaderQLogLevel = 'LvL'
// string HeaderQ1 = 'h.Q1' //Header Text
// string HeaderQ2 = 'h.Q2'
// string HeaderQ3 = 'h.Q3'
// string HeaderQ4 = ''
// string HeaderQ5 = ''
// string HeaderQ6 = ''
// int TabSizeQ1 = 0 //Q Tabe size
// int TabSizeQ2 = 0
// int TabSizeQ3 = 0
// int TabSizeQ4 = 0
// int TabSizeQ5 = 0
// int TabSizeQ6 = 0
// ```
// `General settings`
// ```
// int ShowMinimumLevel= 0 //Shows log messages at or above this level
// bool AutoMerge = true
// bool ColorText = true //Text coloring requires this setting to be on
// bool HighlightText = false //Text highlighting requires this setting to be on
// bool MarkNewBar = true
// bool PageOnEveryBar = false
// int PageHistory = 0 //Used with PageOnEveryBar, how many bars of messages will be retained when paging on every bar
// bool PrefixLogLevel = false //Only for Console, to prefix all messages with Log Level
// bool MoveLogUp = true //Reverses the direction of log scrolling
// int MinWidth = 40 //Minumum width to display for Logx/Console.
// bool ReplaceWithCodes= false //When used with ShowLogLevels in Logx, replaces log level codes with log level names.
// bool RestrictLevelsToKey7 = false //If set to true, will only record log levels from TRACE to CRITICAL and rest levels will not be logged with message.
// ```
// #### `Field Methods`
//```
// method dateTimeFormat(string format='') => // Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm
// method setFontHeader(string font=na) => // Sets up font to be used for Header (only on Logx)
// method setFontStatus(string font=na) => // Sets up font to be used for Status
// method setFontMetaStatus(string font=na)=> // Sets up font to be used for meta info in Status
//```
//```
// method resetTextColor() => // Resets the text color of the log to library default
// method resetTextColorBG() => // Resets the background color of the log to library default
// method resetHeaderColor() => // Resets the color used for Headers, to library default.
// method resetHeaderColorBG() => // Resets the background color used for Headers, to library default.
// method resetStatusColor() => // Resets the text color of the status row, to library default.
// method resetStatusColorBG() => // Resets the background color of the status row, to library default.
// method resetFrameColor() => // Resets the color used for the frame around the log table, to library default.
//```
//```
// method setColors(color[] c) => // Sets the colors corresponding to color codes.
// method setColorsHC(color[] c) => // Sets the highlight colors corresponding to color codes.
// method setColorsBG(color[] c) => // Sets the background colors corresponding to color codes.
// method setColor(int e, color c) => // Sets the color corresponding to color code
// method setColor(int e, color fg, color bg, color hc)
// method setColorHC(int e, color c) => // Sets the highlight color corresponding to error code
// method setColorBG(int e, color c) => // Sets the background color corresponding to error code
// method getColor(int e) => // Returns the color corresponding to color code
// method getColorHC(int e) => // Returns the highlight color corresponding to color code
// method getColorBG(int e) => // Returns the background color corresponding to color code
//```
//```
// method resetLevelNames(prefix='Level ', suffix='')=> // Resets the log level names used for corresponding level codes
// method setLevelNames(string[] names) => // Resets the log level names used for corresponding level codes
// method setLevelName(int e, string levelName)=> // Sets the Log level name corresponding to code supplied.
// method getLevelName(int e) => // Gets the Log level name corresponding to error code supplied.
//```
//___
//> import GETpacman/logger/3 as logger\
//> `logger.usage()`\
//> `logger.fields()`\
//> `logger.methods()`\
//> `logger.docs()`
//___
export fields()=>
''
// @function
// #### `Helper String Overloads`
//```
// method getTextAlign(string) => ('Top').getTextAlign()
// method getTextSize() => ('Small').getTextSize()
// method getTablePosition() => ('Bottom Right').getTablePosition()
//```
// #### `Helper conversions`
//```
// method upper(string this) => // convert to upper string
// method upper(bool this) => // convert to upper string from bool
//```
//```
// method lower(string this) => // convert to lower string
// method lower(bool this) => // convert to lower string from bool
//```
//```
// method f(bool this) => // convert to float from bool
// method f(string this, int decimals=6) => // convert to float from string
// method f(int this) => // convert to float from int
// method f(float this, int decimals=6) => // rounds float to specified decimals `.f(int deciimals=6)
//```
//```
// method i(bool this) => // convert to int from bool
// method i(string this) => // convert to int from string
// method i(float this) => // convert to int from float
//```
//```
// method s(bool this) => // convert to string from bool
// method s(int this) => // convert to string from int
// method s(float this) => // convert to string from float
//```
//```
// method b(int this) => // convert to bool from int
// method b(float this) => // convert to bool from float
// method b(string this) => // convert to bool from string
//```
// ### `Logger Methods`
// #### `Initialise`
//```
// method init (int rows=50, isConsole=true) => // Sets up data for logging. It consists of 6 separate message queues, and 3 additional queues for bar index, time and log level/error code. Do not directly alter the contents, as library could break.
// method initConsole (int rows=50) => // Sets up logger as Console. It consists of one message queue, and 3 additional queues for bar index, time and log level/error code.
// method initLogx (int rows=50) => // Sets up logger as Logx. It consists of six message queues, and 3 additional queues for bar index, time and log level/error code.
//```
// #### `Clear / Resize / Undo`
//```
// method clear() => // Clears all the queue, including bar_index and time queues, of existing messages
// method resize (int rows=40) => // Resizes the message queues. If size is decreased then removes the oldest message.
// method undo (int rows=1) => // Undo messages logged. Will not undo when messages have been logged asynchronously
// method undoq (int q, int rows=1) => // Undo asynchronously logged messages. Will not undo normally logged messages.
//```
//```
// method undo1 (int rows=1) => // Undo asynchronously logged messages from Q1. Will not undo normally logged messages.
// method undo2 (int rows=1) => // Undo asynchronously logged messages from Q2. Will not undo normally logged messages.
// method undo3 (int rows=1) => // Undo asynchronously logged messages from Q3. Will not undo normally logged messages.
// method undo4 (int rows=1) => // Undo asynchronously logged messages from Q4. Will not undo normally logged messages.
// method undo5 (int rows=1) => // Undo asynchronously logged messages from Q5. Will not undo normally logged messages.
// method undo6 (int rows=1) => // Undo asynchronously logged messages from Q6. Will not undo normally logged messages.
//```
// #### `Logging messages`
//```
// // Logs messages to the queues , including, time/date, bar_index, and error code
// method log ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// // Logs messages to the queues , including, time/date, bar_index, and error code. All messages from previous bars are cleared
// method page ( string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
// method page (int lvl, int c, string m1=na, string m2=na, string m3=na, string m4=na, string m5=na, string m6=na, int c1=na, int c2=na, int c3=na, int c4=na, int c5=na, int c6=na, string tooltip=na, string font=na, int tv=time, bool page=true)
//
// method turnPage (bool turn=true) => // Set the messages to be on a new page, clearing messages from previous page.
//```
//```
// // Logs messages asyncronously to the queue, including, time/date, bar_index, and error code
// method alog ( string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method alog (int lvl, int c, string msg=na, int q=1, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// // Logs messages asyncronously to the queue 1/2/3/4/5/6, including, time/date, bar_index, and error code
// method log1(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, int c, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log1(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6(int lvl, string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method log1( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log2( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log3( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log4( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log5( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
// method log6( string msg=na, int cq=na, string tooltip=na, string font=na, int tv=time, bool log=true)
//```
//```
// method attach(log attach, string position='anywhere') => // Attaches a console to Logx, or moves already attached console around Logx
// method detach(log attachment) => // Detaches the attached console from Logx.
//```
//```
// // Display Message Q, Index Q, Time Q, and Log Levels
// method show (string position=position.bottom_right, string hhalign=text.align_left, string hvalign=text.align_top, string hsize=size.auto, string thalign=text.align_left, string tvalign=text.align_top, string tsize=size.auto, bool show=true, log attach=na)
//```
//```
// // Displays a separate table, showing what Error Colors (maximum 200 colors)
// method showColors (string position=position.bottom_left,bool showColors=true)
//```
// #### `Settings`
//```
// method dateTimeFormat(string format='') => // Re/set the date time format used for displaying date and time. Default resets to dd.MMM.yy HH:mm
// method setFontHeader(string font=na) => // Sets up font to be used for Header (only on Logx)
// method setFontStatus(string font=na) => // Sets up font to be used for Status
// method setFontMetaStatus(string font=na)=> // Sets up font to be used for meta info in Status
//```
//```
// method resetTextColor() => // Resets the text color of the log to library default
// method resetTextColorBG() => // Resets the background color of the log to library default
// method resetHeaderColor() => // Resets the color used for Headers, to library default.
// method resetHeaderColorBG() => // Resets the background color used for Headers, to library default.
// method resetStatusColor() => // Resets the text color of the status row, to library default.
// method resetStatusColorBG() => // Resets the background color of the status row, to library default.
// method resetFrameColor() => // Resets the color used for the frame around the log table, to library default.
//```
//```
// method setColors(color[] c) => // Sets the colors corresponding to color codes.
// method setColorsHC(color[] c) => // Sets the highlight colors corresponding to color codes.
// method setColorsBG(color[] c) => // Sets the background colors corresponding to color codes.
// method setColor(int e, color c) => // Sets the color corresponding to color code
// method setColor(int e, color fg, color bg, color hc)
// method setColorHC(int e, color c) => // Sets the highlight color corresponding to error code
// method setColorBG(int e, color c) => // Sets the background color corresponding to error code
// method getColor(int e) => // Returns the color corresponding to color code
// method getColorHC(int e) => // Returns the highlight color corresponding to color code
// method getColorBG(int e) => // Returns the background color corresponding to color code
//```
//```
// method resetLevelNames(prefix='Level ', suffix='') => // Resets the log level names used for corresponding level codes
// method setLevelNames(string[] names) => // Resets the log level names used for corresponding level codes
// method setLevelName(int e, string levelName) => // Sets the Log level name corresponding to code supplied.
// method getLevelName(int e) => // Gets the Log level name corresponding to error code supplied.
//```
//___
//> import GETpacman/logger/3 as logger\
//> `logger.usage()`\
//> `logger.fields()`\
//> `logger.methods()`\
//> `logger.docs()`
//___
export methods()=>
''
// @function
// Library demo link => https://www.tradingview.com/script/wITCQP6R-libhs-log-DEMO/
//___
// ## **Console Sample Code**
// Console = A sleek single cell logging with a limit of 4096 characters. When you dont need a large logging capability.
//```
// //@version=5
// indicator("demo.Console", overlay=true)
// plot(na)
//```
//```
// ipdc_showTable = input.bool (true, 'Show Console? ',inline='console1', group='Console')
// ipdc_position = input.string('Bottom Left', 'Position', inline='console1', group='Console', options=['Top Left','Top Center','Top Right','Middle Left','Middle Center','Middle Right','Bottom Left','Bottom Center','Bottom Right'])
// ipdc_tsize = input.string('Auto', 'Text Size', inline='console1', group='Console', options=['Auto','Tiny','Small','Normal','Large','Huge'])
// ipdc_hsize = ipdc_tsize
// ipdc_hhalign = 'Left'
// ipdc_hvalign = 'Top'
// ipdc_thalign = 'Left'
// ipdc_tvalign = 'Top'
//```
//```
// import GETpacman/logger/3 as logger
//```
//```
// var console = logger.log.new()
// console.init() // init() should be called as first line after variable declaration
// console.MarkNewBar:=false
// console.PageOnEveryBar:=true
//```
//```
// console.FrameColor:=color.green
// console.log(' ')
// console.log(' ')
// console.log('Hello World')
// console.log(' ')
// console.log(' ',c1=2)
//```
//```
// console.FrameColor:=color.blue
// console.ShowHeader:=false //this wont throw error but is not used for console
//```
//```
// console.show(ipdc_position.getTablePosition(),ipdc_hhalign.getTextAlign(), ipdc_hvalign.getTextAlign(), ipdc_tsize.getTextSize(),ipdc_thalign.getTextAlign(), ipdc_tvalign.getTextAlign(), ipdc_tsize.getTextSize(),show=ipdc_showTable)
//```
//>
//>
//___
//
// ## **Logx Sample Code**
// Logx = Multiple columns logging with a limit of 4096 characters each message. When you need to log large number of messages.
//```
// //@version=5
// indicator("demo.Logx", overlay=true)
// plot(na)
//```
//```
// ipdd_showTable = input.bool (true, 'Show Logx? ',inline='logx1', group='Logx')
// ipdd_position = input.string('Bottom Right','Position', inline='logx1', group='Logx', options=['Top Left','Top Center','Top Right','Middle Left','Middle Center','Middle Right','Bottom Left','Bottom Center','Bottom Right'])
// ipdd_tsize = input.string('Auto', 'Text Size', inline='logx1', group='Logx', options=['Auto','Tiny','Small','Normal','Large','Huge'])
// ipdd_hsize = ipdd_tsize
// ipdd_hhalign = 'Left'
// ipdd_hvalign = 'Top'
// ipdd_thalign = 'Left'
// ipdd_tvalign = 'Top'
//```
//```
// import GETpacman/logger/3 as logger
//```
//```
// var logx = logger.log.new()
// logx.init(isConsole=false) // init() should be called as first line after variable declaration
// logx.MarkNewBar:=false
// logx.PageOnEveryBar:=true
// logx.ShowBarIndex:=false
//```
//```
// logx.FrameColor:=color.green
// logx.log(' ')
// logx.log(' ')
// logx.log(m2='Hello',m3='World',c2=2,c3=3)
// logx.log(' ')
// logx.log(' ')
//```
//```
// logx.HeaderQ1:=''
// logx.HeaderQ2:=''
// logx.HeaderQ3:=''
// logx.FrameColor:=color.olive //settings can be changed anytime before show method is called. Even twice. The last call will set the final value
//```
//```
// logx.show(ipdd_position.getTablePosition(),ipdd_hhalign.getTextAlign(), ipdd_hvalign.getTextAlign(), ipdd_tsize.getTextSize(),ipdd_thalign.getTextAlign(), ipdd_tvalign.getTextAlign(), ipdd_tsize.getTextSize(),show=ipdd_showTable) //this should be the last line of your code, after all methods and settings have been dealt with.
//```
//___
//> import GETpacman/logger/3 as logger\
//> `logger.usage()`\
//> `logger.fields()`\
//> `logger.methods()`\
//> `logger.docs()`
//___
export usage()=>
''
// this.v3 libhs.logger.rcUAT.v34 libhs.logger.rcSIT.45/dev.110/SITdev.v78 |
Cleaner Screeners Library | https://www.tradingview.com/script/1kg8lH8X-Cleaner-Screeners-Library/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 58 | 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/
//@version=5
// © kaigouthro
// Thanks @ PineCoders , and the Group members for setting the bar high.
// @description # Screener Panel.
// > This indicator displays a panel with a list of symbols and their indications.
// > It can be used as a screener for multiple timess and symbols
// > in any timeframe and with any indication in any combination.
// ### Features
// > - Multiple timeframes
// > - Multiple symbols
// > - Multiple indications per group
// > - Vertical or horizontal layouts
// > - Acceepts External Inputs
// > - Customizable colors with 170 presets included (dark and light)
// > - Customizable icons
// > - Customizable text size and font
// > - Customizable cell size width and height
// > - Customizable frame width and border width
// > - Customizable position
// > - Customizable strong and weak values
// > - Accepts any indicator as input
// > - Only 4 functions to call, easy to use
// ### Usage
//
// `local setup for methods on our script`
// ```
//
// import kaigouthro/cleanscreen/2
// method Screener ( cleanscreen.panel p , string _name ) => cleanscreens.Screener ( p, _name)
// method Indicator ( cleanscreen.screener s , string _tf, string name, float val ) => cleanscreens.Indicator ( s , _tf, name, val)
// method display ( cleanscreen.panel p ) => cleanscreens.display ( p )
//
// // Initialize the panel with
// _paneel = cleanscreens.init()
// // Add groupd with
// _screener = _paneel.Screener("Group Name")
// // Add indicartors to screeener groups with
// _screener.Indication( "Indicator Name", _source)
//
// Update the panel with
// _paneel.display(_paneel)
//
//```
library("cleanscreens",true)
____z()=>
/////////////////////////////////////////////////////////////////////////////////
_o = ' █▀ █▀▀ █▀█ █▀▀ █▀▀ █▄░█ █▀▀ █▀█ █░░ █ █▄▄ '
_o := ' ▄█ █▄▄ █▀▄ ██▄ ██▄ █░▀█ ██▄ █▀▄ █▄▄ █ █▄█ '
/////////////////////////////////////////////////////////////////////////////////
import TradingView/TechnicalRating/1 as techrate
import kaigouthro/theme_presets/2
import kaigouthro/theme_engine/1 as thm
import kaigouthro/calc/6
import kaigouthro/font/5
import kaigouthro/hsvColor/15 as h
import kaigouthro/ColorArray/7 as ca
import kaigouthro/SizeAndPlace/2 as ssp
// @type single indication for a symbol screener
// @field name name of the indication
// @field icon icon name
// @field rating rating
// @field value value
// @field col color of the indication
// @field tf timeframe
// @field avg average value
// @field tooltip tooltip text
// @field normalized color value
// @field init init
export type indication
string name = ''
string icon = ''
string rating = ''
float value = 0
color col = color.gray
string tf = timeframe.period
string tooltip = ''
float normalized = 0
bool init = false
// @type single symbol screener
// @field ticker ticker name
// @field icon icon name
// @field rating rating
// @field value value
// @field bg background color
// @field fg foreground color
// @field items list of indications
// @field init init
export type screener
string ticker = ''
string icon = ''
string rating = ''
float value = 0.
color bg = #000000
color fg = #000000
indication [] items
bool init = false
// @type screener configuration
// @field strong strong value
// @field weak weak value
// @field theme theme name
// @field vert vertical layout
// @field cellwidth cell width
// @field cellheight cell height
// @field textsize text size
// @field font font index
// @field framewidth frame width
// @field borders border width
// @field position position
export type config
float strong = 50
float weak = 20
string theme = 'dark'
bool vert = true
float cellwidth = 0.
float cellheight = 0.
string textsize = size.small
int font = 1
int framewidth = 1
int borders = 1
string position = position.bottom_center
// @type screener Icons
// @field buy buy icon
// @field sell sell icon
// @field strong strong icon
export type icons
string buy
string sell
string strong
// @type screener panel object
// @field items list of symbols
// @field table table object
// @field config config object
// @field thm.theme theme object
// @field icons icons object
export type panel
screener[] items
table table
config config
thm.theme theme
icons icons
// helper functions
method icon(panel panel, string _str ) =>
strong = panel.icons.strong
buy = panel.icons.buy
sell = panel.icons.sell
icon = ''
if str.contains(_str, 'Strong')
icon += strong
icon += switch
str.contains(_str, 'Buy' ) => buy
str.contains(_str, 'Sell' ) => sell
else
if str.contains(_str, '*')
icon += strong
icon += switch
str.contains(_str, 'Buy' ) => buy
str.contains(_str, 'Sell' ) => sell
//@function get the rating of the indication
//@param panel panel panel object
//@param value float value
method rate(panel p,float value) =>
_strong = p.config.strong/100
_weak = p.config.weak/100
thin = p.config.cellwidth < math.min(10, (100/array.size(p.items))) or (not p.config.vert)
out = switch
value > _strong => thin ? '*B*' : 'Strong Buy'
value < - _strong => thin ? '*S*' : 'Strong Sell'
value > _weak => thin ? 'B' : 'Buy'
value < - _weak => thin ? 'S' : 'Sell'
=> " "
method rate(panel p,indication i) =>
i.rating := rate(p,i.value)
i.rating := icon(p,i.rating)
method getTotal(indication[] items, _count)=>
sum = 0.
den = 0.
for [i,item] in items
sum += item.normalized
den += 1
sum/den
method cell(panel p , _col , _row ,_string , _width , _height ,_textcolor , _hAlign , _vAlign ,_textSize , _cellcolor , _tip ) =>
_table = p.table
table.cell(_table , _col , _row ,_string , _width , _height ,_textcolor , _hAlign , _vAlign ,_textSize , _cellcolor , _tip )
export method decorate(panel p,thm.varient t)=>
table.set_bgcolor (p.table, t.accent)
table.set_frame_color (p.table, t.bg)
table.set_border_color (p.table, t.bg)
table.set_frame_width (p.table, p.config.framewidth)
table.set_border_width (p.table, p.config.borders)
table.set_position (p.table, p.config.position)
method col ( panel p, float _source, color[] _colsin) =>
_th = p.config.weak/100, _thmax = math.min(0.99,math.max(_th*1.01,p.config.strong/100))
_cols = _colsin
_s3a = _cols.get(0), _s2a = _cols.get(1)
_s1a = _cols.get(2), _s1b = _cols.get(3)
_s2b = _cols.get(4), _s3b = _cols.get(5)
_1 = math.max(0.01,math.min(_th,_thmax * 0.99 ))
_2 = math.min(0.99,math.max(_1*1.01 ,_thmax ))
_3 = 1.01
src = _source
hc3 = h.hsv_gradient( src , _2 , _3 , _s2b , _s3b )
lc3 = h.hsv_gradient( src , -_2 , - _3 , _s2a , _s3a )
hc2 = h.hsv_gradient( src , _1 , _2 , _s1b , hc3 )
lc2 = h.hsv_gradient( src , -_1 , - _2 , _s1a , lc3 )
hc1 = h.hsv_gradient( src , 0 , _1 , lc2 , hc2 )
lc1 = h.hsv_gradient( src , -_1 , 0 , lc2 , hc2 )
out = h.hsv_gradient( src , -_1 , _1 , lc1 , hc1 )
//@function Normalizer to retrieve a value between -1 and 1 for consistent coloring
//@param float value: value to normalize
method norm_value (float value)=>
varip min = float (value)
varip max = float (value)
varip out = 0.
min := math.min(value,nz(min,value))
max := math.max(value,nz(max,value))
out := (value - min) / (max - min) * 2 - 1
/// EXPORTS
// @function # Panel init
// > init a panel for all the screens
// ### Example:
// ```
//
// import kaigouthro/cleanscreen/2
// method Screener ( cleanscreen.panel p , string _name ) => cleanscreens.Screener ( p, _name)
// method Indicator ( cleanscreen.screener s , string _tf, string name, float val ) => cleanscreens.Indicator ( s , _tf, name, val)
// method display ( cleanscreen.panel p ) => cleanscreens.display ( p )
//
//
// // Theme names for the theme input a botom (place here)
// string GRP1 = "Settings"
// // init panel with theme and location
// var loc = input.int(9, ' Table loc (1-9)', 1, 9)
// var _panel = init(input.string(SILK, 'Theme Choice', options = [APATHY,APPRENTICE,ASHES,ATELIER_CAVE,ATELIER_DUNE,ATELIER_ESTUARY,ATELIER_FOREST,ATELIER_HEATH,ATELIER_LAKESIDE,ATELIER_PLATEAU,ATELIER_SAVANNA,ATELIER_SEASIDE,ATELIER_SULPHURPOOL,ATLAS,AYU,AYU_MIRAGE,BESPIN,BLACK_METAL,BLACK_METAL_BATHORY,BLACK_METAL_BURZUM,BLACK_METAL_FUNERAL,BLACK_METAL_GORGOROTH,BLACK_METAL_IMMORTAL,BLACK_METAL_KHOLD,BLACK_METAL_MARDUK,BLACK_METAL_MAYHEM,BLACK_METAL_NILE,BLACK_METAL_VENOM,BLUE_FOREST,BLUEISH,BREWER,BRIGHT,BROGRAMMER,BRUSH_TREES,CATPPUCCIN,CHALK,CIRCUS,CLASSIC,CLRS,CODESCHOOL,CUPCAKE,CUPERTINO,DA_ONE_BLACK,DA_ONE_GRAY,DA_ONE_OCEAN,DA_ONE_PAPER,DA_ONE_SEA,DA_ONE_WHITE,DANQING,DARCULA,DARK_VIOLET,DARKMOSS,DARKTOOTH,DECAF,DIRTYSEA,DRACULA,EDGE,EIGHTIES,EMBERS,EMIL,EQUILIBRIUM,EQUILIBRIUM_GRAY,ESPRESSO,EVA,EVERFOREST,FLAT,FRAMER,FRUIT_SODA,GIGAVOLT,GITHUB,GOOGLE,GOTHAM,GRAYSCALE,GREEN_SCREEN,GRUBER,GRUVBOX_HARD,GRUVBOX_MEDIUM,GRUVBOX_PALE,GRUVBOX_SOFT,GRUVBOX_MATERIAL_HARD,GRUVBOX_MATERIAL_MEDIUM,GRUVBOX_MATERIAL_SOFT,HARDCORE,HARMONIC16,HEETCH,HELIOS,HOPSCOTCH,HORIZON,HORIZON_TERMINAL,HUMANOID,IA,ICY,IR_BLACK,ISOTOPE,KANAGAWA,KATY,KIMBER,LIME,LONDON_TUBE,MACINTOSH,MARRAKESH,MATERIA,MATERIAL,MATERIALDARKER,MATERIAL_PALENIGHT,MATERIAL_VIVID,MELLOW_PURPLE,MOCHA,MONOKAI,NEBULA,NORD,NOVA,OCEAN,OCEANICNEXT,ONEDARK,OUTRUN,PANDORA,PAPERCOLOR,PARAISO,PASQUE,PHD,PICO,PINKY,POP,PORPLE,PRIMER,PURPLEDREAM,QUALIA,RAILSCASTS,REBECCA,ROSE_PINE,ROSE_PINE_DAWN,ROSE_PINE_MOON,SAGELIGHT,SAKURA,SANDCASTLE,SETI_UI,SHADES_OF_PURPLE,SHADESMEAR,SHAPESHIFTER,SILK,SNAZZY,SOLAR_FLARE,SOLARIZED,SPACEDUCK,SPACEMACS,STELLA,STILL_ALIVE,SUMMERCAMP,SUMMERFRUIT,SYNTH_MIDNIGHT_TERMINAL,TANGO,TENDER,TOKYO_CITY,TOKYO_CITY_TERMINAL,TOKYO_NIGHT,TOKYO_NIGHT_STORM,TOKYO_NIGHT_TERMINAL,TOKYO_NIGHT_TERMINAL_STORM,TOKYODARK,TOKYODARK_TERMINAL,TOMORROW,TOMORROW_NIGHT,TOMORROW_NIGHT_EIGHTIES,TWILIGHT,UNIKITTY,UNIKITTY_REVERSIBLE,UWUNICORN,VICE,VULCAN,WINDOWS_10,WINDOWS_95,WINDOWS_HIGH_CONTRAST,WINDOWS_NT,WOODLAND,XCODE_DUSK]),
// loc)
// var tfInput = input.timeframe("", "Higher timeframe", group = GRP1)
// if barstate.isfirst
// panel.config.theme := input.string ( 'light' , "Theme Variewnt" , options=['light' , 'dark'] , inline='ic' , group='Icons' )
// panel.config.cellwidth := input.float ( 7.5 , 'cellwidth' , step=0.5 , inline = "Cellsize" , group=GRP1 )
// panel.config.cellheight := input.float ( 7.5 , 'cellheight' , step=0.5 , inline = "Cellsize" , group=GRP1 )
// panel.config.textsize := input.string ( size.auto , 'Textsize' , options=[size.auto, size.small, size.normal, size.large, size.huge] , inline = "set" , group=GRP1 )
// panel.config.font := input.int ( 15 , 'Font' , 1 , 17 , inline = "set" , group=GRP1 )
// panel.config.framewidth := input.int ( 10 , 'Framewidth' , 0 , 20 , inline = "set" , group=GRP1 )
// panel.config.borders := input.int ( 1 , 'Borders' , -1 , 10 , inline = "set" , group=GRP1 )
// panel.config.vert := input.bool ( true , 'vert' ) //int ( 1 , 'Borders' , -1 , 10 )
// // Icons
// panel.icons.strong := input.string('💸', 'Strong ✼', inline='ic', group='Icons')
// panel.icons.buy := input.string('💰', 'Buy ⇡', inline='ic', group='Icons')
// panel.icons.sell := input.string('🔥', 'Sell ⇣', inline='ic', group='Icons')
//
// // Add groupd with _screener = _paneel.Screener("Group Name")
// // Add indicartors to screeener groups with _screener.Indication( "Indicator Name", _source)
// // Update the panel with _paneel.display(_paneel)
//
// var string APATHY = "Apathy", var string APPRENTICE = "Apprentice", var string ASHES = "Ashes", var string ATELIER_CAVE = "Atelier Cave", var string ATELIER_DUNE = "Atelier Dune", var string ATELIER_ESTUARY = "Atelier Estuary", var string ATELIER_FOREST = "Atelier Forest", var string ATELIER_HEATH = "Atelier Heath", var string ATELIER_LAKESIDE = "Atelier Lakeside", var string ATELIER_PLATEAU = "Atelier Plateau", var string ATELIER_SAVANNA = "Atelier Savanna", var string ATELIER_SEASIDE = "Atelier Seaside", var string ATELIER_SULPHURPOOL = "Atelier Sulphurpool", var string ATLAS = "Atlas", var string AYU = "Ayu", var string AYU_MIRAGE = "Ayu Mirage", var string BESPIN = "Bespin", var string BLACK_METAL = "Black Metal", var string BLACK_METAL_BATHORY = "Black Metal (bathory)", var string BLACK_METAL_BURZUM = "Black Metal (burzum)", var string BLACK_METAL_FUNERAL = "Black Metal (dark Funeral)", var string BLACK_METAL_GORGOROTH = "Black Metal (gorgoroth)", var string BLACK_METAL_IMMORTAL = "Black Metal (immortal)", var string BLACK_METAL_KHOLD = "Black Metal (khold)", var string BLACK_METAL_MARDUK = "Black Metal (marduk)", var string BLACK_METAL_MAYHEM = "Black Metal (mayhem)", var string BLACK_METAL_NILE = "Black Metal (nile)", var string BLACK_METAL_VENOM = "Black Metal (venom)", var string BLUE_FOREST = "Blue Forest", var string BLUEISH = "Blueish", var string BREWER = "Brewer", var string BRIGHT = "Bright", var string BROGRAMMER = "Brogrammer", var string BRUSH_TREES = "Brush Trees", var string CATPPUCCIN = "Catppuccin", var string CHALK = "Chalk", var string CIRCUS = "Circus", var string CLASSIC = "Classic", var string CLRS = "Colors", var string CODESCHOOL = "Codeschool", var string CUPCAKE = "Cupcake", var string CUPERTINO = "Cupertino", var string DA_ONE_BLACK = "Da One Black", var string DA_ONE_GRAY = "Da One Gray", var string DA_ONE_OCEAN = "Da One Ocean", var string DA_ONE_PAPER = "Da One Paper", var string DA_ONE_SEA = "Da One Sea", var string DA_ONE_WHITE = "Da One White", var string DANQING = "Danqing", var string DARCULA = "Darcula", var string DARK_VIOLET = "Dark Violet", var string DARKMOSS = "Darkmoss", var string DARKTOOTH = "Darktooth", var string DECAF = "Decaf", var string DIRTYSEA = "Dirtysea", var string DRACULA = "Dracula", var string EDGE = "Edge", var string EIGHTIES = "Eighties", var string EMBERS = "Embers", var string EMIL = "Emil", var string EQUILIBRIUM = "Equilibrium", var string EQUILIBRIUM_GRAY = "Equilibrium Gray", var string ESPRESSO = "Espresso", var string EVA = "Eva", var string EVERFOREST = "Everforest", var string FLAT = "Flat", var string FRAMER = "Framer", var string FRUIT_SODA = "Fruit Soda", var string GIGAVOLT = "Gigavolt", var string GITHUB = "Github", var string GOOGLE = "Google", var string GOTHAM = "Gotham", var string GRAYSCALE = "Grayscale", var string GREEN_SCREEN = "Green Screen", var string GRUBER = "Gruber", var string GRUVBOX_HARD = "Gruvbox Dark, Hard", var string GRUVBOX_MEDIUM = "Gruvbox Dark, Medium", var string GRUVBOX_PALE = "Gruvbox Dark, Pale", var string GRUVBOX_SOFT = "Gruvbox Dark, Soft", var string GRUVBOX_MATERIAL_HARD = "Gruvbox Material Dark, Hard", var string GRUVBOX_MATERIAL_MEDIUM = "Gruvbox Material Dark, Medium", var string GRUVBOX_MATERIAL_SOFT = "Gruvbox Material Dark, Soft", var string HARDCORE = "Hardcore", var string HARMONIC16 = "Harmonic16", var string HEETCH = "Heetch", var string HELIOS = "Helios", var string HOPSCOTCH = "Hopscotch", var string HORIZON = "Horizon", var string HORIZON_TERMINAL = "Horizon Terminal", var string HUMANOID = "Humanoid", var string IA = "Ia", var string ICY = "Icy", var string IR_BLACK = "Ir Black", var string ISOTOPE = "Isotope", var string KANAGAWA = "Kanagawa", var string KATY = "Katy", var string KIMBER = "Kimber", var string LIME = "Lime", var string LONDON_TUBE = "London Tube", var string MACINTOSH = "Macintosh", var string MARRAKESH = "Marrakesh", var string MATERIA = "Materia", var string MATERIAL = "Material", var string MATERIALDARKER = "Material Darker", var string MATERIAL_PALENIGHT = "Material Palenight", var string MATERIAL_VIVID = "Material Vivid", var string MELLOW_PURPLE = "Mellow Purple", var string MOCHA = "Mocha", var string MONOKAI = "Monokai", var string NEBULA = "Nebula", var string NORD = "Nord", var string NOVA = "Nova", var string OCEAN = "Ocean", var string OCEANICNEXT = "Oceanicnext", var string ONEDARK = "Onedark", var string OUTRUN = "Outrun", var string PANDORA = "Pandora", var string PAPERCOLOR = "Papercolor", var string PARAISO = "Paraiso", var string PASQUE = "Pasque", var string PHD = "Phd", var string PICO = "Pico", var string PINKY = "Pinky", var string POP = "Pop", var string PORPLE = "Porple", var string PRIMER = "Primer", var string PURPLEDREAM = "Purpledream", var string QUALIA = "Qualia", var string RAILSCASTS = "Railscasts", var string REBECCA = "Rebecca", var string ROSE_PINE = "Rosé Pine", var string ROSE_PINE_DAWN = "Rosé Pine Dawn", var string ROSE_PINE_MOON = "Rosé Pine Moon", var string SAGELIGHT = "Sagelight", var string SAKURA = "Sakura", var string SANDCASTLE = "Sandcastle", var string SETI_UI = "Seti Ui", var string SHADES_OF_PURPLE = "Shades Of Purple", var string SHADESMEAR = "Shadesmear", var string SHAPESHIFTER = "Shapeshifter", var string SILK = "Silk", var string SNAZZY = "Snazzy", var string SOLAR_FLARE = "Solar Flare", var string SOLARIZED = "Solarized", var string SPACEDUCK = "Spaceduck", var string SPACEMACS = "Spacemacs", var string STELLA = "Stella", var string STILL_ALIVE = "Still Alive", var string SUMMERCAMP = "Summercamp", var string SUMMERFRUIT = "Summerfruit", var string SYNTH_MIDNIGHT_TERMINAL = "Synth Midnight Terminal", var string TANGO = "Tango", var string TENDER = "Tender", var string TOKYO_CITY = "Tokyo City", var string TOKYO_CITY_TERMINAL = "Tokyo City Terminal", var string TOKYO_NIGHT = "Tokyo Night", var string TOKYO_NIGHT_STORM = "Tokyo Night Storm", var string TOKYO_NIGHT_TERMINAL = "Tokyo Night Terminal", var string TOKYO_NIGHT_TERMINAL_STORM = "Tokyo Night Terminal Storm", var string TOKYODARK = "Tokyodark", var string TOKYODARK_TERMINAL = "Tokyodark Terminal", var string TOMORROW = "Tomorrow", var string TOMORROW_NIGHT = "Tomorrow Night", var string TOMORROW_NIGHT_EIGHTIES = "Tomorrow Night Eighties", var string TWILIGHT = "Twilight", var string UNIKITTY = "Unikitty", var string UNIKITTY_REVERSIBLE = "Unikitty Reversible", var string UWUNICORN = "Uwunicorn", var string VICE = "Vice", var string VULCAN = "Vulcan", var string WINDOWS_10 = "Windows 10", var string WINDOWS_95 = "Windows 95", var string WINDOWS_HIGH_CONTRAST = "Windows High Contrast", var string WINDOWS_NT = "Windows Nt", var string WOODLAND = "Woodland", var string XCODE_DUSK = "Xcode Dusk"
//
//
// ```
//@param _themein string: Theme Preset Name
//@param loc int :
// 1 = left top,
// 2 = middle top,
// 3 = right top,
// 4 = left middle,
// 5 = middle middle,
// 6 = right middle,
// 7 = left bottom,
// 8 = middle bottom,
// 9 = right bottom
//
//@returns panel
export init ( string _themein, int loc) =>
var _screens = array.new<screener>()
var _names = array.new<string>()
var _tf = array.new<string>()
var _table = table.new(ssp.table_posittion(loc),80,80)
var _config = config.new(50,10,'dark',true)
var _theme = theme_presets.getTheme(_themein)
var _icons = icons.new('','','')
var _panel = panel.new(_screens,_table,_config,_theme,_icons)
_panel
//@function # Screener - Create a new screener
// ### Example:
// ```
// cleanscreen.Screeneer(panel, 'Crpyto Screeners')
// ```
//@param panel p: Panel Object
//@param string _name: Name of the Screener
export method Screener ( panel p, string _name) =>
var _icon = ''
var _rating = ''
var _value = 0.
var _bg = #ffffff
var _fg = #ffffff
var _screen = screener.new(_name,_icon,_rating,_value,_bg,_fg,array.new<indication>())
switch _screen.init
false =>
if p.items.includes(_screen) == false
p.items.push(_screen)
else
_screen.init:=true
_screen
_screen
//@function # Indicator - Create a new Indicator
// ### Example:
// ```
// cleanscreen.Inidcator('1h', 'RSI', ta.rsi(close, 14))
// ```
//@param screener s: Screener Object
//@param string _tf: Timeframe
//@param string name: Name of the Indicator
//@param float val: Value of the Indicator
export method Indicator ( screener s , string _tf, string name, float val) =>
var _name = name
var _icon = ''
var _rating = ''
var _value = 0.
var _color = #000000
var tmf = _tf
var _indicator = indication.new(_name,_icon,_rating,_value,_color, tmf, '', 0)
switch _indicator.init
false =>
if not s.items.includes(_indicator)
s.items.push(_indicator)
else
_indicator.init := true
_indicator.value:= val
_indicator.normalized := nz(norm_value(_indicator.value))
_indicator
//@function # Display - Display the Panel
// ### Example:
// ```
//
// cleanscreen.display(panel)
//
// ```
//@param panel p: Panel Object
export method display ( panel p ) =>
var _colsize = p.items.size() - 1
var color _nocol = color.new(color.black,100)
var color _bg = na , var color _fg = na
var string _string = na , var float _value = na
var string _tip = na , theme = p.theme
var _theme = p.config.theme == 'dark' ? theme.dark : theme.light
var _cols = ca.makeGradient(6,array.from(theme.red,theme.orange,theme.yellow,theme.green,theme.aqua,theme.blue))
if barstate.islastconfirmedhistory
p.decorate(_theme)
for _x = 0 to array.size(p.items)-1
symbol = array.get(p.items,_x)
symbol.value := getTotal(symbol.items, array.size(symbol.items))
symbol.bg := p.col (symbol.value,_cols)
symbol.fg := p.col (symbol.value,_cols)
symbol.rating := p.rate(symbol.value )
symbol.icon := p.icon(symbol.rating )
_rowsize = array.size(symbol.items)
_hAlign = text.align_left
_vAlign = text.align_center
_textSize = p.config.textsize
for _y = 0 to _rowsize + 1
_width = p.config.cellwidth
_height = p.config.cellheight
_col = p.config.vert ? _x : _y
_row = p.config.vert ? _y : _x
switch _y
0 =>
_string := font.uni(str.replace(symbol.ticker,syminfo.prefix(symbol.ticker)+':',''),p.config.font)
_fg := col (p, symbol.value,_cols)
_bg := p.theme.dark.bg
_tip := str.tostring(symbol.value)
_height /= 2
_width *= p.config.vert ? 1 :1.5
1 =>
_string := icon(p, symbol.rating) + ' ' + symbol.rating
_bg := p.theme.dark.accent
_fg := _fg
_height /= 2
=>
_ind = array.get(symbol.items,_y-2)
rate(p,_ind)
_string := str.format(' {1, number, percent} - {0}',
_ind.icon, _ind.normalized)
_tip := str.format("Indicator: {0}\nTimeframe: {1}\nValue: {2}",
_ind.name, _ind.tf, _ind.value)
_bg := col (p, _ind.normalized, _cols)
_fg := h.tripswitch(_bg,.25,#ffffff,#000000)
_hAlign := text.align_right
_string := font.uni(_string,p.config.font)
cell( p , _col , _row ,
_string , _width , _height ,
_fg , _hAlign , _vAlign ,
_textSize , _bg , _tip )
___q()=>
/////////////////////////////////////////////////////////////////////////
_o = ' █▀▄ █▀▀ █▀▄▀█ █▀█ ░░▄▀ ▀█▀ █▀▀ █▀ ▀█▀ '
_o := ' █▄▀ ██▄ █░▀░█ █▄█ ▄▀░░ ░█░ ██▄ ▄█ ░█░ '
///////////////////////////////////////////////////////////////////////////
// ————— Inputs
// Theme names for the theme input
var string APATHY = "Apathy", var string APPRENTICE = "Apprentice", var string ASHES = "Ashes", var string ATELIER_CAVE = "Atelier Cave", var string ATELIER_DUNE = "Atelier Dune", var string ATELIER_ESTUARY = "Atelier Estuary", var string ATELIER_FOREST = "Atelier Forest", var string ATELIER_HEATH = "Atelier Heath", var string ATELIER_LAKESIDE = "Atelier Lakeside", var string ATELIER_PLATEAU = "Atelier Plateau", var string ATELIER_SAVANNA = "Atelier Savanna", var string ATELIER_SEASIDE = "Atelier Seaside", var string ATELIER_SULPHURPOOL = "Atelier Sulphurpool", var string ATLAS = "Atlas", var string AYU = "Ayu", var string AYU_MIRAGE = "Ayu Mirage", var string BESPIN = "Bespin", var string BLACK_METAL = "Black Metal", var string BLACK_METAL_BATHORY = "Black Metal (bathory)", var string BLACK_METAL_BURZUM = "Black Metal (burzum)", var string BLACK_METAL_FUNERAL = "Black Metal (dark Funeral)", var string BLACK_METAL_GORGOROTH = "Black Metal (gorgoroth)", var string BLACK_METAL_IMMORTAL = "Black Metal (immortal)", var string BLACK_METAL_KHOLD = "Black Metal (khold)", var string BLACK_METAL_MARDUK = "Black Metal (marduk)", var string BLACK_METAL_MAYHEM = "Black Metal (mayhem)", var string BLACK_METAL_NILE = "Black Metal (nile)", var string BLACK_METAL_VENOM = "Black Metal (venom)", var string BLUE_FOREST = "Blue Forest", var string BLUEISH = "Blueish", var string BREWER = "Brewer", var string BRIGHT = "Bright", var string BROGRAMMER = "Brogrammer", var string BRUSH_TREES = "Brush Trees", var string CATPPUCCIN = "Catppuccin", var string CHALK = "Chalk", var string CIRCUS = "Circus", var string CLASSIC = "Classic", var string CLRS = "Colors", var string CODESCHOOL = "Codeschool", var string CUPCAKE = "Cupcake", var string CUPERTINO = "Cupertino", var string DA_ONE_BLACK = "Da One Black", var string DA_ONE_GRAY = "Da One Gray", var string DA_ONE_OCEAN = "Da One Ocean", var string DA_ONE_PAPER = "Da One Paper", var string DA_ONE_SEA = "Da One Sea", var string DA_ONE_WHITE = "Da One White", var string DANQING = "Danqing", var string DARCULA = "Darcula", var string DARK_VIOLET = "Dark Violet", var string DARKMOSS = "Darkmoss", var string DARKTOOTH = "Darktooth", var string DECAF = "Decaf", var string DIRTYSEA = "Dirtysea", var string DRACULA = "Dracula", var string EDGE = "Edge", var string EIGHTIES = "Eighties", var string EMBERS = "Embers", var string EMIL = "Emil", var string EQUILIBRIUM = "Equilibrium", var string EQUILIBRIUM_GRAY = "Equilibrium Gray", var string ESPRESSO = "Espresso", var string EVA = "Eva", var string EVERFOREST = "Everforest", var string FLAT = "Flat", var string FRAMER = "Framer", var string FRUIT_SODA = "Fruit Soda", var string GIGAVOLT = "Gigavolt", var string GITHUB = "Github", var string GOOGLE = "Google", var string GOTHAM = "Gotham", var string GRAYSCALE = "Grayscale", var string GREEN_SCREEN = "Green Screen", var string GRUBER = "Gruber", var string GRUVBOX_HARD = "Gruvbox Dark, Hard", var string GRUVBOX_MEDIUM = "Gruvbox Dark, Medium", var string GRUVBOX_PALE = "Gruvbox Dark, Pale", var string GRUVBOX_SOFT = "Gruvbox Dark, Soft", var string GRUVBOX_MATERIAL_HARD = "Gruvbox Material Dark, Hard", var string GRUVBOX_MATERIAL_MEDIUM = "Gruvbox Material Dark, Medium", var string GRUVBOX_MATERIAL_SOFT = "Gruvbox Material Dark, Soft", var string HARDCORE = "Hardcore", var string HARMONIC16 = "Harmonic16", var string HEETCH = "Heetch", var string HELIOS = "Helios", var string HOPSCOTCH = "Hopscotch", var string HORIZON = "Horizon", var string HORIZON_TERMINAL = "Horizon Terminal", var string HUMANOID = "Humanoid", var string IA = "Ia", var string ICY = "Icy", var string IR_BLACK = "Ir Black", var string ISOTOPE = "Isotope", var string KANAGAWA = "Kanagawa", var string KATY = "Katy", var string KIMBER = "Kimber", var string LIME = "Lime", var string LONDON_TUBE = "London Tube", var string MACINTOSH = "Macintosh", var string MARRAKESH = "Marrakesh", var string MATERIA = "Materia", var string MATERIAL = "Material", var string MATERIALDARKER = "Material Darker", var string MATERIAL_PALENIGHT = "Material Palenight", var string MATERIAL_VIVID = "Material Vivid", var string MELLOW_PURPLE = "Mellow Purple", var string MOCHA = "Mocha", var string MONOKAI = "Monokai", var string NEBULA = "Nebula", var string NORD = "Nord", var string NOVA = "Nova", var string OCEAN = "Ocean", var string OCEANICNEXT = "Oceanicnext", var string ONEDARK = "Onedark", var string OUTRUN = "Outrun", var string PANDORA = "Pandora", var string PAPERCOLOR = "Papercolor", var string PARAISO = "Paraiso", var string PASQUE = "Pasque", var string PHD = "Phd", var string PICO = "Pico", var string PINKY = "Pinky", var string POP = "Pop", var string PORPLE = "Porple", var string PRIMER = "Primer", var string PURPLEDREAM = "Purpledream", var string QUALIA = "Qualia", var string RAILSCASTS = "Railscasts", var string REBECCA = "Rebecca", var string ROSE_PINE = "Rosé Pine", var string ROSE_PINE_DAWN = "Rosé Pine Dawn", var string ROSE_PINE_MOON = "Rosé Pine Moon", var string SAGELIGHT = "Sagelight", var string SAKURA = "Sakura", var string SANDCASTLE = "Sandcastle", var string SETI_UI = "Seti Ui", var string SHADES_OF_PURPLE = "Shades Of Purple", var string SHADESMEAR = "Shadesmear", var string SHAPESHIFTER = "Shapeshifter", var string SILK = "Silk", var string SNAZZY = "Snazzy", var string SOLAR_FLARE = "Solar Flare", var string SOLARIZED = "Solarized", var string SPACEDUCK = "Spaceduck", var string SPACEMACS = "Spacemacs", var string STELLA = "Stella", var string STILL_ALIVE = "Still Alive", var string SUMMERCAMP = "Summercamp", var string SUMMERFRUIT = "Summerfruit", var string SYNTH_MIDNIGHT_TERMINAL = "Synth Midnight Terminal", var string TANGO = "Tango", var string TENDER = "Tender", var string TOKYO_CITY = "Tokyo City", var string TOKYO_CITY_TERMINAL = "Tokyo City Terminal", var string TOKYO_NIGHT = "Tokyo Night", var string TOKYO_NIGHT_STORM = "Tokyo Night Storm", var string TOKYO_NIGHT_TERMINAL = "Tokyo Night Terminal", var string TOKYO_NIGHT_TERMINAL_STORM = "Tokyo Night Terminal Storm", var string TOKYODARK = "Tokyodark", var string TOKYODARK_TERMINAL = "Tokyodark Terminal", var string TOMORROW = "Tomorrow", var string TOMORROW_NIGHT = "Tomorrow Night", var string TOMORROW_NIGHT_EIGHTIES = "Tomorrow Night Eighties", var string TWILIGHT = "Twilight", var string UNIKITTY = "Unikitty", var string UNIKITTY_REVERSIBLE = "Unikitty Reversible", var string UWUNICORN = "Uwunicorn", var string VICE = "Vice", var string VULCAN = "Vulcan", var string WINDOWS_10 = "Windows 10", var string WINDOWS_95 = "Windows 95", var string WINDOWS_HIGH_CONTRAST = "Windows High Contrast", var string WINDOWS_NT = "Windows Nt", var string WOODLAND = "Woodland", var string XCODE_DUSK = "Xcode Dusk"
string GRP1 = "Settings"
// init panel with theme and location
var loc = input.int(9, ' Table loc (1-9)', 1, 9)
var panel = init(input.string(SILK, 'Theme Choice', options = [APATHY,APPRENTICE,ASHES,ATELIER_CAVE,ATELIER_DUNE,ATELIER_ESTUARY,ATELIER_FOREST,ATELIER_HEATH,ATELIER_LAKESIDE,ATELIER_PLATEAU,ATELIER_SAVANNA,ATELIER_SEASIDE,ATELIER_SULPHURPOOL,ATLAS,AYU,AYU_MIRAGE,BESPIN,BLACK_METAL,BLACK_METAL_BATHORY,BLACK_METAL_BURZUM,BLACK_METAL_FUNERAL,BLACK_METAL_GORGOROTH,BLACK_METAL_IMMORTAL,BLACK_METAL_KHOLD,BLACK_METAL_MARDUK,BLACK_METAL_MAYHEM,BLACK_METAL_NILE,BLACK_METAL_VENOM,BLUE_FOREST,BLUEISH,BREWER,BRIGHT,BROGRAMMER,BRUSH_TREES,CATPPUCCIN,CHALK,CIRCUS,CLASSIC,CLRS,CODESCHOOL,CUPCAKE,CUPERTINO,DA_ONE_BLACK,DA_ONE_GRAY,DA_ONE_OCEAN,DA_ONE_PAPER,DA_ONE_SEA,DA_ONE_WHITE,DANQING,DARCULA,DARK_VIOLET,DARKMOSS,DARKTOOTH,DECAF,DIRTYSEA,DRACULA,EDGE,EIGHTIES,EMBERS,EMIL,EQUILIBRIUM,EQUILIBRIUM_GRAY,ESPRESSO,EVA,EVERFOREST,FLAT,FRAMER,FRUIT_SODA,GIGAVOLT,GITHUB,GOOGLE,GOTHAM,GRAYSCALE,GREEN_SCREEN,GRUBER,GRUVBOX_HARD,GRUVBOX_MEDIUM,GRUVBOX_PALE,GRUVBOX_SOFT,GRUVBOX_MATERIAL_HARD,GRUVBOX_MATERIAL_MEDIUM,GRUVBOX_MATERIAL_SOFT,HARDCORE,HARMONIC16,HEETCH,HELIOS,HOPSCOTCH,HORIZON,HORIZON_TERMINAL,HUMANOID,IA,ICY,IR_BLACK,ISOTOPE,KANAGAWA,KATY,KIMBER,LIME,LONDON_TUBE,MACINTOSH,MARRAKESH,MATERIA,MATERIAL,MATERIALDARKER,MATERIAL_PALENIGHT,MATERIAL_VIVID,MELLOW_PURPLE,MOCHA,MONOKAI,NEBULA,NORD,NOVA,OCEAN,OCEANICNEXT,ONEDARK,OUTRUN,PANDORA,PAPERCOLOR,PARAISO,PASQUE,PHD,PICO,PINKY,POP,PORPLE,PRIMER,PURPLEDREAM,QUALIA,RAILSCASTS,REBECCA,ROSE_PINE,ROSE_PINE_DAWN,ROSE_PINE_MOON,SAGELIGHT,SAKURA,SANDCASTLE,SETI_UI,SHADES_OF_PURPLE,SHADESMEAR,SHAPESHIFTER,SILK,SNAZZY,SOLAR_FLARE,SOLARIZED,SPACEDUCK,SPACEMACS,STELLA,STILL_ALIVE,SUMMERCAMP,SUMMERFRUIT,SYNTH_MIDNIGHT_TERMINAL,TANGO,TENDER,TOKYO_CITY,TOKYO_CITY_TERMINAL,TOKYO_NIGHT,TOKYO_NIGHT_STORM,TOKYO_NIGHT_TERMINAL,TOKYO_NIGHT_TERMINAL_STORM,TOKYODARK,TOKYODARK_TERMINAL,TOMORROW,TOMORROW_NIGHT,TOMORROW_NIGHT_EIGHTIES,TWILIGHT,UNIKITTY,UNIKITTY_REVERSIBLE,UWUNICORN,VICE,VULCAN,WINDOWS_10,WINDOWS_95,WINDOWS_HIGH_CONTRAST,WINDOWS_NT,WOODLAND,XCODE_DUSK]),
loc)
var tfInput = input.timeframe("", "Higher timeframe", group = GRP1)
if barstate.isfirst
panel.config.theme := input.string ( 'light' , "Theme Variewnt" , options=['light' , 'dark'] , inline='ic' , group='Icons' )
panel.config.cellwidth := input.float ( 7.5 , 'cellwidth' , step=0.5 , inline = "Cellsize" , group=GRP1 )
panel.config.cellheight := input.float ( 7.5 , 'cellheight' , step=0.5 , inline = "Cellsize" , group=GRP1 )
panel.config.textsize := input.string ( size.auto , 'Textsize' , options=[size.auto, size.small, size.normal, size.large, size.huge] , inline = "set" , group=GRP1 )
panel.config.font := input.int ( 15 , 'Font' , 1 , 17 , inline = "set" , group=GRP1 )
panel.config.framewidth := input.int ( 10 , 'Framewidth' , 0 , 20 , inline = "set" , group=GRP1 )
panel.config.borders := input.int ( 1 , 'Borders' , -1 , 10 , inline = "set" , group=GRP1 )
panel.config.vert := input.bool ( true , 'vert' ) //int ( 1 , 'Borders' , -1 , 10 )
panel.config.position := ssp.table_posittion(loc)
// Icons
panel.icons.strong := input.string('💸', 'Strong ✼', inline='ic', group='Icons')
panel.icons.buy := input.string('💰', 'Buy ⇡', inline='ic', group='Icons')
panel.icons.sell := input.string('🔥', 'Sell ⇣', inline='ic', group='Icons')
// Inputs
var _001 = input.symbol('CELOUSDTPERP', group='symbols')
var _002 = input.symbol('MTLUSDTPERP', group='symbols')
var _003 = input.symbol('CVCUSDTPERP', group='symbols')
// Using Pineecoders technical Indicators, and 3 basic buil ins:
method getvals(screener s, simple string ticker, _tf) =>
[ratingTotal, ratingOther, ratingMa] = request.security(ticker, tfInput, techrate.calcRatingAll(), ignore_invalid_symbol = true)
// update screener indicators
s.Indicator(_tf, 'Total', ratingTotal)
s.Indicator(_tf, 'Other', ratingOther)
s.Indicator(_tf, 'MAs ', ratingMa)
// calculating to have maimum off 1,low of -1
// update screener indicators
s.Indicator(_tf, 'RSI', request.security(ticker, _tf, ta.rsi(close,7)))
s.Indicator(_tf, 'mom', request.security(ticker, _tf, ta.mom(close,7)))
s.Indicator(_tf, 'atr', request.security(ticker, _tf, ta.atr(20)))
// Initialize
var _Screener_01 = Screener(panel, _001)
var _Screener_02 = Screener(panel, _001)
var _Screener_03 = Screener(panel, _001)
// Get values for different timeframes
getvals(_Screener_01, _001, '15')
getvals(_Screener_02, _001, '60')
getvals(_Screener_03, _001, '1440')
// Three tickers on same timeframe, wors wihou var as well
_Screener_01a = Screener(panel, _001)
_Screener_02a = Screener(panel, _002)
_Screener_03a = Screener(panel, _003)
// Get values for different ticers
getvals(_Screener_01a, _001, timeframe.period)
getvals(_Screener_02a, _002, timeframe.period)
getvals(_Screener_03a, _003, timeframe.period)
// Display!
if bar_index + 2 >= last_bar_index
panel.display()
|
Metrics using Alternative Portfolio Theory | https://www.tradingview.com/script/4lxXYsv9-Metrics-using-Alternative-Portfolio-Theory/ | TechnicusCapital | https://www.tradingview.com/u/TechnicusCapital/ | 4 | 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/
// © TechnicusCapital
//@version=5
// @description Portfolio metrics using alternative portfolio theory
library("APT_Metrics", overlay = true)
import TradingView/ta/5 as ta
// @function Calculates APT metrics
// @param init Starting Equity (strategy.initial)
// @param src Current Equity Curve (strategy.equity)
// @param start Start date (UNIX)
// @param end End Date (UNIX)
// @param alpha Confidence interval for DaR/CDaR. Defval = 0.05
// @returns Table with APT metrics
export metrics(float init, float cur, int start, int end, float alpha = .05) =>
var inDD = false
var ddBegin = 0.00
var float ddLowPrice = na
var ddLow = 0.00
var dd = 0.00
var ddArr = array.new<float>()
var ui = 0.00
if cur < cur[3] and not inDD
ddLowPrice := cur
inDD := true
ddBegin := cur
array.push(ddArr, 0)
if inDD and cur < ddBegin
ddLowPrice := math.min(ddLowPrice, cur)
dd := (ddBegin - cur)/ddBegin
ddLow := (ddBegin - ddLowPrice)/ddBegin
array.set(ddArr, array.size(ddArr) -1, ddLow)
if inDD and cur > ddBegin
if ddLow < .01 and array.size(ddArr) > 0
array.remove(ddArr, array.size(ddArr) -1)
inDD := false
dd := 0.00
ui := array.stdev(ddArr)
returns_length = 252
volatility_length = 1280
log_returns = ta.roc(cur, 1)
ret_sma = ta.sma(log_returns, returns_length)
ret_annual = ret_sma * returns_length
ret_norm = ret_annual * 100
var entryPrice = 0.00
var exitPrice = 0.00
if time <= end
entryPrice := close
cagr = ta.cagr(start, init, end, cur)/100
hv = ta.stdev(log_returns, volatility_length) * math.sqrt(returns_length)
hv_norm = hv/100
upi = (cagr)/(ui)
DaR = array.percentile_nearest_rank(ddArr, (1-alpha)*100)
cdarArr = array.new<float>()
for each in ddArr
if each > DaR
array.push(cdarArr, each)
CDaR = array.avg(cdarArr)
array.clear(cdarArr)
CDaR_est = array.percentile_nearest_rank(ddArr, 95)
pitfall = CDaR/hv_norm
penalized_risk = ui * pitfall
SR = cagr/penalized_risk
table perfTable1 = table.new(position.bottom_right, 2, 9, border_color = color.yellow, border_width = 1)
table.cell(perfTable1, 0, 0, "ASPECT", text_color = color.white)
table.cell(perfTable1, 1, 0, "VALUE", text_color = color.white)
table.cell(perfTable1, 0, 1, "Ulcer Index", text_color = color.white)
table.cell(perfTable1, 1, 1, str.tostring(math.round(ui*100, 2)) + "%", text_color = color.white)
table.cell(perfTable1, 0, 2, "Ulcer Performance Index", text_color = color.white)
table.cell(perfTable1, 1, 2, str.tostring(math.round(upi,2)), text_color = color.white)
table.cell(perfTable1, 0, 3, "CDaR", text_color = color.white)
table.cell(perfTable1, 1, 3, str.tostring(math.round(CDaR*100, 2)) + "%", text_color = color.white)
//The Pitfall represents the average loss of the biggest drawdowns expressed in units of volatility.
table.cell(perfTable1, 0, 4, "Pitfall Indicator", text_color = color.white)
table.cell(perfTable1, 1, 4, str.tostring(math.round(pitfall, 2)), text_color = color.white)
table.cell(perfTable1, 0, 5, "Penalized Risk", text_color = color.white)
table.cell(perfTable1, 1, 5, str.tostring(math.round(penalized_risk*100,2)) + "%", text_color = color.white)
table.cell(perfTable1, 0, 6, "Serenity Ratio", text_color = color.white)
table.cell(perfTable1, 1, 6, str.tostring(math.round(SR, 2)), text_color = color.white)
|
libhs_td4 | https://www.tradingview.com/script/qvZEts3J-libhs-td4/ | GETpacman | https://www.tradingview.com/u/GETpacman/ | 0 | 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/
// © GETpacman
//@version=5
// @description td4 Test Data Library for Console Testing
library("libhs_td4")
export fill(matrix<string> dbus, bool fillData=true) =>
string gm1=''
string gm2=''
string gm3=''
string gm4=''
string gm5=''
string gm6=''
string gm=''
string gl=''
string gs=''
string gc=''
string tab2=' '
string tab4=' '
var string o_skiplog = '^skip^'
var string[] alphabet=array.from(' Alpha',' Beta',' Charlie',' Delta',' Echo',' Foxtrot',' Golf',' Hotel',' India',' Juliet',' Kilo',' Lima',' Mike',' November',' Oscar',' Papa',' Quebec',' Romeo',' Sugar',' Tango',' Uniform',' Victor',' Whisky',' Xray',' Yankee',' Zulu')
var string[] alphabetc=array.from('Alpha','Beta','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sugar','Tango','Uniform','Victor','Whisky','Xray','Yankee','Zulu')
int devcolmsg=2, int devcollevelC=3, int devcolstatusC=4, int prodcolmsg=5, int prodcollevelC=6, int prodcolstatusC=7
int devcolm1=8, int devcolm2=9, int devcolm3=10, int devcolm4=11, int devcolm5=12, int devcolm6=13, int devcollevelL=14, int devcolstatusL=15
int prodcolm1=16, int prodcolm2=17, int prodcolm3=18, int prodcolm4=19, int prodcolm5=20, int prodcolm6=21, int prodcollevelL=22, int prodcolstatusL=23
int c=1
var consoleBus=array.new_string()
var bool _filled=false
if fillData and not _filled
consoleBus.push('')
consoleBus.push('Commencing Console Testing') //idzc=1
consoleBus.push('You will need to slowly go through about 600 bars (300 each for Console and Logx) to see full suite of possibilities with this library')
consoleBus.push('Multiple tests will be conducted to show how each feature works of this library')
consoleBus.push('All tests will do one main action at each bar and some supplementary to show the best use of that test case')
consoleBus.push('Console started with 5 rows and is filled up now')
consoleBus.push('Test 1 = Resize (add 5 rows)') //idzc=6
consoleBus.push('@q2=● on next bar call => console.resize(10) ▼')
consoleBus.push(o_skiplog)
consoleBus.push('@q2=More space added to queue')
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 1 completed ▲') //idzc=13
consoleBus.push('Test 2 = Resize (remove 3 rows)') //idzc=14
consoleBus.push('@q2=● on next bar call => console.resize(7) ▼')
consoleBus.push(o_skiplog)
consoleBus.push('@q2=Space removed from the queue'+' (Frame will be removed at end of this test)')
consoleBus.push('Test 2 completed ▲')
consoleBus.push('Test 3 = set text color (to blue)') //idzc=19
consoleBus.push('@q2=● on next bar call => console.textColor:=color.blue ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Text color is now blue')
consoleBus.push('Test 3 completed ▲')
consoleBus.push('Test 4 = set background color (to orange)') //idzc=23
consoleBus.push('@q2=● on next bar call => console.textColorBG:=color.orange ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Background color is now orange')
consoleBus.push('Test 4 completed ▲')
consoleBus.push('Test 5 = reset background color to library default') //idzc=27
consoleBus.push('@q2=● on next bar call => console.resetTextColorBG() ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Background color is same as chart background color')
consoleBus.push('Test 5 completed ▲')
consoleBus.push('Test 6 = reset text color to library default') //idzc=31
consoleBus.push('@q2=● on next bar call => console.resetTextColor() ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Text color is now library default')
consoleBus.push('Test 6 completed ▲')
consoleBus.push('Test 7 = Set Status color to green') //idzc=35
consoleBus.push('@q2=● on next bar call => console.statusColor:=color.green ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Status color is green now')
consoleBus.push('Test 7 completed ▲')
consoleBus.push('Test 8 = Set Status background color to white') //idzc=39
consoleBus.push('@q2=● on next bar call => console.statusColorBG:=color.white ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Status background color is white now')
consoleBus.push('Test 8 completed ▲')
consoleBus.push('Test 9 = Reset Status background color to library default') //idzc=43
consoleBus.push('@q2=● on next bar call => console.resetStatusColorBG() ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Status background color is now library default')
consoleBus.push('Test 9 completed ▲')
consoleBus.push('Test 10 = Reset Status color to library default') //idzc=47
consoleBus.push('@q2=● on next bar call => console.resetStatusColor() ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=Status color is now library default')
consoleBus.push('Test 10 completed ▲')
consoleBus.push('Test 11 = Show a frame around Console (blue colored)') //idzc=51
consoleBus.push('@q2=● on next bar call => console.frameColor:=color.blue ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=A blue frame around Console is visible')
consoleBus.push('Test 11 completed ▲')
consoleBus.push('Test 12 = Remove the colored frame around Console') //idzc=55
consoleBus.push('@q2=● on next bar call => console.resetFrameColor() ▼')
// consoleBus.push(o_skiplog)
consoleBus.push('@q2=There is no frame around Console anymore')
consoleBus.push('Test 12 completed ▲')
consoleBus.push('Test 13 = Color Console as per error codes, with user supplied colors') //idzc=59
consoleBus.push('@q2=● on next bar call => console.setErrorColors(customFG) ▼ (fuschia/olive/maroon/navy @ 100%/65%)')
consoleBus.push('@q2=● on next bar call => console.ColorText:=true ▼')
c:=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 13 completed ▲')
consoleBus.push('Test 14 = Highlight Console as per error codes, with user supplied colors') //idzc=71
consoleBus.push('@q2=● on next bar call => console.setErrorHCcolors(customHC) ▼ (fuschia/olive/maroon/navy @ 100%/65%)')
consoleBus.push('@q2=● on next bar call => console.HighlightText:=true ▼')
c:=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 14 completed ▲')
consoleBus.push('Test 15 = Color Console as per default error codes / Show Log Levels') //idzc=83
consoleBus.push('@q2=● on next bar call => console.resetErrorColors() ▼')
consoleBus.push('@q2=● on next bar call => console.ColorText:=true ▼ console.ShowLogLevels:=true ▼')
c:=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 15 completed ▲')
consoleBus.push('Test 16 = Highlight Console as per default error codes') //idzc=94
consoleBus.push('@q2=● on next bar call => console.resetErrorHCcolors() ▼')
consoleBus.push('@q2=● on next bar call => console.HighlightText:=true ▼')
c:=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 16 completed ▲')
consoleBus.push('Test 17 = ShowColors + setColor/HC/BG + setLevelName') //idzc=105
consoleBus.push('@q2=You can see the color of error codes on a sepatate table, to see how they look')
consoleBus.push('@q2=● on next bar call and remainder of this test call => console.showColors(position=position.bottom_left,showColors=(idzc>=108 and idzc<=123)) ▼')
consoleBus.push('@q2=A table with colors corresponding to error codes can be see on bottom left. It shows how they look with and without highlighting, and what the log level names are.')
consoleBus.push('@q2=At the moment there are 36 error codes. Error Code 36 (in range),40,41 will be set to new colors')
consoleBus.push('@q2=Some codes are out of range, hence the color array codes will be expanded.')
consoleBus.push("@q2=Log Level names do not get expanded when color array gets expanded. ")
consoleBus.push("@q2=To auto expand Log Level names, Log Level for Code 40 will be set to 'Custom Code 40' (36 codes at moment)")
consoleBus.push("@q2=● on next bar call => console.setLevelName(40,'Custom Code 40') ▼")
consoleBus.push('Log Level Name has been expanded, but is not visible as Color Table only goes upto max colors code, which is 36 at the moment. Wait for color expansion')
consoleBus.push('@q2=● on next bar call => console.setColor(36,color.red) ▼')
consoleBus.push('@q2=Error Code 36 has Red Color as foreground.')
consoleBus.push('@q2=● on next bar call => console.setColorHC(40,color.black) ▼ console.setColor(40,color.orange) ▼')
consoleBus.push('@q2=Error Code 40 is now visible with orange foreground and black as highlight color. Background color is taken from TextColorBG')
consoleBus.push('@q2=Log Level for Code 40 is now visible as well, with custom log level name visible')
consoleBus.push('@q2=● on next bar call => console.setColorBG(41,color.yellow) ▼')
consoleBus.push('@q2=Error Code 41 is now visible with Yellow Color as background. Foreground/Highlight has been taken from TexColor/color.white')
consoleBus.push('Color table will be deleted at end of this test')
consoleBus.push('Test 17 completed ▲')
consoleBus.push('Test 18 = Move Status to top') //idzc=124
consoleBus.push('@q2=● on next bar call => console.StatusBarAtBottom:=false ▼')
consoleBus.push(o_skiplog)
consoleBus.push('@q2=Status has moved to the top (will be moved back to bottom at end of this test)')
consoleBus.push('Test 18 completed ▲')
consoleBus.push('Test 19 = Update / Hide Status Meta Info / Hide Status') //idzc=129
consoleBus.push('Test 19a = Update Status')
consoleBus.push('@q2=Status Bar has Test Number at the moment, this will be replaced with a custom status message')
consoleBus.push('@q2=● on next bar call => console.Status:="Look we have a status message now, that will persist across updates" ▼')
consoleBus.push('@q2=Not all of the status message may get updated, as table may expand as per length of logged message.')
consoleBus.push('@q2=Some part of the status is also taken by bar number and other message, hence not full status will be used')
consoleBus.push('@q2=Reset the status using console.Status property')
consoleBus.push('Test 19b = Hide Status Meta Info')
consoleBus.push('@q2=Notice lower right corner has current bar info (bar index, and free characters before overflow)')
consoleBus.push('@q2=● on next bar call => console.ShowMetaStatus:=false ▼')
consoleBus.push('@q2=Meta info no longer visible in status bar and full bar is available for custom status messages')
consoleBus.push('Test 19b = Hide Status')
consoleBus.push('@q2=● on next bar call => console.ShowStatusBar:=false ▼')
consoleBus.push('@q2=Status bar is hidden now')
consoleBus.push('Test 19 completed ▲')
consoleBus.push('Test 20 = Change the scroll direction') //idzc=144
consoleBus.push('@q2=This can get confusing so Console will be cleared first, status moved to top and then')
consoleBus.push('@q2=● on next bar call => console.MoveLogUp:=false ▼')
consoleBus.push('@q2=Commencing scrolling test. messages pile on top and older messages are pushed down')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('Test 20 completed ▼')
consoleBus.push('')
consoleBus.push('')
consoleBus.push('')
consoleBus.push('')
if fillData and not _filled
consoleBus.push('Test 21 = Show Bar Index') //idzc=159
consoleBus.push('@q2=● on next bar call => console.ShowBarIndex:=true ▼')
consoleBus.push('@q2=Bar Index is visible now, at the start of this line')
consoleBus.push('Test 21 completed ▲')
consoleBus.push('Test 22 = Show/Format Date/Time') //idzc=163
consoleBus.push('@q2=● on next bar call => console.ShowDateTime:=true ▼')
consoleBus.push('@q2=Date/Time is visible now. Format will be changed next')
consoleBus.push("@q2=● on next bar call => console.dateTimeFormat('dd.MMM.yy') ▼")
consoleBus.push('@q2=Only date is visible now')
consoleBus.push('@q2=to reset back to default format ● on next bar call => console.dateTimeFormat() ▼')
consoleBus.push('Test 22 completed ▲')
consoleBus.push('Test 23 = Paging! Only messages from current/active bar will be kept') //idzc=170 zc=170
consoleBus.push('@q2=● on next bar call => console.PageOnEveryBar:=true ▼') //idzc=171 zc=171
consoleBus.push('Paging Test 23. Only messages from active bar will be recorded.') //idzc=172 zc=172
consoleBus.push('@q2=All messages from previous bars have been cleared. When paging is on you should see this => ● in status bar')
consoleBus.push('@q2=These messages are not getting cleared as they are on the same bar (even if running on historical bars, its still on same bar).')
c:=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Paging Test 23. This is the 2nd bar with paging setting still on ') //idzc=173 zc=178
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Paging Test 23. This is the 3rd bar with paging setting still on.') //idzc=174 zc=183
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('@q2=on next bar paging history will be increased by calling console.PageHistory:=1')
consoleBus.push('Paging Test 23. This is the 4th bar with paging setting still on. we should now see 2 bars of data only (as remembering 1 page history)') //idzc=175 zc=188
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Paging Test 23. This is the 5th bar with paging setting still on. we should now see 2 bars of data only (as remembering 1 page history)') //idzc=176 zc=193
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Paging Test 23. This is the 6th bar with paging setting still on. we should now see 2 bars of data only (as remembering 1 page history)') //idzc=177 zc=198
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 23 completed ▲') //idzc=178 zc=203
consoleBus.push('With Paging turned off, the messages from previous bars were not erased') //idzc=179 zc=204
consoleBus.push('This happaned as,from that bar Paging was turned off, it stopped clearing old messages')
consoleBus.push('Test 24 = adhoc paging without changing the Paging config') //idzc=181 zc=206
consoleBus.push('@q2=● on next few bars call => console.page ▼')
for x=1 to 3 //idzc=183, 184, 185
consoleBus.push('Adhoc paging Test 24. Paging is not on as there is no ● in the status bar.')
consoleBus.push('Adhoc paged messages will have no history from previous bars, viz it will only show messages from current bar.')
consoleBus.push('@q2=Following messages are logged on same bar via console.page')
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('Test 24 completed ▲') //idzc=186 zc=226
consoleBus.push('Test 25 = Auto Indent (Level 1-7 only) / Prefix log levels to messages ') //idzc=187 zc=227
consoleBus.push('@q2=● on next bar call => console.PrefixLogLevel:=true ▼')
consoleBus.push('@q2=● on next bar call => console.TabSizeQ1:=1 ▼')
c:=1
for x=1 to 7 //idzc=190 to 196
consoleBus.push('Level '+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('Auto Indenting works on error codes 1 to 7 only. To disable auto indenting set tabsizeQ1 to 0')
consoleBus.push('Test 25 completed ▲')
consoleBus.push('Test 26 = Buffer overflow test') //idzc=199 zc=239
consoleBus.push('Test 26 = Buffer overflow test') //idzc=200
consoleBus.push('@q2=There is a limit of 4096 characters to use in the Console')
consoleBus.push('@q2=Pushing some test messages to go over this limit. Keep looking at free chars shown in the status as (+XXXX)')
c:=1
for x=1 to 19 //idzc= old=>//zidxc=193 to 211
tm='sample TRACE message = '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '
+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)
consoleBus.push(tm)
c+=1
consoleBus.push('') //idzc= old=>//zidx=212
consoleBus.push('!> Next 2 messages should make the buffer overflow. When this happens, an x sign will appear in status to show the dump took place, and we will lose some messages at the top <!') //idzc=204 zc=244
tm='sample TRACE message = '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '
+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)
consoleBus.push(tm) //idzc= old=>//zidx=214
c+=1
tm:='sample TRACE message = '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '
+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)
consoleBus.push(tm)
consoleBus.push('')
consoleBus.push('We lost some messages at the top to make way for new text. If need be whole of the Console will be cleared to make way for current message being logged')
consoleBus.push('If the message is more than 4096 characters, TV would throw an error due to size limit and that message wouldnt come to the library at all')
consoleBus.push('Test 26 completed ▲')
consoleBus.push('Test 27 = Mark New Bars') //idzc=230 zc=260
consoleBus.push('@q2=This option adds a marker at start of each new bar')
consoleBus.push('@q2=● on next bar call => console.MarkNewBar:=true ▼')
for x=1 to 12
consoleBus.push('@q2=Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('Test 27 completed ▲')
consoleBus.push('Test 28 = Change mininum Console width') //idzc=237 zc=286
consoleBus.push('@q2=Current minimum Console width is 80. We will be increasing this to 200 minimum')
consoleBus.push('@q2=● on next bar call => console.MinWidth:=200 ▼')
consoleBus.push('@q2=Console Width is now changed to atleast 200 characters wide.')
consoleBus.push('@q2=Reset back to 80 at end of this test')
consoleBus.push('Test 28 completed ▲')
consoleBus.push('Test 29 = Convert Console to Logx') //idzc=243 zc=292
consoleBus.push('@q2=Now Console will be converted into a Logx. There is no need to create a new variable')
consoleBus.push('@q2=● on next bar call => console.IsConsole:=false ▼')
consoleBus.push(o_skiplog)
consoleBus.push('Look this is a Logx now')
consoleBus.push('Converting to a Logx wont make you lose any data')
consoleBus.push('though converting back to Console will') //idzc=249
c:=1
for x=1 to 3 //idzc=250, 251, 252
c+=1
tm:='<Q1 message = '+alphabetc.get((c-1)%26)+'>'
for y=2 to 6
c+=1
tm+='@q'+str.tostring(y)+'=<Q'+str.tostring(y)+' message = '+alphabetc.get((c-1)%26)+'>'
consoleBus.push(tm)
consoleBus.push('Now lets convert this back to Console')
consoleBus.push('@q2=● on next bar call => console.IsConsole:=true ▼')
consoleBus.push('Test 29 completed ▲') //idzc=255 zc=304
consoleBus.push('Test 30 = Turning a page') //idzc=256 zc=305
consoleBus.push('@q2=All messages are logged on a "page", which could be turned at any point of time.')
consoleBus.push('@q2=This is different from console.page which will flush all messages from previous bars')
consoleBus.push('@q2=This is also different from PageOnEveryBar which will flush all messages from previous bars, based on Page History')
consoleBus.push('@q2=turnPage will clear all older messages at the point turnPage is called, and is independent from above')
c:=1
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
c+=1
consoleBus.push('@q2=Error Code used = '+str.tostring(c)+'@q3= Sample message = '+alphabetc.get((c-1)%26))
consoleBus.push('@q2=● on next bar call => console.turnPage() ▼')
consoleBus.push('@q2=All older messages have been cleared and we are on a new page (not dependent on PageOnEveryBar or console.page)')
consoleBus.push('@q2=So, effectively, there are 3 ways to page messages')
consoleBus.push('Test 30 completed ▲') //idzc=267 zc=317
// consoleBus.push('All Console Tests completed') //idzc=294 zc=343
consoleBus.push('Test 31 = Asynchronous Logging') //zidc=268 zc=318
consoleBus.push('@q2=Another way to log messages is to log them to each queue individually')
consoleBus.push('@q2=This may be needed when you need to log messages at different times')
consoleBus.push('@q2=Logging four sample messages to Q1 at one go, using console.alog(0,msg,1). These will be followed by logging to Q2 and Q3 separately, using console.alog(0,msg,2) and console.alog(0,msg,3) ')
c:=1
consoleBus.push('▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) //zidc=272 zc=322
c+=1
consoleBus.push('▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) //zidc=273 zc=323
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q3=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) //zidc=280 zc=330
c+=1
consoleBus.push('@q3=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q3=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q3=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) //zidc=284 zc=333
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push('@q2=▷ Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
consoleBus.push('@q2=Some of the messages appeared to shift to left, because there was no data on left side.')
consoleBus.push('@q2=This wont happen during Logx testing as cells are separate, whereas here they are not. This is not a bug, but expected behaviour')
consoleBus.push('@q2=As soon as normal log method is used all queues are logged in sync')
consoleBus.push('Test 31 completed ▲') //zidc=293 zc=342
consoleBus.push('Test 32 = Buffer overflow test using async logging') //idzc=294 zc=343
consoleBus.push('@q2=Test 32 = Buffer overflow test using async logging') //idzc=295
consoleBus.push('@q2='+tab4+'Pushing some test messages at one go, to over 4096 chars limit. Keep looking at free chars shown in the status as (+XXXX)')
c:=1
while c<=20 //idzc=297 to 306 zc=346 to 365
tm:='@q2='+tab4+'sample TRACE message #'+str.tostring(c)+'= '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '
+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)+', '+alphabet.get((c-1)%26)
consoleBus.push(tm)
c+=1
consoleBus.push('@q2=')
consoleBus.push('@q2='+tab4+'!> now some messages will be pushed to Q1 to check buffer over flow <!') //idzc=296
consoleBus.push('Did this cause buffer overflow?') //idzc=297
consoleBus.push('Did this cause buffer overflow?') //idzc=298
consoleBus.push('Only 86 characters to eat up') //idzc=299
consoleBus.push('Pushing some more data yet') //idzc=300
consoleBus.push('Only 32 characters to eat up') //idzc=301
consoleBus.push('!! Buffer Overflow !!') //idzc=302
consoleBus.push('We lost some messages at the top to make way for new text. If need be whole of the Console will be cleared to make way for current message being logged')
consoleBus.push('Test 32 completed ▲') //idzc=304 zc=
consoleBus.push('Test 33 = Show Specific Log Level messages.') //idzc=305 zc=
consoleBus.push('Logging some sample messages with the Log Level 0 to 7')
c:=1
consoleBus.push(tab4+'Level 0'+tab4+'No Level'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2) //zidc= zc=
c+=1
consoleBus.push(tab4+'Level 1'+tab4+'TRACE'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 2'+tab4+'DEBUG'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 3'+tab4+'INFO'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 4'+tab4+'WARNING'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 5'+tab4+'ERROR'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 6'+tab4+'CRITICAL'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
c+=1
consoleBus.push(tab4+'Level 7'+tab4+'FATAL'+tab4+' Sample message = '+alphabetc.get((c-1)%26)+' ◁'+tab2)
consoleBus.push('Setting sit.ShowMinimumLvel := 3 to display INFO or higher messages')
consoleBus.push('Setting sit.ShowMinimumLvel := 4 to display WARNING or higher messages')
consoleBus.push('Test 33 completed ▲') //idzc=310 zc=
consoleBus.push('Test 34 = Undo logged messages') //idzc=311 zc=
consoleBus.push('@q2=Pushing some sample messages')
consoleBus.push('@q2=First message #15 will be removed, followed by removal of #14, #13, #12 and finally all sample messages')
c:=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
c+=1
consoleBus.push('@q2=#'+str.tostring(c)+' Sample message = '+alphabetc.get((c-1)%26)+' ▼')
consoleBus.push('@q2=All messages were removed')
consoleBus.push('@q2=Undo will remove messages logged via logx.log and stop as soon as it finds asynchronously logged messages')
consoleBus.push('Test 34 completed ▲') //idzc=320 zc=
consoleBus.push('All Console Tests completed') //idzc=321 zc=
// _________________________________________________________________________Console Testing ends on idzc=305
if fillData and not _filled
//______ == ______________________________ attachment Testing starts on idza=1
consoleBus.push('Attachment Test 1 = Attaching a Console to Logx') //idza=1
consoleBus.push( o_skiplog)
consoleBus.push( o_skiplog)
consoleBus.push('Console ready for attachment testing with Logx')
consoleBus.push('.....still waiting ◯')
consoleBus.push('..»▷ ATTACHED to Logx! ◁«..') //idza=6
consoleBus.push( o_skiplog)
consoleBus.push( o_skiplog)
consoleBus.push( o_skiplog)
consoleBus.push( o_skiplog)
consoleBus.push('waiting to be moved to the left')
consoleBus.push('.. still waiting ◯') //idza=12
consoleBus.push('@q2=Console is now on left of Logx')
consoleBus.push('@q3=Waiting for Status Bar to be moved to the top')
consoleBus.push('Status Bar moved to the top') //idza=15
consoleBus.push('@q2=Console is now on top of Logx')
consoleBus.push('')
consoleBus.push('waiting to be moved to the right of Logx') //idza=18
consoleBus.push('@q2=Console is now at right of Logx')
consoleBus.push('')
consoleBus.push('Preparing to move the Status Bar') //idza=21
consoleBus.push('Status Bar is at top now')
consoleBus.push('At default location = Bottom of Logx')
consoleBus.push('')
consoleBus.push('Waiting to be detached') //idza=25
consoleBus.push('◁«.. DETACHED from Logx ..»▷')
consoleBus.push('Attachment Test 1 completed ▲')
consoleBus.push('Attachment testing is completed now !!')
//______ xx ______________________________ attachment Testing ends on idza=28
var int commonBusSize = int(str.tonumber(dbus.get(0,0)))
for zc=0 to consoleBus.size() -1
gc:=consoleBus.get(zc)
dbus.set(zc,1,gc)
if str.contains(gc,'Test') and str.contains(gc,'=') and not str.contains(gc,'@q')
gs:=gc
if str.contains(gc,'Test') and str.contains(gc,'completed')
gs:=''
q2pos=str.pos(gc,'@q2=')
q3pos=str.pos(gc,'@q3=')
q4pos=str.pos(gc,'@q4=')
q5pos=str.pos(gc,'@q5=')
q6pos=str.pos(gc,'@q6=')
end=str.length(gc)
gm1:= str.substring(gc,0,na(q2pos)?na(q3pos)?na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos:q3pos:q2pos)
gm2:= na(q2pos) ? '' : str.substring(gc,q2pos+4,na(q3pos)?na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos:q3pos)
gm3:= na(q3pos) ? '' : str.substring(gc,q3pos+4,na(q4pos)?na(q5pos)?na(q6pos)?end:q6pos:q5pos:q4pos)
gm4:= na(q4pos) ? '' : str.substring(gc,q4pos+4,na(q5pos)?na(q6pos)?end:q6pos:q5pos)
gm5:= na(q5pos) ? '' : str.substring(gc,q5pos+4,na(q6pos)?end:q6pos)
gm6:= na(q6pos) ? '' : str.substring(gc,q6pos+4,end)
gm:=gm1+(gm2==''?'':(tab4+gm2))+(gm3==''?'':(tab4+gm3))+(gm4==''?'':(tab4+gm4))+(gm5==''?'':(tab4+gm5))+(gm6==''?'':(tab4+gm6))
if (zc>=299 and zc<=301) or (zc>=321 and zc<=343) or (zc>=348 and zc<=371)
dbus.set(zc, devcolm1, str.replace_all(gm1,'logx.','sit.'))
dbus.set(zc, devcolm2, str.replace_all(gm2,'logx.','sit.'))
dbus.set(zc, devcolm3, str.replace_all(gm3,'logx.','sit.'))
dbus.set(zc, devcolm4, str.replace_all(gm4,'logx.','sit.'))
dbus.set(zc, devcolm5, str.replace_all(gm5,'logx.','sit.'))
dbus.set(zc, devcolm6, str.replace_all(gm6,'logx.','sit.'))
dbus.set(zc, prodcolm1, str.replace_all(gm1,'logx.','demo.'))
dbus.set(zc, prodcolm2, str.replace_all(gm2,'logx.','demo.'))
dbus.set(zc, prodcolm3, str.replace_all(gm3,'logx.','demo.'))
dbus.set(zc, prodcolm4, str.replace_all(gm4,'logx.','demo.'))
dbus.set(zc, prodcolm5, str.replace_all(gm5,'logx.','demo.'))
dbus.set(zc, prodcolm6, str.replace_all(gm6,'logx.','demo.'))
dbus.set(zc, devcollevelL,'zc='+ str.tostring(zc))
dbus.set(zc, prodcollevelL,'zc='+ str.tostring(zc))
dbus.set(zc, devcolmsg, str.replace_all(gm,'console.','sit.'))
dbus.set(zc, prodcolmsg, str.replace_all(gm,'console.','demo.'))
dbus.set(zc, devcolstatusC,'<SIT zc = ' + str.tostring(zc)+' ▶ '+gs+'>')
dbus.set(zc, prodcolstatusC,gs)
dbus.set(zc, devcollevelC,'zc='+ str.tostring(zc))
dbus.set(zc, prodcollevelC,'zc='+ str.tostring(zc))
for x=consoleBus.size() to dbus.rows()-1
dbus.set(x, devcolmsg,'Console testing has been completed #'+str.tostring(x))
dbus.set(x, prodcolmsg,'Console testing has been completed #'+str.tostring(x))
_filled:=true
consoleBus.clear()
// td4 dev.110
|
ETF Holdings and Sectors [SS] | https://www.tradingview.com/script/UnDOkfSb-ETF-Holdings-and-Sectors-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// © Steversteves
//@version=5
indicator("ETF Holdings and Sectors [SS]", overlay=true)
import Steversteves/ETFHoldingsLib/5 as etf
import Steversteves/ETFFinderLib/3 as etfsearch
// Groups
g1 = "Auto vs Manual Select"
g2 = "Performance Timeframe"
g3 = "Plot Options"
g4 = "Search ETFs for Current Ticker"
g5 = "Search by Sector"
g6 = "Search by Interest"
// User Inputs
manual_select = input.string("Auto", "Select ETF Manually or Auto", ["Auto", "SPY", "QQQ", "IWM", "ARKK", "VEA", "BRK.B", "ITA", "BLCR", "VGT", "VIG", "VNQ", "VTV", "XBI", "VUG", "VWO", "XLE", "XLF", "XLV", "DIA", "FNGG", "FNGU", "BNGE", "IXP", "FCOM", "PNQI", "CHPS", "SOXX", "XLK", "MOON", "UFO", "VDC", "IEDI", "VIRS", "FTXG", "JETS", "IYJ", "FXR", "IYC", "XLY", "IYK", "FDIS", "PEJ", "IYT", "FTXR", "XTN", "SEA"], group = g1)
perf_over = input.int(252, "Performance Over # Days", group = g2)
show_top10 = input.bool(true, "Show Top 10 Holdings", group = g3)
show_sectors = input.bool(true, "Show Sectors", group = g3)
search_etfs = input.bool(true, "Search ETFs for Current Ticker", group = g4)
search_sector = input.string("None", "Search by Sector", ["None", "Basic Materials", "Consumer Cyclical", "Financial Services", "Real Estate", "Consumer Defensive", "Healthcare", "Utilities", "Communication Services", "Energy", "Industrials", "Technology"], group = g5)
search_int = input.string("None", "Search area of Interest", ["None", "Aviation", "Food and Foodstuffs", "Transportation", "Maratime", "Gaming", "Computing", "Telecommunications", "Commerce and Stores", "Industrials and Heavy Machinary", "Entertainment", "Finance and Banking", "Real Estate"], group = g6)
// Current Ticker for Auto Select
current = syminfo.ticker
// Colours
color black = color.rgb(0, 0, 0)
color white =color.white
var table data = table.new(position.top_right, 6, 14, bgcolor = black, frame_color = white, frame_width = 3)
annual_performance = request.security(syminfo.tickerid, "D", (close - close[perf_over]) / close[perf_over] * 100)
// Pull ETF Data
[qqq_info1, qqq_info2, qqq_info3, qqq_info4] = etf.qqq_get()
// Search by sector
if search_sector != "None"
[sector_etf_result, sector_etf_holding] = etfsearch.etf_search_sectors(str.tostring(search_sector))
var table sector_table = table.new(position.middle_center, 3, 40, bgcolor = color.blue, frame_color = white, frame_width = 2, border_color = color.gray, border_width = 1)
table.cell(sector_table, 1, 1, text = str.tostring(search_sector), bgcolor = color.blue, text_color = color.white)
table.merge_cells(sector_table, 1, 1, 2, 1)
table.cell(sector_table, 1, 2, text = "ETF", bgcolor = color.blue, text_color = color.white)
table.cell(sector_table, 2, 2, text = "% Holding", bgcolor = color.blue, text_color = color.white)
for i = 0 to array.size(sector_etf_result) - 1
table.cell(sector_table, 1, 3 + i, text = str.tostring(array.get(sector_etf_result, i)), bgcolor = color.blue, text_color = white)
table.cell(sector_table, 2, 3 + i, text = str.tostring(array.get(sector_etf_holding, i)), bgcolor = color.blue, text_color = white)
// Search by Ticker
if search_etfs
[info, comp] = etfsearch.etf_search_ticker(syminfo.ticker)
var table results = table.new(position.bottom_right, 3, 40, bgcolor = color.gray, frame_color = white, frame_width = 3, border_color = color.blue, border_width = 1)
if array.size(info) > 0
table.cell(results, 1, 1, text = "ETF", bgcolor = color.gray, text_color = white)
table.cell(results, 2, 1, text = "% ETF \n Holding", bgcolor = color.gray, text_color = white)
for i = 0 to array.size(info) - 1
table.cell(results, 1, 2 + i, text = str.tostring(array.get(info, i)), bgcolor = color.gray, text_color = color.white)
for i = 0 to array.size(comp) - 1
table.cell(results, 2, 2 + i, text = str.tostring(array.get(comp, i)) + "%", bgcolor = color.gray, text_color = color.white)
// Search by Intereste
f_search_interest(interest_input) =>
output = array.new<string>()
if interest_input == "Aviation"
array.push(output, "ITA")
array.push(output, "JETS")
array.push(output, "IYT")
array.push(output, "IYJ")
if interest_input == "Food and Foodstuffs"
array.push(output, "VDC")
array.push(output, "IEDI")
array.push(output, "PEJ")
if interest_input == "Transportation"
array.push(output, "SEA")
array.push(output, "IYT")
array.push(output, "FTXR")
array.push(output, "XTN")
if interest_input == "Maratime"
array.push(output, "SEA")
array.push(output, "PEJ")
if interest_input == "Gaming"
array.push(output, "BNGE")
array.push(output, "CHPS")
array.push(output, "SOXX")
if interest_input == "Computing"
array.push(output, "SOXX")
array.push(output, "CHPS")
array.push(output, "FNGG")
array.push(output, "FNGU")
array.push(output, "BLCR")
array.push(output, "PNQI")
if interest_input == "Telecommunications"
array.push(output, "FCOM")
array.push(output, "CHPS")
array.push(output, "IXP")
array.push(output, "UFO")
if interest_input == "Commerce and Stores"
array.push(output, "VDC")
array.push(output, "IEDI")
array.push(output, "VIRS")
array.push(output, "IYC")
if interest_input == "Industrials and Heavy Machinary"
array.push(output, "IYJ")
array.push(output, "ITA")
array.push(output, "SEA")
array.push(output, "DIA")
if interest_input == "Entertainment"
array.push(output, "PEJ")
array.push(output, "JETS")
if interest_input == "Finance and Banking"
array.push(output, "XLF")
array.push(output, "VIG")
array.push(output, "VTV")
array.push(output, "BRK.B")
if interest_input == "Real Estate"
array.push(output, "VNQ")
output
if search_int != "None" and search_sector == "None"
output_array = f_search_interest(str.tostring(search_int))
var table sector_table = table.new(position.middle_center, 3, 40, bgcolor = color.blue, frame_color = white, frame_width = 2, border_color = color.gray, border_width = 1)
table.cell(sector_table, 1, 1, text = str.tostring(search_int), bgcolor = color.blue, text_color = color.white)
for i = 0 to array.size(output_array) - 1
table.cell(sector_table, 1, i + 2, text = str.tostring(array.get(output_array, i)), bgcolor = color.blue, text_color = color.white)
// PLOT ETF Data
if current == "SPY" or current == "UPRO" or current == "SPXL" or current == "SPXS" or current == "SPXU" or manual_select == "SPY"
[spy_info1, spy_info2, spy_info3, spy_info4] = etf.spy_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(spy_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(spy_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(spy_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(spy_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(spy_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(spy_info4, i)), bgcolor = black, text_color = color.white)
if current == "QQQ" or current == "TQQQ" or current == "SQQQ" or manual_select == "QQQ"
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(qqq_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(qqq_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(qqq_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(qqq_info4, i)), bgcolor = black, text_color = color.white)
if current == "IWM" or current == "TNA" or current == "TZA" or manual_select == "IWM"
[iwm_info1, iwm_info2, iwm_info3, iwm_info4] = etf.iwm_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iwm_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iwm_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iwm_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iwm_info4, i)), bgcolor = black, text_color = color.white)
if current == "ARKK"or current == "SARK" or manual_select == "ARKK"
[arkk_info1, arkk_info2, arkk_info3, arkk_info4] = etf.arkk_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(arkk_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(arkk_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(arkk_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(arkk_info4, i)), bgcolor = black, text_color = color.white)
if current == "VEA" or manual_select == "VEA"
[vea_info1, vea_info2, vea_info3, vea_info4] = etf.vea_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vea_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vea_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vea_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vea_info4, i)), bgcolor = black, text_color = color.white)
if current == "BRK.B" or manual_select == "BRK.B"
[brk_info1, brk_info2, brk_info3, brk_info4] = etf.brk_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(brk_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(brk_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(brk_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(brk_info4, i)), bgcolor = black, text_color = color.white)
if current == "ITA" or manual_select == "ITA" or current == "DFEN"
[ita_info1, ita_info2, ita_info3, ita_info4] = etf.ita_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(ita_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(ita_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(ita_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(ita_info4, i)), bgcolor = black, text_color = color.white)
if current == "BLCR" or manual_select == "BLCR"
[blcr_info1, blcr_info2, blcr_info3, blcr_info4] = etf.blcr_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(blcr_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(blcr_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(blcr_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(blcr_info4, i)), bgcolor = black, text_color = color.white)
if current == "VGT" or manual_select == "VGT"
[vgt_info1, vgt_info2, vgt_info3, vgt_info4] = etf.vgt_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vgt_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vgt_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vgt_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vgt_info4, i)), bgcolor = black, text_color = color.white)
if current == "VIG" or manual_select == "VIG"
[vig_info1, vig_info2, vig_info3, vig_info4] =etf.vig_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vig_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vig_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vig_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vig_info4, i)), bgcolor = black, text_color = color.white)
if current == "VNQ" or manual_select == "VNQ"
[vnq_info1, vnq_info2, vnq_info3, vnq_info4] = etf.vnq_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vnq_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vnq_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vnq_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vnq_info4, i)), bgcolor = black, text_color = color.white)
if current == "VTV" or manual_select == "VTV"
[vtv_info1, vtv_info2, vtv_info3, vtv_info4] = etf.vtv_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vtv_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vtv_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vtv_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vtv_info4, i)), bgcolor = black, text_color = color.white)
if current == "XBI" or current == "LABU" or current == "LABD" or manual_select == "XBI"
[xbi_info1, xbi_info2, xbi_info3, xbi_info4] = etf.xbi_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xbi_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xbi_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xbi_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xbi_info4, i)), bgcolor = black, text_color = color.white)
if current == "VUG" or manual_select == "VUG"
[vug_info1, vug_info2, vug_info3, vug_info4] = etf.vug_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vug_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vug_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vug_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vug_info4, i)), bgcolor = black, text_color = color.white)
if current == "VWO" or manual_select == "VWO"
[vwo_info1, vwo_info2, vwo_info3, vwo_info4] = etf.vwo_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vwo_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vwo_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vwo_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vwo_info4, i)), bgcolor = black, text_color = color.white)
if current == "XLE" or manual_select == "XLE"
[xle_info1, xle_info2, xle_info3, xle_info4] = etf.xle_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xle_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xle_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xle_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xle_info4, i)), bgcolor = black, text_color = color.white)
if current == "XLF" or manual_select == "XLF"
[xlf_info1, xlf_info2, xlf_info3, xlf_info4] = etf.xlf_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xlf_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xlf_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xlf_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xlf_info4, i)), bgcolor = black, text_color = color.white)
if current == "XLV" or manual_select == "XLV"
[xlv_info1, xlv_info2, xlv_info3, xlv_info4] = etf.xlv_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xlv_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xlv_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xlv_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xlv_info4, i)), bgcolor = black, text_color = color.white)
if current == "DIA" or manual_select == "DIA"
[dia_info1, dia_info2, dia_info3, dia_info4] = etf.dia_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(dia_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(dia_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(dia_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(dia_info4, i)), bgcolor = black, text_color = color.white)
if current == "FNGG" or manual_select == "FNGG"
[fngg_info1, fngg_info2, fngg_info3, fngg_info4] = etf.fngg_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(fngg_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(fngg_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(fngg_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(fngg_info4, i)), bgcolor = black, text_color = color.white)
if current == "FNGU" or manual_select == "FNGU"
[fngu_info1, fngu_info2, fngu_info3, fngu_info4] = etf.fngu_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(fngu_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(fngu_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(fngu_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(fngu_info4, i)), bgcolor = black, text_color = color.white)
if current == "BNGE" or manual_select == "BNGE"
[bnge_info1, bnge_info2, bnge_info3, bnge_info4] = etf.bnge_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(bnge_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(bnge_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(bnge_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(bnge_info4, i)), bgcolor = black, text_color = color.white)
if current == "IXP" or manual_select == "IXP"
[ixp_info1, ixp_info2, ixp_info3, ixp_info4] = etf.ixp_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(ixp_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(ixp_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(ixp_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(ixp_info4, i)), bgcolor = black, text_color = color.white)
if current == "FCOM" or manual_select == "FCOM"
[fcom_info1, fcom_info2, fcom_info3, fcom_info4] = etf.fcom_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(fcom_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(fcom_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(fcom_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(fcom_info4, i)), bgcolor = black, text_color = color.white)
if current == "PNQI" or manual_select == "PNQI"
[pnqi_info1, pnqi_info2, pnqi_info3, pnqi_info4] = etf.pnqi_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(pnqi_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(pnqi_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(pnqi_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(pnqi_info4, i)), bgcolor = black, text_color = color.white)
if current == "CHPS" or manual_select == "CHPS"
[chps_info1, chps_info2, chps_info3, chps_info4] = etf.chps_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(chps_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(chps_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(chps_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(chps_info4, i)), bgcolor = black, text_color = color.white)
if current == "SOXX" or manual_select == "SOXX"
[soxx_info1, soxx_info2, soxx_info3, soxx_info4] = etf.soxx_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(soxx_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(soxx_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(soxx_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(soxx_info4, i)), bgcolor = black, text_color = color.white)
if current == "XLK" or manual_select == "XLK"
[xlk_info1, xlk_info2, xlk_info3, xlk_info4] = etf.xlk_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xlk_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xlk_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xlk_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xlk_info4, i)), bgcolor = black, text_color = color.white)
if current == "MOON" or manual_select == "MOON"
[moon_info1, moon_info2, moon_info3, moon_info4] = etf.moon_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(moon_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(moon_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(moon_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(moon_info4, i)), bgcolor = black, text_color = color.white)
if current == "UFO" or manual_select == "UFO"
[ufo_info1, ufo_info2, ufo_info3, ufo_info4] = etf.ufo_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(ufo_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(ufo_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(ufo_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(ufo_info4, i)), bgcolor = black, text_color = color.white)
if current == "VDC" or manual_select == "VDC"
[vdc_info1, vdc_info2, vdc_info3, vdc_info4] = etf.vdc_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(vdc_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(vdc_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(vdc_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(vdc_info4, i)), bgcolor = black, text_color = color.white)
if current == "IEDI" or manual_select == "IEDI"
[iedi_info1, iedi_info2, iedi_info3, iedi_info4] = etf.iedi_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iedi_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iedi_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iedi_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iedi_info4, i)), bgcolor = black, text_color = color.white)
if current == "VIRS" or manual_select == "VIRS"
[virs_info1, virs_info2, virs_info3, virs_info4] = etf.virs_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(virs_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(virs_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(virs_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(virs_info4, i)), bgcolor = black, text_color = color.white)
if current == "FTXG" or manual_select == "FTXG"
[ftxg_info1, ftxg_info2, ftxg_info3, ftxg_info4] = etf.ftxg_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(ftxg_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(ftxg_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(ftxg_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(ftxg_info4, i)), bgcolor = black, text_color = color.white)
if current == "JETS" or manual_select == "JETS"
[jets_info1, jets_info2, jets_info3, jets_info4] = etf.jets_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(jets_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(jets_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(jets_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(jets_info4, i)), bgcolor = black, text_color = color.white)
if current == "IYJ" or manual_select == "IYJ"
[iyj_info1, iyj_info2, iyj_info3, iyj_info4] = etf.iyj_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iyj_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iyj_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iyj_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iyj_info4, i)), bgcolor = black, text_color = color.white)
if current == "FXR" or manual_select == "FXR"
[fxr_info1, fxr_info2, fxr_info3, fxr_info4] = etf.fxr_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(fxr_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(fxr_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(fxr_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(fxr_info4, i)), bgcolor = black, text_color = color.white)
if current == "IYC" or manual_select == "IYC"
[iyc_info1, iyc_info2, iyc_info3, iyc_info4] = etf.iyc_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iyc_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iyc_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iyc_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iyc_info4, i)), bgcolor = black, text_color = color.white)
if current == "XLY" or manual_select == "XLY"
[xly_info1, xly_info2, xly_info3, xly_info4] = etf.xly_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xly_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xly_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xly_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xly_info4, i)), bgcolor = black, text_color = color.white)
if current == "IYK" or manual_select == "IYK"
[iyk_info1, iyk_info2, iyk_info3, iyk_info4] = etf.iyk_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iyk_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iyk_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iyk_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iyk_info4, i)), bgcolor = black, text_color = color.white)
if current == "FDIS" or manual_select == "FDIS"
[fdis_info1, fdis_info2, fdis_info3, fdis_info4] = etf.fdis_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(fdis_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(fdis_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(fdis_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(fdis_info4, i)), bgcolor = black, text_color = color.white)
if current == "PEJ" or manual_select == "PEJ"
[pej_info1, pej_info2, pej_info3, pej_info4] = etf.pej_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(pej_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(pej_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(pej_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(pej_info4, i)), bgcolor = black, text_color = color.white)
if current == "IYT" or manual_select == "IYT"
[iyt_info1, iyt_info2, iyt_info3, iyt_info4] = etf.iyt_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(iyt_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(iyt_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(iyt_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(iyt_info4, i)), bgcolor = black, text_color = color.white)
if current == "FTXR" or manual_select == "FTXR"
[ftxr_info1, ftxr_info2, ftxr_info3, ftxr_info4] = etf.ftxr_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(ftxr_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(ftxr_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(ftxr_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(ftxr_info4, i)), bgcolor = black, text_color = color.white)
if current == "XTN" or manual_select == "XTN"
[xtn_info1, xtn_info2, xtn_info3, xtn_info4] = etf.xtn_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(xtn_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(xtn_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(xtn_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(xtn_info4, i)), bgcolor = black, text_color = color.white)
if current == "SEA" or manual_select == "SEA"
[sea_info1, sea_info2, sea_info3, sea_info4] = etf.sea_get()
table.cell(data, 1, 12, text = "Performance over \n" + str.tostring(perf_over) + " Days", bgcolor = black, text_color = color.white)
table.cell(data, 2, 12, text = str.tostring(math.round(annual_performance,2)) + "%", bgcolor = black, text_color = annual_performance > 0 ? color.lime : color.red)
if show_top10
table.cell(data, 1, 1, text = "Top 10 \n Holdings", bgcolor = black, text_color = color.white)
table.cell(data, 2, 1, text = "Top 10 \n Holdings %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info1) - 1
table.cell(data, 1, 2 + i, text = str.tostring(array.get(sea_info1, i)), bgcolor = black, text_color = color.white)
table.cell(data, 2, 2 + i, text = str.tostring(array.get(sea_info2, i)), bgcolor = black, text_color = color.white)
if show_sectors
table.cell(data, 3, 1, text = "Sector \n Breakdown", bgcolor = black, text_color = color.white)
table.cell(data, 4, 1, text = "Sector \n Breakdown %", bgcolor = black, text_color = color.white)
for i = 0 to array.size(qqq_info3) - 1
table.cell(data, 3, 2 + i, text = str.tostring(array.get(sea_info3, i)), bgcolor = black, text_color = color.white)
table.cell(data, 4, 2 + i, text = str.tostring(array.get(sea_info4, i)), bgcolor = black, text_color = color.white)
|
One Setup for Life ICT | https://www.tradingview.com/script/9RE75oTe/ | minerlancer | https://www.tradingview.com/u/minerlancer/ | 35 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © minerlancer
//@version=5
indicator('One Setup for Life ICT' , overlay = true , precision = 0 , max_boxes_count = 500 , max_labels_count = 500 , max_lines_count = 500 , max_bars_back = 500)
max_tf = input.int(defval = 60 , title = 'Max TF Show ' , inline = '0' , group = 'Input')
max_line = input.int(defval = 500 , title = 'Max Bars Back' , maxval = 500 , inline = '0' , group = 'Input')
Timezone = 'America/New_York'
DOM = (timeframe.multiplier <= max_tf) and (timeframe.isintraday)
//--------------
//---Function
//--------------
is_newbar(sess) =>
t = time('D', sess, Timezone)
na(t[1]) and not na(t) or t[1] < t
is_session(sess) =>
not na(time('D', sess, Timezone))
//--------------
//---End Function
//--------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
// Divider Daily and open NY
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
//---Input
show_daily= input.bool(defval = true , title = 'Daily' , inline = 'divider' , inline = '0' , group = 'Divider')
col_D = input.color(defval = color.new(color.gray,85) , title = '' , inline = '0' , group = 'Divider')
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
// One set up for life
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
show_Sess = input.bool(defval = false , title = 'Session ' , inline = '00' , group = 'Session One Set Up for Life')
show_Box_Sess = input.bool(defval = true , title = 'Box ' , inline = '00' , group = 'Session One Set Up for Life')
show_txt_box = input.bool(defval = true , title = 'Text Box ' , inline = '00' , group = 'Session One Set Up for Life')
show_Tody_Lin_Sess = input.bool(defval = false , title = 'Today H/L' , inline = '01' , group = 'Session One Set Up for Life')
show_txt_Lin_Sess = input.bool(defval = false , title = 'Text ' , inline = '01' , group = 'Session One Set Up for Life')
show_price_ses = input.bool(defval = false , title = 'Price' , inline = '01' , group = 'Session One Set Up for Life')
show_Prev_Lin_Sess = input.bool(defval = true , title = 'Prev. H/L ' , inline = '02' , group = 'Session One Set Up for Life')
Show_OND = input.bool(defval = false , title = 'Show Only for Today' , inline = '02' , group = 'Session One Set Up for Life')
choise_start_OSFL = input.string(defval = '09:30' , title = 'Start time when you take Prev.H/L' , options = ['08:30' , '09:30'] , inline = '03' , group = 'Session One Set Up for Life')
show_line_start = input.bool(defval = true , title = 'Line Start' , inline = '03' , group = 'Session One Set Up for Life')
col_line_start = input.color(defval = color.new(color.orange,60) , title = '' , inline = '03' , group = 'Session One Set Up for Life')
show_Sess_0 = input.bool(defval = false , title = 'London' , inline = '0' , group = 'Session One Set Up for Life')
Sess_0 = '0200-0500'
col_Sess_0 = input.color(defval = color.blue , title = '' , inline = '1' , group = 'Session One Set Up for Life')
txt_Sess_0 = 'London'
show_Sess_1 = input.bool(defval = false , title = 'Prev.AM' , inline = '0' , group = 'Session One Set Up for Life')
Sess_1 = '0930-1200'
col_Sess_1 = input.color(defval = color.red , title = ' ' , inline = '1' , group = 'Session One Set Up for Life')
txt_Sess_1 = 'Prev.AM'
show_Sess_2 = input.bool(defval = false , title = 'Lunch' , inline = '0' , group = 'Session One Set Up for Life')
Sess_2 = '1200-1330'
col_Sess_2 = input.color(defval = color.yellow , title = ' ' , inline = '1' , group = 'Session One Set Up for Life')
txt_Sess_2 = 'Lunch'
show_Sess_3 = input.bool(defval = false , title = 'PM' , inline = '0' , group = 'Session One Set Up for Life')
Sess_3 = '1330-1600'
col_Sess_3 = input.color(defval = color.purple , title = ' ' , inline = '1' , group = 'Session One Set Up for Life')
txt_Sess_3 = 'PM'
time_start = choise_start_OSFL == '08:30' ? timestamp(Timezone , year , month , dayofmonth , 8, 30 , 00) : timestamp(Timezone , year , month , dayofmonth , 9, 30 , 00)
// Daily Dividers
is_new_session = time(timeframe.period, '0000-0001', Timezone)
is_line_start = choise_start_OSFL == '08:30' ? time(timeframe.period, '0830-0831', Timezone) : time(timeframe.period, '0930-0931', Timezone)
var line D_open = na
var line Ny_open = na
if is_new_session and show_daily and DOM
D_open := line.new(bar_index , bar_index , bar_index , bar_index + 1 , extend = extend.both , color = col_D , style = line.style_solid)
if is_line_start and show_line_start and DOM
Ny_open := line.new(bar_index , bar_index , bar_index , bar_index + 1 , extend = extend.both , color = col_line_start , style = line.style_dotted)
//--------------
//---Text Box
//--------------
if DOM and show_Sess
var float top_bottom = 0
var color kz_color = na
var bool in_kz = na
var string kz_text = na
if show_txt_box
if show_Sess_0 and time(timeframe.period, Sess_0 , Timezone)
in_kz := true
kz_color := color.new(col_Sess_0 , 80)
kz_text := txt_Sess_0
else if show_Sess_1 and time(timeframe.period, Sess_1 , Timezone)
in_kz := true
kz_color := color.new(col_Sess_1 , 80)
kz_text := txt_Sess_1
else if show_Sess_2 and time(timeframe.period, '1201-1330' , Timezone)
in_kz := true
kz_color := color.new(col_Sess_2 , 80)
kz_text := txt_Sess_2
else if show_Sess_3 and time(timeframe.period, '1331-1600' , Timezone)
in_kz := true
kz_color := color.new(col_Sess_3 , 80)
kz_text := txt_Sess_3
else
in_kz := false
else
in_kz := true
var box kz_box = na
var line kz_start_line = na
var line kz_end_line = na
if show_txt_box
if in_kz and not in_kz[1]
kz_box := box.new(bar_index, high, bar_index, low, border_color = color.new(color.red, 100), bgcolor = kz_color, text = kz_text , text_size = size.small)
kz_start_line := line.new(bar_index, high, bar_index, box.get_top(kz_box), color = kz_color, style = line.style_dotted)
top_bottom := 0
if in_kz[1]
box.set_right(kz_box, bar_index)
if high>box.get_bottom(kz_box)
box.set_bottom(kz_box,1.0010* high)
box.set_top(kz_box,1.0015*high)
line.set_y2(kz_start_line, box.get_top(kz_box))
if in_kz[1] and not in_kz
kz_end_line := line.new(bar_index, high, bar_index, box.get_top(kz_box), color = kz_color, style = line.style_dotted)
//--------------
//---High Low Prev Session
//--------------
if DOM and show_Sess and show_Sess_0 and show_Box_Sess
var box box_sess_0 = na
if is_newbar(Sess_0)
box_sess_0 := box.new(bar_index, high, bar_index, low , border_color = color.new(#c78234, 100) , bgcolor = color.new(col_Sess_0 , 90))
if Show_OND
box.delete(box_sess_0[1])
else if is_session(Sess_0)
box.set_right(box_sess_0, bar_index+1)
if high > box.get_top(box_sess_0)
box.set_top(box_sess_0, high)
if low < box.get_bottom(box_sess_0)
box.set_bottom(box_sess_0, low)
var bool can_draw_high_sess_0 = false
var bool can_draw_low_sess_0 = false
var line high_sess_0 = na
var line low_sess_0 = na
var label LBhigh_sess_0 = na
var label LBlow_sess_0 = na
if (is_new_session) and show_Sess_0 and show_Prev_Lin_Sess
can_draw_high_sess_0 := true
can_draw_low_sess_0 := true
high_sess_0 := line.new(bar_index, box.get_top(box_sess_0), bar_index, box.get_top(box_sess_0), color = col_Sess_0) // Get new line id
low_sess_0 := line.new(bar_index, box.get_bottom(box_sess_0), bar_index, box.get_bottom(box_sess_0), color = col_Sess_0)
if Show_OND
line.delete(high_sess_0[2])
line.delete(low_sess_0[2])
if show_txt_Lin_Sess
LBhigh_sess_0 := label.new(x = last_bar_index , y = box.get_top(box_sess_0) , text = show_price_ses ? txt_Sess_0 +' High '+ str.tostring(box.get_top(box_sess_0)) : txt_Sess_0 +' High ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_down, textcolor = col_Sess_0 , textalign = text.align_right , tooltip = 'Prev.PM High' )
LBlow_sess_0 := label.new(x = last_bar_index , y = box.get_bottom(box_sess_0) , text = show_price_ses ? txt_Sess_0 +' Low ' +str.tostring(box.get_bottom(box_sess_0)): txt_Sess_0 +' Low ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_center, textcolor = col_Sess_0 , textalign = text.align_right , tooltip = 'Prev.PM Low')
label.delete(LBhigh_sess_0[1])
label.delete(LBlow_sess_0[1])
else
if (can_draw_high_sess_0)
if (time > (time_start + 0 * 1000*60) and high > line.get_y1(high_sess_0))
can_draw_high_sess_0 := false
label.delete(LBhigh_sess_0[0])
else
line.set_x2(high_sess_0, bar_index)
if (can_draw_low_sess_0)
if (time > (time_start + 0 * 1000*60) and low < line.get_y1(low_sess_0))
can_draw_low_sess_0 := false
label.delete(LBlow_sess_0[0])
else
line.set_x2(low_sess_0, bar_index)
// _1
if DOM and show_Sess and show_Sess_1 and show_Box_Sess
var box box_sess_1 = na
if is_newbar(Sess_1)
box_sess_1 := box.new(bar_index, high, bar_index, low , border_color = color.new(#c78234, 100), bgcolor = color.new(col_Sess_1 , 90))
if Show_OND
box.delete(box_sess_1[1])
else if is_session(Sess_1)
box.set_right(box_sess_1, bar_index+1)
if high > box.get_top(box_sess_1)
box.set_top(box_sess_1, high)
if low < box.get_bottom(box_sess_1)
box.set_bottom(box_sess_1, low)
var bool can_draw_high_sess_1 = false
var bool can_draw_low_sess_1 = false
var line high_sess_1 = na
var line low_sess_1 = na
var label LBhigh_sess_1 = na
var label LBlow_sess_1 = na
if (is_new_session) and show_Sess_1 and show_Prev_Lin_Sess
can_draw_high_sess_1 := true
can_draw_low_sess_1 := true
high_sess_1 := line.new(bar_index, box.get_top(box_sess_1), bar_index, box.get_top(box_sess_1), color = col_Sess_1) // Get new line id
low_sess_1 := line.new(bar_index, box.get_bottom(box_sess_1), bar_index, box.get_bottom(box_sess_1), color = col_Sess_1)
if Show_OND
line.delete(high_sess_1[2])
line.delete(low_sess_1[2])
if show_txt_Lin_Sess
LBhigh_sess_1 := label.new(x = last_bar_index , y = box.get_top(box_sess_1) , text = show_price_ses ? txt_Sess_1 +' High '+ str.tostring(box.get_top(box_sess_1)) : txt_Sess_1 +' High ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_down, textcolor = col_Sess_1 , textalign = text.align_right , tooltip = 'Prev.PM High' )
LBlow_sess_1 := label.new(x = last_bar_index , y = box.get_bottom(box_sess_1) , text = show_price_ses ? txt_Sess_1 +' Low ' +str.tostring(box.get_bottom(box_sess_1)): txt_Sess_1 +' Low ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_center, textcolor = col_Sess_1 , textalign = text.align_right , tooltip = 'Prev.PM Low')
label.delete(LBhigh_sess_1[1])
label.delete(LBlow_sess_1[1])
else
if (can_draw_high_sess_1)
if (time > (time_start + 0 * 1000*60) and high > line.get_y1(high_sess_1))
can_draw_high_sess_1 := false
label.delete(LBhigh_sess_1[0])
else
line.set_x2(high_sess_1, bar_index)
if (can_draw_low_sess_1)
if (time > (time_start + 0 * 1000*60) and low < line.get_y1(low_sess_1))
can_draw_low_sess_1 := false
label.delete(LBlow_sess_1[0])
else
line.set_x2(low_sess_1, bar_index)
// _2
if DOM and show_Sess and show_Sess_2 and show_Box_Sess
var box box_sess_2 = na
if is_newbar(Sess_2)
box_sess_2 := box.new(bar_index, high, bar_index, low , border_color = color.new(#c78234, 100) , bgcolor = color.new(col_Sess_2 , 90))
if Show_OND
box.delete(box_sess_2[1])
else if is_session(Sess_2)
box.set_right(box_sess_2, bar_index+1)
if high > box.get_top(box_sess_2)
box.set_top(box_sess_2, high)
if low < box.get_bottom(box_sess_2)
box.set_bottom(box_sess_2, low)
var bool can_draw_high_sess_2 = false
var bool can_draw_low_sess_2 = false
var line high_sess_2 = na
var line low_sess_2 = na
var label LBhigh_sess_2 = na
var label LBlow_sess_2 = na
if (is_new_session) and show_Sess_2 and show_Prev_Lin_Sess
can_draw_high_sess_2 := true
can_draw_low_sess_2 := true
high_sess_2 := line.new(bar_index, box.get_top(box_sess_2), bar_index, box.get_top(box_sess_2), color = col_Sess_2) // Get new line id
low_sess_2 := line.new(bar_index, box.get_bottom(box_sess_2), bar_index, box.get_bottom(box_sess_2), color = col_Sess_2)
if Show_OND
line.delete(high_sess_2[2])
line.delete(low_sess_2[2])
if show_txt_Lin_Sess
LBhigh_sess_2 := label.new(x = last_bar_index , y = box.get_top(box_sess_2) , text = show_price_ses ? txt_Sess_2 +' High '+ str.tostring(box.get_top(box_sess_2)) : txt_Sess_2 +' High ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_down, textcolor = col_Sess_2 , textalign = text.align_right , tooltip = 'Prev.PM High' )
LBlow_sess_2 := label.new(x = last_bar_index , y = box.get_bottom(box_sess_2) , text = show_price_ses ? txt_Sess_2 +' Low ' +str.tostring(box.get_bottom(box_sess_2)): txt_Sess_2 +' Low ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_center, textcolor = col_Sess_2 , textalign = text.align_right , tooltip = 'Prev.PM Low')
label.delete(LBhigh_sess_2[1])
label.delete(LBlow_sess_2[1])
else
if (can_draw_high_sess_2)
if (time > (time_start + 0 * 1000*60) and high > line.get_y1(high_sess_2))
can_draw_high_sess_2 := false
label.delete(LBhigh_sess_2[0])
else
line.set_x2(high_sess_2, bar_index)
if (can_draw_low_sess_2)
if (time > (time_start + 0 * 1000*60) and low < line.get_y1(low_sess_2))
can_draw_low_sess_2 := false
label.delete(LBlow_sess_2[0])
else
line.set_x2(low_sess_2, bar_index)
// -3
if DOM and show_Sess and show_Sess_3 and show_Box_Sess
var box box_sess_3 = na
if is_newbar(Sess_3)
box_sess_3 := box.new(bar_index, high, bar_index, low , border_color = color.new(#c78234, 100), bgcolor = color.new(col_Sess_3 , 90))
if Show_OND
box.delete(box_sess_3[2])
else if is_session(Sess_3)
box.set_right(box_sess_3, bar_index+1)
if high > box.get_top(box_sess_3)
box.set_top(box_sess_3, high)
if low < box.get_bottom(box_sess_3)
box.set_bottom(box_sess_3, low)
var bool can_draw_high_sess_3 = false
var bool can_draw_low_sess_3 = false
var line high_sess_3 = na
var line low_sess_3 = na
var label LBhigh_sess_3 = na
var label LBlow_sess_3 = na
if (is_new_session) and show_Sess_3 and show_Prev_Lin_Sess
can_draw_high_sess_3 := true
can_draw_low_sess_3 := true
high_sess_3 := line.new(bar_index, box.get_top(box_sess_3), bar_index, box.get_top(box_sess_3), color = col_Sess_3) // Get new line id
low_sess_3 := line.new(bar_index, box.get_bottom(box_sess_3), bar_index, box.get_bottom(box_sess_3), color = col_Sess_3)
if Show_OND
line.delete(high_sess_3[3])
line.delete(low_sess_3[3])
if show_txt_Lin_Sess
LBhigh_sess_3 := label.new(x = last_bar_index , y = box.get_top(box_sess_3) , text = show_price_ses ? txt_Sess_3 +' High '+ str.tostring(box.get_top(box_sess_3)) : txt_Sess_3 +' High ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_down, textcolor = col_Sess_3 , textalign = text.align_right , tooltip = 'Prev.PM High' )
LBlow_sess_3 := label.new(x = last_bar_index , y = box.get_bottom(box_sess_3) , text = show_price_ses ? txt_Sess_3 +' Low ' +str.tostring(box.get_bottom(box_sess_3)): txt_Sess_3 +' Low ', xloc = xloc.bar_index , yloc = yloc.price , color = na , style = label.style_label_center, textcolor = col_Sess_3 , textalign = text.align_right , tooltip = 'Prev.PM Low')
label.delete(LBhigh_sess_3[1])
label.delete(LBlow_sess_3[1])
else
if (can_draw_high_sess_3)
if (time > (time_start + 0 * 1000*60) and high > line.get_y1(high_sess_3))
can_draw_high_sess_3 := false
label.delete(LBhigh_sess_3[0])
else
line.set_x2(high_sess_3, bar_index)
if (can_draw_low_sess_3)
if (time > (time_start + 0 * 1000*60) and low < line.get_y1(low_sess_3))
can_draw_low_sess_3 := false
label.delete(LBlow_sess_3[0])
else
line.set_x2(low_sess_3, bar_index)
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
// Today H/L + Taken
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
//Sessions
//---Ln
sess_today_LN = time(timeframe.period , Sess_0 , Timezone)
var float h_ses_LN = na
var float l_ses_LN = na
var line line_H_LN = na
var line line_L_LN = na
var label labe_H_LN = na
var label labe_L_LN = na
var float line_H_LN_value = na
var float line_L_LN_value = na
var float labe_L_LN_value = na
if sess_today_LN
if high >= nz(h_ses_LN, 0)
h_ses_LN := high
else
h_ses_LN := h_ses_LN
if low <= nz(l_ses_LN, high)
l_ses_LN := low
else
l_ses_LN := l_ses_LN
else
h_ses_LN := na
l_ses_LN := na
start_H_LN = ta.valuewhen(na(h_ses_LN[1]) and h_ses_LN, bar_index, 0)
start_L_LN = ta.valuewhen(na(l_ses_LN[1]) and l_ses_LN, bar_index, 0)
//---pre_AM
sess_today_pre_AM = time(timeframe.period , Sess_1 , Timezone)
var float h_ses_prev_AM = na
var float l_ses_prev_AM = na
var line line_H_prev_AM = na
var line line_L_prev_AM = na
var float line_H_prev_AM_value = na
var float line_L_prev_AM_value = na
if sess_today_pre_AM
if high >= nz(h_ses_prev_AM, 0)
h_ses_prev_AM := high
else
h_ses_prev_AM := h_ses_prev_AM
if low <= nz(l_ses_prev_AM, high)
l_ses_prev_AM := low
else
l_ses_prev_AM := l_ses_prev_AM
else
h_ses_prev_AM := na
l_ses_prev_AM := na
start_H_prev_AM = ta.valuewhen(na(h_ses_prev_AM[1]) and h_ses_prev_AM, bar_index, 0)
start_L_prev_AM = ta.valuewhen(na(l_ses_prev_AM[1]) and l_ses_prev_AM, bar_index, 0)
//---Lunch
sess_today_Lunch = time(timeframe.period , Sess_2 , Timezone)
var float h_ses_LC = na
var float l_ses_LC = na
var line line_H_LC = na
var line line_L_LC = na
var float line_H_LC_value = na
var float line_L_LC_value = na
if sess_today_Lunch
if high >= nz(h_ses_LC, 0)
h_ses_LC := high
else
h_ses_LC := h_ses_LC
if low <= nz(l_ses_LC, high)
l_ses_LC := low
else
l_ses_LC := l_ses_LC
else
h_ses_LC := na
l_ses_LC := na
start_H_LC = ta.valuewhen(na(h_ses_LC[1]) and h_ses_LC, bar_index, 0)
start_L_LC = ta.valuewhen(na(l_ses_LC[1]) and l_ses_LC, bar_index, 0)
//---PM
sess_today_PM = time(timeframe.period , Sess_3 , Timezone)
var float h_ses_PM = na
var float l_ses_PM = na
var line line_H_PM = na
var line line_L_PM = na
var float line_H_PM_value = na
var float line_L_PM_value = na
if sess_today_PM
if high >= nz(h_ses_PM, 0)
h_ses_PM := high
else
h_ses_PM := h_ses_PM
if low <= nz(l_ses_PM, high)
l_ses_PM := low
else
l_ses_PM := l_ses_PM
else
h_ses_PM := na
l_ses_PM := na
start_H_PM = ta.valuewhen(na(h_ses_PM[1]) and h_ses_PM, bar_index, 0)
start_L_PM = ta.valuewhen(na(l_ses_PM[1]) and l_ses_PM, bar_index, 0)
//---Plot H/L lines
//---LN to NY
if show_Tody_Lin_Sess and DOM
if sess_today_LN and show_Sess_0
line_H_LN_value := h_ses_LN
line_L_LN_value := l_ses_LN
if sess_today_pre_AM
line_H_prev_AM_value := h_ses_prev_AM
line_L_prev_AM_value := l_ses_prev_AM
if sess_today_Lunch
line_H_LC_value := h_ses_LC
line_L_LC_value := l_ses_LC
if sess_today_PM
line_H_PM_value := h_ses_PM
line_L_PM_value := l_ses_PM
isToday = dayofweek(time) == dayofweek(timenow)
sess_to = time(timeframe.period , '0500-0930' , Timezone)
take_col_H_LN = line_H_prev_AM_value > line_H_LN_value
take_col_L_LN = line_L_prev_AM_value < line_L_LN_value
col_H_LN = take_col_H_LN ? col_Sess_0 : na
col_L_LN = take_col_L_LN ? col_Sess_0 : na
plot(isToday and show_Sess and show_Tody_Lin_Sess and DOM and sess_to ? line_H_LN_value : na , '' , col_H_LN , 1 , plot.style_steplinebr) , plot(isToday and show_Sess and not sess_today_LN and DOM and not take_col_H_LN ? line_H_LN_value : na , '' , col_H_LN , 1 , plot.style_steplinebr)
plot(isToday and show_Sess and show_Tody_Lin_Sess and DOM and sess_to ? line_L_LN_value : na , '' , col_L_LN , 1 , plot.style_steplinebr) , plot(isToday and show_Sess and not sess_today_LN and DOM and not take_col_L_LN ? line_L_LN_value : na , '' , col_L_LN , 1 , plot.style_steplinebr)
sess_to_prev_AM = time(timeframe.period , '1200-1330' , Timezone)
take_col_H_prev_AM = line_H_PM_value > line_H_prev_AM_value
take_col_L_prev_AM = line_L_PM_value < line_L_prev_AM_value
col_H_prev_AM = take_col_H_prev_AM ? col_Sess_1 : na
col_L_prev_AM = take_col_L_prev_AM ? col_Sess_1 : na
plot(isToday and show_Sess and show_Tody_Lin_Sess and DOM and sess_to_prev_AM ? line_H_prev_AM_value : na , '' , col_H_prev_AM , 1 , plot.style_steplinebr) , plot(isToday and show_Sess and not sess_to_prev_AM and DOM and not take_col_H_prev_AM ? line_H_prev_AM_value : na , '' , col_H_prev_AM , 1 , plot.style_steplinebr)
plot(isToday and show_Sess and show_Tody_Lin_Sess and DOM and sess_to_prev_AM ? line_L_prev_AM_value : na , '' , col_L_prev_AM , 1 , plot.style_steplinebr) , plot(isToday and show_Sess and not sess_to_prev_AM and DOM and not take_col_L_prev_AM ? line_L_prev_AM_value : na , '' , col_L_prev_AM , 1 , plot.style_steplinebr)
|
Immediate rebalance | https://www.tradingview.com/script/hMmoRqGE/ | minerlancer | https://www.tradingview.com/u/minerlancer/ | 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/
// © minerlancer
//@version=5
indicator('Immediate rebalance' , overlay = true , max_lines_count = 500)
Timezone = 'America/New_York'
DOMD = (timeframe.multiplier <= 1440)
DOM60 = (timeframe.multiplier == 60)
DOM30 = (timeframe.multiplier <= 30)
//Input
tf = input.timeframe(defval = '' , title = '' , inline = '0' , group = 'Timeframe')
Show_macro = input.bool(defval = false , title = 'Rebalance in Macro' , inline = '0' , group = 'Rebalance in Macro')
Show_macro_1h = input.bool(defval = false , title = '1h' , inline = '1' , group = 'Rebalance in Macro')
Show_macro_ltf = input.bool(defval = false , title = 'ltf ' , inline = '1' , group = 'Rebalance in Macro')
x_line_Macro = input.int(defval = 5 , title = 'Max Show' , minval = 1 , maxval = 10 , step = 1 , inline = '1' , group = 'Rebalance in Macro')
Show_normal = input.bool(defval = false , title = 'Normal Rebalance' , inline = '0' , group = 'Normal Rebalance')
Show_bull = input.bool(defval = false , title = 'Bullish' , inline = '1' , group = 'Normal Rebalance')
Show_bear = input.bool(defval = false , title = 'Bearish ' , inline = '1' , group = 'Normal Rebalance')
x_line_ = input.int(defval = 1 , title = 'Max Show' , minval = 1 , maxval = 10 , step = 1 , inline = '1' , group = 'Normal Rebalance')
col_bull = input.color(defval = color.green , title = '' , inline = '1' , group = 'Color Rebalance')
col_bear = input.color(defval = color.red , title = '/' , inline = '1' , group = 'Color Rebalance')
col_50 = input.color(defval = color.white , title = '50%' , inline = '2' , group = 'Color Rebalance')
col_75 = input.color(defval = color.gray , title = '75%' , inline = '2' , group = 'Color Rebalance')
col_25 = input.color(defval = color.gray , title = '25%' , inline = '2' , group = 'Color Rebalance')
// Timeframe
HTF(tf,ex) =>
request.security(syminfo.tickerid , tf , ex , gaps = barmerge.gaps_off , lookahead = barmerge.lookahead_on)
O_1 = HTF(tf , open[1])
O_2 = HTF(tf , open[2])
H_2 = HTF(tf , high[2])
C_1 = HTF(tf , close[1])
C_2 = HTF(tf , close[2])
L_2 = HTF(tf , low[2])
// time Macro
// 1h
is_macro_3 = time(timeframe.period, '0200-0301', Timezone) , is_macro_4 = time(timeframe.period, '0300-0401', Timezone) , is_macro_9 = time(timeframe.period, '0800-0901', Timezone)
is_macro_10 = time(timeframe.period, '0900-1001', Timezone) , is_macro_11 = time(timeframe.period, '1000-1101', Timezone) , is_macro_12 = time(timeframe.period, '1100-1201', Timezone)
is_macro_15 = time(timeframe.period, '1400-1501', Timezone)
// ltf
t_Macro_LN_0 = time(timeframe.period , '0233-0300' , Timezone) , t_Macro_LN_1 = time(timeframe.period , '0403-0430' , Timezone)
t_Macro_NY_0 = time(timeframe.period , '0850-0910' , Timezone) , t_Macro_NY_1 = time(timeframe.period , '0950-1010' , Timezone) , t_Macro_NY_2 = time(timeframe.period , '1050-1110' , Timezone)
t_Macro_NY_3 = time(timeframe.period , '1135-1145' , Timezone) , t_Macro_NY_4 = time(timeframe.period , '1150-1210' , Timezone)
t_Macro_PM_0 = time(timeframe.period , '1310-1340' , Timezone) , t_Macro_PM_1 = time(timeframe.period , '1450-1510' , Timezone) , t_Macro_PM_2 = time(timeframe.period , '1515-1545' , Timezone)
// for Macro 1h
Macro_1h = Show_macro and DOM60 and Show_macro_1h ? is_macro_3 or is_macro_4 or is_macro_9 or is_macro_10 or is_macro_11 or is_macro_12 or is_macro_15 : na
// for Macro < 1h
Macro_ltf = Show_macro and DOM30 and Show_macro_ltf ? t_Macro_LN_0 or t_Macro_LN_1 or t_Macro_NY_0 or t_Macro_NY_1 or t_Macro_NY_2 or t_Macro_NY_3 or t_Macro_NY_4 or t_Macro_PM_0 or t_Macro_PM_1 or t_Macro_PM_2 : na
// Condition
Long = O_1 < C_1 and C_1 > H_2
Ber_L_50 = Long and O_2 > C_2 ? (O_2+H_2)/2 : (C_2+H_2)/2 // Candel bearish for Short
Ber_L_75 = Long and O_2 > C_2 ? H_2+(O_2-H_2)*0.75 : H_2+(C_2-H_2)*0.75 // Candel bearish for Short
Ber_L_25 = Long and O_2 > C_2 ? H_2+(O_2-H_2)*0.25 : H_2+(C_2-H_2)*0.25 // Candel bearish for Short
Short = O_1 > C_1 and C_1 < L_2
Bul_S_50 = Short and O_2 < C_2 ? (O_2+L_2)/2 : (C_2+L_2)/2 // Candel bullish for Short
Bul_S_75 = Short and O_2 < C_2 ? L_2+(O_2-L_2)*0.75 : L_2+(C_2-L_2)*0.75 // Candel bullish for Short
Bul_S_25 = Short and O_2 < C_2 ? L_2+(O_2-L_2)*0.25 : L_2+(C_2-L_2)*0.25 // Candel bullish for Short
// Plotting lines for Long
if (Long and Show_normal and Show_bull and not Show_macro) or (Long and Show_macro and (Macro_1h or Macro_ltf))
hh = line.new(bar_index[2] , H_2 , bar_index , H_2 , width = 1, color = col_bull , style = line.style_solid)
hh_50 = line.new(bar_index[2] , Ber_L_50 , bar_index , Ber_L_50 , width = 1 , color = col_50 , style = line.style_dashed)
hh_75 = line.new(bar_index[2] , Ber_L_75 , bar_index , Ber_L_75 , width = 1 , color = col_75 , style = line.style_dotted)
hh_25 = line.new(bar_index[2] , Ber_L_25 , bar_index , Ber_L_25 , width = 1 , color = col_25 , style = line.style_dotted)
if not (Macro_1h or Macro_ltf)
line.delete(hh[x_line_]) , line.delete(hh_50[x_line_]) , line.delete(hh_75[x_line_]) , line.delete(hh_25[x_line_])
else
line.delete(hh[x_line_Macro]) , line.delete(hh_50[x_line_Macro]) , line.delete(hh_75[x_line_Macro]) , line.delete(hh_25[x_line_Macro])
// Plotting lines for Short
if (Short and Show_normal and Show_bear and not Show_macro) or (Short and Show_macro and (Macro_1h or Macro_ltf))
ll = line.new(bar_index[2] , L_2 , bar_index , L_2 , width = 1 , color = col_bear , style = line.style_solid)
ll_50 = line.new(bar_index[2] , Bul_S_50 , bar_index , Bul_S_50 , width = 1 , color = col_50 , style = line.style_dashed)
ll_75 = line.new(bar_index[2] , Bul_S_75 , bar_index , Bul_S_75 , width = 1 , color = col_75 , style = line.style_dotted)
ll_25 = line.new(bar_index[2] , Bul_S_25 , bar_index , Bul_S_25 , width = 1 , color = col_25 , style = line.style_dotted)
if not (Macro_1h or Macro_ltf)
line.delete(ll[x_line_]) , line.delete(ll_50[x_line_]) , line.delete(ll_75[x_line_]) , line.delete(ll_25[x_line_])
else
line.delete(ll[x_line_Macro]) , line.delete(ll_50[x_line_Macro]) , line.delete(ll_75[x_line_Macro]) , line.delete(ll_25[x_line_Macro])
|
YD_Divergence_RSI+CMF | https://www.tradingview.com/script/digDVGmQ/ | Yonsei_dent | https://www.tradingview.com/u/Yonsei_dent/ | 232 | 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/
// © Yonsei_dent
//
// \\ // ⇗⩸⇖ || || ⇗⁼⁼⁼⁼⁼ ∥⁼⁼⁼⁼ ⁼⁼₪⁼⁼ ₪₪⁼⁼⁼⁼⇘
// \\// ∥ ∥ ||\\ || ⇘‗‗‗‗‗ ∥‗‗‗‗ ‖ || ∥ ⇗⁼⁼⁼⇘ ∥⇗⁼⁼⁼⇘ ‗‗‖‗‗
// ‖‖ ∥ ∥ || \\|| ⇘ ∥ ‖ || ∥ ‖⇘₌₌⇗ ∥ ∥ ‖
// ‖‖ ⇘⩸⇙ || || ‗‗‗‗‗⇗ ∥‗‗‗‗ ‗‗‖‗‗ ‗‗‗ ||‗‗‗‗⇗ ⇘‗‗‗ ∥ ∥ ‖‗‗⇗ ©©
//
//@version=5
indicator("YD_Divergence_RSI+CMF", overlay = true, format = format.price)
// 변수설정-1. Pivot
pivotgroup = 'Pivot Setting'
pivottip = 'If pivot length is too long, The signal will be delayed. The range for "Pivot Length" is set from 1 to 50.'
price_length = input.int(5, "Pivot Length", minval = 1, maxval = 50, group = pivotgroup, tooltip = pivottip)
pivotprice = input.string('High/Low (고/저가)', "Pivot Reference", options = ['High/Low (고/저가)','Close (종가)'], group = pivotgroup)
pivotplot = input.bool(false, 'Pivot High/Low Marker', group = pivotgroup)
// 변수설정-2. RSI
rsigroup = 'RSI Setting'
rsi_length = input.int(14, 'RSI Length', minval =1, maxval = 50, group = rsigroup)
rsi = ta.rsi(close, rsi_length)
// 변수설정-3. Chaikin Money Flow
cmfgroup = 'CMF Setting'
cmf_length = input.int(20, 'CMF Length', minval=1, maxval = 50, group = cmfgroup)
mfv = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
cmf = math.sum(mfv, cmf_length) / math.sum(volume, cmf_length)
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
// 변수설정-4. label
labelgroup = 'Label Setting'
bullbearlabel = input.string('Bullish/Bearish', 'Bull/Bear Label Text', options = ['Bullish/Bearish', 'Bull/Bear','None'], group = labelgroup)
divergencelabel = input.string('Divergence', 'Divergence Label Text', options = ['Divergence','None'], group = labelgroup)
bullshow = input.bool(true, '', inline = 'bull', group = labelgroup)
bulllinecol = input.color(color.green, 'Bullish Divergence Line ', inline = 'bull', group = labelgroup)
bulllinewid = input.int(1, '', maxval = 4, minval = 1, inline = 'bull', group = labelgroup)
bulllinest = input.string('────', '', options=['────', 'ㅡㅡㅡㅡ', '••••••••'], inline = 'bull', group = labelgroup)
bearshow = input.bool(true, '', inline = 'bear', group = labelgroup)
bearlinecol = input.color(color.red, 'Bearish Divergence Line ', inline = 'bear', group = labelgroup)
bearlinewid = input.int(1, '', maxval = 4, minval = 1, inline = 'bear', group = labelgroup)
bearlinest = input.string('────', '', options=['────', 'ㅡㅡㅡㅡ', '••••••••'], inline = 'bear', group = labelgroup)
bulllabelshow = input.bool(true, '', inline = 'bulllabel', group = labelgroup)
bulllabelcol = input.color(color.green, 'Bullish Divergence Label ', inline = 'bulllabel', group = labelgroup)
bulllabeltext = input.string('Normal', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], inline = 'bulllabel', group= labelgroup)
bulllabelst = input.string('Label', '', options = ['Arrow', 'Label', 'Triangle', 'Text'], inline = 'bulllabel', group = labelgroup)
bearlabelshow = input.bool(true, '', inline = 'bearlabel', group = labelgroup)
bearlabelcol = input.color(color.red, 'Bearish Divergence Label ', inline = 'bearlabel', group = labelgroup)
bearlabeltext = input.string('Normal', '', options = ['Tiny', 'Small', 'Normal', 'Large', 'Auto'], inline = 'bearlabel', group= labelgroup)
bearlabelst = input.string('Label', '', options = ['Arrow', 'Label', 'Triangle', 'Text'], inline = 'bearlabel', group = labelgroup)
lastshow = input.bool(false, ' Display Only the Last Label.', group = labelgroup)
labeltextcol = input.color(color.white, 'Label Text Color', group = labelgroup)
// divergence 생성조건
// 1-1. 가격의 Pivot High / Low 구하기
php = ta.pivothigh(pivotprice=='High/Low (고/저가)'?high:close, price_length, price_length)
plp = ta.pivotlow(pivotprice=='High/Low (고/저가)'?low:close, price_length, price_length)
phfound = na(php) ? false : true
plfound = na(plp) ? false : true
plot(pivotplot?php:na, "Pivot High", color = color.green, linewidth = 3, style = plot.style_linebr, offset = -(price_length))
plot(pivotplot?plp:na, "Pivot Low", color = color.red, linewidth = 3, style = plot.style_linebr, offset = -(price_length))
// 2. 가격의 HH, LL 갱신
is_price_higher = ta.valuewhen(phfound, pivotprice=='High/Low (고/저가)'?high[price_length]:close[price_length], 0) > ta.valuewhen(phfound, pivotprice=='High/Low (고/저가)'?high[price_length]:close[price_length], 1)
is_price_lower = ta.valuewhen(plfound, pivotprice=='High/Low (고/저가)'?low[price_length]:close[price_length], 0) < ta.valuewhen(plfound, pivotprice=='High/Low (고/저가)'?low[price_length]:close[price_length], 1)
// 3. 지표의 divergence
is_rsi_lower = ta.valuewhen(phfound, rsi[price_length], 0) < ta.valuewhen(phfound, rsi[price_length], 1)
is_rsi_higher = ta.valuewhen(plfound, rsi[price_length], 0) > ta.valuewhen(plfound, rsi[price_length], 1)
is_cmf_lower = ta.valuewhen(phfound, cmf[price_length], 0) < ta.valuewhen(phfound, cmf[price_length], 1)
is_cmf_higher = ta.valuewhen(plfound, cmf[price_length], 0) > ta.valuewhen(plfound, cmf[price_length], 1)
// 4. 2개의 피봇간 Range 제한
_inRange(cond) =>
bars = ta.barssince(cond == true)
5 <= bars and bars <= 50
// Bullish RSI Divergence 조건설정
bull_rsi_div = plfound and is_price_lower and is_rsi_higher and _inRange(plfound[1])
// Bullish CMF Divergence 조건설정
bull_cmf_div = plfound and is_price_lower and is_cmf_higher and _inRange(plfound[1])
// Bearish RSI Divergence 조건설정
bear_rsi_div = phfound and is_price_higher and is_rsi_lower and _inRange(phfound[1])
// Bearish CMF Divergence 조건설정
bear_cmf_div = phfound and is_price_higher and is_cmf_lower and _inRange(phfound[1])
// 함수 설정
RSIdirection() =>
if bull_rsi_div and bullbearlabel == 'Bullish/Bearish'
"Bullish RSI"
else if bull_rsi_div and bullbearlabel == 'Bull/Bear'
"Bull RSI"
else if bear_rsi_div and bullbearlabel == 'Bullish/Bearish'
"Bearish RSI"
else if bear_rsi_div and bullbearlabel == 'Bull/Bear'
"Bear RSI"
else if bull_rsi_div or bear_rsi_div and bullbearlabel == 'None'
"RSI"
else
na
CMFdirection() =>
if bull_cmf_div and bullbearlabel == 'Bullish/Bearish'
"Bullish CMF"
else if bull_cmf_div and bullbearlabel == 'Bull/Bear'
"Bull CMF"
else if bear_cmf_div and bullbearlabel == 'Bullish/Bearish'
"Bearish CMF"
else if bear_cmf_div and bullbearlabel == 'Bull/Bear'
"Bear CMF"
else if bull_cmf_div or bear_cmf_div and bullbearlabel == 'None'
"CMF"
else
na
divergence() =>
if divergencelabel == 'Divergence'
" Divergence"
else if divergencelabel == 'None'
na
bullbear() =>
if bull_rsi_div or bull_cmf_div
"Bull"
else if bear_rsi_div or bear_cmf_div
"Bear"
else
na
switchLineStyle(x) =>
switch x
'────' => line.style_solid
'ㅡㅡㅡㅡ' => line.style_dashed
'••••••••' => line.style_dotted
switchsize(x) =>
switch x
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Auto' => size.auto
switchbulllabel(x) =>
switch x
'Arrow' => label.style_arrowup
'Label' => label.style_label_up
'Triangle' => label.style_triangleup
'Text' => label.style_text_outline
switchbearlabel(x) =>
switch x
'Arrow' => label.style_arrowdown
'Label' => label.style_label_down
'Triangle' => label.style_triangledown
'Text' => label.style_text_outline
drawdl(x1, y1, x2, y2, col, wid, st) =>
dl = line.new(x1, y1, x2, y2, color = col, width = wid, style = switchLineStyle(st))
bullbearRSI = RSIdirection()
bullbearCMF = CMFdirection()
divergence = divergence()
rsiresult = ""
CMFresult = ""
// 입력값 호출
if not na(bullbearRSI)
rsiresult := bullbearRSI + divergence
else
rsiresult := ""
if not na(bullbearCMF)
CMFresult := bullbearCMF + divergence
else
CMFresult := ""
var finalresult = "na"
if na(bullbearRSI) and not na(bullbearCMF)
finalresult := CMFresult
else if not na(bullbearRSI) and na(bullbearCMF)
finalresult := rsiresult
else if not na(bullbearRSI) and not na(bullbearCMF)
finalresult := rsiresult + "\n" + CMFresult
// Divergence Line 작도
var line[] buline = array.new_line(0)
var line[] beline = array.new_line(0)
var line bullline = na
var line bearline = na
var int dhx1 = na, var float dhy1 = na
var int dhx2 = na, var float dhy2 = na
var int dlx1 = na, var float dly1 = na
var int dlx2 = na, var float dly2 = na
if plfound
dhx1 := dhx2, dhy1 := dhy2
dhx2 := bar_index[price_length], dhy2 := plp
if bullbear() == "Bull" and bullshow
bullline := drawdl(dhx1, dhy1, dhx2, dhy2, bulllinecol, bulllinewid, bulllinest)
array.push(buline, bullline)
array.reverse(buline)
if lastshow and array.size(buline) >= 2
line.delete(array.pop(buline))
if phfound
dlx1 := dlx2, dly1 := dly2
dlx2 := bar_index[price_length], dly2 := php
if bullbear() == "Bear" and bearshow
bearline := drawdl(dlx1, dly1, dlx2, dly2, bearlinecol, bearlinewid, bearlinest)
array.push(beline, bearline)
array.reverse(beline)
if lastshow and array.size(beline) >= 2
line.delete(array.pop(beline))
// Divergence Mark 작도
var label[] bulabel = array.new_label(0)
var label[] belabel = array.new_label(0)
if bullbear() == "Bull" and bulllabelshow
bulllabel = label.new(
x = bar_index[price_length],
y = low[price_length],
style = switchbulllabel(bulllabelst),
text = finalresult,
color = bulllabelcol,
size = switchsize(bulllabeltext),
yloc = yloc.belowbar,
textcolor = labeltextcol
)
array.push(bulabel, bulllabel)
array.reverse(bulabel)
if lastshow and array.size(bulabel) >= 2
label.delete(array.pop(bulabel))
if bullbear() == "Bear" and bearlabelshow
bearlabel = label.new(
x = bar_index[price_length],
y = high[price_length],
style = switchbearlabel(bearlabelst),
text = finalresult,
color = bearlabelcol,
size = switchsize(bearlabeltext),
yloc = yloc.abovebar,
textcolor = labeltextcol
)
array.push(belabel, bearlabel)
array.reverse(belabel)
if lastshow and array.size(belabel) >= 2
label.delete(array.pop(belabel))
// Alert 설정
if bull_rsi_div
alert("RSI Bullish Divergence", alert.freq_once_per_bar_close)
else if bear_rsi_div
alert("RSI Bearish Divergence", alert.freq_once_per_bar_close)
else if bull_cmf_div
alert("CMF Bullish Divergence", alert.freq_once_per_bar_close)
else if bear_cmf_div
alert("CMF Bearish Divergence", alert.freq_once_per_bar_close) |
Volume Spread Analysis [Ahmed] | https://www.tradingview.com/script/TNYBbUTr-Volume-Spread-Analysis-Ahmed/ | aothmaan | https://www.tradingview.com/u/aothmaan/ | 46 | 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/
// © aothmaan
//@version=5
indicator("Volume Spread Analysis [Ahmed]",shorttitle ='VSA [Ahmed]', overlay=false)
//Relative Volume
length = input.int(50, minval=1)
maType = input.string("SMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
src = volume
ma(source, length, _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
basis = ma(src, length, maType)
SD1 = basis + 1 * ta.stdev(src, length)
SD2 = basis + 2 * ta.stdev(src, length)
color1= input.color(color.new(#008000, 0), "Lower Color")
color2= input.color(color.new(#ffffff, 0), "MA Color")
color3= input.color(color.new(#ff9800, 0), "MA + 1 SD Color")
color4= input.color(color.new(#ff0000, 0), "MA + 2 SD Color")
offset = input.int(0, "Offset", minval = -500, maxval = 500)
base=plot(basis, "MA", color=color.new(#ffffff, 70), offset = offset)
p1 = plot(SD1, "MA + 1 SD", color=color3, offset = offset, display=display.none)
p2 = plot(SD2, "MA + 2 SD", color=color4, offset = offset, display=display.none)
fill(p1, p2, color=color.new(#ffffff, 70))
histocolor=volume>SD2?color4 :volume>SD1?color3:volume>basis?color2: color1
plot(volume, "Volume",style=plot.style_histogram, color=histocolor, linewidth = 4)
|
MyCandleLibrary | https://www.tradingview.com/script/DBfTjauZ-MyCandleLibrary/ | rezaraz | https://www.tradingview.com/u/rezaraz/ | 1 | 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/
// © rezaraz
//@version=5
// @description TODO: Candle Pattern Library
library("MyCandleLibrary")
// @function TODO: Identify Bullish Engulfing Candle
// @param n TODO: Candle Number
// @returns TODO: If Identify Bullish Engulfing candle return True
export IsEngulfingCandle(int n) =>
//TODO : add function body and return value here
var trendRule1 = "SMA50"
var trendRule2 = "SMA50,SMA200"
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
C_BodyHi = math.max(close[n], open[n])
C_BodyLo = math.min(close[n], open[n])
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high[n] - C_BodyHi
C_DnShadow = C_BodyLo - low[n]
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open[n] < close[n]
C_BlackBody = open[n] > close[n]
C_Range = high[n]-low[n]
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
//patternLabelPosLow = low - (ta.atr(30) * 0.6)
//patternLabelPosHigh = high + (ta.atr(30) * 0.6)
//label_color_bullish = input(color.blue, "Label Color Bullish")
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close[n] >= open[n+1] and open[n] <= close[n+1] and ( close[n] > open[n+1] or open[n] < close[n+1] )
//C_EngulfingBullish = C_UpTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close[n] >= (close[n+1]+open[n+1])/2
//alertcondition(C_EngulfingBullish, title = "New pattern detected", message = "New Engulfing – Bullish pattern detected")
//if C_EngulfingBullish
//var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
//label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
//bgcolor(ta.highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.new(color.blue, 90) : na, offset=-(C_EngulfingBullishNumberOfCandles-1))
C_EngulfingBullish
/////////////////////////////////////////////////// White Cloade //////////////////////////////////////////////////////
// @function TODO: Identify White Cloade Candle
// @param n TODO: Candle Number
// @returns TODO: If Identify White Cloade candle return True otherwise False
export IsWhiteCloadeCandle(int n) =>
//TODO : add function body and return value here
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
C_BodyHi = math.max(close[n], open[n])
C_BodyLo = math.min(close[n], open[n])
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high[n] - C_BodyHi
C_DnShadow = C_BodyLo - low[n]
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open[n] < close[n]
C_BlackBody = open[n] > close[n]
C_Range = high[n]-low[n]
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
//patternLabelPosLow = low - (ta.atr(30) * 0.6)
//patternLabelPosHigh = high + (ta.atr(30) * 0.6)
//label_color_bullish = input(color.blue, "Label Color Bullish")
C_WhiteCloadeNumberOfCandles = 2
C_WhiteCloade = C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close[n] > ((close[n+1] + open[n+1]) / 2)
//C_EngulfingBullish = C_UpTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close[n] >= (close[n+1]+open[n+1])/2
//alertcondition(C_EngulfingBullish, title = "New pattern detected", message = "New Engulfing – Bullish pattern detected")
//if C_EngulfingBullish
//var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
//label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
//bgcolor(ta.highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.new(color.blue, 90) : na, offset=-(C_EngulfingBullishNumberOfCandles-1))
C_WhiteCloade
/////////////////////////////////////////////////// White Hammer //////////////////////////////////////////////////////
// @function TODO: Identify White Hammer Candle
// @param n TODO: Candle Number
// @returns TODO: If Identify White Hammer candle return True otherwise False
export IsWhiteHammerCandle(int n) =>
//TODO : add function body and return value here
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_BodyHi = math.max(close[n], open[n])
C_BodyLo = math.min(close[n], open[n])
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high[n] - C_BodyHi
C_DnShadow = C_BodyLo - low[n]
C_hight = high[n]-low[n]
Avg = ta.ema(hlc3[n],14)
C_WhiteHammer = C_Body < C_BodyAvg and C_Body < C_hight and C_UpShadow<= C_Body and C_DnShadow > (2*C_Body) and (low[n+1] > low[n]) and hl2[n]<Avg and ((C_Body[1]>C_BodyAvg and close[n+1]<open[n+1]) or (C_Body[2]>C_BodyAvg and close[n+2]<open[n+2]) or (C_Body[3]>C_BodyAvg and close[n+3]<open[n+3])) ? true : false
C_WhiteHammer |
Harmonic Trend Fusion [kikfraben] | https://www.tradingview.com/script/Q2k01HEp-Harmonic-Trend-Fusion-kikfraben/ | kikfraben | https://www.tradingview.com/u/kikfraben/ | 38 | 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/
// © kikfraben
// Updated last on Nov 16 2023
// @version = 5
indicator("Harmonic Trend Fusion [kikfraben]", shorttitle = "HTF", overlay = false, precision = 2)
// Baseline
src = input.source(close, "Source", group = "Base Inputs")
// Plot Options
plot_signal = input.bool(true, "Plot Signal?", group = "Plot Options")
plot_table = input.bool(true, "Plot Table?", group = "Plot Options")
plot_aroon = input.bool(false, "Plot Aroon?", group = "Plot Options")
plot_dmi = input.bool(false, "Plot DMI?", group = "Plot Options")
plot_macd_ma = input.bool(false, "Plot MACD MA's?", group = "Plot Options", inline = "5")
plot_macd_hist = input.bool(false, "Plot MACD Hist?", group = "Plot Options", inline = "5")
plot_parabolic_sar = input.bool(false, "Plot Parabolic SAR?", group = "Plot Options")
plot_rsi = input.bool(false, "Plot RSI?", group = "Plot Options")
plot_supertrend = input.bool(false, "Plot Supertrend?", group = "Plot Options")
plot_smi_ergodic = input.bool(false, "Plot SMI Ergodic?", group = "Plot Options")
// Color Inputs
color_bull = input.color(#3fa8c9, title = "Bullish Color", group = "Color Inputs", inline = "1")
color_bear = input.color(#c93f3f, title = "Bearish Color", group = "Color Inputs", inline = "1")
// Input 1 -> Aroon
aroon_length = input.int(14, "Aroon Length", group = "Aroon Inputs")
aroon_upper = 100 * (ta.highestbars(high, aroon_length + 1) + aroon_length) / aroon_length
aroon_lower = 100 * (ta.lowestbars(low, aroon_length + 1) + aroon_length) / aroon_length
plot(plot_aroon ? aroon_upper : na, "Aroon Up", color = color_bull)
plot(plot_aroon ? aroon_lower : na, "Aroon Down", color = color_bear)
binary_aroon = aroon_upper > aroon_lower ? 1 : -1
// Input 2 -> DMI
dmi_length = input.int(14, "DMI Length", group = "DMI Inputs")
dmi_up = ta.change(high)
dmi_down = -ta.change(low)
plusDM = na(dmi_up) ? na : (dmi_up > dmi_down and dmi_up > 0 ? dmi_up : 0)
minusDM = na(dmi_down) ? na : (dmi_down > dmi_up and dmi_down > 0 ? dmi_down : 0)
dmi_trur = ta.rma(ta.tr, dmi_length)
dmi_plus = fixnan(100 * ta.rma(plusDM, dmi_length) / dmi_trur)
dmi_minus = fixnan(100 * ta.rma(minusDM, dmi_length) / dmi_trur)
plot(plot_dmi ? dmi_plus : na, "DMI+", color = color_bull)
plot(plot_dmi ? dmi_minus : na, "DMI-", color = color_bear)
binary_dmi = dmi_plus > dmi_minus ? 1 : -1
// Input 3 -> MACD
macd_fast_length = input(12, "MACD Fast Length", group = "MACD Inputs")
macd_slow_length = input(26, "MACD Slow Length", group = "MACD Inputs")
macd_signal_length = input(9, "MACD Signal Length", group = "MACD Inputs")
macd_ma_source = input.string("EMA", "Oscillator MA Type", options = ["SMA", "EMA"], group = "MACD Inputs")
macd_ma_signal = input.string("EMA", "Signal MA Type", options = ["SMA", "EMA"], group = "MACD Inputs")
macd_fast_ma = macd_ma_source == "SMA" ? ta.sma(src, macd_fast_length) : ta.ema(src, macd_fast_length)
macd_slow_ma = macd_ma_source == "SMA" ? ta.sma(src, macd_slow_length) : ta.ema(src, macd_slow_length)
macd = macd_fast_ma - macd_slow_ma
macd_signal = macd_ma_signal == "SMA" ? ta.sma(macd, macd_signal_length) : ta.ema(macd, macd_signal_length)
macd_hist = macd - macd_signal
hline(plot_macd_hist ? 0 : na, "Zero Line", color = color.new(#787B86, 50))
plot(plot_macd_hist ? macd_hist : na, "Histogram", style = plot.style_columns, color = (macd_hist >= 0 ? (macd_hist[1] <
macd_hist ? color_bull : color.new(color_bull, 50)) : (macd_hist[1] < macd_hist ? color.new(color_bear, 50) : color_bear)))
plot(plot_macd_ma ? macd : na, "MACD", color = color_bull)
plot(plot_macd_ma ? macd_signal : na, "Signal", color = color_bear)
binary_macd = macd_hist > 0 ? 1 : -1
// Input 4 -> Parabolic SAR
sar_start = input(0.02, "SAR Start", group = "Parabolic SAR Inputs")
sar_increment = input(0.02, "SAR Increment", group = "Parabolic SAR Inputs")
sar_maximum = input(0.2, "SAR Maximum", group = "Parabolic SAR Inputs")
sar = ta.sar(sar_start, sar_increment, sar_maximum)
plot(plot_parabolic_sar ? sar : na, "Parabolic SAR", style = plot.style_cross, color = sar < src ? color_bull : color_bear)
binary_sar = sar < src ? 1 : -1
// Input 5 -> RSI
rsi_len = input.int(22, title="RSI Length", group="RSI Inputs")
rsi_up = ta.rma(math.max(ta.change(src), 0), rsi_len)
rsi_down = ta.rma(-math.min(ta.change(src), 0), rsi_len)
rsi = rsi_down == 0 ? 100 : rsi_up == 0 ? 0 : 100 - (100 / (1 + rsi_up / rsi_down))
rsi_col = rsi > 50 ? color_bull : color_bear
rsiPlot = plot(plot_rsi ? rsi : na, "RSI", color = rsi_col)
rsiUpperBand = hline(plot_rsi ? 70 : na, "RSI Upper Band", color=#787B86)
midline = hline(plot_rsi ? 50 : na, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(plot_rsi ? 30 : na, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
binary_rsi = rsi > 50 ? 1 : -1
// Input 6 -> Supertrend
st_length = input(22, "Supertrend Length", group = "Supertrend Inputs")
st_factor = input.float(2.22, "Supertrend Factor", step = 0.01, group = "Supertrend Inputs")
[supertrend, direction] = ta.supertrend(st_factor, st_length)
bodyMiddle = plot(plot_supertrend ? (open + close) / 2 : na, display=display.none)
upTrend = plot(plot_supertrend ? direction < 0 ? supertrend : na : na, "Up Trend", color = color_bull, style=plot.style_linebr)
downTrend = plot(plot_supertrend ? direction < 0 ? na : supertrend : na, "Down Trend", color = color_bear, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color_bull, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color_bear, 90), fillgaps=false)
binary_st = direction < 0 ? 1 : -1
// Input 7 -> SMI Ergodic Oscillator
smi_longlen = input.int(20, "SMI Long Length", group = "SMI Ergodic Oscillator Inputs")
smi_shortlen = input.int(5, "SMI Short Length", group = "SMI Ergodic Oscillator Inputs")
smi_siglen = input.int(5, "SMI Signal Line Length", group = "SMI Ergodic Oscillator Inputs")
smi_erg = ta.tsi(close, smi_shortlen, smi_longlen)
smi_sig = ta.ema(smi_erg, smi_siglen)
smi_osc = smi_erg - smi_sig
plot(plot_smi_ergodic ? smi_osc : na, "SMI Ergodic Oscillator", style = plot.style_columns, color = (smi_osc >= 0 ? (smi_osc[1] < smi_osc
? color_bull : color.new(color_bull, 50)) : (smi_osc[1] < smi_osc ? color.new(color_bear, 50) : color_bear)))
binary_smi = smi_osc > 0 ? 1 : -1
// Signal
signal = math.avg(binary_aroon, binary_dmi, binary_macd, binary_sar, binary_rsi, binary_st, binary_smi)
plot(plot_signal ? signal : na, "SMI Ergodic Oscillator", style = plot.style_columns, color = (signal >= 0 ? (signal[1] < signal ? color_bull
: color.new(color_bull, 50)) : (signal[1] < signal ? color.new(color_bear, 50) : color_bear)))
// Table
if plot_table == true
table = table.new(position = position.top_right, columns = 2, rows = 2, bgcolor = color.new(color.white, 95), border_width = 1, border_color
= color.new(color.white, 80), frame_width = 1, frame_color = color.new(color.white, 80))
table.cell(table_id = table, column = 0, row = 0, text = "HTF", text_color = color.new(color.white, 25))
table.cell(table_id = table, column = 1, row = 0, text = str.tostring(signal, format = "#.##"), text_color = signal > 0 ? color_bull : color_bear)
table.cell(table_id = table, column = 0, row = 1, text = "Trend", text_color = color.new(color.white, 25))
table.cell(table_id = table, column = 1, row = 1, text = signal > 0 ? "Bullish" : "Bearish", text_color = signal > 0 ? color_bull : color_bear) |
FinandyHookLib | https://www.tradingview.com/script/o4WeLfoF-finandyhooklib/ | Hamster-Coder | https://www.tradingview.com/u/Hamster-Coder/ | 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/
// © Hamster-Coder
//@version=5
// @description TODO: add library description here
library("FinandyHookLib", true)
import Hamster-Coder/OrderLib/41 as orderLib
import Hamster-Coder/TextLib/6 as textLib
createOpenElementJson(orderLib.tradePositionModel model, textLib.textFormatOptions options) =>
string result = ""
result := textLib.concatLine(result, " \"open\": {")
result := textLib.concatLine(result, " \"amountType\": \"sumUsd\",")
result := textLib.concatLine(result, str.format(" \"amount\": \"{0}\",", str.tostring(model.enter.amount.value, options.currency_format)))
result := textLib.concatLine(result, str.format(" \"leverage\": \"{0}\",", model.leverage))
result := textLib.concatLine(result, str.format(" \"price\": \"{0}\"", str.tostring(model.enter.price.value, options.currency_format)))
result := textLib.concatLine(result, " }")
result
createStopLossJson(orderLib.tradePositionModel model, textLib.textFormatOptions options) =>
string result = ""
if (na(model.stop_loss) == false)
result := textLib.concatLine(result, " \"sl\": {")
result := textLib.concatLine(result, str.format(" \"price\": \"{0}\"", str.tostring(model.stop_loss.price.value, options.currency_format)))
result := textLib.concatLine(result, " }")
result
createSlxJson(orderLib.tradePositionModel model, textLib.textFormatOptions options) =>
string result = ""
if (na(model.breakeven) == false or na(model.trailing_stop) == false)
result := textLib.concatLine(result, " \"slx\": {")
result := textLib.concatLine(result, " \"mode\": \"trailing\",")
result := textLib.concatLine(result, str.format(" \"trailingBreakevenProfit\": \"{0}\",", na(model.breakeven) ? "" : str.tostring(model.breakeven.target.price.offset, options.percent_format)))
result := textLib.concatLine(result, str.format(" \"trailingBreakeven\": \"{0}\",", na(model.breakeven) ? "" : str.tostring(model.breakeven.trigger.offset, options.percent_format)))
result := textLib.concatLine(result, str.format(" \"trailingProfit\": \"{0}\",", na(model.trailing_stop) ? "" : str.tostring(model.trailing_stop.trigger.offset, options.percent_format)))
result := textLib.concatLine(result, str.format(" \"trailingLag\": \"{0}\",", na(model.trailing_stop) ? "" : str.tostring(model.trailing_stop.lag_offset, options.percent_format)))
result := textLib.concatLine(result, " \"trailingMode\": \"lp\"")
result := textLib.concatLine(result, " }")
result
createTakeProfitElementJson(orderLib.orderPointModel tp, textLib.textFormatOptions options) =>
string result = ""
result := textLib.concatLine(result, " {")
result := textLib.concatLine(result, str.format(" \"price\": \"{0}\",", str.tostring(tp.price.value, options.currency_format)))
result := textLib.concatLine(result, str.format(" \"piece\": \"{0}\"", tp.amount.position_piece_prc))
result := textLib.concatLine(result, " }")
result
createTakeProfitElementJson(orderLib.tradePositionModel model, textLib.textFormatOptions options) =>
string result = ""
if (na(model.take_profit_collection) == false)
if (model.take_profit_collection.size() > 0)
result := textLib.concatLine(result, " \"tp\": {")
result := textLib.concatLine(result, " \"orders\": [")
for [index, tp] in model.take_profit_collection
if (index > 0)
result := textLib.concatLine(result, ",")
result := textLib.concatLine(result, createTakeProfitElementJson(tp, options = options))
result := textLib.concatLine(result, " ],")
result := textLib.concatLine(result, str.format(" \"qty\": \"{0}\"", model.take_profit_collection.size()))
result := textLib.concatLine(result, " }")
result
addPrefixComma(string value) =>
string result = value
if (value != "")
result := str.format(",{0}", value)
result
export createOrderJson(orderLib.tradePositionModel model, string hook_secret, textLib.textFormatOptions options) =>
string result = ""
result := textLib.concatLine(result, "{")
result := textLib.concatLine(result, str.format(" \"secret\": \"{0}\",", hook_secret))
result := textLib.concatLine(result, str.format(" \"side\": \"{0}\",", model.side == 1 ? "buy" : "sell"))
result := textLib.concatLine(result, str.format(" \"symbol\": \"{0}\",", model.ticker))
// add open element
result := textLib.concatLine(result, createOpenElementJson(model, options = options))
// add stop loss element
result := textLib.concatLine(result, addPrefixComma(createStopLossJson(model, options = options)))
// add slx element
result := textLib.concatLine(result, addPrefixComma(createSlxJson(model, options = options)))
// add take profit element
result := textLib.concatLine(result, addPrefixComma(createTakeProfitElementJson(model, options = options)))
result := textLib.concatLine(result, "}")
result
|
LibraryTimeframeHelper | https://www.tradingview.com/script/idwxU6HS-LibraryTimeframeHelper/ | SimpleCryptoLife | https://www.tradingview.com/u/SimpleCryptoLife/ | 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/
// © SimpleCryptoLife
//@version=5
// @description Helper functions to work with timeframes: to get the next higher TF, to make the string pretty for use in labels, and so on.
library("LibraryTimeframeHelper")
// 🟦🟦🟦
// @function f_getHigherTF(): Converts the input timeframe into the next one up in the list of commonly used timeframes. NOTE: You can NOT use a TF from this function as input to a request.security() call if called from this library because it gets converted to a series (since there's nothing special about this function, I expect this probably goes for any library). However, you CAN copy the code and use it directly in your script, in which case the output is only a simple variable and thus suitable for the timeframe of a request.security() call.
// @param string _TF: The timeframe to convert.
// @returns: A string in standard timeframe format.
export f_getHigherTF(string _TF) =>
_HTF = switch _TF
"1" => "2" // 1 minute
"2" => "3"
"3" => "5"
"5" => "10"
"10" => "15"
"15" => "30"
"30" => "60"
"60" => "120" // 2H
"120" => "180" // 3H
"180" => "240" // 4H
"240" => "480" // 8H
"480" => "720" // 12H
"720" => "D" // D
"D" => "2D"
"2D" => "3D"
"3D" => "W"
"W" => "2W"
"2W" => "M"
=> na // If the TF isn't listed, or the output would be too high, return na, so that it's empty, instead of copying the chart TF
// EXAMPLE
string TF1 = f_getHigherTF(timeframe.period) // One higher than the chart timeframe
string TF2 = f_getHigherTF(TF1) // One higher again
var string labelText = na
labelText := "Chart TF: " + str.tostring(timeframe.period)
+ "\n TF1: " + TF1 + ", TF2: " + str.tostring(TF2)
// 🟦🟦🟦
// @function f_prettifyTF(): Converts the input timeframe from standard timeframe format to the format shown by TradingView on a chart. The output is not suitable for use as an input timeframe of a request.security() call.
// @param string _TF: The timeframe to convert.
// @returns: A string in prettified timeframe format.
export f_prettifyTF(string _TF) =>
int _secs = timeframe.in_seconds(_TF)
string _prettyTF = _secs > 59 and _secs < 3600 ? str.tostring(value=(_secs/60), format="##m") : _secs > 3599 and _secs < 86400 ? str.tostring(value=(_secs/3600), format="##h") : _TF == "D" or _TF == "W" or _TF == "M" ? "1" + _TF : _TF
// EXAMPLE
in_TF = input.timeframe(title="Timeframe to prettify", defval="")
string prettyTF = f_prettifyTF(in_TF)
labelText := labelText + "\nInput TF: " + in_TF
+ "\nPrettified TF: " + prettyTF
// PRINT THE EXAMPLE LABEL
exampleLabel=label.new(x=bar_index+4, y=0, text=labelText, xloc=xloc.bar_index, yloc=yloc.price, color=chart.fg_color, style=label.style_label_left, textcolor=chart.bg_color, size=size.normal, textalign=text.align_center)
label.delete(exampleLabel[1])
|
AlgebraLib | https://www.tradingview.com/script/lijMZ3D2/ | M_0_2_8 | https://www.tradingview.com/u/M_0_2_8/ | 0 | 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/
// © M_0_2_8
//@version=5
// @description: Algebra Library with useful and recurring functions
library("AlgebraLib", overlay=true)
// @function: Draw a simple label with Buy or Sell signal
// @param side: STRING, Signal Side (ex: "BUY" or "SELLa progressive number)
// @param date: INT, Signal date/time (ex: timestamp("Europe/Amsterdam",2023, 05, 29, 16, 0, 0))
// @returns: VOID, it draws a new label
export signaldraw(string _side, int _date) =>
if barstate.islast
if _side == "BUY"
label.new(_date, low , _side, xloc.bar_time, yloc.belowbar, color=color.green, textcolor=color.white, style=label.style_label_up)
else
label.new(_date, high , _side, xloc.bar_time, yloc.abovebar, color=color.red, textcolor=color.white, style=label.style_label_down)
|
RelativeValue | https://www.tradingview.com/script/cZnSLls2-RelativeValue/ | TradingView | https://www.tradingview.com/u/TradingView/ | 123 | 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/
// © TradingView
// @version=5
library("RelativeValue")
// RelativeValue Library
// v2, 2023.09.20
// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html
//#region ———————————————————— Library functions
// @type A structure that contains collected values and corresponding timestamps within a period.
// @field data An array containing the values collected since the `startTime` of the period.
// @field times An array containing the timestamps corresponding to each value entry in the `data` array.
// @field startTime The starting time of the period for time offset calculations.
type collectedData
array<float> data
array<int> times
int startTime
// @function Adds a `value` to the `id` array, and removes its first value if the array's size exceeds
// the specified `maxSize`. Can be used as either a method or a function.
// @param id (array<collectedData>) An array of `collectedData` objects.
// @param maxSize (simple int) The maximum size of the `id` array.
// @param value (series collectedData) The value of the element added to the end of the `id` array.
// @returns (void) Function has no explicit return value.
method maintainArray(array<collectedData> id, simple int maxSize, series collectedData value) =>
id.push(value)
if id.size() > maxSize
id.shift()
// @function Calculates the average of all elements in the `data` field of every `collectedData` object
// in the `id` array that correspond to the time offset closest to the specified `timeOffset`.
// If the current index exceeds the last index of any past period, it uses the last available
// value from that past period instead. Can be used as either a method or a function.
// @param id (array<collectedData>) An array of `collectedData` objects that reference the values from
// all necessary periods.
// @param timeOffset (series int) The target difference between values in the `times` array from each
// `collectedData` object and the object's `startTime`.
// @returns (float) The average `data` value from each `collectedData` instance corresponding to
// time differences closest to the `timeOffset`.
method calcAverageByTime(array<collectedData> id, series int timeOffset) =>
float sum = 0.0
for eachItem in id
int startTime = eachItem.startTime
int index = eachItem.times.binary_search_leftmost(startTime + timeOffset)
float adjData = eachItem.data.size() - 1 >= index ? eachItem.data.get(index) : eachItem.data.last()
sum += adjData
float result = sum / id.size()
// @function Calculates the cumulative sum of the `source` since the last bar where `anchor` was `true`.
// @param source (series float) Source used for the calculation.
// @param anchor (series bool) The condition that triggers the reset of the calculation. The calculation
// resets when `anchor` is `true`, and continues accumulating values since the previous reset
// when `anchor` is `false`.
// @param adjustRealtime (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the
// data since the last `anchor` condition. Optional. The default is `false`.
// @returns (float) The cumulative sum of the `source`.
export calcCumulativeSeries(series float source, series bool anchor, simple bool adjustRealtime = false) =>
var float sum = 0.0
var int lastAnchor = na
if anchor
sum := 0.0
lastAnchor := time
sum += source
if adjustRealtime and not barstate.isconfirmed
int timePassed = math.min(timenow, time_close) - lastAnchor
int timeTotal = time_close - lastAnchor
float currentRatio = sum / timePassed
sum := currentRatio * timeTotal
float result = sum
// @function (Overload 1 of 2) Calculates the average `source` value over `length` periods, where the
// values in the average are from each bar whose time offset from the start of its respective
// period is closest to that of the current bar in the most recent period.
// @param source (series float) Source used for the calculation.
// @param length (simple int) The number of periods to use for the historical average calculation.
// @param anchor (series bool) The condition that triggers the onset of a new period. A new period starts
// when `anchor` is `true`.
// @param isCumulative (simple bool) If `true`, calculates the average of cumulative `source` values in each
// period at the current time offset. Optional. The default is `true`.
// @returns (float) The historical average of the `source` series at the current time offset.
export averageAtTime(
series float source, simple int length, series bool anchor, simple bool isCumulative = true
) =>
var array<collectedData> historicalData = array.new<collectedData>()
var collectedData newData = collectedData.new(array.new<float>(), array.new<int>())
float src = isCumulative ? calcCumulativeSeries(source, anchor) : source
if anchor
historicalData.maintainArray(length, newData)
newData := collectedData.new(array.new<float>(), array.new<int>(), time)
newData.times.push(time)
newData.data.push(src)
float result = calcAverageByTime(historicalData, time - newData.startTime)
// @function (Overload 2 of 2) Calculates the average `source` value over `length` periods, where the
// values in the average are from each bar whose time offset from the start of its respective
// period is closest to that of the current bar in the most recent period.
// @param source (series float) Source used for the calculation.
// @param length (simple int) The number of periods to use for the historical average calculation.
// @param timeframe (series string) Specifies the size of each period in the average calculation. A new period
// begins when a new bar opens on the specified timeframe.
// @param isCumulative (simple bool) If `true`, calculates the average of cumulative `source` values in each
// period at the current time offset. Optional. The default is `true`.
// @returns (float) The historical average of the `source` series at the current time offset.
export averageAtTime(
series float source, simple int length, simple string timeframe, simple bool isCumulative = true
) =>
var array<collectedData> historicalData = array.new<collectedData>()
var collectedData newData = collectedData.new(array.new<float>(), array.new<int>(), time(timeframe))
bool anchor = timeframe.change(timeframe)
float src = isCumulative ? calcCumulativeSeries(source, anchor) : source
if anchor
historicalData.maintainArray(length, newData)
newData := collectedData.new(array.new<float>(), array.new<int>(), time(timeframe))
newData.times.push(time)
newData.data.push(src)
float result = calcAverageByTime(historicalData, time - newData.startTime)
//#endregion
//#region ———————————————————— Example Code
// Color variables
color TEAL = color.new(color.teal, 50)
color RED = color.new(color.red, 50)
color GRAY = color.new(color.gray, 70)
// String options
string MI01 = "Cumulative"
string MI02 = "Regular"
string EQ01 = "On"
string EQ02 = "Off"
// Tooltips
string TT_RT = "The timeframe for the period reset condition. Default is 'D'."
string TT_LI = "The number of periods in the average volume calculation. Default is 5."
string TT_MI = "Choose between 'Cumulative' for a running total of volume since the last anchor point, or 'Regular' for
non-cumulative volume. Default is 'Cumulative'"
string TT_SR = "If enabled, the volume will be displayed as 'Relative Volume', which is the ratio of the current volume
to the historical average volume."
string TT_AR = "When activated in 'Cumulative' mode, this feature estimates the volume of the unclosed bar using the
volume data from the current session."
// @variable The timeframe of periods to compare.
string resetTimeInput = input.timeframe("D", "Anchor Timeframe", tooltip = TT_RT)
// @variable The number of periods to include in the average calculation.
int lengthInput = input.int(5, "No. of periods to avg.", tooltip = TT_LI)
// @variable Controls whether the average calculation will use cumulative or non-cumulative values.
string modeInput = input.string("Cumulative", "Calculation Mode", tooltip = TT_MI, options = [MI01, MI02])
// @variable If `true`, the script will display the relative volume ratio.
bool showRvolInput = input.string(EQ02, "Show as Relative Ratio", tooltip = TT_SR, options = [EQ01, EQ02]) == EQ01
// @variable If `true` and `modeInput` is "Cumulative", estimates the cumulative volume on unclosed bars.
bool estimateInput = input.string(EQ02, "Estimate Unconfirmed", tooltip = TT_AR, options = [EQ01, EQ02]) == EQ01
// @variable Is `true` when a new bar opens on the `resetTimeInput` timeframe.
bool anchor = timeframe.change(resetTimeInput)
// @variable Is `true` when the `modeInput` is "Cumulative".
bool isCumulative = modeInput == MI01
// @variable The average volume at the current time offset over the last `lengthInput` periods.
float pastVolume = averageAtTime(volume, lengthInput, resetTimeInput, isCumulative)
// @variable The current cumulative or non-cumulative volume in the current period.
float currentVolume = isCumulative ? calcCumulativeSeries(volume, anchor, estimateInput) : volume
// @variable The relative volume ratio.
float relativeValue = currentVolume / pastVolume
// Dispaly the values.
display(show) => show ? display.all : display.data_window
plot(relativeValue, "Relative Value", relativeValue >= 1 ? TEAL : RED, 1, plot.style_columns, display = display( showRvolInput), histbase = 1)
plot(pastVolume, "Past Volume Avg", GRAY, 1, plot.style_columns, display = display(not showRvolInput))
plot(currentVolume, "Current Volume", close >= open ? TEAL : RED, 1, plot.style_columns, display = display(not showRvolInput))
//#endregion
|
TypesBeta | https://www.tradingview.com/script/ykDTog6g-TypesBeta/ | Mutik159 | https://www.tradingview.com/u/Mutik159/ | 0 | 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/
// © Mutik159
//@version=5
// @description [SNG_BETA] Types Library
library("TypesBeta")
export type Level
float priceLow
float priceHigh
int weight
string name
int barIndex = 0
int barExpiration = 0
string timeframe = ""
export type Zone
line priceLow
line priceHigh
int confluenceScore
string confluences = "" |
cphelper | https://www.tradingview.com/script/GSNwrQwD-cphelper/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 27 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//
//@version=5
// @description ACPU helper library
library("cphelper", overlay = true)
import HeWhoMustNotBeNamed/drawingutils/8 as dr
import HeWhoMustNotBeNamed/_matrix/5 as ma
import HeWhoMustNotBeNamed/arrays/1 as pa
getSum(matrix<int> closedStats, int row)=>
statArray = matrix.row(closedStats, row)
sum = array.sum(statArray)
validSum = sum - array.get(statArray, 0)
[statArray, sum, validSum]
// @function calculates risk reward for given targets
// @param targetArray array of targets
// @param rrArray array of risk reward
// @param breakevenOnTarget1 option to breakeven
// @returns array<float> rrArray
export calculate_rr(float[] targetArray, float[] rrArray, simple bool breakevenOnTarget1=false)=>
entry = array.get(targetArray, 2)
stop = array.get(targetArray, 1)
target1 = array.get(targetArray, 3)
target2 = array.get(targetArray, 4)
t1RR = math.round((target1 - entry) / (entry - stop), 2)
t2RR = math.round((target2 - entry) / (entry - stop), 2)
t2stop = breakevenOnTarget1 ? entry : stop
t2TRR = math.round((target2-target1) / (target1-t2stop), 2)
array.concat(rrArray, array.from(t1RR, t2RR, t2TRR))
// @function creates trendline pairs
// @param l1StartX startX of first line
// @param l1StartY startY of first line
// @param l1EndX endX of first line
// @param l1EndY endY of first line
// @param l2StartX startX of second line
// @param l2StartY startY of second line
// @param l2EndX endX of second line
// @param l2EndY endY of second line
// @param zgColor line color
// @returns [line, line]
export trendPairs(int l1StartX, float l1StartY, int l1EndX, float l1EndY, int l2StartX, float l2StartY, int l2EndX, float l2EndY, color zgColor)=>
l1t = line.new(l1StartX, l1StartY, l1EndX, l1EndY, color=zgColor, extend=extend.both)
l2t = line.new(l2StartX, l2StartY, l2EndX, l2EndY, color=zgColor, extend=extend.both)
startBar = math.min(l2StartX, l1StartX)
endBar = l1EndX
l1Start = line.get_price(l1t, startBar)
l1End = line.get_price(l1t, endBar)
l2Start = line.get_price(l2t,startBar)
l2End = line.get_price(l2t, endBar)
line.set_extend(l1t, extend.none)
line.set_extend(l2t, extend.none)
line.set_x1(l1t, startBar)
line.set_y1(l1t, l1Start)
line.set_x2(l1t, endBar)
line.set_y2(l1t, l1End)
line.set_x1(l2t, startBar)
line.set_y1(l2t, l2Start)
line.set_x2(l2t, endBar)
line.set_y2(l2t, l2End)
[l1t, l2t]
// @function Finds type based on trendline pairs
// @param l1t line1
// @param l2t line2
// @param channelThreshold theshold for channel identification
// @returns [int, array<bool>] pattern type and flags
export find_type(line l1t, line l2t, simple float channelThreshold = 2)=>
l1Start = line.get_y1(l1t)
l1End = line.get_y2(l1t)
l2Start = line.get_y1(l2t)
l2End = line.get_y2(l2t)
startBar = line.get_x1(l1t)
endBar = line.get_x2(l2t)
l1Angle = l1End - l1Start
l2Angle = l2End - l2Start
startDiff = math.abs(l1Start-l2Start)
endDiff = math.abs(l1End-l2End)
convergenceMultiplier = (math.min(startDiff, endDiff)/math.abs(startDiff-endDiff))
maxMinRatio = math.min(startDiff, endDiff)/math.max(startDiff, endDiff)
isChannel = convergenceMultiplier >= channelThreshold
isTriangle = not isChannel and math.sign(l1Angle)!= math.sign(l2Angle)
isWedge = not isChannel and math.sign(l1Angle)==math.sign(l2Angle)
isExpanding = startDiff < endDiff
isContracting = startDiff > endDiff
flatQuotient = math.sign(l1Start-l2Start) == math.sign(l1Start-l2End) and math.sign(l1End - l2End) == math.sign(l1End - l2Start)
isFlat = isChannel and flatQuotient
isRising = not isFlat and math.sign(l1Angle) > 0 and math.sign(l2Angle) > 0
isFalling = not isFlat and math.sign(l1Angle) < 0 and math.sign(l2Angle) < 0
patternType = isChannel and isRising? 0:
isChannel and isFalling? 1:
isChannel and isFlat? 2:
isTriangle and isContracting? 3:
isTriangle and isExpanding? 4:
isWedge and isRising? (isContracting? 5 : 6):
isWedge and isFalling? (isContracting? 7 :8) : 9
[patternType, array.from(isChannel, isTriangle, isWedge, isExpanding, isContracting, isFlat, isRising, isFalling)]
// @function Flatten flags
// @param flags array of flags
// @returns [boolean, boolean, boolean, boolean, boolean, boolean, boolean] - flattened flags isChannel, isTriangle, isWedge, isExpanding, isContracting, isFlat, isRising, isFalling
export getFlags(bool[] flags)=>[array.get(flags, 0), array.get(flags, 1), array.get(flags, 2),
array.get(flags, 3), array.get(flags, 4), array.get(flags, 5),
array.get(flags, 6), array.get(flags, 7)]
// @function Get type based on type number
// @param typeNum number representing type
// @returns String value of type
export getType(int typeNum)=>
typeNum == 0? "Uptrend Channel":
typeNum == 1? "Downtrend Channel":
typeNum == 2? "Ranging Channel":
typeNum == 3? "Contracting Triangle":
typeNum == 4? "Expanding Triangle":
typeNum == 5? "Rising Wedge(Contracting)":
typeNum == 6? "Rising Wedge(Expanding)":
typeNum == 7? "Falling Wedge(Contracting)":
typeNum == 8? "Falling Wedge(Expanding)": "Indeterminate"
// @function Get status based on integer value representations
// @param status integer representing current status
// @param maxStatus integer representing max status
// @returns String status value
export getStatus(int status, int maxStatus)=>
status == -1?
(maxStatus == 0? 'Failed(Complete)':
maxStatus == 1? 'Stopped(Complete)':
maxStatus == 2? 'Target1(Complete)':
maxStatus == 3? 'Target2(Complete)': 'Unknown(Complete)'):
(maxStatus == 0? 'Awaiting Entry':
maxStatus == 1? 'Trade Active':
maxStatus == 2? 'Target1 Reached':
maxStatus == 3? 'Target2 Reached': 'Unknown')
// @function Calculate targets based on trend lines
// @param trendLines trendline pair array
// @param settingsMatrix matrix containing settings
// @param patternTypeMapping array containing pattern type mapping
// @param patternType pattern type
// @returns [array<float>, array<float>] arrays containing long and short calculated targets
export calculate_simple_targets(line[] trendLines, matrix<float> settingsMatrix, string[] patternTypeMapping, int patternType)=>
ratios = matrix.row(settingsMatrix, patternType)
line1 = array.get(trendLines, 0)
line2 = array.get(trendLines, 1)
pivots = array.from(line.get_y1(line1), line.get_y2(line1), line.get_y1(line2), line.get_y2(line2))
patternTradeType = array.get(patternTypeMapping, patternType)
contractingType = patternTradeType == 'Contracting'
base = array.max(pivots) - array.min(pivots)
longStart = contractingType? math.max(line.get_y2(line1), line.get_y2(line2)): line.get_y2(line1)
shortStart = contractingType? math.min(line.get_y2(line1), line.get_y2(line2)): line.get_y2(line1)
longStop = longStart + base*array.get(ratios, 0)
longEntry = longStart + base*array.get(ratios, 1)
longTarget1 = longStart + base*array.get(ratios, 2)
longTarget2 = longStart + base*array.get(ratios, 3)
shortStop = shortStart - base*array.get(ratios, 0)
shortEntry = shortStart - base*array.get(ratios, 1)
shortTarget1 = shortStart - base*array.get(ratios, 2)
shortTarget2 = shortStart - base*array.get(ratios, 3)
[array.from(longStop, longStop, longEntry, longTarget1, longTarget2),
array.from(shortStop, shortStop, shortEntry, shortTarget1, shortTarget2)]
// @function Recalculate position values
// @param patternTypeAndStatusMatrix matrix containing pattern type and status
// @param targetMatrix matrix containing targets
// @param index current index
// @param pIndex pattern index
// @param status current status
// @param maxStatus max status reached
// @param targetValue current target value
// @param stopValue current stop value
// @param dir direction
// @param breakevenOnTarget1 flag to breakeven upon target1
// @param patternType pattern type
// @returns [int, int] new status and maxStatus values
export recalculate_position(matrix<int> patternTypeAndStatusMatrix, matrix<float> targetMatrix, int index, int pIndex, int status, int maxStatus,
float targetValue, float stopValue, int dir, simple bool breakevenOnTarget1)=>
iStop = matrix.get(targetMatrix, index, 0)
tStop = matrix.get(targetMatrix, index, 1)
Entry = matrix.get(targetMatrix, index, 2)
Target1 = matrix.get(targetMatrix, index, 3)
Target2 = matrix.get(targetMatrix, index, 4)
newStatus = status
newMaxStatus = maxStatus
if(status!=-1 and status != 3)
newStatus := targetValue*dir > Target2*dir and maxStatus <=2 ? 3 :
targetValue*dir > Target1*dir and maxStatus <= 1? 2 :
targetValue*dir > Entry*dir and maxStatus == 0? 1 : (maxStatus > 0 and stopValue*dir < tStop*dir)? -1 : newStatus
increment = true
newMaxStatus := newStatus
if(newMaxStatus <= maxStatus)
increment := false
newMaxStatus := maxStatus
if(newStatus < status and newStatus != -1)
newStatus := status
if(increment and newMaxStatus >=2 and breakevenOnTarget1)
matrix.set(targetMatrix, index, 1, Entry)
retouch = matrix.get(patternTypeAndStatusMatrix, index, pIndex+2)
if(retouch == 0 and stopValue*dir < Entry*dir and maxStatus == 1)
matrix.set(patternTypeAndStatusMatrix, index, pIndex+2, 1)
matrix.set(patternTypeAndStatusMatrix, index, pIndex, newStatus)
matrix.set(patternTypeAndStatusMatrix, index, pIndex+1, newMaxStatus)
[newStatus, newMaxStatus]
// @function Draw targets on chart
// @param longTargets matrix containing long targets
// @param shortTargets matrix containing short targets
// @param index current index
// @param labelColor color of lines and labels
// @param patternName Pattern name
// @param positionIndex position on the chart
// @param longMaxStatus max status for long
// @param longStatus long status value
// @param shortMaxStatus max status for short
// @param shortStatus short status value
// @param tempBoxes temporary box array
// @param tempLines temporary lines array
// @param tempLabels temporary labels array
// @returns void
export draw_targets(matrix<float> longTargets, matrix<float> shortTargets, int index, color labelColor, string patternName,
int positionIndex, int longMaxStatus, int longStatus, int shortMaxStatus, int shortStatus,
box[] tempBoxes, line[] tempLines, label[] tempLabels)=>
longStop = matrix.get(longTargets, index, 0)
longEntry = matrix.get(longTargets, index, 2)
lTarget1 = matrix.get(longTargets, index, 3)
lTarget2 = matrix.get(longTargets, index, 4)
shortStop = matrix.get(shortTargets, index, 0)
shortEntry = matrix.get(shortTargets, index, 2)
sTarget1 = matrix.get(shortTargets, index, 3)
sTarget2 = matrix.get(shortTargets, index, 4)
if(longStatus == 0 and shortStatus == 0)
dr.draw_labelled_box(longEntry, shortEntry, labelColor, patternName, positionIndex, tempBoxes, tempLabels)
if(longStatus > 0)
dr.draw_labelled_box(longEntry, longStop, labelColor, patternName, positionIndex, tempBoxes, tempLabels)
dr.draw_labelled_line(lTarget1, 'Target - 1(L)', color.green, labelColor, positionIndex, longMaxStatus <= 1 and longStatus >0, tempLines, tempLabels)
dr.draw_labelled_line(lTarget2, 'Target - 2(L)', color.green, labelColor, positionIndex, longMaxStatus <= 2 and longStatus >0, tempLines, tempLabels)
if(shortStatus > 0)
dr.draw_labelled_box(shortEntry, shortStop, labelColor, patternName, positionIndex, tempBoxes, tempLabels)
dr.draw_labelled_line(sTarget1, 'Target - 1(S)', color.red, labelColor, positionIndex, shortMaxStatus <= 1 and shortStatus > 0, tempLines, tempLabels)
dr.draw_labelled_line(sTarget2, 'Target - 2(S)', color.red, labelColor, positionIndex, shortMaxStatus <= 2 and shortStatus > 0, tempLines, tempLabels)
// @function Populate open stats table
// @param patternIdArray pattern Ids
// @param barMatrix matrix containing bars
// @param patternTypeAndStatusMatrix matrix containing pattern type and status
// @param patternColorArray array containing current patter colors
// @param longTargets matrix of long targets
// @param shortTargets matrix of short targets
// @param patternRRMatrix pattern risk reward matrix
// @param OpenStatPosition table position
// @param lblSizeOpenTrades text size
// @returns void
export populate_open_stats(int[] patternIdArray, matrix<int> barMatrix, matrix<int> patternTypeAndStatusMatrix, color[] patternColorArray,
matrix<float> longTargets, matrix<float> shortTargets, matrix<float> patternRRMatrix,
simple string OpenStatPosition=position.top_right, simple string lblSizeOpenTrades = size.small)=>
var table stats = na
table.delete(stats)
numberOfPatterns = array.size(patternColorArray)
stats := table.new(position=OpenStatPosition, columns=numberOfPatterns+1, rows=20, border_width=1)
if(numberOfPatterns > 0)
rrHeader = '\nR:R\nLive R:R'
rrHeaderT2 = '\nR:R\nTrailing R:R\nLive R:R'
tableHeaders = array.from('ID', 'Pattern', 'Size/Age', 'Status', 'Long TP2'+rrHeaderT2, 'Long TP1'+rrHeader, 'Long Entry\nShort Stop', 'Short Entry\nLongStop', 'Short TP1'+rrHeader, 'Short TP2'+rrHeaderT2)
for [index, tableHeader] in tableHeaders
table.cell(table_id=stats, column=numberOfPatterns, row=index, text=tableHeader, bgcolor=color.black, text_color=color.white, text_size=lblSizeOpenTrades)
for [index, patternColor] in patternColorArray
id = array.get(patternIdArray, index)
patternType = matrix.get(patternTypeAndStatusMatrix, index, 0)
longStatus = matrix.get(patternTypeAndStatusMatrix, index, 1)
longMaxStatus = matrix.get(patternTypeAndStatusMatrix, index, 2)
longRetestStatus = matrix.get(patternTypeAndStatusMatrix, index, 3)
shortStatus = matrix.get(patternTypeAndStatusMatrix, index, 4)
shortMaxStatus = matrix.get(patternTypeAndStatusMatrix, index, 5)
shortRetestStatus = matrix.get(patternTypeAndStatusMatrix, index, 6)
patternName = getType(patternType)
barArray = matrix.row(barMatrix, index)
size = array.max(barArray) - array.min(barArray)
age = bar_index - array.max(barArray)
sizeAndAge = str.tostring(size)+'/'+str.tostring(age)
longStatusStr = getStatus(longStatus, longMaxStatus) + (longRetestStatus == 1? ' (Retested)' : '')
shortStatusStr = getStatus(shortStatus, shortMaxStatus) + (shortRetestStatus == 1? ' (Retested)' : '')
strStatus = longStatus > 0 ? longStatusStr : shortStatusStr
statusColor = longStatus > 0? color.green : shortStatus >0 ? color.red : color.silver
lTStop = math.round_to_mintick(matrix.get(longTargets, index, 1))
lEntry = math.round_to_mintick(matrix.get(longTargets, index, 2))
lTarget1 = math.round_to_mintick(matrix.get(longTargets, index, 3))
lTarget2 = math.round_to_mintick(matrix.get(longTargets, index, 4))
sTStop = math.round_to_mintick(matrix.get(shortTargets, index, 1))
sEntry = math.round_to_mintick(matrix.get(shortTargets, index, 2))
sTarget1 = math.round_to_mintick(matrix.get(shortTargets, index, 3))
sTarget2 = math.round_to_mintick(matrix.get(shortTargets, index, 4))
lRR1 = matrix.get(patternRRMatrix, index, 0)
lRR2 = matrix.get(patternRRMatrix, index, 1)
lTRR2 = matrix.get(patternRRMatrix, index, 2)
sRR1 = matrix.get(patternRRMatrix, index, 3)
sRR2 = matrix.get(patternRRMatrix, index, 4)
sTRR2 = matrix.get(patternRRMatrix, index, 5)
lLongRisk = math.abs(close-lTStop)
lStopRisk = math.abs(close-sTStop)
lLongT1Reward = math.abs(lTarget1 - close)
lLongT2Reward = math.abs(lTarget2 - close)
liveLRR1 = longMaxStatus == 1 ? str.tostring(math.round(lLongT1Reward/lLongRisk, 2)) : '-'
liveLRR2 = longMaxStatus > 0 ? str.tostring(math.round(lLongT2Reward/lLongRisk, 2)) : '-'
lShortT1Reward = math.abs(sTarget1 - close)
lShortT2Reward = math.abs(sTarget2 - close)
liveSRR1 = shortMaxStatus == 1 ? str.tostring(math.round(lShortT1Reward/lStopRisk, 2)) : '-'
liveSRR2 = shortMaxStatus > 0 ? str.tostring(math.round(lShortT2Reward/lStopRisk, 2)) : '-'
l2Str = str.tostring(lTarget2) + '\nRR : '+str.tostring(lRR2) + '\nTRR : '+str.tostring(lTRR2) + '\n' + liveLRR2
l1Str = str.tostring(lTarget1) + '\nRR : '+str.tostring(lRR1) + '\n' + liveLRR1
s1Str = str.tostring(sTarget1) + '\nRR : '+str.tostring(sRR1) + '\n' + liveSRR1
s2Str = str.tostring(sTarget2) + '\nRR : '+str.tostring(sRR2) + '\nTRR : '+str.tostring(sTRR2) + '\n' + liveSRR2
longEntryStr = str.tostring(lEntry)+'▲\n'+str.tostring(lTStop)+'■'
shortEntryStr = str.tostring(sEntry)+'▼\n'+str.tostring(sTStop)+'■'
tableColumns = array.from(str.tostring(id), patternName, sizeAndAge, strStatus, l2Str, l1Str, longEntryStr, shortEntryStr, s1Str, s2Str)
columnBgColors = array.from(statusColor, statusColor, statusColor, statusColor, color.green, color.green, color.lime, color.orange, color.red, color.red)
highlight = array.from(true, true, true, true, longMaxStatus >=2, longMaxStatus>=1, shortMaxStatus==0, longMaxStatus==0, shortMaxStatus>=1, shortMaxStatus>=2)
for [row, tableColumn] in tableColumns
table.cell(table_id=stats, column=index, row=row, text=tableColumn, bgcolor=color.new(array.get(columnBgColors, row), array.get(highlight, row)? 80 : 90),
text_color=color.new(patternColor, array.get(highlight, row)? 0 : 50), text_size=lblSizeOpenTrades)
export draw_pattern_label(line[] trendLines, matrix<bool> patternFlagMatrix, matrix<int> patternTypeAndStatusMatrix,
color[] patternColorArray, bool[] patternFlags, label[] patternLabelArray,
color zgColor, int patternType, simple bool drawLabel, simple bool clearOldPatterns, simple bool safeRepaint,
simple int maxPatternsReference)=>
l1t = array.get(trendLines, 0)
l2t = array.get(trendLines, 1)
ma.push(patternFlagMatrix, patternFlags, maxPatternsReference)
ma.push(patternTypeAndStatusMatrix, array.from(patternType, 0, 0, 0, 0, 0, 0), maxPatternsReference)
pa.push(patternColorArray, zgColor, maxPatternsReference)
if(drawLabel)
bar = line.get_x2(l1t)
l1End = line.get_y2(l1t)
l2End = line.get_y2(l2t)
[isChannel, isTriangle, isWedge, isExpanding, isContracting, isFlat, isRising, isFalling] = getFlags(patternFlags)
y = (isChannel or isWedge) and isRising? math.max(l1End, l2End) : math.min(l1End, l2End)
lblStyle = (isChannel or isWedge) and isRising? label.style_label_down : label.style_label_up
patternLabel = label.new(bar, y, getType(patternType), style=lblStyle, yloc=yloc.price, color=zgColor, textcolor=color.black,
tooltip=patternType==9?'Error calculating angle. Hence, flagged as indeterminate':'')
if(clearOldPatterns or safeRepaint)
pa.push(patternLabelArray, patternLabel, maxPatternsReference)
getClosedCellVal(matrix<int> closedStats, matrix<float> closedRRStats, matrix<int> retouchStats, matrix<int> sizeStats,
int rowNumber, int cIndex, int[] statsRow, int sum, int validSum, int[] retouchRow, int[] sizeRow, bool showStatsInPercentage)=>
currentCount = matrix.get(closedStats, rowNumber, cIndex)
lastCount = cIndex!=0 ? matrix.get(closedStats, rowNumber, cIndex-1) : 0
count = cIndex > 1? array.sum(array.slice(statsRow, cIndex, matrix.columns(closedStats))) : matrix.get(closedStats, rowNumber, cIndex)
touchCount = cIndex > 1? array.sum(array.slice(retouchRow, cIndex, matrix.columns(retouchStats))) : matrix.get(retouchStats, rowNumber, cIndex)
countPercent = cIndex == 0? (sum > 0? (count*100/sum) : 0) : (validSum > 0 ? (count*100/validSum) : 0)
tcount = count+lastCount == 0 ? 0 : count*100/(count+lastCount)
rr = cIndex >1 and sum > 0? matrix.get(closedRRStats, rowNumber, cIndex-2)/sum : 0.0
trr = (cIndex > 2 and sum > 0)? matrix.get(closedRRStats, rowNumber, cIndex-1)/sum : 0.0
avgSize = cIndex >1 and count > 0 ? int(array.sum(array.slice(sizeRow, cIndex, matrix.columns(sizeStats)))/count) : 0.0
rrStr = cIndex > 1 and sum > 0 ? '\n'+str.tostring(math.round(rr,2))+ (trr != 0 and cIndex >2 ? ' / '+str.tostring(math.round(trr, 2)):'') : ''
wrStr = (showStatsInPercentage? str.tostring(countPercent, format.percent) + (cIndex > 2? ' / ' + str.tostring(tcount, format.percent): ''):
(cIndex > 1? str.tostring(touchCount)+' / ': '') +str.tostring(count))
cellVal = wrStr+(showStatsInPercentage ? rrStr : '\n('+str.tostring(avgSize)+')')
cellVal
export populate_closed_stats(matrix<int> patternTypeAndStatusMatrix,
matrix<int> bullishCounts, matrix<int> bearishCounts,
matrix<int> bullishRetouchCounts, matrix<int> bearishRetouchCounts,
matrix<int> bullishSizeMatrix, matrix<int> bearishSizeMatrix,
matrix<float> bullishRR, matrix<float> bearishRR,
simple string ClosedStatsPosition, simple string lblSizeClosedTrades,
simple bool showSelectivePatternStats, simple bool showPatternStats, simple bool showStatsInPercentage)=>
if(barstate.islast)
closedStats = table.new(ClosedStatsPosition, 14, matrix.rows(bullishCounts)+3, border_color=color.black, border_width=2)
rowMain = array.from("Pattern/\nStatus", "", "", "Long", "", "", "", "", "Short", "", "")
rowHeaders = array.from("", "Failed", "Stopped", "Target1", "Target2", "Total", "Failed", "Stopped", "Target1", "Target2", "Total")
showOpenPatternStats = showSelectivePatternStats and matrix.rows(patternTypeAndStatusMatrix) > 0
for [index, val] in rowMain
if(showPatternStats or showOpenPatternStats or index > 1) and index!=1 and index!=2 and index!=6 and index!=7
table.cell(closedStats, index, 0, val, text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.maroon)
table.cell(closedStats, index, 1, array.get(rowHeaders, index), text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.maroon)
longColumnStart = 3
longColumnEnd = longColumnStart + matrix.columns(bullishCounts)-2
shortColumnStart = longColumnEnd + 3
shortColumnEnd = shortColumnStart + matrix.columns(bearishCounts)-2
numberOfRows = matrix.rows(bullishCounts)
if(showPatternStats or showOpenPatternStats)
table.merge_cells(closedStats, 0,0,0,1)
table.merge_cells(closedStats, longColumnStart,0,longColumnEnd,0)
table.merge_cells(closedStats, shortColumnStart,0,shortColumnEnd,0)
closedStatsTooltip = (showStatsInPercentage? 'Win Rate / Trailing Win Rate\nRisk Reward / Trailing Risk Reward':'Retest Count / Hit Count\n(Average Size of Patterns)')
closedStatsTooltipT1 = (showStatsInPercentage? 'Win Rate\nRisk Reward':'Retest Count / Hit Count\n(Average Size of Patterns)')
totalsTooltip = 'Retest Count/ Valid Count / Total Patterns\n(Average Size of Patterns)'
if(showPatternStats or showOpenPatternStats)
for i=0 to numberOfRows-2
patternColumn = matrix.col(patternTypeAndStatusMatrix, 0)
patternIndex = array.indexof(patternColumn, i)
if(not showOpenPatternStats or showPatternStats or patternIndex >= 0)
[bullishRow, lSum, lValidSum] = getSum(bullishCounts, i)
[bearishRow, sSum, sValidSum] = getSum(bearishCounts, i)
[bullishRowRetouch, lSumRetouch, lValidSumRetouch] = getSum(bullishRetouchCounts, i)
[bearishRowRetouch, sSumRetouch, sValidSumRetouch] = getSum(bearishRetouchCounts, i)
[bullishRowSize, lSumSize, lValidSumSize] = getSum(bullishSizeMatrix, i)
[bearishRowSize, sSumSize, sValidSumSize] = getSum(bearishSizeMatrix, i)
if(lSum != 0 or sSum != 0)
table.cell(closedStats, 0, i+2, getType(i), text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.teal)
for j=2 to matrix.columns(bullishCounts)-1
cellVal = getClosedCellVal(bullishCounts, bullishRR, bullishRetouchCounts, bullishSizeMatrix, i, j, bullishRow,
lSum, lValidSum, bullishRowRetouch, bullishRowSize, showStatsInPercentage)
table.cell(closedStats, j+longColumnStart-2, i+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.new(color.lime,20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeLongStr = str.tostring(int(lValidSumSize/math.max(lValidSum, 1)))
fCellTxtLong = str.tostring(lValidSumRetouch)+'/'+str.tostring(lValidSum)+'/'+str.tostring(lSum)+'\n('+avgSizeLongStr+')'
table.cell(closedStats, longColumnEnd, i+2, fCellTxtLong, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.aqua, tooltip=totalsTooltip)
for j=2 to matrix.columns(bearishCounts)-1
cellVal = getClosedCellVal(bearishCounts, bearishRR, bearishRetouchCounts, bearishSizeMatrix, i, j, bearishRow,
sSum, sValidSum, bearishRowRetouch, bearishRowSize, showStatsInPercentage)
table.cell(closedStats, j+shortColumnStart-2, i+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.new(color.orange, 20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeShortStr = str.tostring(int(sValidSumSize/math.max(sValidSum, 1)))
fCellTxtShort = str.tostring(sValidSumRetouch)+'/'+str.tostring(sValidSum)+'/'+str.tostring(sSum)+'\n('+avgSizeShortStr+')'
table.cell(closedStats, shortColumnEnd, i+2, fCellTxtShort, text_color=color.black, text_size=lblSizeClosedTrades, bgcolor=color.aqua, tooltip=totalsTooltip)
totalColor = color.yellow
[bullishLRow, llSum, llValidSum] = getSum(bullishCounts, numberOfRows-1)
[bearishLRow, slSum, slValidSum] = getSum(bearishCounts, numberOfRows-1)
[bullishLRowRetouch, llSumRetouch, llValidSumRetouch] = getSum(bullishRetouchCounts, numberOfRows-1)
[bearishLRowRetouch, slSumRetouch, slValidSumRetouch] = getSum(bearishRetouchCounts, numberOfRows-1)
[bullishLRowSize, llSumSize, llValidSumSize] = getSum(bullishSizeMatrix, numberOfRows-1)
[bearishLRowSize, slSumSize, slValidSumSize] = getSum(bearishSizeMatrix, numberOfRows-1)
if(showPatternStats or showOpenPatternStats)
table.cell(closedStats, 0, numberOfRows+2, 'Total', text_color=color.white, text_size=lblSizeClosedTrades, bgcolor=color.olive)
for j=2 to matrix.columns(bullishCounts)-1
cellVal = getClosedCellVal(bullishCounts, bullishRR, bullishRetouchCounts, bullishSizeMatrix, numberOfRows-1, j, bullishLRow,
llSum, llValidSum, bullishLRowRetouch, bullishLRowSize, showStatsInPercentage)
table.cell(closedStats, j+longColumnStart-2, numberOfRows+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=color.new(showPatternStats or showOpenPatternStats?totalColor:color.lime,20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeLongStr = str.tostring(int(llValidSumSize/math.max(llValidSum, 1)))
fCellTxtLong = str.tostring(llValidSumRetouch)+'/'+str.tostring(llValidSum)+'/'+str.tostring(llSum)+'\n('+avgSizeLongStr+')'
table.cell(closedStats, longColumnEnd, numberOfRows+2, fCellTxtLong, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=showPatternStats or showOpenPatternStats?totalColor:color.lime,
tooltip=totalsTooltip)
for j=2 to matrix.columns(bearishCounts)-1
cellVal = getClosedCellVal(bearishCounts, bearishRR, bearishRetouchCounts, bearishSizeMatrix, numberOfRows-1, j, bearishLRow,
slSum, slValidSum, bearishLRowRetouch, bearishLRowSize, showStatsInPercentage)
table.cell(closedStats, j+shortColumnStart-2, numberOfRows+2, cellVal, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=color.new(showPatternStats or showOpenPatternStats?totalColor:color.orange, 20),
tooltip=j==2?closedStatsTooltipT1 :closedStatsTooltip)
avgSizeShortStr = str.tostring(int(slValidSumSize/math.max(slValidSum, 1)))
fCellTxtShort = str.tostring(slValidSumRetouch)+'/'+str.tostring(slValidSum)+'/'+str.tostring(slSum)+'\n('+avgSizeShortStr+')'
table.cell(closedStats, shortColumnEnd, numberOfRows+2,fCellTxtShort, text_color=color.black, text_size=lblSizeClosedTrades,
bgcolor=showPatternStats or showOpenPatternStats?totalColor:color.orange,
tooltip=totalsTooltip) |
.print() | https://www.tradingview.com/script/4RillVSY-print/ | FFriZz | https://www.tradingview.com/u/FFriZz/ | 18 | 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
//@version=5
// @description Single function to print any type to console
library("print")
import FFriZz/ObjectHelpers/7 as OBJ
printCheck(string str=na) =>
string _str = str
string join = ""
if not na(_str)
int len = str.length(_str)
split = str.split(_str,"\n------\n")//↓
while len > 3800
split.shift()
_str := split.join("\n------\n")
len := str.length(_str)
"___Debugger___"+_str
timeframeChar(string tf) =>
string _tfL = ''
_tfs = timeframe.in_seconds(tf)
if _tfs < 60
_tfL := str.tostring(_tfs) + 's'
if _tfs >= 60 and _tfs < 3600
_tfL := tf + 'm'
if _tfs >= 3600 and _tfs < 86400
_tfL := str.tostring(str.tonumber(tf) / 60) + 'h'
if _tfs >= 86400
_tfL := tf
_tfL
STR(inp) => str.tostring(inp)
STRF(inp) => str.tostring(inp,"0.00")
STRR(inp) => str.replace_all(inp,"][","]\n[")
// @function `method` convert all types to string
//```
//(overload)
// *.str(any inp) => string
//```
// @param inp `any` - desc | Required
// @returns `string` formatted string
export method str(string inp) => STRR(STR(inp))
export method str(int inp) => STRR(STR(inp))
export method str(float inp) => STRR(STRF(inp))
export method str(bool inp) => STRR(STR(inp))
export method str(linefill inp) =>
_1 = linefill.get_line1(inp)
_2 = linefill.get_line2(inp)
[X,Y,XX,YY] = OBJ.Get(_1)
[x,y,xx,yy] = OBJ.Get(_2)
str = str.format('line1 x1={0,number,integer} y1={1,number,0.00} x2={2,number,integer} y2={3,number,0.00}',X,Y,XX,YY)
str += "\n"
str += str.format('line2 x1={0,number,integer} y1={1,number,0.00} x2={2,number,integer} y2={3,number,0.00}',x,y,xx,yy)
str := str.replace_all(str,",","")
export method str(line inp) =>
[x,y,xx,yy] = OBJ.Get(inp)
str.replace_all(str.format('x1={0,number,integer} y1={1,number,0.00} x2={2,number,integer} y2={3,number,0.00}', x,y,xx,yy),",","")
export method str(box inp) =>
[L,T,R,B] = OBJ.Get(inp)
str.replace_all(str.format('left={0,number,integer} top={1,number,0.00} right={2,number,integer} bottom={3,number,0.00}', L,T,R,B),",","")
export method str(label inp) =>
[x,y,t] = OBJ.Get(inp)
str.replace_all(str.format('x={0,number,integer} y={1,number,0.00}\ntext={2}', x,y,t),",","")
aStr(inp) =>
aStr = array.new<string>()
for OB in inp
aStr.push(OB.str())
str.tostring(aStr)
mStr(inp) =>
mStr = matrix.new<string>()
for r = 0 to inp.rows() > 0 ? inp.rows()-1 : na
aStr = array.new<string>()
for c = 0 to inp.columns()-1
aStr.push(inp.get(r,c).str())
mStr.add_row(r,aStr)
str.tostring(mStr)
export method str(matrix<string> inp) => STRR(STR(inp))
export method str(matrix<int> inp) => STRR(STR(inp))
export method str(matrix<float> inp) => STRR(STRF(inp))
export method str(matrix<bool> inp) => STRR(STR(inp))
export method str(matrix<linefill> inp) => STRR(mStr(inp))
export method str(matrix<line> inp) => STRR(mStr(inp))
export method str(matrix<box> inp) => STRR(mStr(inp))
export method str(matrix<label> inp) => STRR(mStr(inp))
export method str(array<linefill> inp) => STRR(str.replace_all(aStr(inp),", line1", ",\nline1"))
export method str(array<line> inp) => STRR(str.replace_all(aStr(inp),", x1",",\n x1"))
export method str(array<box> inp) => STRR(str.replace_all(aStr(inp),", left",",\n left"))
export method str(array<label> inp) => STRR(str.replace_all(aStr(inp),", x",",\n x"))
export method str(array<string> inp) => STRR(STR(inp))
export method str(array<int> inp) => STRR(STR(inp))
export method str(array<float> inp) => STRR(STRF(inp))
export method str(array<bool> inp) => STRR(STR(inp))
// @function arrayShorten
// @param str `string` - the string to shorten | Required
// @returns `string` - a shortened version of the input string if it is an array with more than 7 elements, otherwise the original string
export method arrayShorten(string str) =>
out = ''
if str.startswith(str,'[') and str.endswith(str,']')
a = str.split(str,"")
a.pop()
a.shift()
out := a.join("")
build = array.new<string>()
final = array.new<string>()
split = str.split(out,',')
size = split.size()
if size >= 6
slice = split.slice(0,3)
final.concat(slice)
final.push(" ...")
slice := split.slice(size-3,size)
final.concat(slice)
out := "["+final.join(",")+"]"
else
out := str
else
out := str
out
arrayOfMatrixShorten(str) =>
_str = str
if not str.startswith(_str,"[")
_str := "["+_str
if not str.endswith(_str,"]")
_str += "]"
arrayShorten(_str)
// @function matrixShorten
// @param str `string` - the string to shorten | Required
// @returns `string` - the shortened matrix string if the input is a matrix, otherwise returns the input string as is
export method matrixShorten(string str) =>
out = ''
if str.startswith(str,'[') and str.endswith(str,']')
split = str.split(str,"]\n[")
if split.size() > 5
size = split.size()
s1 = array.slice(split,0,2)
s2 = array.slice(split,size-2,size)
build1 = ""
build2 = ""
for [k,i] in s1
build1 += arrayOfMatrixShorten(i)
if k < 1
build1 += "\n"
for [k,i] in s2
build2 += arrayOfMatrixShorten(i)
if k < 1
build2 += '\n'
out := "[\n"+build1+"\n...\n"+build2+"\n]"
else
for i in str.split(str,"\n")
out += arrayOfMatrixShorten(i)
out := "[\n"+out+"\n]"
else
out := str
out
method labelCell(label _label,str="",_type,ID) =>
_str = str
_str := "\n------\n"+_type+" "+ID+" = "+str
getText = _label.get_text()
buildText = ""
match = str.match(getText,"<\\w+>\\s+"+ID+"\\s+=\\s+.*")
if match != ""
matchMatch = str.match(match,ID+"\\s+=\\s+.*")
if matchMatch != ""
match := str.replace_all(match,matchMatch,ID+" = "+str)
buildText := match
else
buildText := getText+_str
check = printCheck(str.replace_all(buildText,"___Debugger___",""))
_label.set_text(check)
build2 = "[Debugger] -- "+str.format_time(time, "[MM/dd/yy] -- [HH:mm]", "UTC-5")+"\n------\n"+check
split = str.split(str.replace(build2,"___Debugger___",""),"\n------\n")
table = table.new(position.bottom_right,2,split.size(),#000000,color.lime,1,color.lime,1)
for [y,z] in split
addStr = ""
align = text.align_right
zSplit = str.split(z," = ")
if y == 0
addStr := " -- ["+timeframeChar(timeframe.period)+"] -- [Con"+((table.all).size()).str()+"]"
align := text.align_center
table.merge_cells(table,0,0,1,0)
table.cell(table,0,y,zSplit.get(0) + addStr,0,0,color.lime,align,text.align_top,"small",#000000,font.family_monospace)
if y == 0
continue
table.cell(table,1,y,zSplit.get(1),0,0,color.lime,text.align_left,text.align_top,"small",#000000,font.family_monospace)
if (table.all).size() > 1
(table.all).get(1).delete()
check
labelCheck(str,id,_type) =>
labelAll = label.all
_size = labelAll.size()
var found = false
for i in labelAll
txt = i.get_text()
match = str.contains(txt,"___Debugger___")
if match
found := true
new = i.copy()
i.delete()
new.labelCell(str,_type,id)
break
if not found
label.new(na,na,"___Debugger___"+_type+" "+id+" = "+str,color=color(na),textcolor=color(na))
_print(x,string ID, string _type) =>
switch ID
"" => runtime.error("Must provide (unique) ID for each print call")
if barstate.islast
labelCheck(" "+x.str(),ID,_type)
// @function print all types to theh same console with just this `method/function`
//```
//(overload)
// *.print(any x, string ID, bool shorten=true?) => console
//"param 'shorten' - only for arrays and matrixs" | true
//```
// @param x - `any` input to convert
// @param ID - `string` unique id for label on console `MUST BE UNIQUE`
// @param shorten - `bool` true will shorten arrays and matrixs | true
// @returns adds the `ID` and the `inp` to the console on the chart
export method print(string x, string ID) => _print(x.str(), ID, "<string>"), x
export method print(float x, string ID) => _print(x.str(), ID, "<float>"), x
export method print(int x, string ID) => _print(x.str(), ID, "<int>"), x
export method print(box x, string ID) => _print(x.str(), ID, "<box>"), x
export method print(bool x, string ID) => _print(x.str(), ID, "<bool>"), x
export method print(label x, string ID) => _print(x.str(), ID, "<label>"), x
export method print(line x, string ID) => _print(x.str(), ID, "<line>"), x
export method print(linefill x, string ID) => _print(x.str(), ID, "<linefill>"), x
export method print(array<string> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<string>"), x
export method print(array<float> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<float>"), x
export method print(array<int> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<int>"), x
export method print(array<box> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<box>"), x
export method print(array<bool> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<bool>"), x
export method print(array<label> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<label>"), x
export method print(array<line> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<line>"), x
export method print(array<linefill> x, string ID, bool shorten=true) => _x = shorten ? x.str().arrayShorten() : x.str(), _print(_x, ID, "array<linefill>"), x
export method print(matrix<string> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<string>"), x
export method print(matrix<float> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<float>"), x
export method print(matrix<int> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<int>"), x
export method print(matrix<box> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<box>"), x
export method print(matrix<bool> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<bool>"), x
export method print(matrix<label> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<label>"), x
export method print(matrix<line> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<line>"), x
export method print(matrix<linefill> x, string ID, bool shorten=true) => _x = shorten ? x.str().matrixShorten() : x.str(), _print(_x, ID, "matrix<linefill>"), x
if barstate.islast
label myLabel = label.new(bar_index,high,"Hello World",color=color.white).print("label")
box myBox = box.new(bar_index-10,high,bar_index,low,border_color=color.red,border_width=2,bgcolor=color.green).print("box")
line myLine = line.new(bar_index-5,high,bar_index + 5,high,color=color.blue,width=2).print("line")
line myLineCopy = myLine.copy().print("lineCopy")
line.set_y1(myLineCopy,low)
line.set_y2(myLineCopy,low)
linefill myLineFill = linefill.new(myLine,myLineCopy,color=color.purple).print("linefill")
lineArray = array.from(myLine,myLineCopy).print("lineArray")
boxArray = array.new<box>()
boxArray.push(myBox)
boxArray.push(myBox)
boxArray.print("boxArray")
boxMatrix = matrix.new<box>()
boxMatrix.add_row(0,boxArray)
boxMatrix.add_row(0,boxArray)
boxMatrix.add_row(0,boxArray)
boxMatrix.print("boxMatrix")
for i = 0 to 2
math.random(0,100000).print("random test "+i.str())
m = matrix.new<int>()
m.add_row(0,array.from(1345,11345,10767,186,1055500,105236,10057,100547))
m.add_row(0,array.from(1111,11111,11111,111,1111111,111111,11111,111111))
m.add_row(0,array.from(2222,22222,22222,222,2222222,222222,22222,222222))
m.add_row(0,array.from(3333,33333,33333,333,3333333,333333,33333,333333))
m.add_row(0,array.from(4444,44444,44444,444,4444444,444444,44444,444444))
m.add_row(0,array.from(5555,55555,55555,555,5555555,555555,55555,555555))
m.add_row(0,array.from(6666,66666,66666,666,6666666,666666,66666,666666))
m.add_row(0,array.from(7777,77777,77777,777,7777777,777777,77777,777777))
m.add_row(0,array.from(8853,88382,88588,888,3588238,538888,83538,835678))
m.print("matrix")
array<float> A = array.from(343.33,24.01,33.222,1.1112,44.343,0.443,33.3,3.34).print("array")
tA = (table.all).size().print("tableall")
lA = (label.all).size().print("labelAll")
|
Zigzag Chart Points | https://www.tradingview.com/script/fB9UtJlz-Zigzag-Chart-Points/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 190 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RozaniGhani-RG
//@version=5
indicator('Zigzag Chart Points', 'ZCP', true, max_bars_back = 500)
// 0. Inputs
// 1. Variables and arrays
// 2. Map
// 3. Switches
// 4. Methods
// 5. Executions
//#region ———————————————————— 0. Inputs
G0 = 'Main Settings'
T0 = 'Zigzag values\nDefault : 14\nMin : 2\nMax : 50'
length = input.int( 14, 'Length', group = G0, minval = 2, maxval = 50, tooltip = T0)
colorUp = input.color(color.lime, 'Trend', group = G0, inline = '0')
colorDn = input.color( color.red, '', group = G0, inline = '0')
G1 = 'Line Settings'
T1 = 'Default\nStyle : Solid\nWidth : 4'
showLine = input.bool( true, 'Show / hide', group = G1)
lineType = input.string( 'solid', 'Style', group = G1, options = ['dash', 'dot', 'solid', 'arrow right', 'arrow left'])
extendType = input.string( 'none', 'Extend', group = G1, options = ['left', 'right', 'both', 'none'])
width = input.int( 4, 'Width', group = G1, minval = 1, maxval = 4, tooltip = T1)
G2 = 'Label Settings'
T2 = 'Small font size recommended for mobile app or multiple layout'
showLabel = input.bool( true, 'Show / hide', group = G2)
fontSize = input.string( 'normal', 'Size', group = G2, options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = T2)
//#endregion
//#region ———————————————————— 1. Variables and arrays
float ph = na, ph := ta.highestbars(high, length) == 0 ? high : na
float pl = na, pl := ta.lowestbars( low, length) == 0 ? low : na
var dir = 0, dir := not na(ph) and na(pl) ? 1 : not na(pl) and na(ph) ? -1 : dir
var zigzag = array.new<chart.point>(0)
oldzigzag = zigzag.copy()
dirchanged = dir[0] != dir[1]
var arraySize = 10
//#endregion
//#region ———————————————————— 2. Map
// Create map for label's tooltip
tip = map.new<string, string>()
tip.put('HH', 'HIGHER HIGH')
tip.put('LH', 'LOWER HIGH')
tip.put('LL', 'LOWER LOW')
tip.put('HL', 'HIGHER LOW')
//#endregion
//#region ———————————————————— 3. Switches
switchLine = switch lineType
'dash' => line.style_dashed
'dot' => line.style_dotted
'solid' => line.style_solid
'arrow right' => line.style_arrow_right
'arrow left' => line.style_arrow_left
switchExtend = switch extendType
'left' => extend.left
'right' => extend.right
'both' => extend.both
'none' => extend.none
//#endregion
//#region ———————————————————— 4. Methods
// @function addPoint
// @param price float value
// @param index int value
// @param arraySize array size for chart.point[]
// @returns chart.point[]
method addPoint(chart.point[] id, float price = na, int index = na, int arraySize = na) =>
id.unshift(chart.point.new(time, index, price))
if id.size() > arraySize
id.pop()
// @function updatePoints
// @param price float value
// @param index int value
// @param arraySize array size for chart.point[]
// @param dir int value
// @returns chart.point[]
method updatePoints(chart.point[] id, float price = na, int index = na, int arraySize = na, int dir = na) =>
if id.size() == 0
id.addPoint(price, index)
else
if dir == 1 and price > id.get(0).price or dir == -1 and price < id.get(0).price
id.set(0, chart.point.new(time, index, price))
chart.point.new(na, na, na)
//#endregion
//#region ———————————————————— 5. Executions
if na(ph) or na(pl)
if dirchanged
zigzag.addPoint(dir == 1 ? ph : pl, bar_index, arraySize)
else
zigzag.updatePoints(dir == 1 ? ph : pl, bar_index, arraySize, dir)
if zigzag.size() >= 3 and oldzigzag.size() >= 3
var line linezigzag = na
var label labelzigzag = na
if zigzag.get(0).index != oldzigzag.get(0).index or zigzag.get(0).price != oldzigzag.get(0).price
if zigzag.get(1).index == oldzigzag.get(1).index and zigzag.get(1).price == oldzigzag.get(1).price
linezigzag.delete()
labelzigzag.delete()
if showLine
linezigzag := line.new(
first_point = zigzag.get(0),
second_point = zigzag.get(1),
xloc = xloc.bar_index,
extend = switchExtend,
color = dir == 1 ? colorUp : colorDn,
style = switchLine,
width = width)
if showLabel
textzigzag = dir == 1 ? zigzag.get(0).price > zigzag.get(2).price ? 'HH' : 'LH' :
zigzag.get(0).price < zigzag.get(2).price ? 'LL' : 'HL'
colorzigzag = dir == 1 ? zigzag.get(0).price > zigzag.get(2).price ? colorDn : colorUp :
zigzag.get(0).price < zigzag.get(2).price ? colorUp : colorDn
currentRes = timeframe.isintraday ? 'dd-MMM-yyyy HH:mm' : 'dd-MMM-yyyy'
labelzigzag := label.new(
point = zigzag.get(0),
text = textzigzag,
xloc = xloc.bar_index,
style = dir == 1 ? label.style_label_down : label.style_label_up,
color = color.new(color.blue, 100),
textcolor = colorzigzag,
size = fontSize,
tooltip = tip.get(textzigzag) + '\n' +
'Time : ' + str.format_time(zigzag.get(0).time, currentRes, syminfo.timezone)+ '\n' +
'Price : ' + str.tostring(zigzag.get(0).price))
//#endregion |
AoDivergenceLibrary_ | https://www.tradingview.com/script/ly8v0ih1-AoDivergenceLibrary/ | SamaaraDas | https://www.tradingview.com/u/SamaaraDas/ | 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/
// © sammie123567858
//@version=5
// @description this has functions which calculate and plot divergences which are used for ao divergences. essentially, this finds divergences by using the ao divergence logic. this logic has been used in "AO Hid & Reg Div with LC & Kernel".
library("AoDivergenceLibrary_", true)
// UTILITY FUNCTIONS
//to find where the ao range starts (the bar at which the ao first started being negative)
findBuyStartPoint(float osc) =>
int shift = 0
int i = 0
while osc[i] < 0
shift := i
i := i + 1
//
shift
//
// @function to find the lowest ao in the given range (starting from _end upto end)
// @param start is for the left side. the parameter value is supposed to be a bar index
// @param _end is for the right side. the parameter value is supposed to be a shift
export findLowestAo(int start, float osc, int _end=0) =>
float lowest = 0
int end = bar_index - start
for i = _end to end
if osc[i] < lowest
lowest := osc[i]
//
lowest
//
// @function to find the lowest price in the given range (starting from start upto end)
// @param start is for the right side. the parameter value is supposed to be a bar index
// @param end is for the left side. the parameter value is supposed to be a bar index
export findLowestPrice(int start, int end) =>
int endShift = bar_index - end
int startShift = bar_index - start
float lowest = low[startShift]
int barTime = 0
for i = startShift to endShift
if low[i] < lowest
lowest := low[i]
barTime := i
//
//
[lowest, barTime]
//
//to find lowest low (in price) in a given price range for updating the trendline
findLowest(int start, int end) =>
int endShift = end
int startShift = start
float lowest = low[startShift]
int barTime = 0
for i = startShift to endShift
if low[i] < lowest
lowest := low[i]
barTime := i
//
//
[lowest, barTime]
//
//------------------------------------------------------------------------------------------------------------------------------------
//to find where the ao range starts (the bar at which the ao first started being negative)
findSellStartPoint(float osc) =>
int shift = 0
int i = 0
while osc[i] > 0
shift := i
i := i + 1
//
shift
//
// @function to find the highes ao in the given range (starting from _end upto end)
// @param start is for the left side. the parameter value is supposed to be a bar index
// @param _end is for the right side. the parameter value is supposed to be a shift
export findHighestAo(int start, float osc, int _end=0) =>
float highest = 0
int end = bar_index - start
for i = _end to end
if osc[i] > highest
highest := osc[i]
//
highest
//
// @function to find the highest price in the given range (starting from start upto end)
// @param start is for the right side. the parameter value is supposed to be a bar index
// @param end is for the left side. the parameter value is supposed to be a bar index
export findHighestPrice(int start, int end) =>
int endShift = bar_index - end
int startShift = bar_index - start
float highest = high[startShift]
int barTime = 0
for i = startShift to endShift
if high[i] > highest
highest := high[i]
barTime := i
//
//
[highest, barTime]
//
//to find lowest low (in price) in a given price range for updating the trendline
findHighest(int start, int end) =>
int endShift = end
int startShift = start
float highest = high[startShift]
int barTime = 0
for i = startShift to endShift
if high[i] > highest
highest := high[i]
barTime := i
//
//
[highest, barTime]
//
// FOR CALCULATING AND PLOTTING REGULAR BULL DIVERGENCES
export regBullDivergence(bool swingLow, float osc, color colour) =>
bool lookingForBull = false
int _check = 0
float curr_lowest = 0
int bullStart = 0
var int bullishTrendlineStart = 0
var latestBullLine = line(na)
var bullLineCounter = -1
bullStart := bar_index - findBuyStartPoint(osc)
curr_lowest := findLowestAo(bullStart, osc)
var minRangesLowest = array.new_float(0)
var minRangesEnd = array.new_int(0)
var minRangesStart = array.new_int(0)
var int lowestIndex = -1
var float lowestVal = 0
var int lowestStart = -1
//start afresh when there is a a zigzag down
if not swingLow
bullStart := 0
curr_lowest := 0
array.clear(minRangesLowest)
array.clear(minRangesEnd)
array.clear(minRangesStart)
lowestIndex := -1
lowestVal := 0
lowestStart := -1
//
if swingLow
if osc < 0
lookingForBull := true
//
//storing the lowest value, start shift & end shift of the current range & updating it as values change
if lookingForBull == true
int lastIndex = array.size(minRangesStart) - 1
if array.size(minRangesStart) >= 1
if array.get(minRangesStart, lastIndex) != bullStart
array.push(minRangesStart, 0)
array.push(minRangesEnd, 0)
array.push(minRangesLowest, 0)
//
//
if array.size(minRangesStart) == 0
array.push(minRangesStart, 0)
array.push(minRangesEnd, 0)
array.push(minRangesLowest, 0)
//
lastIndex := array.size(minRangesStart)-1
array.set(minRangesLowest, lastIndex, curr_lowest) //set the lowest value for the current range
array.set(minRangesStart, lastIndex, bullStart) //set the start shift for the current range
array.set(minRangesEnd, lastIndex, bar_index) //set the end shift for the current range
//
//checking if there is more than 1 range to compare with the lowest ao val up untill the current bar
if array.size(minRangesStart) >= 1
int lastIndex = array.size(minRangesStart) - 1
if array.get(minRangesLowest, lastIndex) < lowestVal
lowestVal := array.get(minRangesLowest, lastIndex)
lowestIndex := lastIndex
//
//
//checking if there are more than 2 ranges to compare/ delete lines
if array.size(minRangesStart) >= 2
int lastIndex = array.size(minRangesStart) - 1
//get the start and end shifts of the 2 ranges
int start2 = array.get(minRangesStart, lastIndex)
int end2 = array.get(minRangesEnd, lastIndex)
int start1 = array.get(minRangesStart, lowestIndex)
int end1 = array.get(minRangesEnd, lowestIndex)
//if lowest in range 2 is greater than lowest in range 1
if array.get(minRangesLowest, lastIndex) > lowestVal
[lowest1, index1] = findLowestPrice(start1, end1)
[lowest2, index2] = findLowestPrice(start2, end2)
//check if lowest price in range 1 > lowest price in range 2
if lowest1 > lowest2
if lowestStart != start1
latestBullLine := line.new(time[index2], lowest2, time[index1], lowest1, xloc = xloc.bar_time, extend = extend.none, color = colour, style = line.style_solid, width = 1)
bullLineCounter := bullLineCounter + 1
lowestStart := start1
//
if lowestStart == start1
//to find the lowest low from the start of trendline to current bar
[currLowest, currLowestIndex] = findLowest(index1, 0)
line.set_x1(latestBullLine, time[currLowestIndex])
line.set_y1(latestBullLine, currLowest)
//
//
//
//
_check
//
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FOR CALCULATING AND PLOTTING REGULAR BEAR DIVERGENCES
export regBearDivergence(bool swingHigh, float osc, color colour) =>
bool lookingForBear = false
int _check = 0
float curr_highest = 0
int bearStart = 0
var int bearishTrendlineStart = 0
var latestBearLine = line(na)
var bearLineCounter = -1
bearStart := bar_index - findSellStartPoint(osc)
curr_highest := findHighestAo(bearStart, osc)
var maxRangesHighest = array.new_float(0)
var maxRangesEnd = array.new_int(0)
var maxRangesStart = array.new_int(0)
var int highestIndex = -1
var float highestVal = 0
var int highestStart = -1
//start afresh when there is a a zigzag up
if swingHigh
bearStart := 0
curr_highest := 0
array.clear(maxRangesHighest)
array.clear(maxRangesEnd)
array.clear(maxRangesStart)
highestIndex := -1
highestVal := 0
highestStart := -1
//
if not swingHigh
if osc > 0
lookingForBear := true
//
//storing the highest value, start shift & end shift of the current range & updating it as values change
if lookingForBear == true
int lastIndex = array.size(maxRangesStart) - 1
if array.size(maxRangesStart) >= 1
if array.get(maxRangesStart, lastIndex) != bearStart
array.push(maxRangesStart, 0)
array.push(maxRangesEnd, 0)
array.push(maxRangesHighest, 0)
//
//
if array.size(maxRangesStart) == 0
array.push(maxRangesStart, 0)
array.push(maxRangesEnd, 0)
array.push(maxRangesHighest, 0)
//
lastIndex := array.size(maxRangesStart)-1
array.set(maxRangesHighest, lastIndex, curr_highest) //set the highest value for the current range
array.set(maxRangesStart, lastIndex, bearStart) //set the start shift for the current range
array.set(maxRangesEnd, lastIndex, bar_index) //set the end shift for the current range
//
//checking if there is more than 1 range to compare with the highest ao val up untill the current bar
if array.size(maxRangesStart) >= 1
int lastIndex = array.size(maxRangesStart) - 1
if array.get(maxRangesHighest, lastIndex) > highestVal
highestVal := array.get(maxRangesHighest, lastIndex)
highestIndex := lastIndex
//
//
//checking if there are more than 2 ranges to compare/ delete lines
if array.size(maxRangesStart) >= 2
int lastIndex = array.size(maxRangesStart) - 1
//get the start and end shifts of the 2 ranges
int start2 = array.get(maxRangesStart, lastIndex)
int end2 = array.get(maxRangesEnd, lastIndex)
int start1 = array.get(maxRangesStart, highestIndex)
int end1 = array.get(maxRangesEnd, highestIndex)
//if highest in range 2 is lower than highest in range 1
if array.get(maxRangesHighest, lastIndex) < highestVal
[highest1, index1] = findHighestPrice(start1, end1)
[highest2, index2] = findHighestPrice(start2, end2)
//check if highest price in range 1 < highest price in range 2
if highest1 < highest2
if highestStart != start1
latestBearLine := line.new(time[index2], highest2, time[index1], highest1, xloc = xloc.bar_time, extend = extend.none, color = colour, style = line.style_solid, width = 1)
bearLineCounter := bearLineCounter + 1
highestStart := start1
//
if highestStart == start1
//to find the highest high from the start of trendline to current bar
[currHighest, currHighestIndex] = findHighest(index1, 0)
line.set_x1(latestBearLine, time[currHighestIndex])
line.set_y1(latestBearLine, currHighest)
//
//
//
//
_check
//
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FOR CALCULATING AND PLOTTING HIDDEN BULL DIVERGENCES
export hidBullDivergence(bool swingHigh, float osc, color colour) =>
bool lookingForBull2 = false
float curr_lowest2 = 0
int bullStart2 = 0
int _check = 0
var minRangesLowest2 = array.new_float(0)
var minRangesHighest2 = array.new_float(0)
var minRangesEnd2 = array.new_int(0)
var minRangesStart2 = array.new_int(0)
var int lowestIndex2 = -1
var int highestLowestIndex2 = -1
var float lowestVal2 = 0
var float highestLowestVal2 = -100000
var int highestStartHid2 = -1
var latestBullLine2 = line(na)
//LOGIC FOR HIDDEN DIV
bullStart2 := bar_index - findBuyStartPoint(osc)
float lowest = 0
int end = bar_index - bullStart2
for i = 0 to end
if osc[i] < lowest
lowest := osc[i]
//
curr_lowest2 := lowest
//start afresh when there is a a zigzag down
if swingHigh
bullStart2 := 0
curr_lowest2 := 0
array.clear(minRangesLowest2)
array.clear(minRangesEnd2)
array.clear(minRangesStart2)
lowestIndex2 := -1
highestLowestIndex2 := -1
lowestVal2 := 0
highestLowestVal2 := -100000
highestStartHid2 := -1
//
if not swingHigh
if osc < 0
lookingForBull2 := true
//
//storing the lowest value, start shift & end shift of the current range & updating it as values change
if lookingForBull2 == true
int lastIndex = array.size(minRangesStart2) - 1
if array.size(minRangesStart2) >= 1 //if there are elements in the arrays already,
if array.get(minRangesStart2, lastIndex) != bullStart2 //and a new range has started, push new elements in the arrays which are made for that range specifically
array.push(minRangesStart2, 0)
array.push(minRangesEnd2, 0)
array.push(minRangesLowest2, 0)
//
//
if array.size(minRangesStart2) == 0 //if there is nothing in the array, push a new element in to store values
array.push(minRangesStart2, 0)
array.push(minRangesEnd2, 0)
array.push(minRangesLowest2, 0)
//
lastIndex := array.size(minRangesStart2)-1
array.set(minRangesLowest2, lastIndex, curr_lowest2) //set the lowest value for the current range
array.set(minRangesStart2, lastIndex, bullStart2) //set the start shift for the current range
array.set(minRangesEnd2, lastIndex, bar_index) //set the end shift for the current range
//
if array.size(minRangesLowest2) >= 2 and osc[1] < osc and osc >= 0
int lastIndex = array.size(minRangesLowest2) - 1
//only compare the lowest value of R2 (current range) with lowest value of R1 (previous range) once R2 is complete
if array.get(minRangesLowest2, lastIndex) > array.get(minRangesLowest2, lastIndex- 1) and array.get(minRangesLowest2, lastIndex) > highestLowestVal2 //checking if there is a higher low in the current range
highestLowestVal2 := array.get(minRangesLowest2, lastIndex)
highestLowestIndex2 := lastIndex
//
//
bool bullHidDiv = false
float _lowest1 = 0, float _lowest2 = 0
int _startShift1 = 0, int _startShift2 = 0
int _index1 = 0, int _index2 = 0
int _endShift1 = 0, int _endShift2 = 0
if array.size(minRangesLowest2) >= 2 and highestLowestIndex2 >= 0
int lastIndex = array.size(minRangesLowest2) - 1
//get the start and end shifts of the 2 ranges
int start2 = array.get(minRangesStart2, lastIndex)
int end2 = array.get(minRangesEnd2, lastIndex)
int start1 = array.get(minRangesStart2, highestLowestIndex2)
int end1 = array.get(minRangesEnd2, highestLowestIndex2)
//if lowest in range 2 is lesser than lowest in range 1
if array.get(minRangesLowest2, lastIndex) < highestLowestVal2 and highestLowestIndex2 < lastIndex
_endShift1 := bar_index - end1
_startShift1 := bar_index - start1
_lowest1 := low[_startShift1]
//DO NOT CHANGE THE WAY THE 2ND IF CONDITION IS WRITTEN, BECAUSE IT ONLY WORKS THIS WAY... I DONT KNOW WHY THOUGH
for i = _startShift1 to _endShift1
if low[i] < _lowest1
_lowest1 := low[i]
//
if low[i] <= _lowest1
_index1 := i
//
//
_endShift2 := bar_index - end2
_startShift2 := bar_index - start2
_lowest2 := low[_startShift2]
//DO NOT CHANGE THE WAY THE 2ND IF CONDITION IS WRITTEN, BECAUSE IT ONLY WORKS THIS WAY... I DONT KNOW WHY THOUGH
for i = _endShift2 to _startShift2
if low[i] < _lowest2
_lowest2 := low[i]
//
if low[i] <= _lowest2
_index2 := i
//
//
//check if lowest price in range 1 < lowest price in range 2
if _lowest1 < _lowest2
bullHidDiv := true
//x1, y1 is the left most part
//x2, y2 is the right most part
latestBullLine2 := line.new(time[_index1], _lowest1, time[_index2], _lowest2, xloc = xloc.bar_time, extend = extend.none, color = colour, style = line.style_solid, width = 1)
//
//
//
_check
//
// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// FOR CALCULATING AND PLOTTING HIDDEN BEAR DIVERGENCES
export hidBearDivergence(bool swingHigh, float osc, color colour) =>
bool lookingForBear2 = false
float curr_highest2 = 0
int bearStart2 = 0
int _check = 0
var maxRangesHighest2 = array.new_float(0)
var maxRangesLowest2 = array.new_float(0)
var maxRangesEnd2 = array.new_int(0)
var maxRangesStart2 = array.new_int(0)
var int highestIndex2 = -1
var int lowestHighestIndex2 = -1
var float lowestHighestVal2 = 100000
var int lowestStartHid2 = -1
var latestBearLine2 = line(na)
//LOGIC FOR HIDDEN DIV
bearStart2 := bar_index - findSellStartPoint(osc)
float highest = 0
int end3 = bar_index - bearStart2
for i = 0 to end3
if osc[i] > highest
highest := osc[i]
//
curr_highest2 := highest
//start afresh when there is a a zigzag down
if not swingHigh
bearStart2 := 0
curr_highest2 := 0
array.clear(maxRangesHighest2)
array.clear(maxRangesEnd2)
array.clear(maxRangesStart2)
highestIndex2 := -1
lowestHighestIndex2 := -1
lowestHighestVal2 := 100000
lowestStartHid2 := -1
//
if swingHigh
if osc > 0
lookingForBear2 := true
//
//storing the highest value, start shift & end shift of the current range & updating it as values change
if lookingForBear2 == true
int lastIndex = array.size(maxRangesStart2) - 1
if array.size(maxRangesStart2) >= 1 //if there are elements in the arrays already,
if array.get(maxRangesStart2, lastIndex) != bearStart2 //and a new range has started, push new elements in the arrays which are made for that range specifically
array.push(maxRangesStart2, 0)
array.push(maxRangesEnd2, 0)
array.push(maxRangesHighest2, 0)
//
//
if array.size(maxRangesStart2) == 0 //if there is nothing in the array, push a new element in to store values
array.push(maxRangesStart2, 0)
array.push(maxRangesEnd2, 0)
array.push(maxRangesHighest2, 0)
//
lastIndex := array.size(maxRangesStart2)-1
array.set(maxRangesHighest2, lastIndex, curr_highest2) //set the highest value for the current range
array.set(maxRangesStart2, lastIndex, bearStart2) //set the start shift for the current range
array.set(maxRangesEnd2, lastIndex, bar_index) //set the end shift for the current range
//
if array.size(maxRangesHighest2) >= 2 and osc[1] > osc and osc < 0
int lastIndex = array.size(maxRangesHighest2) - 1
//only compare the highest value of R2 (current range) with highest value of R1 (previous range) once R2 is complete
if array.get(maxRangesHighest2, lastIndex) < array.get(maxRangesHighest2, lastIndex- 1) and array.get(maxRangesHighest2, lastIndex) < lowestHighestVal2 //checking if there is a lower high in the current range
lowestHighestVal2 := array.get(maxRangesHighest2, lastIndex)
lowestHighestIndex2 := lastIndex
//
//
bool bearHidDiv = false
float _highest1 = 0, float _highest2 = 0
int _startShift1 = 0, _startShift2 = 0
int _index1 = 0, _index2 = 0
int _endShift1 = 0, _endShift2 = 0
if array.size(maxRangesHighest2) >= 2 and lowestHighestIndex2 >= 0
int lastIndex = array.size(maxRangesHighest2) - 1
//get the start and end shifts of the 2 ranges
int start2 = array.get(maxRangesStart2, lastIndex)
int end2 = array.get(maxRangesEnd2, lastIndex)
int start1 = array.get(maxRangesStart2, lowestHighestIndex2)
int end1 = array.get(maxRangesEnd2, lowestHighestIndex2)
//if highest in range 2 is greater than highest in range 1
if array.get(maxRangesHighest2, lastIndex) > lowestHighestVal2 and lowestHighestIndex2 < lastIndex
_startShift1 := bar_index - start1
_endShift1 := bar_index - end1
_highest1 := high[_startShift1]
for i = _startShift1 to _endShift1
if high[i] > _highest1
_highest1 := high[i]
//
if high[i] >= _highest1
_index1 := i
//
//
_startShift2 := bar_index - start2
_endShift2 := bar_index - end2
_highest2 := high[_startShift2]
for i = _startShift2 to _endShift2
if high[i] > _highest2
_highest2 := high[i]
//
if high[i] >= _highest2
_index2 := i
//
//
//check if highest price in range 1 < highest price in range 2
if _highest1 > _highest2
bearHidDiv := true
//x1, y1 is the left most part
//x2, y2 is the right most part
latestBearLine2 := line.new(time[_index1], _highest1, time[_index2], _highest2, xloc = xloc.bar_time, extend = extend.none, color = colour, style = line.style_solid, width = 1)
//
//
//
_check
//
|
Indicators | https://www.tradingview.com/script/t2XN73VR-Indicators/ | SamaaraDas | https://www.tradingview.com/u/SamaaraDas/ | 2 | 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/
// © sammie123567858
//@version=5
// @description this has a calculation for the most used indicators.
library("Indicators", overlay = true)
import jdehorty/KernelFunctions/2 as kernels
import jdehorty/MLExtensions/2 as ml
// FUNCTIONS USED BY THE EXPORTED FUNCTIONS
kernel_regression(_src, _size, _h, r, x_0) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
for i = 0 to _size + x_0
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_h, 2) * 2 * r))), -r)
_currentWeight += y*w
_cumulativeWeight += w
_currentWeight / _cumulativeWeight
//
// FOR DRAWING THE SWING HIGH/LOW LINES
// @function draws swing high/low based on the oscillator given
// @returns (in this order) current high, current low
export drawSwings(float osc, bool isRsi = false, float rsiOb = 70, float rsiOs = 20) =>
// for the bar index of the oscillator range (The start of the oscillator range)
var int negativeStart = int(na)
var int positiveStart = int(na)
// for the lowest/highest value in the current oscillator range
var float lowestVal = float(na)
var float highestVal = float(na)
// for the lowest/highest bar on the chart in the current oscillator range
var int lowestBar = int(na)
var int highestBar = int(na)
// for checking if we are drawing lines from the same point
var int uplineRange = 0
var int dwnlineRange = 0
// for knowing which range we are in (this is only for rsi)
var bool isBullRange = bool(na)
// variables for keeping a track of the last 2 highs/lows
var int previousLow = 0
var int previousLowHigh = 0
var int currentLow = 0
var int previousHigh = 0
var int previousHighLow = 0
var int currentHigh = 0
// to make sure it gets the bar index of when the range starts when the crossover condition cant find it
if (osc < 0 and na(osc[1]) and not isRsi) or (isRsi and not isBullRange and osc >= rsiOb and not na(osc))
if isRsi
isBullRange := true
positiveStart := bar_index
highestVal := high
else
negativeStart := bar_index
lowestVal := low
//
if (osc > 0 and na(osc[1]) and not isRsi) or (isRsi and isBullRange and osc <= rsiOs and not na(osc))
if isRsi
isBullRange := false
negativeStart := bar_index
lowestVal := low
else
positiveStart := bar_index
highestVal := high
//
// to record the start of the range
if osc < 0 and osc[1] > 0 and not isRsi
negativeStart := bar_index
lowestVal := low
//
if osc > 0 and osc[1] < 0 and not isRsi
positiveStart := bar_index
highestVal := high
//
// to find the highest/lowest bar and its price in the range
if (osc < 0 and na(osc[1]) == false and not isRsi) or (isRsi and not isBullRange)
if low <= lowestVal
lowestVal := low
lowestBar := bar_index
//
if (osc > 0 and na(osc[1]) == false and not isRsi) or (isRsi and isBullRange)
if high >= highestVal
highestVal := high
highestBar := bar_index
//
// Draw lines based on the conditions (i had to comment this out because i can't use lines in a function which is being used in the security function)
// var line upline = line(na)
// var line dwnline = line(na)
// if negativeStart < positiveStart
// if negativeStart != uplineRange
// upline := line.new(time[bar_index - lowestBar], lowestVal, time[bar_index - highestBar], highestVal, color = lineColor, xloc = xloc.bar_time, width = lineWidth)
// uplineRange := negativeStart
// else
// upline.set_x2(time[bar_index - highestBar])
// upline.set_y2(highestVal)
// if positiveStart < negativeStart
// if positiveStart != dwnlineRange
// dwnline := line.new(time[bar_index - highestBar], highestVal, time[bar_index - lowestBar], lowestVal, color = lineColor, xloc = xloc.bar_time, width = lineWidth)
// dwnlineRange := positiveStart
// else
// dwnline.set_x2(time[bar_index - lowestBar])
// dwnline.set_y2(lowestVal)
// //
// to get the latest 2 lows
currentLow := lowestBar
if lowestBar >= highestBar and previousLow != lowestBar[1] and previousLowHigh != highestBar
previousLow := lowestBar[1]
previousLowHigh := highestBar
//
// to get the latest 2 highs
currentHigh := highestBar
if highestBar >= lowestBar and previousHigh != highestBar[1] and previousHighLow != lowestBar
previousHigh := highestBar[1]
previousHighLow := lowestBar
//
[highestVal, lowestVal]
//
type Label
int long
int short
int neutral
type FeatureArrays
array<float> f1
array<float> f2
array<float> f3
array<float> f4
array<float> f5
type FeatureSeries
float f1
float f2
float f3
float f4
float f5
type Filter
bool volatility
bool regime
bool adx
//
series_from(feature_string, _close, _high, _low, _hlc3, simple int f_paramA, simple int f_paramB) =>
switch feature_string
"RSI" => ml.n_rsi(_close, f_paramA, f_paramB)
"WT" => ml.n_wt(_hlc3, f_paramA, f_paramB)
"CCI" => ml.n_cci(_close, f_paramA, f_paramB)
"ADX" => ml.n_adx(_high, _low, _close, f_paramA)
get_lorentzian_distance(int i, int featureCount, FeatureSeries featureSeries, FeatureArrays featureArrays) =>
switch featureCount
5 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i))) +
math.log(1+math.abs(featureSeries.f5 - array.get(featureArrays.f5, i)))
4 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i))) +
math.log(1+math.abs(featureSeries.f4 - array.get(featureArrays.f4, i)))
3 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i))) +
math.log(1+math.abs(featureSeries.f3 - array.get(featureArrays.f3, i)))
2 => math.log(1+math.abs(featureSeries.f1 - array.get(featureArrays.f1, i))) +
math.log(1+math.abs(featureSeries.f2 - array.get(featureArrays.f2, i)))
// @function this calculates macd 4c
// @param fastMa is the period for the fast ma. the minimum value is 7
// @param slowMa is the period for the slow ma. the minimum value is 7
// @returns the macd 4c value for the current bar
export macd4C(int fastMa=12, int slowMa=26) =>
[_macd,_,_] = ta.macd(close[0], fastMa, slowMa, 9)
_macd
//
// @function this calculates rsi
// @param rsiSourceInput is the source for the rsi
// @param rsiLengthInput is the period for the rsi
// @returns the rsi value for the current bar
export rsi(float rsiSourceInput=close, simple int rsiLengthInput=14) =>
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))
rsi
//
// @function this calculates ao
// @param source is the source for the ao
// @param fastPeriod is the period for the fast ma
// @param slowPeriod is the period for the slow ma
// @returns the ao value for the current bar
export ao(float source=hl2, int fastPeriod=5, int slowPeriod=34) =>
ao = ta.sma(source,fastPeriod) - ta.sma(source,slowPeriod)
ao
//
// @function this calculates nadaraya watson kernel indicator a.k.a signal line
// @returns the signal line value for the current bar and some other irrelevent stuff (except for _plotColor)
export signalLineKernel(int lag, float h, float r, int x_0, bool smoothColors, float _src=close, color c_bullish=#3AFF17, color c_bearish=#FD1707) =>
_size = array.size(array.from(_src)) // size of the data series
_yhat1 = kernel_regression(_src, _size, h, r, x_0)
_yhat2 = kernel_regression(_src, _size, h - lag, r, x_0)
bool _isBullish = _yhat1[1] < _yhat1
bool _isBullishSmooth = _yhat2 > _yhat1
color _colorByCross = _isBullishSmooth ? c_bullish : c_bearish
color _colorByRate = _isBullish ? c_bullish : c_bearish
color _plotColor = smoothColors ? _colorByCross : _colorByRate
[_yhat1, lag, smoothColors, c_bullish, c_bearish, _plotColor]
//
// @function this calculates zigzag and draws it on the chart (if allowed)
// @returns a bool value which checks if the current swing is a high or a low
export zigzagCalc(int Depth, int Deviation, int Backstep, bool repaint, bool Show_zz, int line_thick=1, color text_color=color.white) =>
var track = 0
var bool swingHigh = false
var last_h1 = 1, last_h1 := last_h1 + 1
var last_l1 = 1, last_l1 := last_l1 + 1
var lw1 = 1, var hg1 = 1
lw1 := lw1 + 1, hg1 := hg1 + 1
p_lw1 = -ta.lowestbars(Depth), p_hg1 = -ta.highestbars(Depth)
lowing1 = lw1 == p_lw1 or low - low[p_lw1] > Deviation*syminfo.mintick
highing1 = hg1 == p_hg1 or high[p_hg1] - high > Deviation*syminfo.mintick
lh1 = ta.barssince(not highing1[1]), ll1 = ta.barssince(not lowing1[1])
down1 = ta.barssince(not (lh1 > ll1)) >= Backstep, lower1 = low[lw1] > low[p_lw1], higher1 = high[hg1] < high[p_hg1]
if lw1 != p_lw1 and (not down1[1] or lower1)
lw1 := p_lw1 < hg1 ? p_lw1 : 0
if hg1 != p_hg1 and (down1[1] or higher1)
hg1 := p_hg1 < lw1 ? p_hg1 : 0
line zz1 = na
label point1 = na
x11 = down1 ? lw1 : hg1
y11 = down1 ? low[lw1] : high[hg1]
if down1 == down1[1]
if repaint
label.delete(point1[1])
line.delete(zz1[1])
down1
if down1 != down1[1]
if down1
last_h1 := hg1
else
last_l1 := lw1
if not repaint
nx = down1?last_h1:last_l1
track := bar_index-nx
swingHigh := down1 ? true: false
if Show_zz == true
zz1 := line.new(bar_index-nx, down1 ? high[nx] : low[nx], bar_index-(down1?last_l1:last_h1), down1 ? low[last_l1] : high[last_h1], width=line_thick, color=down1?color.lime:color.red)
point1 := label.new(bar_index-nx, down1 ? high[nx] : low[nx], down1 ? (high[nx] > high[last_h1[1]]?"HH":"LH") : (low[nx] < low[last_l1[1]] ? "LL" : "HL"), style=down1?label.style_label_down:label.style_label_up, size=size.tiny, color=down1?color.red:color.lime, textcolor=color.new(text_color, 0), tooltip = down1 ? (high[nx] > high[last_h1[1]]?"Higher High":"Lower High") : (low[nx] < low[last_l1[1]] ? "Lower Low" : "Higher Low"))
down1
if repaint
track := bar_index-x11
swingHigh := down1 ? false: true
if Show_zz == true
zz1 := line.new(bar_index-(down1?last_h1:last_l1), down1 ? high[last_h1] : low[last_l1], bar_index-x11, y11, width=line_thick, color=down1?color.red:color.lime)
point1 := label.new(bar_index-x11, y11, down1 ? (low[x11] < low[last_l1] ? "LL" : "HL") : (high[x11] > high[last_h1]?"HH":"LH"), style=down1?label.style_label_up:label.style_label_down, size=size.tiny, color=down1?color.lime:color.red, textcolor=color.new(text_color, 0), tooltip = down1 ? (low[x11] < low[last_l1] ? "Lower Low" : "Higher Low") : (high[x11] > high[last_h1]?"Higher High":"Lower High"))
//
swingHigh
//
// @function this calculates LC labels and LC kernel line
// @returns a tuple of the long and short signal. you can choose which bar you want it from. the default is 1. this means that it will give those signals from shift 1.
export lc(bool useVolatilityFilter, float regimeThreshold, bool useRegimeFilter, float source, int adxThreshold, bool useAdxFilter, string f1_string, simple int f1_paramA, simple int f1_paramB, string f2_string, simple int f2_paramA, simple int f2_paramB, string f3_string, simple int f3_paramA, simple int f3_paramB, string f4_string, simple int f4_paramA, simple int f4_paramB, string f5_string, simple int f5_paramA, simple int f5_paramB, int maxBarsBack, bool useEmaFilter, bool useSmaFilter, simple int emaPeriod, simple int smaPeriod, int featureCount, int neighborsCount, simple int h1, simple float r1, simple int x, simple int lag1, bool useKernelSmoothing, bool useKernelFilter, int shift=1) =>
var prediction = 0.0
Filter filter = Filter.new(ml.filter_volatility(1, 10, useVolatilityFilter), ml.regime_filter(ohlc4, regimeThreshold, useRegimeFilter), ml.filter_adx(source, 14, adxThreshold, useAdxFilter))
//
// FeatureSeries Object: Calculated Feature Series based on Feature Variables
featureSeries = FeatureSeries.new(
series_from(f1_string, close, high, low, hlc3, f1_paramA, f1_paramB), // f1
series_from(f2_string, close, high, low, hlc3, f2_paramA, f2_paramB), // f2
series_from(f3_string, close, high, low, hlc3, f3_paramA, f3_paramB), // f3
series_from(f4_string, close, high, low, hlc3, f4_paramA, f4_paramB), // f4
series_from(f5_string, close, high, low, hlc3, f5_paramA, f5_paramB) // f5
)
//
var f1Array = array.new_float()
var f2Array = array.new_float()
var f3Array = array.new_float()
var f4Array = array.new_float()
var f5Array = array.new_float()
array.push(f1Array, featureSeries.f1)
array.push(f2Array, featureSeries.f2)
array.push(f3Array, featureSeries.f3)
array.push(f4Array, featureSeries.f4)
array.push(f5Array, featureSeries.f5)
featureArrays = FeatureArrays.new(
f1Array, // f1
f2Array, // f2
f3Array, // f3
f4Array, // f4
f5Array // f5
)
Label direction = Label.new(
long=1,
short=-1,
neutral=0
)
_ema = ta.ema(close, emaPeriod)
_sma = ta.ema(close, smaPeriod)
maxBarsBackIndex = last_bar_index >= maxBarsBack ? last_bar_index - maxBarsBack : 0
isEmaUptrend = useEmaFilter ? close > _ema : true
isEmaDowntrend = useEmaFilter ? close < _ema : true
isSmaUptrend = useSmaFilter ? close > _sma : true
isSmaDowntrend = useSmaFilter ? close < _sma : true
src = source
y_train_series = src[4] < src[0] ? direction.short : src[4] > src[0] ? direction.long : direction.neutral
var y_train_array = array.new_int(0)
// Variables used for ML Logic
var predictions = array.new_float(0)
var signal = direction.neutral
var distances = array.new_float(0)
array.push(y_train_array, y_train_series)
lastDistance = -1.0
size = math.min(maxBarsBack-1, array.size(y_train_array)-1)
sizeLoop = math.min(maxBarsBack-1, size)
if bar_index >= maxBarsBackIndex //{
for i = 0 to sizeLoop //{
d = get_lorentzian_distance(i, featureCount, featureSeries, featureArrays)
if d >= lastDistance and i%4 //{
lastDistance := d
array.push(distances, d)
array.push(predictions, math.round(array.get(y_train_array, i)))
if array.size(predictions) > neighborsCount //{
lastDistance := array.get(distances, math.round(neighborsCount*3/4))
array.shift(distances)
array.shift(predictions)
//}
//}
//}
prediction := array.sum(predictions)
//}
filter_all = filter.volatility and filter.regime and filter.adx
signal := prediction > 0 and filter_all ? direction.long : prediction < 0 and filter_all ? direction.short : nz(signal[1])
var int barsHeld = 0
barsHeld := ta.change(signal) ? 0 : barsHeld + 1
isHeldFourBars = barsHeld == 4
isHeldLessThanFourBars = 0 < barsHeld and barsHeld < 4
// Fractal Filters: Derived from relative appearances of signals in a given time series fractal/segment with a default length of 4 bars
isDifferentSignalType = ta.change(signal)
isEarlySignalFlip = ta.change(signal) and (ta.change(signal[1]) or ta.change(signal[2]) or ta.change(signal[3]))
isBuySignal = signal == direction.long and isEmaUptrend and isSmaUptrend
isSellSignal = signal == direction.short and isEmaDowntrend and isSmaDowntrend
isLastSignalBuy = signal[4] == direction.long and isEmaUptrend[4] and isSmaUptrend[4]
isLastSignalSell = signal[4] == direction.short and isEmaDowntrend[4] and isSmaDowntrend[4]
isNewBuySignal = isBuySignal and isDifferentSignalType
isNewSellSignal = isSellSignal and isDifferentSignalType
c_green = color.new(#009988, 20)
c_red = color.new(#CC3311, 20)
transparent = color.new(#000000, 100)
yhat1 = kernels.rationalQuadratic(source, h1, r1, x)
yhat2 = kernels.gaussian(source, h1-lag1, x)
kernelEstimate = yhat1
// Kernel Rates of Change
bool wasBearishRate = yhat1[2] > yhat1[1]
bool wasBullishRate = yhat1[2] < yhat1[1]
bool isBearishRate = yhat1[1] > yhat1
bool isBullishRate = yhat1[1] < yhat1
isBearishChange = isBearishRate and wasBullishRate
isBullishChange = isBullishRate and wasBearishRate
// Kernel Crossovers
bool isBullishSmooth = yhat2 >= yhat1
bool isBearishSmooth = yhat2 <= yhat1
// Bullish and Bearish Filters based on Kernel
isBullish = useKernelFilter ? (useKernelSmoothing ? isBullishSmooth : isBullishRate) : true
isBearish = useKernelFilter ? (useKernelSmoothing ? isBearishSmooth : isBearishRate) : true
// Entry Conditions: Booleans for ML Model Position Entries
startLongTrade = isNewBuySignal and isBullish and isEmaUptrend and isSmaUptrend
startShortTrade = isNewSellSignal and isBearish and isEmaDowntrend and isSmaDowntrend
[startLongTrade[shift], startShortTrade[shift]]
//
|
Micro Dots with VMA line [Crypto_Chili_] | https://www.tradingview.com/script/OqTwtKuy-Micro-Dots-with-VMA-line-Crypto-Chili/ | Crypto_Chili_ | https://www.tradingview.com/u/Crypto_Chili_/ | 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/
// © Crypto_Chili_
// Credit to LazyBear for the Variable Moving Average
// Credit to KivancOzbilgic for his Supertrend
// The Micro Dots were hours of testing different combinations of indicators and settings to find what looked and worked best. This is what I came up with, use it as a rough draft as it could probably be added to or changed around.
// Send me a message if you create something I'd love it see it!
// Thank you friends I hope you enjoy!
//@version=5
indicator('Micro Dots with VMA line', shorttitle='Micro Track', overlay=true, format=format.price, precision=0)
microDots = input.bool(true, title='Show Micro Dots?')
stl=input.bool(true, title="Show VMA Trend Line?", inline='1')
vmaString = input.string('Fast', ' Intensity:', options=['Fast', 'Medium', 'Slow'], inline='1')
vmalength = vmaString == 'Fast' ? 9 : vmaString == 'Medium' ? 18 : 27
// Micro Dot Super Trend
MD_Multiplier =
timeframe.period == '720' ? 1.2
: timeframe.period == 'D' ? 1.3
: timeframe.period == '2D' ? 1.3
: timeframe.period == '3D' ? 1.3
: timeframe.period == '4D' ? 1.3
: timeframe.period == '5D' ? 1.3
: timeframe.period == '6D' ? 1.3 : 1.1
MD_Periods = 10
MD_src = hl2
MD_atr = ta.sma(ta.tr, MD_Periods)
MD_up = MD_src - (MD_Multiplier * MD_atr)
MD_up := close[1] > nz(MD_up[1], MD_up) ? math.max(MD_up, nz(MD_up[1], MD_up)) : MD_up
MD_dn = MD_src + (MD_Multiplier * MD_atr)
MD_dn := close[1] < nz(MD_dn[1], MD_dn) ? math.min(MD_dn, nz(MD_dn[1], MD_dn)) : MD_dn
MD_trend = 1
MD_trend := nz(MD_trend[1], MD_trend)
MD_trend := MD_trend == -1 and close > nz(MD_dn[1], MD_dn) ? 1 : MD_trend == 1 and close < nz(MD_up[1], MD_up) ? -1 : MD_trend
// Micro Dot Variable Moving Average
MD_vmasrc = close
MD_vmalength = 3
MD_k = 1.0/MD_vmalength
MD_pdm = math.max((MD_vmasrc - MD_vmasrc[1]), 0)
MD_mdm = math.max((MD_vmasrc[1] - MD_vmasrc), 0)
MD_pdmS = 0.0
MD_pdmS := ((1 - MD_k)*nz(MD_pdmS[1]) + MD_k*MD_pdm)
MD_mdmS = 0.0
MD_mdmS := ((1 - MD_k)*nz(MD_mdmS[1]) + MD_k*MD_mdm)
MD_s = MD_pdmS + MD_mdmS
MD_pdi = MD_pdmS/MD_s
MD_mdi = MD_mdmS/MD_s
MD_pdiS = 0.0
MD_pdiS := ((1 - MD_k)*nz(MD_pdiS[1]) + MD_k*MD_pdi)
MD_mdiS = 0.0
MD_mdiS := ((1 - MD_k)*nz(MD_mdiS[1]) + MD_k*MD_mdi)
MD_d = math.abs(MD_pdiS - MD_mdiS)
MD_s1 = MD_pdiS + MD_mdiS
MD_iS = 0.0
MD_iS := ((1 - MD_k)*nz(MD_iS[1]) + MD_k*MD_d/MD_s1)
MD_hhv = ta.highest(MD_iS, MD_vmalength)
MD_llv = ta.lowest(MD_iS, MD_vmalength)
MD_d1 = MD_hhv - MD_llv
MD_vI = (MD_iS - MD_llv)/MD_d1
MD_vma = 0.0
MD_vma := (1 - MD_k*MD_vI)*nz(MD_vma[1]) + MD_k*MD_vI*MD_vmasrc
// Micro Dot Moving Average
srcMD = (close)
lengthMD = (18)
maMD = ta.sma(srcMD, lengthMD)
// MOM
lenMD = 7
srcmomMD = hlc3
mom = srcmomMD - srcmomMD[lenMD]
// Calculating Data
trendUp = MD_trend == 1 ? MD_up : na
trendDown = MD_trend == 1 ? na : MD_dn
// Variable Moving Average
vmaUp = MD_vma < close
vmaDown = MD_vma > close
// Moving Average
maUp = close > maMD
maDown = close < maMD
// Momentum
momUp = mom > 0
momDown = mom < 0
//
// Mixing Data
microUp = momUp and vmaUp and maUp and trendUp and not vmaDown
microDown = momDown and maDown and maDown and trendDown and not vmaUp
// Plotting Micro Dots
plotshape(microDots ? microUp : na, title="Strength Dot", color=#00ff8f, style=shape.circle, size=size.auto, location=location.belowbar)
plotshape(microDots ? microDown : na, title="Weakness Dot", color=#f74557, style=shape.circle, size=size.auto, location=location.abovebar)
alertcondition(microUp != 0, title="Strength Dot", message="Strength Dot has started, and may indicator the new direction of the overall Trend")
alertcondition(microDown != 0, title="Weakness Dot", message="Weakness Dot has started, and may indicator the new direction of the overall Trend")
alertcondition(microUp or microDown == 0, title="No Dots", message="No dots are dispalying, trend could be reversing")
// VMA Trend Line
vmasrc=close
k = 1.0/vmalength
pdm = math.max((vmasrc - vmasrc[1]), 0)
mdm = math.max((vmasrc[1] - vmasrc), 0)
pdmS = 0.0
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS = 0.0
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = 0.0
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS = 0.0
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = 0.0
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = ta.highest(iS, vmalength)
llv = ta.lowest(iS, vmalength)
d1 = hhv - llv
vI = (iS - llv)/d1
vma = 0.0
vma := (1 - k*vI)*nz(vma[1]) + k*vI*vmasrc
vmaC=(vma > vma[1]) ? color.new(#008000,10) : (vma<vma[1]) ? color.new(#FF0000,10) : (vma==vma[1]) ? color.new(#ff9800,10) : na
plot(vma, color=stl?vmaC:na, linewidth=3, title="VMA Trend Line") |
Spot Symbols for Crypto | https://www.tradingview.com/script/LHeG1DDl-Spot-Symbols-for-Crypto/ | weak_hand | https://www.tradingview.com/u/weak_hand/ | 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/
// © weak_hand
//@version=5
// @description This Library has one purpose only. It generate Symbols for the Crypto Spot Market, like all the currencies pairs of most Crypto Exchanges available to TradingView.
library("CryptoSpotSymbols")
// @function Generate 27 Symbols for the Spot Market of Binance.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [ARS, BIDR, BNB, BUSD, BRL, BTC, DAI, DOT, DOGE, ETH, EUR, GBP, IDRT, NGN, PLN, RON, RUB, TRY, TRX, TUSD, UAH, USD, USDC, USDT, VAI, XRP, ZAR]
export Binance(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BINANCE"
string binance01 = str.format("{0}:{1}ARS" , prefix, basecurrency)
string binance02 = str.format("{0}:{1}BIDR", prefix, basecurrency)
string binance03 = str.format("{0}:{1}BNB" , prefix, basecurrency)
string binance04 = str.format("{0}:{1}BUSD", prefix, basecurrency)
string binance05 = str.format("{0}:{1}BRL" , prefix, basecurrency)
string binance06 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string binance07 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string binance08 = str.format("{0}:{1}DOT" , prefix, basecurrency)
string binance09 = str.format("{0}:{1}DOGE", prefix, basecurrency)
string binance10 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string binance11 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string binance12 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string binance13 = str.format("{0}:{1}IDRT", prefix, basecurrency)
string binance14 = str.format("{0}:{1}NGN" , prefix, basecurrency)
string binance15 = str.format("{0}:{1}PLN" , prefix, basecurrency)
string binance16 = str.format("{0}:{1}RON" , prefix, basecurrency)
string binance17 = str.format("{0}:{1}RUB" , prefix, basecurrency)
string binance18 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string binance19 = str.format("{0}:{1}TRX" , prefix, basecurrency)
string binance20 = str.format("{0}:{1}TUSD", prefix, basecurrency)
string binance21 = str.format("{0}:{1}UAH" , prefix, basecurrency)
string binance22 = str.format("{0}:{1}USD" , prefix, basecurrency)
string binance23 = str.format("{0}:{1}USDC", prefix, basecurrency)
string binance24 = str.format("{0}:{1}USDT", prefix, basecurrency)
string binance25 = str.format("{0}:{1}VAI" , prefix, basecurrency)
string binance26 = str.format("{0}:{1}XRP" , prefix, basecurrency)
string binance27 = str.format("{0}:{1}ZAR" , prefix, basecurrency)
[binance01, binance02, binance03, binance04, binance05, binance06, binance07, binance08, binance09, binance10, binance11, binance12, binance13, binance14, binance15, binance16, binance17, binance18, binance19, binance20, binance21, binance22, binance23, binance24, binance25, binance26, binance27]
// @function Generate seven Symbols for the Spot Market of BinanceUS.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BUSD, BTC, DAI, ETH, USD, USDC, USDT]
export BinanceUS(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BINANCEUS"
string binanceus01 = str.format("{0}:{1}BUSD", prefix, basecurrency)
string binanceus02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string binanceus03 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string binanceus04 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string binanceus05 = str.format("{0}:{1}USD" , prefix, basecurrency)
string binanceus06 = str.format("{0}:{1}USDC", prefix, basecurrency)
string binanceus07 = str.format("{0}:{1}USDT", prefix, basecurrency)
[binanceus01, binanceus02, binanceus03, binanceus04, binanceus05, binanceus06, binanceus07]
// @function Generate 12 Symbols for the Spot Market of Bitfinex.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, CNHT, EUR, EUT, GBR, JPY, MIM, MXNT, TRY, USD, UST, XAUT]
export Bitfinex(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITFINEX"
string bitfinex01 = basecurrency == "BTC" ? na : str.format("{0}:{1}BTC", prefix, basecurrency)
string bitfinex02 = str.format("{0}:{1}CNHT", prefix, basecurrency)
string bitfinex03 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bitfinex04 = str.format("{0}:{1}EUT" , prefix, basecurrency)
string bitfinex05 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string bitfinex06 = str.format("{0}:{1}JPY" , prefix, basecurrency)
string bitfinex07 = str.format("{0}:{1}MIM" , prefix, basecurrency)
string bitfinex08 = str.format("{0}:{1}MXNT", prefix, basecurrency)
string bitfinex09 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string bitfinex10 = str.format("{0}:{1}USD" , prefix, basecurrency)
string bitfinex11 = str.format("{0}:{1}UST" , prefix, basecurrency)
string bitfinex12 = str.format("{0}:{1}XAUT", prefix, basecurrency)
[bitfinex01, bitfinex02, bitfinex03, bitfinex04, bitfinex05, bitfinex06, bitfinex07, bitfinex08, bitfinex09, bitfinex10, bitfinex11, bitfinex12]
// @function Generate three Symbols for the Spot Market of bitFlyer.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, JPY, USD]
export bitFlyer(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITFLYER"
string bitflyer01 = str.format("{0}:{1}BTC", prefix, basecurrency)
string bitflyer02 = str.format("{0}:{1}JPY", prefix, basecurrency)
string bitflyer03 = str.format("{0}:{1}USD", prefix, basecurrency)
[bitflyer01, bitflyer02, bitflyer03]
// @function Generate seven Symbols for the Spot Market of Bitget.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BRL, BTC, ETH, EUR, GBP, USDC, USDT]
export Bitget(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITGET"
string bitget01 = str.format("{0}:{1}BRL" , prefix, basecurrency)
string bitget02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string bitget03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string bitget04 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bitget05 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string bitget06 = str.format("{0}:{1}USDC", prefix, basecurrency)
string bitget07 = str.format("{0}:{1}USDT", prefix, basecurrency)
[bitget01, bitget02, bitget03, bitget04, bitget05, bitget06, bitget07]
// @function Generate two Symbols for the Spot Market of Bithumb.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [KRW, BTC]
export Bithumb(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITHUMB"
string bithumb01 = str.format("{0}:{1}KRW", prefix, basecurrency)
string bithumb02 = str.format("{0}:{1}BTC", prefix, basecurrency)
[bithumb01, bithumb02]
// @function Generate one Symbol for the Spot Market of bitkub.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns THB
export bitkub(simple string basecurrency = syminfo.basecurrency) =>
string bitkub01 = str.format("BITKUB:{0}THB", basecurrency)
bitkub01
// @function Generate two Symbols for the Spot Market of BitMEX.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [USDT, XBT]
export BitMEX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITMEX"
string bcur_imp = basecurrency == "BTC" ? "XBT" : basecurrency
string bitmex01 = str.format("{0}:{1}USDT", prefix, bcur_imp)
string bitmex02 = str.format("{0}:{1}XBT" , prefix, bcur_imp)
[bitmex01, bitmex02]
// @function Generate six Symbols for the Spot Market of bitpanda pro.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [CHF, EUR, EUROC, GBP, USDC, USDT]
export bitpanda_pro(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITPANDAPRO"
string bitpandapro01 = str.format("{0}:{1}CHF" , prefix, basecurrency)
string bitpandapro02 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bitpandapro03 = str.format("{0}:{1}EUROC", prefix, basecurrency)
string bitpandapro04 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string bitpandapro05 = str.format("{0}:{1}USDC" , prefix, basecurrency)
string bitpandapro06 = str.format("{0}:{1}USDT" , prefix, basecurrency)
[bitpandapro01, bitpandapro02, bitpandapro03, bitpandapro04, bitpandapro05, bitpandapro06]
// @function Generate nine Symbols for the Spot Market of bitrue.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [ADA, BTR, BUSD, BTC, ETH, SOL, USDC, USDT, XRP]
export bitrue(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITRUE"
string bitrue01 = str.format("{0}:{1}ADA" , prefix, basecurrency)
string bitrue02 = str.format("{0}:{1}BTR" , prefix, basecurrency)
string bitrue03 = str.format("{0}:{1}BUSD", prefix, basecurrency)
string bitrue04 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string bitrue05 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string bitrue06 = str.format("{0}:{1}SOL" , prefix, basecurrency)
string bitrue07 = str.format("{0}:{1}USDC", prefix, basecurrency)
string bitrue08 = str.format("{0}:{1}USDT", prefix, basecurrency)
string bitrue09 = str.format("{0}:{1}XRP" , prefix, basecurrency)
[bitrue01, bitrue02, bitrue03, bitrue04, bitrue05, bitrue06, bitrue07, bitrue08, bitrue09]
// @function Generate eight Symbols for the Spot Market of Bitstamp.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, EUR, ETH, GBP, PAX, USD, USDC, USDT]
export Bitstamp(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITSTAMP"
string bitstamp01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string bitstamp02 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bitstamp03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string bitstamp04 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string bitstamp05 = str.format("{0}:{1}PAX" , prefix, basecurrency)
string bitstamp06 = str.format("{0}:{1}USD" , prefix, basecurrency)
string bitstamp07 = str.format("{0}:{1}USDC", prefix, basecurrency)
string bitstamp08 = str.format("{0}:{1}USDT", prefix, basecurrency)
[bitstamp01, bitstamp02, bitstamp03, bitstamp04, bitstamp05, bitstamp06, bitstamp07, bitstamp08]
// @function Generate six Symbols for the Spot Market of BITTREX.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, EUR, ETH, USD, USDC, USDT]
export BITTREX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BITTREX"
string bittrex01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string bittrex02 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bittrex03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string bittrex04 = str.format("{0}:{1}USD" , prefix, basecurrency)
string bittrex05 = str.format("{0}:{1}USDC", prefix, basecurrency)
string bittrex06 = str.format("{0}:{1}USDT", prefix, basecurrency)
[bittrex01, bittrex02, bittrex03, bittrex04, bittrex05, bittrex06]
// @function Generate 15 Symbols for the Spot Market of BTSE.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [AED, AUD, CAD, CHF, EUR, GBP, HKD, INR, JPY, SGD, USD, USDC, USDP, USDT]
export BTSE(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BTSE"
string btse01 = str.format("{0}:{1}AED" , prefix, basecurrency)
string btse02 = str.format("{0}:{1}AUD" , prefix, basecurrency)
string btse03 = str.format("{0}:{1}CAD" , prefix, basecurrency)
string btse04 = str.format("{0}:{1}CHF" , prefix, basecurrency)
string btse05 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string btse06 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string btse07 = str.format("{0}:{1}HKD" , prefix, basecurrency)
string btse08 = str.format("{0}:{1}INR" , prefix, basecurrency)
string btse09 = str.format("{0}:{1}JPY" , prefix, basecurrency)
string btse10 = str.format("{0}:{1}MYR" , prefix, basecurrency)
string btse11 = str.format("{0}:{1}SGD" , prefix, basecurrency)
string btse12 = str.format("{0}:{1}USD" , prefix, basecurrency)
string btse13 = str.format("{0}:{1}USDC", prefix, basecurrency)
string btse14 = str.format("{0}:{1}USDP", prefix, basecurrency)
string btse15 = str.format("{0}:{1}USDT", prefix, basecurrency)
[btse01, btse02, btse03, btse04, btse05, btse06, btse07, btse08, btse09, btse10, btse11, btse12, btse13, btse14, btse15]
// @function Generate five Symbols for the Spot Market of BYBIT.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, DAI, EUR, USDC, USDT]
export BYBIT(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "BYBIT"
string bybit01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string bybit02 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string bybit03 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string bybit04 = str.format("{0}:{1}USDC", prefix, basecurrency)
string bybit05 = str.format("{0}:{1}USDT", prefix, basecurrency)
[bybit01, bybit02, bybit03, bybit04, bybit05]
// @function Generate five Symbols for the Spot Market of capital.com.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, EUR, GBP, JPY, USD]
export CapitalCom(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "CAPITALCOM"
string capitalcom01 = str.format("{0}:{1}BTC", prefix, basecurrency)
string capitalcom02 = str.format("{0}:{1}EUR", prefix, basecurrency)
string capitalcom03 = str.format("{0}:{1}GBP", prefix, basecurrency)
string capitalcom04 = str.format("{0}:{1}JPY", prefix, basecurrency)
string capitalcom05 = str.format("{0}:{1}USD", prefix, basecurrency)
[capitalcom01, capitalcom02, capitalcom03, capitalcom04, capitalcom05]
// @function Generate seven Symbols for the Spot Market of coinbase.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, DAI, ETH, EUR, GBP, USD, USDT]
export coinbase(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "COINBASE"
string coinbase01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string coinbase02 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string coinbase03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string coinbase04 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string coinbase05 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string coinbase06 = str.format("{0}:{1}USD" , prefix, basecurrency)
string coinbase07 = str.format("{0}:{1}USDT", prefix, basecurrency)
[coinbase01, coinbase02, coinbase03, coinbase04, coinbase05, coinbase06, coinbase07]
// @function Generate three Symbols for the Spot Market of CoinEx.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, USDC, USDT]
export CoinEx(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "COINEX"
string coinex01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string coinex02 = str.format("{0}:{1}USDC", prefix, basecurrency)
string coinex03 = str.format("{0}:{1}USDT", prefix, basecurrency)
[coinex01, coinex02, coinex03]
// @function Generate 30 Symbols for the Spot Market of currency.com.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [AUD, BGN, BTC, BYN, CAD, CHF, CRC, CZK, DKK, ETH, EUR, GBP, HUF, IDR, ILS, INR, MXN, NOK, NZD, PHP, PKR, RON, RUB, SEK, SGD, THB, TRY, USD, USDT, ZAR]
export CurrencyCom(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "CURRENCYCOM"
string currencycom01 = str.format("{0}:{1}AUD" , prefix, basecurrency)
string currencycom02 = str.format("{0}:{1}BGN" , prefix, basecurrency)
string currencycom03 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string currencycom04 = str.format("{0}:{1}BYN" , prefix, basecurrency)
string currencycom05 = str.format("{0}:{1}CAD" , prefix, basecurrency)
string currencycom06 = str.format("{0}:{1}CHF" , prefix, basecurrency)
string currencycom07 = str.format("{0}:{1}CRC" , prefix, basecurrency)
string currencycom08 = str.format("{0}:{1}CZK" , prefix, basecurrency)
string currencycom09 = str.format("{0}:{1}DKK" , prefix, basecurrency)
string currencycom10 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string currencycom11 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string currencycom12 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string currencycom13 = str.format("{0}:{1}HUF" , prefix, basecurrency)
string currencycom14 = str.format("{0}:{1}IDR" , prefix, basecurrency)
string currencycom15 = str.format("{0}:{1}ILS" , prefix, basecurrency)
string currencycom16 = str.format("{0}:{1}INR" , prefix, basecurrency)
string currencycom17 = str.format("{0}:{1}MXN" , prefix, basecurrency)
string currencycom18 = str.format("{0}:{1}NOK" , prefix, basecurrency)
string currencycom19 = str.format("{0}:{1}NZD" , prefix, basecurrency)
string currencycom20 = str.format("{0}:{1}PHP" , prefix, basecurrency)
string currencycom21 = str.format("{0}:{1}PKR" , prefix, basecurrency)
string currencycom22 = str.format("{0}:{1}RON" , prefix, basecurrency)
string currencycom23 = str.format("{0}:{1}RUB" , prefix, basecurrency)
string currencycom24 = str.format("{0}:{1}SEK" , prefix, basecurrency)
string currencycom25 = str.format("{0}:{1}SGD" , prefix, basecurrency)
string currencycom26 = str.format("{0}:{1}THB" , prefix, basecurrency)
string currencycom27 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string currencycom28 = str.format("{0}:{1}USD" , prefix, basecurrency)
string currencycom29 = str.format("{0}:{1}USDT", prefix, basecurrency)
string currencycom30 = str.format("{0}:{1}ZAR" , prefix, basecurrency)
[currencycom01, currencycom02, currencycom03, currencycom04, currencycom05, currencycom06, currencycom07, currencycom08, currencycom09, currencycom10, currencycom11, currencycom12, currencycom13, currencycom14, currencycom15, currencycom16, currencycom17, currencycom18, currencycom19, currencycom20, currencycom21, currencycom22, currencycom23, currencycom24, currencycom25, currencycom26, currencycom27, currencycom28, currencycom29, currencycom30]
// @function Generate one Symbol for the Spot Market of Delta.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns USDT
export Delta(simple string basecurrency = syminfo.basecurrency) =>
string delta01 = str.format("DELTA:{0}USDT", basecurrency)
delta01
// @function Generate two Symbols for the Spot Market of Deribit.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, USDC]
export Deribit(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "DERIBIT"
string deribit01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string deribit02 = str.format("{0}:{1}USDC", prefix, basecurrency)
[deribit01, deribit02]
// @function Generate one Symbol for the Spot Market of easyMarkets.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns USD
export easyMarkets(simple string basecurrency = syminfo.basecurrency) =>
string bcur_imp =
basecurrency == "LINK" ? "LNK"
: basecurrency == "MATIC" ? "MTC"
: basecurrency == "DOGE" ? "DOG"
: basecurrency
string easymarkets01 = str.format("EASYMARKETS:{0}USD", bcur_imp)
easymarkets01
// @function Generate one Symbol for the Spot Market of Eightcap.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns USD
export Eightcap(simple string basecurrency = syminfo.basecurrency) =>
eightcap01 = str.format("EIGHTCAP:{0}USD", basecurrency)
eightcap01
// @function Generate ten Symbols for the Spot Market of ExMo.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, DAI, ETH, EUR, GBP, LTC, PLN, UAH, USD, USDT]
export ExMo(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "EXMO"
string exmo01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string exmo02 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string exmo03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string exmo04 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string exmo05 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string exmo06 = str.format("{0}:{1}LTC" , prefix, basecurrency)
string exmo07 = str.format("{0}:{1}PLN" , prefix, basecurrency)
string exmo08 = str.format("{0}:{1}UAH" , prefix, basecurrency)
string exmo09 = str.format("{0}:{1}USD" , prefix, basecurrency)
string exmo10 = str.format("{0}:{1}USDT", prefix, basecurrency)
[exmo01, exmo02, exmo03, exmo04, exmo05, exmo06, exmo07, exmo08, exmo09, exmo10]
// @function Generate four Symbols for the Spot Market of FOREX.com.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [AUD, EUR, GBP, USD]
export FOREXcom(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "FOREXCOM"
string forex01 = str.format("{0}:{1}AUD", prefix, basecurrency)
string forex02 = str.format("{0}:{1}EUR", prefix, basecurrency)
string forex03 = str.format("{0}:{1}GBP", prefix, basecurrency)
string forex04 = str.format("{0}:{1}USD", prefix, basecurrency)
[forex01, forex02, forex03, forex04]
// @function Generate three Symbols for the Spot Market of FXCM.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [EUR, GBP, USD]
export FXCM(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "FXCM"
string fxcm01 = str.format("{0}:{1}EUR", prefix, basecurrency)
string fxcm02 = str.format("{0}:{1}GBP", prefix, basecurrency)
string fxcm03 = str.format("{0}:{1}USD", prefix, basecurrency)
[fxcm01, fxcm02, fxcm03]
// @function Generate five Symbols for the Spot Market of Gate.io.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, ETH, TRY, USD, USDT]
export GateIO(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "GATEIO"
string gateio01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string gateio02 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string gateio03 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string gateio04 = str.format("{0}:{1}USD" , prefix, basecurrency)
string gateio05 = str.format("{0}:{1}USDT", prefix, basecurrency)
[gateio01, gateio02, gateio03, gateio04, gateio05]
// @function Generate ten Symbols for the Spot Market of Gemini.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BCH, BTC, DAI, ETH, EUR, GBP, GUSD, LTC, SGD, USDT]
export Gemini(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "GEMINI"
string gemini01 = str.format("{0}:{1}BCH" , prefix, basecurrency)
string gemini02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string gemini03 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string gemini04 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string gemini05 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string gemini06 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string gemini07 = str.format("{0}:{1}GUSD", prefix, basecurrency)
string gemini08 = str.format("{0}:{1}LTC" , prefix, basecurrency)
string gemini09 = str.format("{0}:{1}SGD" , prefix, basecurrency)
string gemini10 = str.format("{0}:{1}USDT", prefix, basecurrency)
[gemini01, gemini02, gemini03, gemini04, gemini05, gemini06, gemini07, gemini08, gemini09, gemini10]
// @function Generate 14 Symbols for the Spot Market of Kraken.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [AED, AUD, BTC, CAD, CHF, DAI, DOT, ETH, EUR, GBP, JPY, USD, USDC, USDT]
export Kraken(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "KRAKEN"
string kraken01 = str.format("{0}:{1}AED" , prefix, basecurrency)
string kraken02 = str.format("{0}:{1}AUD" , prefix, basecurrency)
string kraken03 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string kraken04 = str.format("{0}:{1}CAD" , prefix, basecurrency)
string kraken05 = str.format("{0}:{1}CHF" , prefix, basecurrency)
string kraken06 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string kraken07 = str.format("{0}:{1}DOT" , prefix, basecurrency)
string kraken08 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string kraken09 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string kraken10 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string kraken11 = str.format("{0}:{1}JPY" , prefix, basecurrency)
string kraken12 = str.format("{0}:{1}USD" , prefix, basecurrency)
string kraken13 = str.format("{0}:{1}USDC", prefix, basecurrency)
string kraken14 = str.format("{0}:{1}USDT", prefix, basecurrency)
[kraken01, kraken02, kraken03, kraken04, kraken05, kraken06, kraken07, kraken08, kraken09, kraken10, kraken11, kraken12, kraken13, kraken14]
// @function Generate 13 Symbols for the Spot Market of KuCoin.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BRL, BTC, DAI, DOGE, ETH, EUR, GBP, KCS, TRX, TUSD, USD, USDC, USDT]
export KuCoin(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "KUCOIN"
string kucoin01 = str.format("{0}:{1}BRL" , prefix, basecurrency)
string kucoin02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string kucoin03 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string kucoin04 = str.format("{0}:{1}DOGE", prefix, basecurrency)
string kucoin05 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string kucoin06 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string kucoin07 = str.format("{0}:{1}GBP" , prefix, basecurrency)
string kucoin08 = str.format("{0}:{1}KCS" , prefix, basecurrency)
string kucoin09 = str.format("{0}:{1}TRX" , prefix, basecurrency)
string kucoin10 = str.format("{0}:{1}TUSD", prefix, basecurrency)
string kucoin11 = str.format("{0}:{1}USD" , prefix, basecurrency)
string kucoin12 = str.format("{0}:{1}USDC", prefix, basecurrency)
string kucoin13 = str.format("{0}:{1}USDT", prefix, basecurrency)
[kucoin01, kucoin02, kucoin03, kucoin04, kucoin05, kucoin06, kucoin07, kucoin08, kucoin09, kucoin10, kucoin11, kucoin12, kucoin13]
// @function Generate six Symbols for the Spot Market of MEXC.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, BUSD, ETH, TUSD, USDC, USDT]
export MEXC(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "MEXC"
string mexc01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string mexc02 = str.format("{0}:{1}BUSD", prefix, basecurrency)
string mexc03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string mexc04 = str.format("{0}:{1}TUSD", prefix, basecurrency)
string mexc05 = str.format("{0}:{1}USDC", prefix, basecurrency)
string mexc06 = str.format("{0}:{1}USDT", prefix, basecurrency)
[mexc01, mexc02, mexc03, mexc04, mexc05, mexc06]
// @function Generate one Symbol for the Spot Market of OANDA.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns USD
export OANDA(simple string basecurrency = syminfo.basecurrency) =>
string oanda01 = str.format("OANDA:{0}USD", basecurrency)
oanda01
// @function Generate six Symbols for the Spot Market of OKX.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, DAI, ETH, EURT, USDC, USDT]
export OKX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "OKX"
string okx01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string okx02 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string okx03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string okx04 = str.format("{0}:{1}EURT", prefix, basecurrency)
string okx05 = str.format("{0}:{1}USDC", prefix, basecurrency)
string okx06 = str.format("{0}:{1}USDT", prefix, basecurrency)
[okx01, okx02, okx03, okx04, okx05, okx06]
// @function Generate one Symbol for the Spot Market of Pepperstone.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns USD
export Pepperstone(simple string basecurrency = syminfo.basecurrency) =>
string pepperstone01 = str.format("PEPPERSTONE:{0}USD", basecurrency)
pepperstone01
// @function Generate four Symbols for the Spot Market of phemex.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BRZ, TRY, USDC, USDT]
export phemex(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "PHEMEX"
string phemex01 = str.format("{0}:{1}BRZ" , prefix, basecurrency)
string phemex02 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string phemex03 = str.format("{0}:{1}USDC", prefix, basecurrency)
string phemex04 = str.format("{0}:{1}USDT", prefix, basecurrency)
[phemex01, phemex02, phemex03, phemex04]
// @function Generate nine Symbols for the Spot Market of POLONIEX.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BNB, BTC, BUSD, ETH, TRX, TUSD, USDC, USDD, USDT]
export POLONIEX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "POLONIEX"
string poloniex01 = str.format("{0}:{1}BNB" , prefix, basecurrency)
string poloniex02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string poloniex03 = str.format("{0}:{1}BUSD", prefix, basecurrency)
string poloniex04 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string poloniex05 = str.format("{0}:{1}TRX" , prefix, basecurrency)
string poloniex06 = str.format("{0}:{1}TUSD", prefix, basecurrency)
string poloniex07 = str.format("{0}:{1}USDC", prefix, basecurrency)
string poloniex08 = str.format("{0}:{1}USDD", prefix, basecurrency)
string poloniex09 = str.format("{0}:{1}USDT", prefix, basecurrency)
[poloniex01, poloniex02, poloniex03, poloniex04, poloniex05, poloniex06, poloniex07, poloniex08, poloniex09]
// @function Generate three Symbols for the Spot Market of Pyth.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BRL, RUB, USD]
export Pyth(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "PYTH"
string pyth01 = str.format("{0}:{1}BRL", prefix, basecurrency)
string pyth02 = str.format("{0}:{1}RUB", prefix, basecurrency)
string pyth03 = str.format("{0}:{1}USD", prefix, basecurrency)
[pyth01, pyth02, pyth03]
// @function Generate four Symbols for the Spot Market of Skilling.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [EUR, GBP, JPY, USD]
export Skilling(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "SKILLING"
string skilling01 = str.format("{0}:{1}EUR", prefix, basecurrency)
string skilling02 = str.format("{0}:{1}GBP", prefix, basecurrency)
string skilling03 = str.format("{0}:{1}JPY", prefix, basecurrency)
string skilling04 = str.format("{0}:{1}USD", prefix, basecurrency)
[skilling01, skilling02, skilling03, skilling04]
// @function Generate six Symbols for the Spot Market of TimeX.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [AUDT, BTC, ETH, USD, USDC, USDT]
export TimeX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "TIMEX"
string timex01 = str.format("{0}:{1}AUDT", prefix, basecurrency)
string timex02 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string timex03 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string timex04 = str.format("{0}:{1}USD" , prefix, basecurrency)
string timex05 = str.format("{0}:{1}USDC", prefix, basecurrency)
string timex06 = str.format("{0}:{1}USDT", prefix, basecurrency)
[timex01, timex02, timex03, timex04, timex05, timex06]
// @function Generate four Symbols for the Spot Market of TradeStation.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, ETH, USD, USDC]
export TradeStation(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "TRADESTATION"
string tradestation01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string tradestation02 = str.format("{0}:{1}ETH" , prefix, basecurrency)
string tradestation03 = str.format("{0}:{1}USD" , prefix, basecurrency)
string tradestation04 = str.format("{0}:{1}USDC", prefix, basecurrency)
[tradestation01, tradestation02, tradestation03, tradestation04]
// @function Generate four Symbols for the Spot Market of UpBit.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, KRW, SGD, USDT]
export UpBit(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "UPBIT"
string upbit01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string upbit02 = str.format("{0}:{1}KRW" , prefix, basecurrency)
string upbit03 = str.format("{0}:{1}SGD" , prefix, basecurrency)
string upbit04 = str.format("{0}:{1}USDT", prefix, basecurrency)
[upbit01, upbit02, upbit03, upbit04]
// @function Generate 13 Symbols for the Spot Market of whitebit.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [BTC, DAI, DECL, EUR, EURT, GEL, KZT, TRY, TUSD, UAH, USD, USDC, USDT]
export whitebit(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "WHITEBIT"
string whitebit01 = str.format("{0}:{1}BTC" , prefix, basecurrency)
string whitebit02 = str.format("{0}:{1}DAI" , prefix, basecurrency)
string whitebit03 = str.format("{0}:{1}DECL", prefix, basecurrency)
string whitebit04 = str.format("{0}:{1}EUR" , prefix, basecurrency)
string whitebit05 = str.format("{0}:{1}EURT", prefix, basecurrency)
string whitebit06 = str.format("{0}:{1}GEL" , prefix, basecurrency)
string whitebit07 = str.format("{0}:{1}KZT" , prefix, basecurrency)
string whitebit08 = str.format("{0}:{1}TRY" , prefix, basecurrency)
string whitebit09 = str.format("{0}:{1}TUSD", prefix, basecurrency)
string whitebit10 = str.format("{0}:{1}UAH" , prefix, basecurrency)
string whitebit11 = str.format("{0}:{1}USD" , prefix, basecurrency)
string whitebit12 = str.format("{0}:{1}USDC", prefix, basecurrency)
string whitebit13 = str.format("{0}:{1}USDT", prefix, basecurrency)
[whitebit01, whitebit02, whitebit03, whitebit04, whitebit05, whitebit06, whitebit07, whitebit08, whitebit09, whitebit10, whitebit11, whitebit12, whitebit13]
// @function Generate two Symbols for the Spot Market of WOO.
// @param basecurrency Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
// @returns [USDC, USDT]
export WOOX(simple string basecurrency = syminfo.basecurrency) =>
string prefix = "WOONETWORK"
string woox01 = str.format("{0}:{1}USDC", prefix, basecurrency)
string woox02 = str.format("{0}:{1}USDT", prefix, basecurrency)
[woox01, woox02]
// ----------------------------------------------}
// ALL IN ONE
// ----------------------------------------------{
// @function Generate up to 30 Symbols for the Spot Market, depending on the market picked.
// @param exchange The name of an Exchange. Case insensitivity. Optional. Default value is `syminfo.prefix`. If something else is put in here it will return `na` values.
// @param basecurrency The Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`
// @returns 30x string as tuple
export find(simple string exchange = syminfo.prefix, simple string basecurrency = syminfo.basecurrency) =>
string prefix_cap = str.upper(exchange)
string symbol01 = na, string symbol02 = na, string symbol03 = na, string symbol04 = na, string symbol05 = na, string symbol06 = na, string symbol07 = na, string symbol08 = na, string symbol09 = na, string symbol10 = na
string symbol11 = na, string symbol12 = na, string symbol13 = na, string symbol14 = na, string symbol15 = na, string symbol16 = na, string symbol17 = na, string symbol18 = na, string symbol19 = na, string symbol20 = na
string symbol21 = na, string symbol22 = na, string symbol23 = na, string symbol24 = na, string symbol25 = na, string symbol26 = na, string symbol27 = na, string symbol28 = na, string symbol29 = na, string symbol30 = na
//string symbol31 = na, string symbol32 = na, string symbol33 = na, string symbol34 = na, string symbol35 = na, string symbol36 = na, string symbol37 = na, string symbol38 = na, string symbol39 = na, string symbol40 = na
if str.contains(prefix_cap, "BINANCEUS")
[s01, s02, s03, s04, s05, s06, s07] = BinanceUS(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07
else if str.contains(prefix_cap, "BINANCE")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27] = Binance(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
symbol07 := s07, symbol08 := s08, symbol09 := s09
symbol10 := s10, symbol11 := s11, symbol12 := s12
symbol13 := s13, symbol14 := s14, symbol15 := s15
symbol16 := s16, symbol17 := s17, symbol18 := s18
symbol19 := s19, symbol20 := s20, symbol21 := s21
symbol22 := s22, symbol23 := s23, symbol24 := s24
symbol25 := s25, symbol26 := s26, symbol27 := s27
else if str.contains(prefix_cap, "BITFINEX")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12] = Bitfinex(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06
symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10, symbol11 := s11, symbol12 := s12
else if str.contains(prefix_cap, "BITFLYER")
[s01, s02, s03] = bitFlyer(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
else if str.contains(prefix_cap, "BITGET")
[s01, s02, s03, s04, s05, s06, s07] = Bitget(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07
else if str.contains(prefix_cap, "BITHUMB")
[s01, s02] = Bithumb(basecurrency)
symbol01 := s01, symbol02 := s02
else if str.contains(prefix_cap, "BITKUB")
s01 = bitkub(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "BITMEX")
[s01, s02] = BitMEX(basecurrency)
symbol01 := s01, symbol02 := s02
else if str.contains(prefix_cap, "BITPANDA")
[s01, s02, s03, s04, s05, s06] = bitpanda_pro(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
else if str.contains(prefix_cap, "BITRUE")
[s01, s02, s03, s04, s05, s06, s07, s08, s09] = bitrue(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09
else if str.contains(prefix_cap, "BITSTAMP")
[s01, s02, s03, s04, s05, s06, s07, s08] = Bitstamp(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04
symbol05 := s05, symbol06 := s06, symbol07 := s07, symbol08 := s08
else if str.contains(prefix_cap, "BITTREX")
[s01, s02, s03, s04, s05, s06] = BITTREX(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
else if str.contains(prefix_cap, "BTSE")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15] = BTSE(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10
symbol11 := s11, symbol12 := s12, symbol13 := s13, symbol14 := s14, symbol15 := s15
else if str.contains(prefix_cap, "BYBIT")
[s01, s02, s03, s04, s05] = BYBIT(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
else if str.contains(prefix_cap, "CAPITAL")
[s01, s02, s03, s04, s05] = CapitalCom(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
else if str.contains(prefix_cap, "COINBASE")
[s01, s02, s03, s04, s05, s06, s07] = coinbase(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07
else if str.contains(prefix_cap, "COINEX")
[s01, s02, s03] = CoinEx(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
else if str.contains(prefix_cap, "CURRENCY")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30] = CurrencyCom(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10
symbol11 := s11, symbol12 := s12, symbol13 := s13, symbol14 := s14, symbol15 := s15
symbol16 := s16, symbol17 := s17, symbol18 := s18, symbol19 := s19, symbol20 := s20
symbol21 := s21, symbol22 := s22, symbol23 := s23, symbol24 := s24, symbol25 := s25
symbol26 := s26, symbol27 := s27, symbol28 := s28, symbol29 := s29, symbol30 := s30
else if str.contains(prefix_cap, "DELTA")
s01 = Delta(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "DERIBIT")
[s01, s02] = Deribit(basecurrency)
symbol01 := s01, symbol02 := s02
else if str.contains(prefix_cap, "EASYMARKETS")
s01 = easyMarkets(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "EIGHTCAP")
s01 = Eightcap(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "EXMO")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10] = ExMo(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10
else if str.contains(prefix_cap, "FOREX")
[s01, s02, s03, s04] = FOREXcom(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04
else if str.contains(prefix_cap, "FXCM")
[s01, s02, s03] = FXCM(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
else if str.contains(prefix_cap, "GATE")
[s01, s02, s03, s04, s05] = GateIO(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
else if str.contains(prefix_cap, "GEMINI")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10] = Gemini(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05
symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10
else if str.contains(prefix_cap, "KRAKEN")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14] = Kraken(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07
symbol08 := s08, symbol09 := s09, symbol10 := s10, symbol11 := s11, symbol12 := s12, symbol13 := s13, symbol14 := s14
else if str.contains(prefix_cap, "KUCOIN")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13] = KuCoin(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10, symbol11 := s11, symbol12 := s12, symbol13 := s13
else if str.contains(prefix_cap, "MEXC")
[s01, s02, s03, s04, s05, s06] = MEXC(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
else if str.contains(prefix_cap, "OANDA")
s01 = OANDA(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "OKX")
[s01, s02, s03, s04, s05, s06] = OKX(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
else if str.contains(prefix_cap, "PEPPERSTONE")
s01 = Pepperstone(basecurrency)
symbol01 := s01
else if str.contains(prefix_cap, "PHEMEX")
[s01, s02, s03, s04] = phemex(basecurrency)
symbol01 := s01, symbol02 := s02
symbol03 := s03, symbol04 := s04
else if str.contains(prefix_cap, "POLONIEX")
[s01, s02, s03, s04, s05, s06, s07, s08, s09] = POLONIEX(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09
else if str.contains(prefix_cap, "PYTH")
[s01, s02, s03] = Pyth(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
else if str.contains(prefix_cap, "SKILLING")
[s01, s02, s03, s04] = Skilling(basecurrency)
symbol01 := s01, symbol02 := s02
symbol03 := s03, symbol04 := s04
else if str.contains(prefix_cap, "TIMEX")
[s01, s02, s03, s04, s05, s06] = TimeX(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03
symbol04 := s04, symbol05 := s05, symbol06 := s06
else if str.contains(prefix_cap, "TRADESTATION")
[s01, s02, s03, s04] = TradeStation(basecurrency)
symbol01 := s01, symbol02 := s02
symbol03 := s03, symbol04 := s04
else if str.contains(prefix_cap, "UPBIT")
[s01, s02, s03, s04] = UpBit(basecurrency)
symbol01 := s01, symbol02 := s02
symbol03 := s03, symbol04 := s04
else if str.contains(prefix_cap, "WHITEBIT")
[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13] = whitebit(basecurrency)
symbol01 := s01, symbol02 := s02, symbol03 := s03, symbol04 := s04, symbol05 := s05, symbol06 := s06, symbol07 := s07, symbol08 := s08, symbol09 := s09, symbol10 := s10, symbol11 := s11, symbol12 := s12, symbol13 := s13
else if str.contains(prefix_cap, "WOO")
[s01, s02] = WOOX(basecurrency)
symbol01 := s01, symbol02 := s02
[symbol01, symbol02, symbol03, symbol04, symbol05, symbol06, symbol07, symbol08, symbol09, symbol10, symbol11, symbol12, symbol13, symbol14, symbol15, symbol16, symbol17, symbol18, symbol19, symbol20, symbol21, symbol22, symbol23, symbol24, symbol25, symbol26, symbol27, symbol28, symbol29, symbol30]
|
Ice Cream Volume Profile [Visible range] | https://www.tradingview.com/script/3bycEjxC-Ice-Cream-Volume-Profile-Visible-range/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 53 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TZack88
//@version=5
indicator("Ice Cream Volume Profile [Visible range]",overlay = true,max_bars_back = 2000)
type ice
array<float> LOWS
array<float> HIGH
array<float> VOL
array<float> SCR
array<float> Levels
array<float> Total
array<float> Green
array<float> Red
array<chart.point> Top
array<chart.point> LowTop
array<polyline> Cone
array<label> Labels
color OFF
var ICE = ice.new(
array.new<float>(),
array.new<float>(),
array.new<float>(),
array.new<float>(),
array.new<float>(10),
array.new<float>(10,0.0),
array.new<float>(10,0.0),
array.new<float>(10,0.0),
array.new<chart.point>(),
array.new<chart.point>(),
array.new<polyline>(9),
array.new<label>(9),
color.new(color.black,100)
)
string Voldata = input.string("Volume",title = "Volume Type",
group = "CORE",
options=["Volume","Points","Delta"],
tooltip = "Choose Volume Type to Show in Boxes",inline = "C")
BullCol = input.color(color.rgb(225, 142, 10, 60),"",group = "CORE",inline = "C")
BearCol = input.color(color.rgb(8, 145, 99, 31),"",group = "CORE",inline = "C")
// chcck the Bull , Bear volume ratio
method VolCal(ice self) =>
GreenV = array.new<float>()
RedV = array.new<float>()
Vtotal = array.new<float>()
for i = 0 to self.SCR.size() -1
if self.SCR.get(i) > open[i]
GreenV.push(volume[i])
else if self.SCR.get(i) < open[i]
RedV.push(volume[i])
Vtotal.push(volume[i])
GreenRatio = math.round(GreenV.sum() / Vtotal.sum()* 100,2)
RedRatio = math.round(RedV.sum() / Vtotal.sum()* 100,2)
Out = GreenRatio > 30 ? color.rgb(10, 170, 16, 49) : RedRatio > 55 ? color.rgb(204, 15, 15, 35) : color.rgb(245, 221, 8, 48)
Out
// visable range data
if time > chart.left_visible_bar_time
ICE.LOWS.push(low)
ICE.HIGH.push(high)
ICE.VOL.push(volume)
ICE.SCR.push(close)
GenCol(i,L,M)=>
color.from_gradient(i,L,M,BullCol,BearCol)
volATR(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
ATR = volATR(30)
if barstate.islast
var polyline Pol1 = na , polyline.delete(Pol1)
var polyline Pol2 = na , polyline.delete(Pol2)
var num = 0
var mean = 0
Bartime = time - time[1]
var TIME = time + (Bartime * 5)
int [] PNT = array.new_int(10,0)
// levels calculation
TOP = ICE.HIGH.max() - (ATR* 20)
Last = ICE.LOWS.min()
step = (TOP - Last) / 8
for i = 0 to 8 by 1
Pos = TOP - step * i
ICE.Levels.set(i,Pos)
// check if the bar is within a level and add to the points <array> counter
for i = 0 to ICE.SCR.size() -1
for x = 0 to ICE.Levels.size() -2
if ICE.SCR.get(i) < ICE.Levels.get(x)
and
ICE.SCR.get(i) > ICE.Levels.get(x+1)
PNT.set(x,PNT.get(x)+1)
ICE.Total.set(x,ICE.Total.get(x) + volume[i])
// check Bull , Bear volume within the range
if ICE.SCR.get(i) < open[i]
ICE.Green.set(x,ICE.Green.get(x) + volume[i])
if ICE.SCR.get(i) > open[i]
ICE.Red.set(x,ICE.Red.get(x) + volume[i])
break
// levels build
for i = 1 to 8 by 1
Poly = array.new<chart.point>()
polyline.delete(ICE.Cone.get(i))
Start = TIME + (Bartime * (4 + num) )
END = TIME + (Bartime * (56 - num))
Poly.push(chart.point.from_time( Start , ICE.Levels.get(i)))
Poly.push(chart.point.from_time( END , ICE.Levels.get(i)))
Poly.push(chart.point.from_time( END , ICE.Levels.get(i-1)))
Poly.push(chart.point.from_time( Start , ICE.Levels.get(i-1)))
Value = Voldata == "Points" ? PNT.get(i) : ICE.Total.get(i)
Min = Voldata == "Points" ? PNT.min() : ICE.Total.min()
MAX = Voldata == "Points" ? PNT.max() : ICE.Total.max()
ColCond = color.new(GenCol(i == 0 ? Value : Voldata == "Points" ? PNT.get(i-1):
Voldata == "Volume" or Voldata == "Delta" ? ICE.Total.get(i-1) : Value ,Min,MAX), 80)
ICE.Cone.set(i,polyline.new(Poly,false,true,xloc.bar_time,color.new(#484749, 80),fill_color = ColCond))
// label text position
mean := ((TIME + (Bartime * (56 - num))) + (TIME + (Bartime * (4 + num)))) /2
num +=3
// data labels
str = ""
for i = 0 to ICE.Levels.size() -2
label.delete(ICE.Labels.get(i))
Delta = ICE.Green.get(i) - ICE.Red.get(i)
if ICE.Total.get(i) > 0
str := switch Voldata
"Volume" => str.tostring(ICE.Total.get(i),format.volume)
"Points" => str.tostring(PNT.get(i))
"Delta" => str.tostring(Delta,format.volume)
if i < 8
ICE.Labels.set(i,label.new(mean,((ICE.Levels.get(i) + ICE.Levels.get(i+1)) /2) ,str,style = label.style_label_center,color = ICE.OFF , textcolor = Voldata == "Delta" and Delta < 0 ? color.red : color.rgb(255, 255, 255, 31),xloc = xloc.bar_time))
// Mango and Watermelon top
ICE.Top.push(chart.point.from_time(TIME , ICE.HIGH.max()- (ATR* 20)))
ICE.Top.push(chart.point.from_time(TIME + (Bartime * 30) , ICE.HIGH.max() +(ATR* 8) ))
ICE.Top.push(chart.point.from_time(TIME + (Bartime * 60) , ICE.HIGH.max()- (ATR* 20)))
ICE.LowTop.push(chart.point.from_time(TIME , ICE.HIGH.max() - (ATR* 20)))
ICE.LowTop.push(chart.point.from_time(TIME + (Bartime * 30) , ICE.HIGH.max() -(ATR* 8) ))
ICE.LowTop.push(chart.point.from_time(TIME + (Bartime * 60) , ICE.HIGH.max() - (ATR* 20)))
Pol1:=polyline.new(ICE.Top,true,false,xloc.bar_time,color.new(#2d2d2e, 29),fill_color = ICE.VolCal())
Pol2:=polyline.new(ICE.LowTop,true,false,xloc.bar_time,color.new(#333434, 50),fill_color = color.rgb(180, 180, 187, 54))
|
Risk Management | https://www.tradingview.com/script/m2rYcLGI-Risk-Management/ | weak_hand | https://www.tradingview.com/u/weak_hand/ | 10 | 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/
// © weak_hand
//@version=5
// @description This library keeps your money in check, and is used for testing and later on webhook-applications too. It has four volatility functions and two of them can be used to calculate a Stop-Loss, like Average True Range. It also can calculate Position Size, and the Risk Reward Ratio. But those calculations don't take leverage into account.
library("RiskManagement")
calc_qty(float p = 0, float r = 2.0, float e = 0.0, float s = 0.0) => // This function calculates the quantity of contracts/shares/units.
risk_per_trade = r <= 100 and r > 0.0 ? p * r / 100 : 0.0 // if risk is equal or below 100 then calculate risk amount, other wise take zero risk
risk_per_unit = e > s ? e - s : s - e // calculate ticks between entry and stop loss
risk_per_trade / risk_per_unit // calculate quantity of contracts/shares/units
// @function This function calculates the definite amount of contracts/shares/units you should use to buy or sell. This value can used by `strategy.entry(qty)` for example.
// @param portfolio This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
// @param risk This is the percentage of your Portfolio you willing to loose on a single trade. Possible values are between 0.1 and 100%. Same usecase with strategy(default_qty_type=strategy.percent_of_equity,default_qty_value=100), except its calculation the risk only.
// @param entry This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
// @param stop_loss This is the limit-/market-price when to exit the trade, to minimize your losses.
// @param use_leverage This value is optional. When not used or when set to false then this function will let you invest your portfolio at max.
// @param qty_as_integer This value is optional. When set to true this function will return a value used with integers. The largest integer less than or equal to the given number. Because some Broker/Exchanges let you trade hole contracts/shares/units only.
// @returns float
export position_size(float portfolio = 10000.0, float risk = 2.0, float entry = 0.0, float stop_loss = 0.0, bool use_leverage = false, bool qty_as_integer = false) =>
float sum = portfolio > 0.0 ? calc_qty(portfolio,risk,entry,stop_loss) : 0.0
float qty = not use_leverage ? sum : sum * entry > portfolio ? portfolio / entry : sum
if qty_as_integer
math.floor(qty)
else
qty
// @function This function calculates the definite amount of currency you should use when going long or short.
// @param portfolio This is the total amount of the currency you own, and is also used by strategy.initial_capital, for example. The amount is needed to calculate the maximum risk you are willing to take per trade.
// @param risk This is the percentage of your Portfolio you willing to loose on a single trade. For example: 1 is 100% and 0,01 is 1%. Default amount is 0.02 (2%).
// @param entry This is the limit-/market-price for the current investment. In other words: The price per contract/share/units you willing to buy or sell.
// @param stop_loss This is the limit-/market-price when to exit the trade, to minimize your losses.
// @returns float
export position_size_currency(float portfolio = 10000.0, float risk = 2.0, float entry = 0.0, float stop_loss = 0.0) => math.round_to_mintick(calc_qty(portfolio,risk,entry,stop_loss) * entry) // return value: currency amount
// @function percentage trailing Stop Loss
//export pc_tsl(float portfolio = 10000, float risk = 0.02, float entry = 0.0, float average_true_range = 0.0) =>
// @function This function calculates the Risk Reward Ratio. Common values are between 1.5 and 2.0 and you should not go lower except for very few special cases.
// @param entry This is the limit-/market-price for the investment. In other words: The price per contract/share/unit you willing to buy or sell.
// @param stop_loss This is the limit-/market-price when to exit the trade, to minimize your losses.
// @param take_profit This is the limit-/market-price when to take profits.
// @returns float
export rrr(float entry = 0.0, float stop_loss = 0.0, float take_profit = 0.0) =>
float reward = 0.0
if take_profit > stop_loss
reward := (take_profit - entry) / (entry - stop_loss)
else if stop_loss > take_profit
reward := (entry - take_profit) / (stop_loss - entry)
reward
// @function Hoffman Trailing Stop Loss. This function returns trailing stop loss levels.
// @param entry This is the price at which contracts/shares/units where bought/sold.
// @param take_profit This is target price of the contracts/shares/units.
// @returns tuple with three float values as pice. The tsl50% and tsl80% and tsl90%.
//export hoffman_tsl(float entry = 0.0, float take_profit = 0.0) =>
//float ticks_total = take_profit > entry ? take_profit - entry : entry - take_profit
//float ticks_tsl_50 = math.round_to_mintick(ticks_total * 0.5)
//float ticks_tsl_80 = math.round_to_mintick(ticks_total * 0.8)
//float ticks_tsl_90 = math.round_to_mintick(ticks_total * 0.9)
//if take_profit > entry
//[entry + ticks_tsl_50, entry + ticks_tsl_80, entry + ticks_tsl_90]
//else
//[entry - ticks_tsl_50, entry - ticks_tsl_80, entry - ticks_tsl_90]
// @function This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export change_in_price(int length = 14) =>
math.round_to_mintick(close - close[length]) // This code is of the book "Trading Systems and Methods."
// @function This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export maximum_price_fluctuation(int length = 14) =>
float highest_high = ta.highest(source = high, length = length)
float lowest_low = ta.lowest(source = low, length = length)
math.round_to_mintick(highest_high - lowest_low) // This code is of the book "Trading Systems and Methods."
// @function This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export absolute_price_changes(int length = 14) =>
math.round_to_mintick(math.sum(math.abs(close[2] - close[1]), length - 1)) // This code is of the book "Trading Systems and Methods."
// @function This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export annualized_volatility(int length = 20) =>
int trading_days = syminfo.type == "crypto" or syminfo.type == "forex" ? 365 : 252
float resolution =
timeframe.isseconds ? 86400 * trading_days / timeframe.multiplier
: timeframe.isminutes ? 1440 * trading_days / timeframe.multiplier
: timeframe.isdaily ? trading_days / timeframe.multiplier
: timeframe.isweekly ? 52 / timeframe.multiplier
: timeframe.ismonthly ? 12 / timeframe.multiplier : na
ta.stdev(math.log(close / close[1]), length) * math.sqrt(resolution)
|
Predictive Candles Variety Pack [SS] | https://www.tradingview.com/script/FLok5JCG-Predictive-Candles-Variety-Pack-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 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/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// © Steversteves
//@version=5
indicator("Predictive Candles Variety Pack [SS]", overlay=true)
// Tooltips
t1 = "Adjusts the transparency/strength of the colours of the candles."
t2 = "Select the type of predictive candle you would like."
t3 = "Show Backtest results (over length)"
len = input.int(500, "Length")
transp = input.int(85, "Transparency", tooltip = t1)
candle_type = input.string("LinReg Candles", "Candle Types", ["LinReg Candles", "MFI Based Candles", "Stochastic Based Candles", "RSI Based Candles", "9 EMA Candles", "ARIMA Candles"], tooltip = t2)
bt = input.bool(false, "Backtest", tooltip = t3)
// Candle Plot
float op = 0.0
float hi = 0.0
float lo = 0.0
float cl = 0.0
// Range Variables
hitoop = high[1] - open[1]
optolo = open[1] - low[1]
optoclose = close[1] - open[1]
// Functions
ar_f() =>
array.new_float()
f_linreg(y, x, len, bool stationarity_test) =>
float result = 0.0
float std_err = 0.0
float cor = 0.0
float r2 = 0.0
float slope = 0.0
dep_array = array.new<float>()
indep_array = array.new<float>()
for i = 0 to len
array.push(dep_array, y[i])
array.push(indep_array, x[i])
// Average
dep_avg = array.avg(dep_array)
indep_avg = array.avg(indep_array)
// Covariance
covariance = array.covariance(dep_array, indep_array)
variance = array.variance(indep_array)
slope := (covariance / variance)
intercept = dep_avg - (indep_avg * slope)
result := (x * slope) + intercept
result
f_stationarity(y, x, len, bool stationarity_test) =>
float result = 0.0
float std_err = 0.0
float cor = 0.0
float r2 = 0.0
float slope = 0.0
dep_array = array.new<float>()
indep_array = array.new<float>()
for i = 0 to len
array.push(dep_array, y[i])
array.push(indep_array, x[i])
// Average
dep_avg = array.avg(dep_array)
indep_avg = array.avg(indep_array)
// Covariance
covariance = array.covariance(dep_array, indep_array)
variance = array.variance(indep_array)
slope := (covariance / variance)
intercept = dep_avg - (indep_avg * slope)
result := (x * slope) + intercept
// Standard Error
se_residuals = array.new_float()
for i = 0 to len
array.push(se_residuals, (result[i] - y[i]) * (result[i] - y[i]))
se_add = array.sum(se_residuals)
r1 = se_add / (len - 2)
std_err := stationarity_test ? 0 : math.sqrt(r1)
// Correlation
sd1 = array.stdev(dep_array)
sd2 = array.stdev(indep_array)
cor := covariance / (sd1 * sd2)
r2 := math.pow(cor,2)
[result, std_err, cor, r2, slope]
f_armia_basic_stationary(x) =>
float t_stat = 0.0
bool result = na
//returns = (x - x[1]) / x[1] * 100
float lagged_x = x[1]
float delta_x = (x - x[1])
[r, er, cor, r2, sl] = f_stationarity(delta_x, lagged_x, len, true)
t_stat := (sl / er)
result := t_stat <= -1.62 ? true : false
result
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if candle_type == "LinReg Candles"
op := f_linreg(open, open[1], len, false)
hi := f_linreg(high, high[1], len, false)
lo := f_linreg(low, low[1], len, false)
cl := f_linreg(close, close[1], len, false)
if candle_type == "MFI Based Candles"
mfi = ta.mfi(close[1], 14)
prev_mfi = mfi[1]
cur_mfi_a = ar_f()
mfi_hi_rng_a = ar_f()
mfi_lo_rng_a = ar_f()
mfi_cl_rng_a = ar_f()
mfi_ar = ar_f()
// Ranges
float mfi_hi_tgt = 0.0
float mfi_lo_tgt = 0.0
float mfi_cl_tgt = 0.0
int mfi_int = 0
for i = 0 to 1
array.push(cur_mfi_a, mfi[i])
for i = 0 to len
array.push(mfi_ar, prev_mfi[i])
array.push(mfi_hi_rng_a, hitoop[i])
array.push(mfi_lo_rng_a, optolo[i])
array.push(mfi_cl_rng_a, optoclose[i])
// Search
current_mfi = array.get(cur_mfi_a, 0)
for i = 0 to array.size(mfi_ar) - 1
if array.get(mfi_ar, i) >= current_mfi - 0.5 and array.get(mfi_ar, i) <= current_mfi + 0.5
mfi_int += 1
mfi_hi_tgt += array.get(mfi_hi_rng_a, i)
mfi_lo_tgt += array.get(mfi_lo_rng_a, i)
mfi_cl_tgt += array.get(mfi_cl_rng_a, i)
op := open
hi := open + (mfi_hi_tgt / mfi_int)
lo := open - (mfi_lo_tgt / mfi_int)
cl := open + (mfi_cl_tgt / mfi_int)
if candle_type == "RSI Based Candles"
rsi= ta.rsi(close[1], 14)
prev_rsi = rsi[1]
cur_rsi_a = ar_f()
rsi_hi_rng_a = ar_f()
rsi_lo_rng_a = ar_f()
rsi_cl_rng_a = ar_f()
rsi_ar = ar_f()
// Ranges
float rsi_hi_tgt = 0.0
float rsi_lo_tgt = 0.0
float rsi_cl_tgt = 0.0
int rsi_int = 0
for i = 0 to 1
array.push(cur_rsi_a, rsi[i])
for i = 0 to len
array.push(rsi_ar, prev_rsi[i])
array.push(rsi_hi_rng_a, hitoop[i])
array.push(rsi_lo_rng_a, optolo[i])
array.push(rsi_cl_rng_a, optoclose[i])
// Search
current_rsi = array.get(cur_rsi_a, 0)
for i = 0 to array.size(rsi_ar) - 1
if array.get(rsi_ar, i) >= current_rsi - 0.5 and array.get(rsi_ar, i) <= current_rsi + 0.5
rsi_int += 1
rsi_hi_tgt += array.get(rsi_hi_rng_a, i)
rsi_lo_tgt += array.get(rsi_lo_rng_a, i)
rsi_cl_tgt += array.get(rsi_cl_rng_a, i)
op := open
hi := open + (rsi_hi_tgt / rsi_int)
lo := open - (rsi_lo_tgt / rsi_int)
cl := open + (rsi_cl_tgt / rsi_int)
if candle_type == "Stochastic Based Candles"
sto = ta.stoch(close[1], high[1], low[1], 14)
prev_sto = sto[1]
cur_sto_a = ar_f()
sto_hi_rng_a = ar_f()
sto_lo_rng_a = ar_f()
sto_cl_rng_a = ar_f()
sto_ar = ar_f()
// Ranges
float sto_hi_tgt = 0.0
float sto_lo_tgt = 0.0
float sto_cl_tgt = 0.0
int sto_int = 0
for i = 0 to 1
array.push(cur_sto_a, sto[i])
for i = 0 to len
array.push(sto_ar, prev_sto[i])
array.push(sto_hi_rng_a, hitoop[i])
array.push(sto_lo_rng_a, optolo[i])
array.push(sto_cl_rng_a, optoclose[i])
// Search
current_sto = array.get(cur_sto_a, 0)
for i = 0 to array.size(sto_ar) - 1
if array.get(sto_ar, i) >= current_sto - 0.5 and array.get(sto_ar, i) <= current_sto + 0.5
sto_int += 1
sto_hi_tgt += array.get(sto_hi_rng_a, i)
sto_lo_tgt += array.get(sto_lo_rng_a, i)
sto_cl_tgt += array.get(sto_cl_rng_a, i)
op := open
hi := open + (sto_hi_tgt / sto_int)
lo := open - (sto_lo_tgt / sto_int)
cl := open + (sto_cl_tgt / sto_int)
if candle_type == "9 EMA Candles"
op := ta.ema(open, 9)
hi := ta.ema(high, 9)
lo := ta.ema(low, 9)
cl := ta.ema(close, 9)
if candle_type == "ARIMA Candles"
op_lag_5 = open[5], op_lag_10 = open[10],
hi_lag_5 = high[5], hi_lag_10 = high[10],
lo_lag_5 = low[5], lo_lag_10 = low[10],
cl_lag_5 = close[5], cl_lag_10 = close[10],
// Stationarity
op_lag_5_r = f_armia_basic_stationary(op_lag_5), op_lag_10_r = f_armia_basic_stationary(op_lag_10),
hi_lag_5_r = f_armia_basic_stationary(hi_lag_5), hi_lag_10_r = f_armia_basic_stationary(hi_lag_10),
lo_lag_5_r = f_armia_basic_stationary(lo_lag_5), lo_lag_10_r = f_armia_basic_stationary(lo_lag_10),
cl_lag_5_r = f_armia_basic_stationary(cl_lag_5), cl_lag_10_r = f_armia_basic_stationary(cl_lag_10),
int oplag = op_lag_5_r == true ? 5 : op_lag_10_r == true ? 10 : 20
int hilag = hi_lag_5_r == true ? 5 : hi_lag_10_r == true ? 10 : 20
int lolag = lo_lag_5_r == true ? 5 : lo_lag_10_r == true ? 10 : 20
int cllag = cl_lag_5_r == true ? 5 : cl_lag_10_r == true ? 10 : 20
op := f_linreg(open, open[oplag], len, false)
hi := f_linreg(high, high[hilag], len, false)
lo := f_linreg(low, low[lolag], len, false)
cl := f_linreg(close, close[cllag], len, false)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
color red = color.new(color.red, transp)
color green = color.new(color.lime, transp)
color black = color.rgb(0, 0, 0)
color white = color.white
color candlecolor = op > cl ? red : cl > op ? green : green
plotcandle(op, hi, lo, cl, color = candlecolor)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if bt
int candle_color = 0
int hi_obtained = 0
int lo_obtained = 0
bool candle_color_pass = cl > op and close > open or op > cl and open > close
bool hi_pass = high >= hi
bool lo_pass = low <= lo
for i = 0 to len
if candle_color_pass[i]
candle_color += 1
if hi_pass[i]
hi_obtained += 1
if lo_pass[i]
lo_obtained += 1
hi_perc = (hi_obtained / len) * 100
lo_perc = (lo_obtained / len) * 100
candle_perc = (candle_color / len) * 100
var table bt_table = table.new(position.middle_right, 5, 5, bgcolor = black, frame_color = white, frame_width=3)
table.cell(bt_table, 1, 1, text = "Backtest Results for \n" + str.tostring(candle_type), bgcolor = black, text_color = white)
table.cell(bt_table, 1, 2, text = "Candle Sentiment Pass Rate: " + str.tostring(math.round(candle_perc,2)) + "%", bgcolor = black, text_color = white)
table.cell(bt_table, 1, 3, text = "High Target Success Rate: " + str.tostring(math.round(hi_perc,2)) + "%", bgcolor = black, text_color = white)
table.cell(bt_table, 1, 4, text = "Low Target Success Rate : " + str.tostring(math.round(lo_perc,2)) + "%", bgcolor = black, text_color = white)
|
Debug | https://www.tradingview.com/script/L2F3gAkj-Debug/ | weak_hand | https://www.tradingview.com/u/weak_hand/ | 1 | 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/
// © weak_hand
//@version=5
// https://www.tradingview.com/pine-script-docs/en/v5/writing/Debugging.html
// @description Some debugging functions.
library("Debug", true)
// @function Prints a label on every bar. By default, only the last 50 labels will be shown on the chart. You can increase this amount up to a maximum of 500 by using `max_labels_count = 500` parameter inside `indicator()` or `strategy()`.
// @param txt The text to show on the label.
// @param y_position Y-position (price) to display the label. Optional. Default is `high`.
// @param label_size Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.small`.
// @param label_color Change background color. Optional. Default value is `color.blue`.
// @param txt_color Change text color. Optional. Default value is `color.white`.
// @returns label ID
export label_on_each_bar(string txt = "", float y_position = high, string label_size = size.small, color label_color = color.blue, color txt_color = color.white) =>
label.new(bar_index, y_position, txt, color = label_color, size = label_size, textcolor = txt_color)
// @function Prints a label at last bar only.
// @param txt The text to show on the label.
// @param y_position Y-position (price) to display the label. Optional. Default is `high`.
// @param label_size Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.large`.
// @param label_color Change background color. Optional. Default value is `color.blue`.
// @param txt_color Change text color. Optional. Default value is `color.white`.
// @param txt_align Text alignment. Optional. Possible values: `text.align_left`, `text.align_center`, `text.align_right`. Default value is `text.align_center`.
// @returns label ID
export label_on_last_bar(string txt = "", float y_position = high, string label_size = size.large, color label_color = color.blue, color txt_color = color.white, string txt_align = text.align_center) =>
var label_debug = label.new(bar_index, na, txt, xloc = xloc.bar_index, yloc = yloc.price)
label.set_xy( label_debug, bar_index, y_position)
label.set_size( label_debug, label_size)
label.set_color( label_debug, label_color)
label.set_textalign(label_debug, txt_align)
label.set_textcolor(label_debug, txt_color)
label.set_text( label_debug, txt)
label_debug
// @function Prints a table to show all symbol information available, including the commands.
// @param table_position Position of the table. Optional. Possible values are: `position.top_left`, `position.top_center`, `position.top_right`, `position.middle_left`, `position.middle_center`, `position.middle_right`, `position.bottom_left`, `position.bottom_center`, `position.bottom_right`. Default value is `position.middle_right`.
// @param table_color The background color of the table. Optional. The default is `color.yellow`.
// @param text_color The color of the text. Optional. The default is `color.black`.
// @param text_size Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.auto`.
// @returns table ID
export table_symbol_informations(string table_position = position.middle_right, color table_color = color.yellow, color text_color = color.black, string text_size = size.auto) =>
var table_syminfo = table.new(table_position, 2, 1)
nl = "\n"
column_left =
"syminfo.basecurrency: " + nl +
"syminfo.currency: " + nl +
"syminfo.description: " + nl +
"syminfo.mintick: " + nl +
"syminfo.pointvalue: " + nl +
"syminfo.prefix: " + nl +
"syminfo.root: " + nl +
"syminfo.session: " + nl +
"syminfo.ticker: " + nl +
"syminfo.tickerid: " + nl +
"syminfo.timezone: " + nl +
"syminfo.type: "
column_right =
syminfo.basecurrency + nl +
syminfo.currency + nl +
syminfo.description + nl +
str.tostring(syminfo.mintick) + nl +
str.tostring(syminfo.pointvalue) + nl +
syminfo.prefix + nl +
syminfo.root + nl +
syminfo.session + nl +
syminfo.ticker + nl +
syminfo.tickerid + nl +
syminfo.timezone + nl +
syminfo.type
if barstate.isfirst
table.cell(table_syminfo, 0, 0, column_left , bgcolor = table_color, text_color = text_color, text_halign = text.align_right, text_size = text_size)
table.cell(table_syminfo, 1, 0, column_right, bgcolor = table_color, text_color = text_color, text_halign = text.align_left , text_size = text_size)
table_syminfo
// this is a all in one function for the following four functions (table_array_boolean, table_array_float, table_array_integer, and table_array_string)
table_array(array_for_table, columns, rows, position, bgcolor, txt_color, txt_size) =>
int row_count = 0
if rows == 0
row_count := math.ceil(array_for_table.size() / columns)
else
row_count := rows
if barstate.islast
my_table = table.new(position, columns, row_count, bgcolor)
int count_columns = 0
int count_rows = -1
for counter = 0 to array_for_table.size() - 1
count_rows += 1
if count_rows > row_count - 1
count_columns += 1
count_rows := 0
if count_columns > columns - 1
continue
else
my_table.cell(count_columns, count_rows, str.format("{0}: {1}", counter, array_for_table.get(counter)), text_color = txt_color, text_size = txt_size)
my_table
// @function Prints a table to show boolean values of an array.
// @param array_boolean The array to display on the table. The type of the array has to use boolean values!
// @param columns The number of columns to use. Optional. Default is one.
// @param rows The number of rows to show the values. Optional. Default is `array_float.size()`.
// @param position Position of the table. Optional. Possible values are: `position.top_left`, `position.top_center`, `position.top_right`, `position.middle_left`, `position.middle_center`, `position.middle_right`, `position.bottom_left`, `position.bottom_center`, `position.bottom_right`. Default value is `position.middle_center`.
// @param bgcolor The background color of the table. Optional. There is no color by default.
// @param txt_color The color of the text. Optional. Default value is `color.blue`.
// @param txt_size The size of the Text. Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.auto`.
// @returns table ID
export table_array_boolean(bool[] array_boolean, int columns = 1, int rows = 0, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_array(array_boolean, columns, rows, position, bgcolor, txt_color, txt_size)
// @function Prints a table to show float values of an array.
// @param array_float The array to display on the table. The type of the array has to use float values!
// @param columns The number of columns to use. Optional. Default is one.
// @param rows The number of rows to show the values. Optional. Default is `array_float.size()`.
// @param position Position of the table. Optional. Possible values are: `position.top_left`, `position.top_center`, `position.top_right`, `position.middle_left`, `position.middle_center`, `position.middle_right`, `position.bottom_left`, `position.bottom_center`, `position.bottom_right`. Default value is `position.middle_center`.
// @param bgcolor The background color of the table. Optional. There is no color by default.
// @param txt_color The color of the text. Optional. Default value is `color.blue`.
// @param txt_size The size of the Text. Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.auto`.
// @returns table ID
export table_array_float(float[] array_float, int columns = 1, int rows = 0, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_array(array_float, columns, rows, position, bgcolor, txt_color, txt_size)
// @function Prints a table to show int values of an array.
// @param array_int The array to display on the table. The type of the array has to use int values!
// @param columns The number of columns to use. Optional. Default is one.
// @param rows The number of rows to show the values. Optional. Default is `array_float.size()`.
// @param position Position of the table. Optional. Possible values are: `position.top_left`, `position.top_center`, `position.top_right`, `position.middle_left`, `position.middle_center`, `position.middle_right`, `position.bottom_left`, `position.bottom_center`, `position.bottom_right`. Default value is `position.middle_center`.
// @param bgcolor The background color of the table. Optional. There is no color by default.
// @param txt_color The color of the text. Optional. Default value is `color.blue`.
// @param txt_size The size of the Text. Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.auto`.
// @returns table ID
export table_array_integer(int[] array_int, int columns = 1, int rows = 0, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_array(array_int, columns, rows, position, bgcolor, txt_color, txt_size)
// @function Prints a table to show string values of an array.
// @param array_string The array to display on the table. The type of the array has to use string values!
// @param columns The number of columns to use. Optional. Default is one.
// @param rows The number of rows to show the values. Optional. Default is `array_float.size()`.
// @param position Position of the table. Optional. Possible values are: `position.top_left`, `position.top_center`, `position.top_right`, `position.middle_left`, `position.middle_center`, `position.middle_right`, `position.bottom_left`, `position.bottom_center`, `position.bottom_right`. Default value is `position.middle_center`.
// @param bgcolor The background color of the table. Optional. There is no color by default.
// @param txt_color The color of the text. Optional. Default value is `color.blue`.
// @param txt_size The size of the Text. Possible values: `size.auto`, `size.tiny`, `size.small`, `size.normal`, `size.large`, `size.huge`. Optional. Default value is `size.auto`.
// @returns table ID
export table_array_string(string[] array_string, int columns = 1, int rows = 0, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_array(array_string, columns, rows, position, bgcolor, txt_color, txt_size)
table_matrix(matrix_for_table, from_column, to_column, from_row, to_row, position, bgcolor, txt_color, txt_size, is_string = false) =>
int column_count = na
if na(to_column)
column_count := matrix_for_table.columns()
else
column_count := to_column
int row_count = na
if na(to_row)
row_count := matrix_for_table.rows()
else
row_count := to_row
submatrix_for_table = matrix_for_table.submatrix(from_row, row_count, from_column, column_count)
my_table = table.new(position, submatrix_for_table.columns(), submatrix_for_table.rows(), bgcolor)
for columns_counter = 0 to submatrix_for_table.columns() - 1
for rows_counter = 0 to submatrix_for_table.rows() - 1
if is_string
my_table.cell(columns_counter, rows_counter, str.tostring(submatrix_for_table.get(rows_counter, columns_counter)), text_color = txt_color, text_size = txt_size)
else
my_table.cell(columns_counter, rows_counter, str.tostring(submatrix_for_table.get(rows_counter, columns_counter)), text_color = txt_color, text_size = txt_size)
my_table
// log.info("\n is_string: {0}", str.tostring(is_string))
export table_matrix_boolean(matrix<bool> matrix_boolean, int from_column = 0, int to_column = na, int from_row = 0, int to_row = na, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_matrix(matrix_boolean, from_column, to_column, from_row, to_row, position, bgcolor, txt_color, txt_size, false)
export table_matrix_float(matrix<float> matrix_float, int from_column = 0, int to_column = na, int from_row = 0, int to_row = na, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_matrix(matrix_float, from_column, to_column, from_row, to_row, position, bgcolor, txt_color, txt_size, false)
export table_matrix_integer(matrix<int> matrix_int, int from_column = 0, int to_column = na, int from_row = 0, int to_row = na, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_matrix(matrix_int, from_column, to_column, from_row, to_row, position, bgcolor, txt_color, txt_size, false)
export table_matrix_string(matrix<string> matrix_string, int from_column = 0, int to_column = na, int from_row = 0, int to_row = na, string position = position.middle_center, color bgcolor = na, color txt_color = color.blue, string txt_size = size.auto) =>
table_matrix(matrix_string, from_column, to_column, from_row, to_row, position, bgcolor, txt_color, txt_size, false)
// ----------------------------------------------}
// OUTPUTS
// ----------------------------------------------{
//label_on_each_bar(str.tostring(bar_index), high)
//label_on_last_bar("Hello\nWorld!")
//table_symbol_informations()
//var my_array = array.from(.815, .815, .815)
//table_array_float(my_array, 4)
//var my_array = array.from(1, 2, 3)
//table_array_integer(my_array, 4, 2)
//var my_array = array.from("Hello")
//var table my_id = na
//if barstate.islast
// if my_array.size() == 1 and barstate.isconfirmed
// my_array.push("World")
// my_id.delete()
// else if my_array.size() == 2 and barstate.isconfirmed
// my_array.push("!")
// my_id.delete()
// my_id := table_array_string(my_array)
//var my_matrix = matrix.new<int>(3, 3, 4711)
//var table my_id = na
//if barstate.islast
// if my_matrix.columns() < 10 and barstate.isconfirmed
// my_id.delete()
// my_matrix.add_col()
// my_matrix.fill(666, 0, my_matrix.rows(), my_matrix.columns() - 1, my_matrix.columns())
// my_id := table_matrix_integer(my_matrix)
|
Relative Volatility Measure (RVM) | https://www.tradingview.com/script/Ae9cNmI4-Relative-Volatility-Measure-RVM/ | AIFinPlot | https://www.tradingview.com/u/AIFinPlot/ | 54 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AIFinPlot
//@version=5
indicator("Relative Volatility Measure (RVM)", shorttitle="RVM")
// Inputs
lookbackPeriod = input.int(15, minval=1, title="Lookback Period")
showBgColor = input.bool(true, title="Show Background Color")
// Short-term ATRs
short1 = ta.atr(3)
short2 = ta.atr(5)
short3 = ta.atr(8)
shortAvg = (short1 + short2 + short3) / 3
// Long-term ATRs
long1 = ta.atr(55)
long2 = ta.atr(89)
long3 = ta.atr(144)
longAvg = (long1 + long2 + long3) / 3
// Combined ATR value
combinedATR = (shortAvg + longAvg) / 2
// Highest and lowest combined ATR over lookback period
highestCombinedATR = ta.highest(combinedATR, lookbackPeriod)
lowestCombinedATR = ta.lowest(combinedATR, lookbackPeriod)
// RVM Calculation
rvm = (combinedATR - lowestCombinedATR) / math.max(highestCombinedATR - lowestCombinedATR, 0.001) * 100
// Plotting
plot(rvm, title="RVM", color=color.blue, linewidth=2)
hline(50, "Midpoint", color=color.gray, linestyle=hline.style_dotted)
hline(20, "Midpoint", color=color.rgb(37, 214, 238), linestyle=hline.style_dotted)
hline(10, "Midpoint", color=color.rgb(21, 216, 34), linestyle=hline.style_dotted)
// Background color conditions
bgcolor(showBgColor and rvm >= 0 and rvm <= 10 ? color.rgb(21, 216, 34) : na)
bgcolor(showBgColor and rvm > 10 and rvm <= 20 ? color.rgb(37, 214, 238) : na)
// Label Logic
var label myLabel = na
if barstate.islast
myLabel := label.new(bar_index + 4, rvm, text="RVM: " + str.tostring(rvm, '#.##'), style=label.style_none, color=color.blue, textcolor=color.white, size=size.tiny, yloc=yloc.price)
// Update the label position and text on each bar
if not na(myLabel)
label.set_xy(myLabel, bar_index + 4, rvm)
label.set_text(myLabel, "RVM: " + str.tostring(rvm, '#.##'))
|
DerivativeAlertPlaceHolders | https://www.tradingview.com/script/Z2EgBUM1-DerivativeAlertPlaceHolders/ | TradeWiseWithEase | https://www.tradingview.com/u/TradeWiseWithEase/ | 2 | 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/
// © TradeWiseWithEase
//@version=5
// @description TODO: Creation of Placeholders for Alerts, for using in FNO segment.
library(title = "DerivativeAlertPlaceHolders", overlay = true)
// @BasicPH TODO: Creates Basic PlaceHolders
// @param CustomMessage TODO: Requires Custom Input of Message
// @returns TODO: String with PH
export BasicPH(string CustomMessage) =>
//TODO : add function body and return value here
ExchReplacement = str.replace_all(CustomMessage, "{{exch}}", syminfo.prefix)
TFReplacement = str.replace_all(ExchReplacement, "{{timeframe}}", timeframe.period)
CloseReplacement = str.replace_all(TFReplacement, "{{close}}", str.tostring(close, format.mintick))
OpenReplacement = str.replace_all(CloseReplacement, "{{open}}", str.tostring(open, format.mintick))
HighReplacement = str.replace_all(OpenReplacement, "{{high}}", str.tostring(high, format.mintick))
LowReplacement = str.replace_all(HighReplacement, "{{low}}", str.tostring(low, format.mintick))
// @CustomPlaceHoldersFNO TODO: Creates FNO placeholders, for 1ITM CE strike use place holder { {100R1} },
// 100 refers to strike intervals of underlying and R refers to Rounded number of underlying, 1 refers to moneyness,
// if underlying price is 2508, with the placeholder for 1ITM CE, for the input of { {100R1} } output shall be 2400.
// @param CustomInputMessage TODO: Requires Custom Input of Message
// @returns TODO: Alert String with PH used in major FNO alert Segments
export CustomPlaceHoldersFNO(string CustomInputMessage, float InputPrice = close) =>
Output = ""
Search_String = array.new_string(0)
Replace_String = array.new_string(0)
BasicConversion = BasicPH(CustomInputMessage)
if str.contains(BasicConversion, "{ ")
CustomInputSplits = str.split(BasicConversion,"{ ")
for [index, value] in CustomInputSplits
if str.startswith(value,"{")
SplitTextWith2Curly = str.split(value,"} }")
TextToGetPH = str.replace_all(SplitTextWith2Curly.first(),"{","")
SplitsOfRequiredPH = str.split(TextToGetPH,"R")
if SplitsOfRequiredPH.size() == 2
Diviser = int(str.tonumber(SplitsOfRequiredPH.first()))
Moneyness = int(str.tonumber(SplitsOfRequiredPH.last()))
Search_String.push("{ {" + TextToGetPH + "} }")
RoundedNumber = InputPrice - (InputPrice % Diviser)
RoundedMoneyNess= (InputPrice % Diviser) > Diviser * 0.5 ? 1 : 0
Replace_String.push(str.tostring(RoundedNumber + nz((Diviser * (Moneyness + RoundedMoneyNess)),0)))
for [index, value] in Search_String
Output := str.replace_all(BasicConversion,value,Replace_String.get(index))
BasicConversion := Output
else
Output := BasicConversion
Output
if barstate.islast
label.new(bar_index, high, CustomPlaceHoldersFNO("Place Your TP Alert Message here.\n\n Alert Trigerred when Price was at {{close}}"))
|
lib_array | https://www.tradingview.com/script/ZSWA1MVd-lib-array/ | robbatt | https://www.tradingview.com/u/robbatt/ | 0 | 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/
// © robbatt
// version history
//@version=5
//@description several array functions for chained calls, batch conversion, incrementing and comparing arrays.
library("lib_array", overlay = true)
///////////////////////
// UTIL
///////////////////////
//@description sort an array and return it (compared to the default function returning void)
//@param id The array to sort (and return again)
//@param descending The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
//@return The array that was passed as parameter id
export method sort(int[] id, bool descending = false) =>
array.sort(id, descending ? order.descending : order.ascending)
id
//@description sort an array and return it (compared to the default function returning void)
//@param id The array to sort (and return again)
//@param descending The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
//@return The array that was passed as parameter id
export method sort(float[] id, bool descending = false) =>
array.sort(id, descending ? order.descending : order.ascending)
id
//@description sort an array and return it (compared to the default function returning void)
//@param id The array to sort (and return again)
//@param descending The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
//@return The array that was passed as parameter id
export method sort(string[] id, bool descending = false) =>
array.sort(id, descending ? order.descending : order.ascending)
id
// IN / DECREMENT
_increment(id, by_value) =>
len = id.size()
for [idx, i] in id
id.set(idx, i + by_value)
id
//@description increment all values in an array by the given value
//@param id The array to increment (and return again)
//@param by_value The value by which to increment (default: 1)
//@return The array that was passed as parameter id
export method increment(int[] id, int by_value = 1) =>
_increment(id, by_value)
//@description increment all values in an array by the given value
//@param id The array to increment (and return again)
//@param by_value The value by which to increment (default: 1)
//@return The array that was passed as parameter id
export method decrement(int[] id, int by_value = 1) =>
id.increment(-by_value)
//@description increment all values in an array by the given value
//@param id The array to increment (and return again)
//@param by_value The value by which to increment (default: 1.0)
//@return The array that was passed as parameter id
export method increment(float[] id, float by_value = 1.0) =>
_increment(id, by_value)
//@description increment all values in an array by the given value
//@param id The array to increment (and return again)
//@param by_value The value by which to increment (default: 1.0)
//@return The array that was passed as parameter id
export method decrement(float[] id, float by_value = 1) =>
id.increment(-by_value)
//////////////////////////
// CONVERSION
//////////////////////////
//@description convert an array of strings that each represent a number into a new array of integers. If the values are not properly formed integers, they will be converted to na
//@param id The array to convert
export method toint(string[] id) =>
int_array = array.new<int>()
for s in id
int_array.push(int(str.tonumber(s)))
int_array
//@description convert an array of floats into a new array of integers.
//@param id The array to convert
export method toint(float[] id) =>
int_array = array.new<int>()
for f in id
int_array.push(int(f))
int_array
//@description convert an array of strings that each represent a number into a new array of integers. If the values are not properly formed integers or floating point values, they will be converted to na
//@param id The array to convert
export method tofloat(string[] id) =>
float_array = array.new<float>()
for s in id
float_array.push(str.tonumber(s))
float_array
//@description convert an array of integers into a new array of floats.
//@param id The array to convert
export method tofloat(int[] id) =>
float_array = array.new<float>()
for i in id
float_array.push(float(i))
float_array
//@description convert an array of integers into a new array of strings. If the values are na, they will be converted to the string "NaN".
//@param id The array to convert
export method tostring(int[] id) =>
str_array = array.new<string>()
for i in id
str_array.push(str.tostring(i))
str_array
//@description convert an array of integers into a new array of strings. If the values are na, they will be converted to the string "NaN".
//@param id The array to convert
export method tostring(float[] id) =>
str_array = array.new<string>()
for i in id
str_array.push(str.tostring(i))
str_array
//@description convert an array of floats into a new array of booleans.
//@param id The array to convert
export method tobool(float[] id) =>
bool_array = array.new<bool>()
for f in id
bool_array.push(bool(f))
bool_array
//@description convert an array of floats into a new array of booleans.
//@param id The array to convert
export method tobool(int[] id) =>
bool_array = array.new<bool>()
for i in id
bool_array.push(bool(i))
bool_array
//@description convert an array of strings into a new array of booleans. A string is true if it is not na AND longer than 0
//@param id The array to convert
export method tobool(string[] id) =>
bool_array = array.new<bool>()
for i in id
bool_array.push(na(i) ? false : str.length(i) > 0)
bool_array
//@description convert an array of booleans to 0/1 and count all the 1s
//@param id The array to convert
export method sum(bool[] id) =>
sum = 0
for b in id
sum += b ? 1 : 0
//////////////////////////
// QUEUES
//////////////////////////
// TODO revise when generics are added to pine script, so we can pass custom types as well
_enqueue(id, item, int max, bool condition = true, bool lifo = false) =>
if not na(item) and condition
if lifo // Last In First Out
array.push(id,item)
if id.size() > max
id.shift()
else // First In Last Out
array.unshift(id,item)
if id.size() > max
id.pop()
id
//@description enqueue a value into an array, if the resulting length of the array exceeds max, the oldest inserted element is removed
//@param id The array that is used as queue
//@param item The item to enqueue (at pos 0, unless lifo = true)
//@param max The max size of the queue
//@param condition An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
//@param lifo An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
//@returns The queue passed as param id
export method enqueue(int[] id, int item, int max, bool condition = true, bool lifo = false) =>
_enqueue (id,item, max, condition, lifo)
//@description enqueue a value into an array, if the resulting length of the array exceeds max, the oldest inserted element is removed
//@param id The array that is used as queue
//@param item The item to enqueue (at pos 0, unless lifo = true)
//@param max The max size of the queue
//@param condition An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
//@param lifo An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
//@returns The queue passed as param id
export method enqueue(float[] id, float item, int max, bool condition = true, bool lifo = false) =>
_enqueue (id,item, max, condition, lifo)
//@description enqueue a value into an array, if the resulting length of the array exceeds max, the oldest inserted element is removed
//@param id The array that is used as queue
//@param item The item to enqueue (at pos 0, unless lifo = true)
//@param max The max size of the queue
//@param condition An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
//@param lifo An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
//@returns The queue passed as param id
export method enqueue(string[] id, string item, int max, bool condition = true, bool lifo = false) =>
_enqueue (id,item, max, condition, lifo)
//@description enqueue a value into an array, if the resulting length of the array exceeds max, the oldest inserted element is removed
//@param id The array that is used as queue
//@param item The item to enqueue (at pos 0, unless lifo = true)
//@param max The max size of the queue
//@param condition An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
//@param lifo An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
//@returns The queue passed as param id
export method enqueue(line[] id, line item, int max, bool condition = true, bool lifo = false) =>
_enqueue (id,item, max, condition, lifo)
//@description enqueue a value into an array, if the resulting length of the array exceeds max, the oldest inserted element is removed
//@param id The array that is used as queue
//@param item The item to enqueue (at pos 0, unless lifo = true)
//@param max The max size of the queue
//@param condition An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
//@param lifo An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
//@returns The queue passed as param id
export method enqueue(box[] id, box item, int max, bool condition = true, bool lifo = false) =>
_enqueue (id,item, max, condition, lifo)
///////////////////////
// TEST
///////////////////////
// import robbatt/lib_log/2 as LOG
// import robbatt/lib_unit/3 as UNIT
// var UNIT.Test assert = UNIT.Test.new(false, true)
// assert.init()
// // test setup
// array<string> initial = array.from('99', '100')
// assert.equals(initial.get(0), '99', 'first item of initial array should be 99')
// assert.equals(initial.get(1), '100', 'second item of initial array should be 100')
// // check sorting and enqueueing works
// array<string> sorted_str = initial.sort()
// assert.equals(sorted_str.get(0), '100', 'first item of sorted string array should be "100" (because 1<9)')
// assert.equals(sorted_str.get(1), '99', 'second item of sorted string array should be "99"')
// // check conversion works from strings to ints
// array<int> converted_int = sorted_str.toint()
// assert.equals(converted_int.get(0), 100, 'first item of sorted string array, converted to integers, should be 100')
// assert.equals(converted_int.get(1), 99, 'second item of sorted string array, converted to integers, should be 99')
// // check sorting and enqueueing works
// array<int> sorted_int = converted_int.sort()
// assert.equals(sorted_int.get(0), 99, 'first item of sorted integer array should be 99')
// assert.equals(sorted_int.get(1), 100, 'second item of sorted integer array should be 100')
// // check calculations on converted numbers
// array<int> incremented = sorted_int.increment()
// assert.equals(incremented.get(0), 100, 'first item of incremented integer array should be 100')
// assert.equals(incremented.get(1), 101, 'second item of incremented integer array should be 101')
// // check enqueueing works
// array<int> enqueued_int = incremented.enqueue(99, 2).enqueue(100, 2)
// assert.equals(enqueued_int.size(), 2, 'length of integer queue should be 2')
// assert.equals(enqueued_int.get(0), 100, 'first item of integer queue should be 100')
// assert.equals(enqueued_int.get(1), 99, 'second item of integer queue should be 99')
// array<string> enqueued_str = array.from('center', 'extra').enqueue('filo', 2).enqueue('lifo', 3, lifo = true)
// assert.equals(enqueued_str.size(), 3, 'length of string queue should be 3')
// assert.equals(enqueued_str.get(0), 'filo', 'first item of string queue should be "filo"')
// assert.equals(enqueued_str.get(1), 'center', 'second item of string queue should be "center"')
// assert.equals(enqueued_str.get(2), 'lifo', 'second item of string queue should be "lifo"')
if barstate.isfirst
label.new(bar_index, close, 'minimum required plot') |
lib_unit | https://www.tradingview.com/script/ZhP4ghrs-lib-unit/ | robbatt | https://www.tradingview.com/u/robbatt/ | 0 | 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/
// © robbatt
//@version=5
import robbatt/lib_log/6 as LOG
// @description functions for unit testing
library("lib_unit", overlay = true)
////////////////////////////
// MODEL
////////////////////////////
export type Test
bool strict = true // if true: throw runtime error, else write to log
bool verbose = true // if true: print Actual value, Expected value AND message, if false: ONLY message
LOG.Logger logger = na
export method init(Test this) =>
if na(this.logger)
this.logger := LOG.Logger.new(name = 'assert', min_level = 3, color_logs = true)
this.logger
////////////////////////////
// CORE
////////////////////////////
assert(Test test, expression, expected, string message, bool condition = true) =>
test.init()
if condition
error_msg = test.verbose ? str.format('Actual: {0} | Expected: {1} | Message: {2}', expression, expected, message) : message
if test.strict
runtime.error(error_msg)
test.logger.error(error_msg)
////////////////////////////
//#region TRUE / FALSE
////////////////////////////
// @function assert that expression is true, if it's false a runtime error will be thrown
// @param expression The value to be true
// @param message The message to print in the runtime error
export method is_true(Test this, bool expression, string message) =>
assert(this, expression, true, message, not (expression == true))
// @function assert that expression is false, if it's true a runtime error will be thrown
// @param expression The value to be false
// @param message The message to print in the runtime error
export method is_false(Test this, bool expression, string message) =>
assert(this, expression, false, message, not (expression == false))
////////////////////////////
//#endregion TRUE / FALSE
////////////////////////////
////////////////////////////
//#region EQUALS
////////////////////////////
_equals(Test test, expression, expected, message) =>
if expression != expected
assert(test, expression, expected, message)
_equals_array(Test test, expression, expected, message) =>
if not na(expression) and not na(expected)
size1 = array.size(expression)
size2 = array.size(expected)
if size1 != size2
assert(test, expression, expected, message)
for [i,e1] in expected
e2 = expression.get(i)
if e1 != e2
assert(test, expression, expected, message)
else if not(na(expression) and na(expected))
assert(test, expression, expected, message)
// both na is OK
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown
// @param expression The value to test
// @param expected The expected value
// @param message The message to print in the runtime error
export method equals(Test this, string expression, string expected, string message) =>
_equals(this, expression, expected, message)
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown
// @param expression The value to test
// @param expected The expected value
// @param message The message to print in the runtime error
export method equals(Test this, int expression, int expected, string message) =>
_equals(this, expression, expected, message)
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown
// @param expression The value to test
// @param expected The expected value
// @param message The message to print in the runtime error
export method equals(Test this, float expression, float expected, string message) =>
_equals(this, expression, expected, message)
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
// @param expression The array to test
// @param expected The expected array
// @param message The message to print in the runtime error
export method equals(Test this, string[] expression, string[] expected, string message) =>
_equals_array(this, expression, expected, message)
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
// @param expression The array to test
// @param expected The expected array
// @param message The message to print in the runtime error
export method equals(Test this, int[] expression, int[] expected, string message) =>
_equals_array(this, expression, expected, message)
// @function assert if expression and expected are equal, if they don't match a runtime error will be thrown. This version is testing length, order and values
// @param expression The array to test
// @param expected The expected array
// @param message The message to print in the runtime error
export method equals(Test this, float[] expression, float[] expected, string message) =>
_equals_array(this, expression, expected, message)
////////////////////////////
//#endregion EQUALS
////////////////////////////
////////////////////////////
//#region NOT NA
////////////////////////////
_not_na(Test test, expression, string message) =>
if na(expression)
assert(test, expression, 'not na', message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, string expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, int expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, float expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, string[] expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, int[] expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
export method not_na(Test this, float[] expression, string message) =>
_not_na(this, expression, message)
// @function assert if expression is not na, if it is a runtime error will be thrown.
// @param expression The value to test
// @param message The message to print in the runtime error
////////////////////////////
//#endregion NOT NA
////////////////////////////
////////////////////////////
//#region COMPARE
////////////////////////////
_gt(Test test, expression1, expression2, message) =>
assert(test, expression1, expression2, message, not (expression1 > expression2))
_gte(Test test, expression1, expression2, message) =>
assert(test, expression1, expression2, message, not (expression1 >= expression2))
_lt(Test test, expression1, expression2, message) =>
assert(test, expression1, expression2, message, not (expression1 < expression2))
_lte(Test test, expression1, expression2, message) =>
assert(test, expression1, expression2, message, not (expression1 <= expression2))
// @function assert that expression1 > expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be greater
// @param expression2 The value that should be lesser
// @param message The message to print in the runtime error
export method gt(Test this, int expression1, int expression2, string message) =>
_gt(this, expression1, expression2, message)
// @function assert that expression1 > expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be greater
// @param expression2 The value that should be lesser
// @param message The message to print in the runtime error
export method gt(Test this, float expression1, int expression2, string message) =>
_gt(this, expression1, expression2, message)
// @function assert that expression1 >= expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be greater or equal
// @param expression2 The value that should be lesser or equal
// @param message The message to print in the runtime error
export method gte(Test this, int expression1, int expression2, string message) =>
_gte(this, expression1, expression2, message)
// @function assert that expression1 >= expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be greater or equal
// @param expression2 The value that should be lesser or equal
// @param message The message to print in the runtime error
export method gte(Test this, float expression1, int expression2, string message) =>
_gte(this, expression1, expression2, message)
// @function assert that expression1 < expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be lesser
// @param expression2 The value that should be greater
// @param message The message to print in the runtime error
export method lt(Test this, int expression1, int expression2, string message) =>
_lt(this, expression1, expression2, message)
// @function assert that expression1 < expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be lesser
// @param expression2 The value that should be greater
// @param message The message to print in the runtime error
export method lt(Test this, float expression1, int expression2, string message) =>
_lt(this, expression1, expression2, message)
// @function assert that expression1 <= expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be lesser or equal
// @param expression2 The value that should be greater or equal
// @param message The message to print in the runtime error
export method lte(Test this, int expression1, int expression2, string message) =>
_lte(this, expression1, expression2, message)
// @function assert that expression1 <= expression2, if it is not, a runtime error will be thrown.
// @param expression1 The value that should be lesser or equal
// @param expression2 The value that should be greater or equal
// @param message The message to print in the runtime error
export method lte(Test this, float expression1, int expression2, string message) =>
_lte(this, expression1, expression2, message)
////////////////////////////
//#endregion COMPARE
////////////////////////////
////////////////////////////
// TEST
////////////////////////////
Test assert = Test.new(strict = false, verbose = true)
if bar_index < 10000
value = close
value1= close[1]
assert.equals(1+1, 2, '1+1 should equal 2')
assert.equals(2, 1, '1 should not be 2')
var row1 = array.from(1,2,3,4,5)
var row2 = array.from(1,2,3,4,5)
var rowx = array.from(1,4,3,2,5)
assert.equals(row1, row2, 'two arrays match')
assert.equals(row1, rowx, 'these arrays dont match')
assert.not_na(value, 'should not be na')
assert.not_na(value, 'should not be na')
assert.not_na(row1, 'should not be na')
string NA = na
assert.is_true(na(NA), 'should be true')
assert.is_false(not na(NA), 'should be false')
NA := 'ABC'
assert.is_false(na(NA), 'should be false, na() returns 0/1 it seems')
// NA := na
assert.is_false(na(NA), 'should be false, na() returns 0/1 it seems2')
plot(1, '1') |
Bitcoin Cycles Indicator | https://www.tradingview.com/script/Ye2uRF8j-Bitcoin-Cycles-Indicator/ | VanHe1sing | https://www.tradingview.com/u/VanHe1sing/ | 57 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VanHe1sing
//@version=5
indicator("Bitcoin Cycles", shorttitle = "BTC: Cycles", overlay = true)
MCR = request.security("COINMETRICS:BTC_MARKETCAPREAL","D",close)
TV = ta.sma(request.security("GLASSNODE:BTC_TOTALVOLUME","D",close), 500) //Total Volume of transfer
//Cycles
cycle = (MCR-TV) / 23000000
multi = 1.5
cycle1= cycle * multi,
multi += 1,
cycle2= cycle * multi,
multi += 1,
cycle3= cycle * multi,
multi += 1,
cycle4= cycle * multi
plot(cycle, color = color.green),
plot(cycle1, color = color.aqua),
plot(cycle2, color = color.purple),
plot(cycle3, color = color.orange),
plot(cycle4, color = color.red)
label_(cycle, name, color)=>
lbl = label.new(na, na, textcolor = color)
label.set_xy(lbl, bar_index+150, cycle/1.05)
label.set_style(lbl, label.style_none)
label.set_text(lbl, name)
if barstate.islast
label_(cycle, "Cycle Lows", color.green),
label_(cycle1, "Under Valued", color.aqua),
label_(cycle2, "Fair Market Value", color.purple),
label_(cycle3, "Aggressively Values", color.orange),
label_(cycle4, "Over Valued", color.red)
|
lib_log | https://www.tradingview.com/script/M0PjfJ4S-lib-log/ | robbatt | https://www.tradingview.com/u/robbatt/ | 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/
// © robbatt
//@version=5
// @description library for logging and debugging pine scripts
library("lib_log", overlay = true)
///////////////////////////////////////////
// HELPERS
///////////////////////////////////////////
level_color(int level, int transparency = 0) =>
col = switch level
4 => color.red
3 => color.orange
2 => color.green
1 => color.aqua
=> chart.bg_color
color.new(col, transparency)
get_level_name(int level) =>
switch level
4 => 'ERROR'
3 => 'WARNING'
2 => 'SUCCESS'
1 => 'INFO'
=> 'DEBUG'
///////////////////////////////////////////
// MODEL
///////////////////////////////////////////
export type LogEntry
int timestamp
int bar
int level
string logger
string message
export type LogDisplay
int max_lines = 5
string table_pos = position.bottom_left
table _table = na
array<LogEntry> log = na
export type Logger
string name = na
// 3 : ERROR
// 2 : WARNING
// 1 : INFO
// 0 : DEBUG
int min_level = 0
// table
bool color_logs = false
LogDisplay display = na
///////////////////////////////////////////
// PRIVATE
///////////////////////////////////////////
method init(LogDisplay this) =>
if na(this.log)
this.log := array.new<LogEntry>(this.max_lines)
if na(this._table) and not na(this.log)
this._table := table.new(this.table_pos, 5, 1 + this.max_lines, chart.bg_color, border_color = chart.bg_color, border_width = 1)
this._table.cell(0, 0, 'time', text_color = chart.fg_color, text_halign = text.align_center, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(1, 0, 'bar', text_color = chart.fg_color, text_halign = text.align_center, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(2, 0, 'level', text_color = chart.fg_color, text_halign = text.align_center, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(3, 0, na, text_color = chart.fg_color, text_halign = text.align_center, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(4, 0, 'log', text_color = chart.fg_color, text_halign = text.align_center, text_size = size.small, bgcolor = chart.bg_color)
for i = 1 to this.max_lines
this._table.cell(0, i, na, text_color = chart.fg_color, text_halign = text.align_right, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(1, i, na, text_color = chart.fg_color, text_halign = text.align_right, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(2, i, na, text_color = chart.fg_color, text_halign = text.align_right, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(3, i, na, text_color = chart.fg_color, text_halign = text.align_left, text_size = size.small, bgcolor = chart.bg_color)
this._table.cell(4, i, na, text_color = chart.fg_color, text_halign = text.align_left, text_size = size.small, bgcolor = chart.bg_color)
this
method initDisplay(Logger this) =>
if na(this.display)
this.display := LogDisplay.new()
this.display.init()
this
method get_level_color(Logger this, int level, int transparency = 0) =>
level_color(this.color_logs ? level : 0, transparency)
method log_bar(Logger this, int level, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
var last = label.new(na, na, na, size = size.small, textcolor = chart.fg_color)
if condition and level >= this.min_level
lbl = last_only ? last : label.new(na, na, na, size = size.small, textcolor = chart.fg_color)
lbl.set_text(message)
lbl.set_xy(bar, y + y_offset)
lbl.set_style(y_offset >= 0 ? label.style_label_down: label.style_label_up)
lbl.set_color(this.get_level_color(level, 80))
method recycle(LogEntry this, int level, string message, string logger) =>
le = this
if na(le)
le := LogEntry.new(time, bar_index, level, logger, message)
else
le.timestamp := time
le.bar := bar_index
le.level := level
le.logger := logger
le.message := message
le
method log_table(Logger this, int level, string message, bool condition = true) =>
this.initDisplay()
if condition and level >= this.min_level
temp = this.display.log.shift().recycle(level, message, this.name)
this.display.log.push(temp)
for [i,le] in this.display.log
if not na(le)
cell_color = this.get_level_color(le.level, 80)
this.display._table.cell_set_text(0, i+1, str.format('{0,date,y.MM.dd hh:mm}', le.timestamp))
this.display._table.cell_set_text(1, i+1, str.tostring(le.bar))
this.display._table.cell_set_text(2, i+1, get_level_name(le.level))
this.display._table.cell_set_text(3, i+1, le.logger)
this.display._table.cell_set_text(4, i+1, le.message)
this.display._table.cell_set_bgcolor(0, i+1, cell_color)
this.display._table.cell_set_bgcolor(1, i+1, cell_color)
this.display._table.cell_set_bgcolor(2, i+1, cell_color)
this.display._table.cell_set_bgcolor(3, i+1, cell_color)
this.display._table.cell_set_bgcolor(4, i+1, cell_color)
///////////////////////////////////////////
// PUBLIC
///////////////////////////////////////////
//@description add a log entry to the log table
//@param this Logger to add the entry to
//@param message The Message to add
//@param condition optional flag to enable disable logging of this entry dynamically (default: true)
export method debug(Logger this, string message, bool condition = true) => this.log_table(0, message, condition)
//@description add a log entry to the log table
//@param this Logger to add the entry to
//@param message The Message to add
//@param condition optional flag to enable disable logging of this entry dynamically (default: true)
export method info(Logger this, string message, bool condition = true) => this.log_table(1, message, condition)
//@description add a log entry to the log table
//@param this Logger to add the entry to
//@param message The Message to add
//@param condition optional flag to enable disable logging of this entry dynamically (default: true)
export method success(Logger this, string message, bool condition = true) => this.log_table(2, message, condition)
//@description add a log entry to the log table
//@param this Logger to add the entry to
//@param message The Message to add
//@param condition optional flag to enable disable logging of this entry dynamically (default: true)
export method warning(Logger this, string message, bool condition = true) => this.log_table(3, message, condition)
//@description add a log entry to the log table
//@param this Logger to add the entry to
//@param message The Message to add
//@param condition optional flag to enable disable logging of this entry dynamically (default: true)
export method error(Logger this, string message, bool condition = true) => this.log_table(4, message, condition)
//@description for debug label on a bar
//@param this Logger object to check global min level condition
//@param message The string to print
//@param bar The bar to print the label at (default: bar_index)
//@param y The price value to print at (default: high)
//@param y_offset A price offset from y if you want to print multiple labels at the same spot
export method debug_bar(Logger this, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
this.log_bar(0, message, bar, y, y_offset, last_only, condition)
//@description for debug label on a bar
//@param this Logger object to check global min level condition
//@param message The string to print
//@param bar The bar to print the label at (default: bar_index)
//@param y The price value to print at (default: high)
//@param y_offset A price offset from y if you want to print multiple labels at the same spot
export method info_bar(Logger this, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
this.log_bar(1, message, bar, y, y_offset, last_only, condition)
//@description for debug label on a bar
//@param this Logger object to check global min level condition
//@param message The string to print
//@param bar The bar to print the label at (default: bar_index)
//@param y The price value to print at (default: high)
//@param y_offset A price offset from y if you want to print multiple labels at the same spot
export method success_bar(Logger this, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
this.log_bar(2, message, bar, y, y_offset, last_only, condition)
//@description for debug label on a bar
//@param this Logger object to check global min level condition
//@param message The string to print
//@param bar The bar to print the label at (default: bar_index)
//@param y The price value to print at (default: high)
//@param y_offset A price offset from y if you want to print multiple labels at the same spot
export method warning_bar(Logger this, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
this.log_bar(3, message, bar, y, y_offset, last_only, condition)
//@description for debug label on a bar
//@param this Logger object to check global min level condition
//@param message The string to print
//@param bar The bar to print the label at (default: bar_index)
//@param y The price value to print at (default: high)
//@param y_offset A price offset from y if you want to print multiple labels at the same spot
export method error_bar(Logger this, string message, int bar = bar_index, float y = high, float y_offset = 0, bool last_only = false, bool condition = true) =>
this.log_bar(4, message, bar, y, y_offset, last_only, condition)
///////////////////////////////////////////
// USAGE
///////////////////////////////////////////
// configure the logger to plot Debug or above, max 10 entries in the table and to enable colors
var LogDisplay d = LogDisplay.new(10, position.bottom_right).init()
var Logger l1 = Logger.new('L1', min_level = 0, color_logs = true, display = d)
var Logger l2 = Logger.new('L2', min_level = 0, color_logs = true, display = d)
var Logger l3 = Logger.new('L3', min_level = 2)
// realtime data
varip tick = 0
if barstate.isnew
tick := 0
tick += 1
// display auto init
if barstate.isfirst
l3.debug('debug ' + str.tostring(tick))
l3.info('info ' + str.tostring(tick))
l3.success('success ' + str.tostring(tick))
l3.warning('warning ' + str.tostring(tick))
l3.error('error ' + str.tostring(tick))
// helper for stacking labels (only necessary if you want to plot multiple labels per bar)
atr = ta.atr(100)
// simple label above bar
l1.debug_bar('debug')
l1.info_bar('info', y_offset = atr)
l1.success_bar('success', y_offset = atr*2)
l1.warning_bar('warning', y_offset = atr*3)
l1.error_bar('error', y_offset = atr*4)
// trailing label below last bar (negative offset switches label to point upwards)
if barstate.islast
l2.debug_bar('last debug ' + str.tostring(tick), y_offset = -atr, last_only = true)
l2.info_bar('last info ' + str.tostring(tick), y_offset = -atr*2, last_only = true)
l2.success_bar('last success ' + str.tostring(tick), y_offset = -atr*3, last_only = true)
l2.warning_bar('last warning ' + str.tostring(tick), y_offset = -atr*4, last_only = true)
l2.error_bar('last error ' + str.tostring(tick), y_offset = -atr*5, last_only = true)
// entries into the log table
l1.debug('debug ' + str.tostring(tick))
l2.info('info ' + str.tostring(tick))
l1.success('success ' + str.tostring(tick))
l2.warning('warning ' + str.tostring(tick))
l1.error('error ' + str.tostring(tick))
|
lib_tracking | https://www.tradingview.com/script/IhJVtzkz-lib-tracking/ | robbatt | https://www.tradingview.com/u/robbatt/ | 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/
// © robbatt
//@version=5
//@description tracking highest and lowest with anchor point to track over dynamic periods, e.g. to track a Session HH/LL live and get the bar/time of the LTF wick that matches the HTF HH/LL
library("lib_tracking", overlay=true)
///////////////////////
// TRACKING
///////////////////////
// DESIGN DECISION
// why anchored replacements for ta.highest / ta.highestbars / ta.lowest / ta.lowestbars:
// 1. they require a fixed length/lookback which makes it easier to calculate, but
// 2. this prevents us from tracking the HH/LL of a changing timeframe, e.g. live tracking the HH/LL of a running session or unfinished higher timeframe
// 3. tracking with anchor/start/reset flag allows to persist values until the next start/reset, so no other external storage is required
track_hl(series float target, int mode, bool reset = false, bool track_this_bar = true) =>
var value = target
var value_time = time
var value_index = bar_index
var track_highest = mode == 1
var track_lowest = mode == -1
if reset or track_this_bar
if reset
or track_highest and target > value
or track_lowest and target < value
value := target
value_time := time
value_index := bar_index
[value, value_time, value_index]
//@description live-track highest value of an unfinished range (e.g. unfinished session or higher timeframe bar) (non constant length to ta.highest would trigger 'max_bars_back error')
//@param series to track
//@param reset boolean flag to restart tracking from this point (a.k.a anchor)
//@param track_this_bar allows enabling and disabling of tracking, e.g. before a session starts or after it ends, values can be kept until next reset.
export track_highest(series float value = high, bool reset = false, bool track_this_bar = true) =>
[highest, highest_time, highest_index] = track_hl(value, 1, reset, track_this_bar)
//@description live-track lowest value of an unfinished range (e.g. unfinished session or higher timeframe bar) (non constant length to ta.lowest would trigger 'max_bars_back error')
//@param series to track
//@param reset boolean flag to restart tracking from this point (a.k.a anchor)
//@param track_this_bar allows enabling and disabling of tracking, e.g. before a session starts or after it ends, values can be kept until next reset.
export track_lowest(series float value = low, bool reset = false, bool track_this_bar = true) =>
[lowest, lowest_time, lowest_index] = track_hl(value, -1, reset, track_this_bar)
//@description track the hh and ll within a higher timeframe bar, plus a signal when the bar is about to close to get the final values asap
//@param htf the higher timeframe in pinescript string notation
//@returns [bool started, bool closing, bool cancelled, float highest, int highest_time, int highest_index, float lowest, int lowest_time, int lowest_index]
export track_hl_htf(string htf, series float value_high = high, series float value_low = low) =>
var previous_closing = false
closing = time_close(htf) == time_close and barstate.isconfirmed
started = timeframe.change(htf)
cancelled = not previous_closing and started
[highest, highest_time, highest_index] = track_hl(value_high, 1, started)
[lowest, lowest_time, lowest_index] = track_hl(value_low, -1, started)
previous_closing := closing
[started, closing, cancelled, highest, highest_time, highest_index, lowest, lowest_time, lowest_index]
///////////////////////
// DEMO
///////////////////////
// TRACKING HH AND LL IN DYNAMIC TIME FRAME
new_day = timeframe.change('1D')
[highest, highest_time, highest_index] = track_highest(high, new_day)
[lowest, lowest_time, lowest_index] = track_lowest(low, new_day)
plot(highest, 'highest')
plot(lowest, 'lowest')
if new_day
// line.new(bar_index, 0, bar_index, 1, extend = extend.both)
line.new(highest_time[1], highest[1], time, highest[1], xloc = xloc.bar_time)
label.new(bar_index, highest[1], 'hh', style = label.style_label_left)
line.new(lowest_time[1], lowest[1], time, lowest[1], xloc = xloc.bar_time)
label.new(bar_index, lowest[1], 'll', style = label.style_label_left)
[htf_started, htf_closing, htf_cancelled, htf_highest, htf_highest_time, htf_highest_index, htf_lowest, htf_lowest_time, htf_lowest_index] = track_hl_htf('2D') // 2D
plot(htf_highest, 'htf_highest', color = color.aqua)
plot(htf_lowest, 'htf_lowest', color = color.aqua)
if htf_started
// line.new(bar_index, 0, bar_index, 1, extend = extend.both, color = color.aqua, style = line.style_dashed)
line.new(htf_highest_time[1], htf_highest[1], time, htf_highest[1], xloc = xloc.bar_time, color = color.aqua)
label.new(bar_index, htf_highest[1], '2d hh', style = label.style_label_left, color = color.aqua)
line.new(htf_lowest_time[1], htf_lowest[1], time, htf_lowest[1], xloc = xloc.bar_time, color = color.aqua)
label.new(bar_index, htf_lowest[1], '2d ll', style = label.style_label_left, color = color.aqua)
|
VolatilityIndicators | https://www.tradingview.com/script/SjSHSqAE-VolatilityIndicators/ | andre_007 | https://www.tradingview.com/u/andre_007/ | 20 | 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/
// © andre_007
// @version=5
// @description This is a library of 'Volatility Indicators'.
// It aims to facilitate the grouping of this category of indicators, and also offer the customized supply of
// the parameters and sources, not being restricted to just the closing price.
// @Thanks and credits:
// 1. Dynamic Zones: Leo Zamansky, Ph.D., and David Stendahl (code by allanster)
// 2. Deviation: Karl Pearson (code by TradingView)
// 3. Variance: Ronald Fisher (code by TradingView)
// 4. Z-score: Veronique Valcu (code by HPotter)
// 5. Standard deviation: Ronald Fisher (code by TradingView)
// 6. ATR (Average True Range): J. Welles Wilder (code by TradingView)
// 7. ATRP (Average True Range Percent): millerrh
// 8. Historical Volatility: HPotter
// 9. Min-Max Scale Normalization: gorx1
// 10. Mean Normalization: gorx1
// 11. Standardization: gorx1
// 12. Scaling to unit length: gorx1
// 13. LS Volatility Index: Alexandre Wolwacz (Stormer), Fabrício Lorenz, Fábio Figueiredo (Vlad) (code by me)
// 14. Bollinger Bands: John Bollinger (code by TradingView)
// 15. Bollinger Bands %: John Bollinger (code by TradingView)
// 16. Bollinger Bands Width: John Bollinger (code by TradingView)
// 17. Keltner Channels: Chester W. Keltner (code by TradingView)
// 18. Keltner Channels %: adapted from Bollinger Bands % by me (andre_007
// 19. Keltner Channels Width: adapted from Bollinger Bands Width by me (andre_007)
// 20. Moving Envelopes: Alan Hull (code by TradingView)
// 21. Donchian Channels: Richard Donchian (code by TradingView)
library("VolatilityIndicators")
import andre_007/MovingAveragesProxy/3 as MAPROXY
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Dispersion
// @function Deviation. Measure the difference between a source in relation to another source
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) Sequential period to calculate the deviation
// @param anotherSource (float) Source to compare
// @returns (float) Bollinger Bands Width
export dev(float source, simple int length, float anotherSource) =>
sum = 0.0
for i = 0 to length - 1
val = source[i]
sum := sum + math.abs(val - anotherSource)
dev = sum/length
// @function Variance. A statistical measurement of the spread between numbers in a data set. More specifically,
// variance measures how far each number in the set is from the mean (average), and thus from every other number in the set.
// Variance is often depicted by this symbol: σ2. It is used by both analysts and traders to determine volatility and market security.
// @param src (float) Source to calculate variance
// @param mean (float) Mean (Moving average)
// @param length (int) The sequential period to calcule the variance (number of values in data set)
// @param biased (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
// @param degreesOfFreedom (int) Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
// Default value is n-1, where n here is length. Only applies when biased parameter is defined as false.
// @returns (float) Standard deviation
export variance(float src, float mean, simple int length, simple bool biased=true, simple int degreesOfFreedom=na) =>
dev = src - mean
variance = if biased
variance = math.sum(dev * dev, length) / length
else
if na(degreesOfFreedom) or (degreesOfFreedom == 0) or (degreesOfFreedom >= length)
runtime.error("When the biased parameter is false (unbiased), the degrees of freedom must be greater than zero and less than or equal to length-1")
variance = math.sum(dev * dev, length) / degreesOfFreedom
// @function Measure the Standard deviation from a source in relation to it's moving average.
// In this implementation, you pass the average as a parameter, allowing a more personalized calculation.
// @param src (float) Source to calculate standard deviation
// @param mean (float) Moving average.
// @param length (int) The sequential period to calcule the standard deviation
// @param biased (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
// else uses unbiased sample variance (n-1 or another value, as long as it is in the range between 1 and n-1), where n=length.
// @param degreesOfFreedom (int) Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
// Default value is n-1, where n here is length. Only applies when biased parameter is defined as false.
// @returns (float) Standard deviation
export stDev(float src, simple int length, float mean, simple bool biased=true, simple int degreesOfFreedom=na) =>
variance = variance(src, mean, length, biased, degreesOfFreedom)
math.sqrt(variance)
// @function Standard Error. The standard error of the mean is a measure of the variation in the sample mean
// relative to the population mean. The formula is given by:
//
// SE = σ / √n
// SE: Standard error of the mean (Standard Error)
// σ: Population standard deviation (Standard Deviation)
// n: Sample Size
//
// In this formula, the population standard deviation (σ) is divided by the square root of the sample size (n).
// This indicates that the standard error decreases as the sample size increases, which means that the estimate of the
// sample mean becomes more accurate.
// @param stdDev (float) Standard Deviation
// @param sampleSize (int) Sample size
// @returns (float) Standard error
export stErr(float stdDev, simple int sampleSize) =>
stderror = stdDev/math.sqrt(sampleSize)
// @function Z-Score. A z-score is a statistical measurement that indicates how many standard deviations a data point is from
// the mean of a data set. It is also known as a standard score. The formula for calculating a z-score is (x - μ) / σ,
// where x is the individual data point, μ is the mean of the data set, and σ is the standard deviation of the data set.
// Z-scores are useful in identifying outliers or extreme values in a data set. A positive z-score indicates that the
// data point is above the mean, while a negative z-score indicates that the data point is below the mean. A z-score of
// 0 indicates that the data point is equal to the mean.
// Z-scores are often used in hypothesis testing and determining confidence intervals. They can also be used to compare
// data sets with different units or scales, as the z-score standardizes the data. Overall, z-scores provide a way to
// measure the relative position of a data point in a data
// @param src (float) Source to calculate z-score
// @param mean (float) Moving average.
// @param length (int) The sequential period to calcule the standard deviation
// @param biased (bool) Defines the type of standard deviation. If true, uses biased sample variance (n),
// else uses unbiased sample variance (n-1 or another value, as long as it is in the range between 1 and n-1), where n=length.
// @param degreesOfFreedom (int) Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
// Default value is n-1, where n here is length. Only applies when biased parameter is defined as false.
// @returns (float) Z-score
export zscore(float src, float mean, simple int length, simple bool biased=true, simple int degreesOfFreedom=na) =>
float zscore = (src - mean) / stDev(src, length, mean, biased, degreesOfFreedom)
// @function T-Score. A t-score is a statistical measurement that indicates how many standard errors a data point is from
// the mean of a data set. It is also known as a standard score. The formula for calculating a t-score is (x - μ) / SE,
// where x is the individual data point, μ is the mean of the data set, and SE is the standard error of the data set.
// T-scores are useful in identifying outliers or extreme values in a data set. A positive t-score indicates that the
// data point is above the mean, while a negative t-score indicates that the data point is below the mean. A t-score of
// 0 indicates that the data point is equal to the mean.
// T-scores are often used in hypothesis testing and determining confidence intervals. They can also be used to compare
// data sets with different units or scales, as the t-score standardizes the data. Overall, t-scores provide a way to
// measure the relative position of a data point in a data.
// When to use t-score instead of z-score? When the sample size is small (n < 30).
// @param src (float) Source to calculate t-score
// @param mean (float) Moving average.
// @param length (int) The sequential period to calcule the sample standard deviation
// @param degreesOfFreedom (int) Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
// Default value is n-1, where n here is length. Only applies when biased parameter is defined as false.
export tscore(float src, float mean, simple int length, simple int degreesOfFreedom) =>
float stdDev = stDev(src=src, length=length, mean=mean, biased=false, degreesOfFreedom=degreesOfFreedom)
float stdError = stErr(stdDev, length)
float tscore = (src - mean) / stdError
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region ATR
// @function ATR: Average True Range. Customized version with source parameter.
// @param source (float) Source
// @param length (int) Length (number of bars back)
// @returns (float) ATR
export atr(float source, simple int length) =>
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
trueRange = na(_high[1]) ? _high-_low : math.max(math.max(_high - _low, math.abs(_high - source[1])), math.abs(_low - source[1]))
ta.rma(trueRange, length)
// @function ATRP (Average True Range Percent)
// @param length (int) Length (number of bars back) for ATR
// @param sourceP (float) Source for calculating percentage relativity
// @returns (float) ATRP
export atrp(simple int length, float sourceP) =>
atr = ta.atr(length)
atrp = (atr/sourceP)*100
// @function ATRP (Average True Range Percent). Customized version with source parameter.
// @param source (float) Source for ATR
// @param length (int) Length (number of bars back) for ATR
// @param sourceP (float) Source for calculating percentage relativity
// @returns (float) ATRP
export atrp(float source, simple int length, float sourceP) =>
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
trueRange = na(_high[1]) ? _high-_low : math.max(math.max(_high - _low, math.abs(_high - source[1])), math.abs(_low - source[1]))
atr = ta.rma(trueRange, length)
atrp = (atr/sourceP)*100
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Historical Volatility
// @function Historical Volatility (Accumulated ATR Version)
// @param lengthATR (int) Length (number of bars back) for ATR
// @param lengthHist (int) Length (number of bars back) for Historical Volatility
// @returns (float) Historical Volatility
export historicalVolatilityATR(simple int lengthATR, simple int lengthHist) =>
historicalVolatility = 0.0
xATR = ta.atr(lengthATR)
historicalVolatility := ((lengthHist - 1) * nz(historicalVolatility[1], 0) + xATR) / lengthHist
// @function Historical Volatility (Accumulated ATR Version)
// @param source (float) Source for ATR
// @param lengthATR (int) Length (number of bars back) for ATR
// @param lengthHist (int) Length (number of bars back) for Historical Volatility
// @returns (float) Historical Volatility
export historicalVolatilityATR(float source, simple int lengthATR, simple int lengthHist) =>
historicalVolatility = 0.0
xATR = atr(source, lengthATR)
historicalVolatility := ((lengthHist - 1) * nz(historicalVolatility[1], 0) + xATR) / lengthHist
// @function Historical Volatility (Returns version)
// @param source (float) Source to calculate returns.
// @param sampleLength (int) Period to calculate mean and standard deviation.
// @param returnLength (int) Period to annualize/monthly/convert historical volatility. 252 for trading days per year,
// 52 for weeks per year, 12 for months per year. Default is 252.
// @param degreesOfFreedom (int) Degrees of freedom. The number of values in the final calculation of a statistic that are free to vary.
// Default value is n-1, where n here is length. Only applies when biased parameter is defined as false.
export historicalVolatilityRet(float source, simple int sampleLength, simple int returnLength=252, simple int degreesOfFreedom=na) =>
_return = math.log(source/source[1])
mean = ta.sma(_return, sampleLength)
stDev = stDev(src=_return, length=sampleLength, mean=mean, biased=false, degreesOfFreedom=degreesOfFreedom)
historicalVolatility = stDev * math.sqrt(returnLength) * 100
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Normalization
// @function Min-Max Scale Normalization. Maximum and minimum values are taken from the sequential range of
// numbars bars back, where numbars is a number defined by the user.
// @param src (float) Source to normalize
// @param numbars (int) Numbers of sequential bars back to seek for lowest and hightest values.
// @returns (float) Normalized value
export minMaxNormalization(series float src, simple int numbars) =>
min = ta.lowest(source=src, length=numbars)
max = ta.highest(source=src, length=numbars)
scaledValue = (src - min)/(max - min)
// @function Min-Max Scale Normalization. Maximum and minimum values are taken from the sequential range of
// numbars bars back, where numbars is a number defined by the user.
// In this implementation, the user explicitly provides the desired minimum (min) and maximum (max) values for the scale,
// rather than using the minimum and maximum values from the data.
// @param src (float) Source to normalize
// @param numbars (int) Numbers of sequential bars back to seek for lowest and hightest values.
// @param minimumLimit (float) Minimum value to scale
// @param maximumLimit (float) Maximum value to scale
// @returns (float) Normalized value
export minMaxNormalization(series float src, simple int numbars, simple float minimumLimit, simple float maximumLimit) =>
min = ta.lowest(source=src, length=numbars)
max = ta.highest(source=src, length=numbars)
scaledValue = minimumLimit + ((src - min)*(maximumLimit - minimumLimit))/(max - min)
// @function Mean Normalization
// @param src (float) Source to normalize
// @param numbars (int) Numbers of sequential bars back to seek for lowest and hightest values.
// @param mean (float) Mean of source
// @returns (float) Normalized value
export meanNormalization(series float src, simple int numbars, float mean) =>
min = ta.lowest(source=src, length=numbars)
max = ta.highest(source=src, length=numbars)
scaledValue = src - mean / (max - min)
// @function Standardization (Z-score Normalization). How "outside the mean" values relate to the standard deviation (ratio between first and second)
// @param src (float) Source to normalize
// @param mean (float) Mean of source
// @param stDev (float) Standard Deviation
// @returns (float) Normalized value
export standardization(series float src, float mean, float stDev) =>
scaledValue = src - mean / stDev
// @function Scaling to unit length
// @param src (float) Source to normalize
// @param numbars (int) Numbers of sequential bars back to seek for lowest and hightest values.
// @returns (float) Normalized value
export scalingToUnitLength(series float src, simple int numbars) =>
min = ta.lowest(source=src, length=numbars)
max = ta.highest(source=src, length=numbars)
scaledValue = src / (max - min)
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region LS Volatility Index
// @function LS Volatility Index. Measures the volatility of price in relation to an moving average.
// @param movingAverage (float) The moving average to be used in the calculation. It can be any moving average,
// not just the simple moving average (SMA). It can be an exponential moving average (EMA), weighted moving average (WMA), etc.
// @param historicalVolatilityType (string) Type of historical volatility to be used in the calculation.\n
// Default value is 'Returns'. Possible values are:\n
// 'Returns': Historical Volatility calculated from returns (logarithmic).\n
// 'Accumulated ATR': Historical Volatility calculated from accumulated ATR.
// @param source (float) Source for calculating the historical volatility
// @param sampleLength (int) Length for calculating the historical volatility.
// @param lengthATR (float) Length for calculating the ATR (Average True Range). Only applies when historicalVolatilityType is 'Accumulated ATR'.
// @param returnLength (int) Period to annualize/monthly/convert historical volatility. 252 for trading days per year,
// 52 for weeks per year, 12 for months per year. Default is 252. Only applies when historicalVolatilityType is 'Returns'.
// @param degreesOfFreedom (int) Degrees of freedom for calculating the historical volatility.
// Default value is n-1, where n here is sampleLength. Only applies when historicalVolatilityType is 'Returns'.
// The standard deviation is calculated using the unbiased sample variance with this degrees of freedom.
// @param lenNormal (float) Length for normalization. If not defined (na value), the result will not be normalized.
// @param lowerLimit (float) Lower limit for normalization. Only used if lenNormal is defined.
// @param upperLimit (float) Upper limit for normalization. Only used if lenNormal is defined.
// @returns (float) LS Volatility Index
export lsVolatilityIndex(
// Moving Average parameters
float movingAverage,
// Historical Volatility parameters
simple string historicalVolatilityType='Returns',
float source, simple int sampleLength,
simple int returnLength=252, simple int degreesOfFreedom,
simple int lengthATR,
// Normalization parameters
simple int lenNormal=na, simple int lowerLimit=0, simple int upperLimit=100) =>
// Distance between price and moving average.
// If price is above MA, take the high value of bar to calculate the distance, otherwise the low value
distanceMA = ( math.abs ( (high >= movingAverage ? high : low) - movingAverage) / movingAverage ) * 100
hvol = switch historicalVolatilityType
'Returns' => historicalVolatilityRet(source=source, sampleLength=sampleLength, returnLength=returnLength, degreesOfFreedom=degreesOfFreedom)
'Accumulated ATR' => historicalVolatilityATR(source=source, lengthATR=lengthATR, lengthHist=sampleLength)
lsVol = (distanceMA/hvol) * 100
lsVol := na(lenNormal) ? lsVol : minMaxNormalization(lsVol, lenNormal, lowerLimit, upperLimit)
// @function LS Volatility Index. Measures the volatility of price in relation to an moving average.
// @param _high (float) High source
// @param _low (float) Low source
// @param movingAverage (float) The moving average to be used in the calculation. It can be any moving average,
// not just the simple moving average (SMA). It can be an exponential moving average (EMA), weighted moving average (WMA), etc.
// @param historicalVolatilityType (string) Type of historical volatility to be used in the calculation.\n
// Default value is 'Returns'. Possible values are:\n
// 'Returns': Historical Volatility calculated from returns (logarithmic).\n
// 'Accumulated ATR': Historical Volatility calculated from accumulated ATR.
// @param source (float) Source for calculating the historical volatility
// @param sampleLength (int) Length for calculating the historical volatility.
// @param lengthATR (float) Length for calculating the ATR (Average True Range). Only applies when historicalVolatilityType is 'Accumulated ATR'.
// @param returnLength (int) Period to annualize/monthly/convert historical volatility. 252 for trading days per year,
// 52 for weeks per year, 12 for months per year. Default is 252. Only applies when historicalVolatilityType is 'Returns'.
// @param degreesOfFreedom (int) Degrees of freedom for calculating the historical volatility.
// Default value is n-1, where n here is sampleLength. Only applies when historicalVolatilityType is 'Returns'.
// The standard deviation is calculated using the unbiased sample variance with this degrees of freedom.
// @param lenNormal (float) Length for normalization. If not defined (na value), the result will not be normalized.
// @param lowerLimit (float) Lower limit for normalization. Only used if lenNormal is defined.
// @param upperLimit (float) Upper limit for normalization. Only used if lenNormal is defined.
// @returns (float) LS Volatility Index
export lsVolatilityIndex(
// Price parameters
float _high, float _low,
// Moving Average parameters
float movingAverage,
// Historical Volatility parameters
simple string historicalVolatilityType='Returns',
float source, simple int sampleLength,
simple int returnLength=252, simple int degreesOfFreedom,
simple int lengthATR,
// Normalization parameters
simple int lenNormal=na, simple int lowerLimit=0, simple int upperLimit=100) =>
// Distance between price and moving average.
// If price is above MA, take the high value of bar to calculate the distance, otherwise the low value
distanceMA = ( math.abs ( (_high >= movingAverage ? _high : _low) - movingAverage) / movingAverage ) * 100
hvol = switch historicalVolatilityType
'Returns' => historicalVolatilityRet(source=source, sampleLength=sampleLength, returnLength=returnLength, degreesOfFreedom=degreesOfFreedom)
'Accumulated ATR' => historicalVolatilityATR(source=source, lengthATR=lengthATR, lengthHist=sampleLength)
lsVol = (distanceMA/hvol) * 100
lsVol := na(lenNormal) ? lsVol : minMaxNormalization(lsVol, lenNormal, lowerLimit, upperLimit)
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Dynamic Zones
// @function Get Dynamic Zones
// @param source (float) Source
// @param sampleLength (int) Sample Length
// @param pcntAbove (float) Calculates the top of the dynamic zone, considering that the maximum values are above x% of the sample
// @param pcntBelow (float) Calculates the bottom of the dynamic zone, considering that the minimum values are below x% of the sample
// @returns [float, float, float] A tuple with 3 series of values: (1) Upper Line of Dynamic Zone;
// (2) Lower Line of Dynamic Zone; (3) Center of Dynamic Zone (x = 50%)
export dynamicZone(float source, simple int sampleLength, simple float pcntAbove, simple float pcntBelow) =>
dZoneAbove = ta.percentile_nearest_rank(source, sampleLength, pcntAbove)
dZoneBelow = ta.percentile_nearest_rank(source, sampleLength, 100 - pcntBelow)
dZoneCenter = ta.percentile_nearest_rank(source, sampleLength, 100 - 50)
[dZoneAbove, dZoneBelow, dZoneCenter]
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Bollinger Bands
// @function Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted
// two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price,
// but can be adjusted to user preferences. In this version you can pass a customized basis (moving average), not only SMA.
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) The time period to be used in calculating the standard deviation
// @param mult (float) Multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float) A tuple of Bollinger Bands, where index 1=basis; 2=basis+dev; 3=basis-dev; and dev=multiplier*stdev
export bollingerBands(float src, simple int length, simple float mult=2.0, float basis) =>
float dev = mult * ta.stdev(src, length)
[basis, basis + dev, basis - dev]
// @function Bollinger Bands (multiple bands version). A Bollinger Band is a technical analysis tool defined by a set of lines plotted
// two standard deviations (positively and negatively) away from a simple moving average (SMA) of the security's price,
// but can be adjusted to user preferences. In this version you can pass a customized basis (moving average), not only SMA.
// Also, various multipliers can be passed, thus getting more bands (instead of just 2).
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) The time period to be used in calculating the standard deviation
// @param aMult (float[]) An array of multipliers used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
// This array of multipliers permit the use of various bands, not only 2.
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float[]) An array of Bollinger Bands, where:
// index 1=basis; 2=basis+dev1; 3=basis-dev1; 4=basis+dev2, 5=basis-dev2, 6=basis+dev2, 7=basis-dev2, Nup=basis+devN, Nlow=basis-devN
// and dev1, dev2, devN are ```multiplier N * stdev```
export bollingerBands(float src, simple int length, simple float[] aMult, float basis) =>
float[] aBands = array.new_float(1, basis)
float dev = ta.stdev(src, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * dev
array.push(aBands, basis + _dev)
array.push(aBands, basis - _dev)
aBands
// @function Bollinger Bands %B - or Percent Bandwidth (%B).
// Quantify or display where price (or another source) is in relation to the bands.
// %B can be useful in identifying trends and trading signals.
// Calculation:
// %B = (Current Price - Lower Band) / (Upper Band - Lower Band)
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) The time period to be used in calculating the standard deviation
// @param mult (float) Multiplier used in standard deviation
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float) Bollinger Bands %B
export bollingerBandsB(float src, simple int length, simple float mult=2.0, float basis) =>
float dev = mult * ta.stdev(src, length)
float upper = basis + dev
float lower = basis - dev
float bbr = (src - lower)/(upper - lower)
// @function Bollinger Bands %B - or Percent Bandwidth (%B). Multiple bands version.
// Quantify or display where price (or another source) is in relation to the bands.
// %B can be useful in identifying trends and trading signals.
// Calculation
// %B = (Current Price - Lower Band) / (Upper Band - Lower Band)
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) The time period to be used in calculating the standard deviation
// @param aMult (float[]) Array of multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
// This array of multipliers permit the use of various bands, not only 2.
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float[]) An array of Bollinger Bands %B. The number of results in this array is equal the numbers of multipliers passed via parameter.
export bollingerBandsB(float src, simple int length, simple float[] aMult, float basis) =>
float[] aBBR = array.new_float(0)
float dev = ta.stdev(src, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * dev
float upper = basis + _dev
float lower = basis - _dev
float bbr = (src - lower)/(upper - lower)
array.push(aBBR, bbr)
aBBR
// @function Bollinger Bands Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands
// Calculation:
// Bollinger Bands Width = (Upper Band - Lower Band) / Middle Band
// @param src (float) Source to calculate standard deviation used in Bollinger Bands
// @param length (int) Sequential period to calculate the standard deviation
// @param mult (float) Multiplier used in standard deviation
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float) Bollinger Bands Width
export bollingerBandsW(float src, simple int length, simple float mult=2.0, float basis) =>
float dev = mult * ta.stdev(src, length)
float upper = basis + dev
float lower = basis - dev
float bbw = (upper-lower)/basis
// @function Bollinger Bands Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands
// Calculation
// Bollinger Bands Width = (Upper Band - Lower Band) / Middle Band
// @param src (float) Source to calculate standard deviation used in Bollinger Bands. Multiple bands version.
// @param length (int) Sequential period to calculate the standard deviation
// @param aMult (float[]) Array of multiplier used in standard deviation. Basically, the upper/lower bands are standard deviation multiplied by this.
// This array of multipliers permit the use of various bands, not only 2.
// @param basis (float) Basis of Bollinger Bands (a moving average)
// @returns (float[]) An array of Bollinger Bands Width. The number of results in this array is equal the numbers of multipliers passed via parameter.
export bollingerBandsW(float src, simple int length, simple float[] aMult, float basis) =>
float[] aBBW = array.new_float(0)
float dev = ta.stdev(src, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * dev
float upper = basis + _dev
float lower = basis - _dev
float bbw = (upper-lower)/basis
array.push(aBBW, bbw)
aBBW
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Keltner Channels
// @function Keltner Channels. The Keltner Channels (KC) indicator is a banded indicator similar to Bollinger Bands
// and Moving Average Envelopes. They consist of an Upper Envelope above a Middle Line as well as a Lower Envelope below
// the Middle Line. The Middle Line is a moving average of price over a user-defined time period. Either a simple moving average or an
// exponential moving average are typically used. The Upper and Lower Envelopes are set a (user-defined multiple) of a
// range away from the Middle Line. This can be a multiple of the daily high/low range, or more commonly a multiple of the Average True Range.
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float) A tuple of Keltner Channels, where index 1=basis; 2=basis+dev; 3=basis-dev; and dev=multiplier*range
export keltnerChannels(simple int length, float basis, simple string bandsStyle="True Range", float multiplier=2) =>
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => ta.atr(length)
"Range" => ta.rma(high - low, length)
upperBand = basis + _range * multiplier
lowerBand = basis - _range * multiplier
[basis, upperBand, lowerBand]
// @function Keltner Channels (version with custom source).
// The Keltner Channels (KC) indicator is a banded indicator similar to Bollinger Bands
// and Moving Average Envelopes. They consist of an Upper Envelope above a Middle Line as well as a Lower Envelope below
// the Middle Line. The Middle Line is a moving average of price over a user-defined time period. Either a simple moving average or an
// exponential moving average are typically used. The Upper and Lower Envelopes are set a (user-defined multiple) of a
// range away from the Middle Line. This can be a multiple of the daily high/low range, or more commonly a multiple of the Average True Range.
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float) A tuple of Keltner Channels, where index 1=basis; 2=basis+dev; 3=basis-dev; and dev=multiplier*range
export keltnerChannels(float source, simple int length, float basis, simple string bandsStyle="True Range", float multiplier=2) =>
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
upperBand = basis + _range * multiplier
lowerBand = basis - _range * multiplier
[basis, upperBand, lowerBand]
// @function Keltner Channels (version with custom source and multiple bands).
// The Keltner Channels (KC) indicator is a banded indicator similar to Bollinger Bands
// and Moving Average Envelopes. They consist of an Upper Envelope above a Middle Line as well as a Lower Envelope below
// the Middle Line. The Middle Line is a moving average of price over a user-defined time period. Either a simple moving average or an
// exponential moving average are typically used. The Upper and Lower Envelopes are set a (user-defined multiple) of a
// range away from the Middle Line. This can be a multiple of the daily high/low range, or more commonly a multiple of the Average True Range.
// @param aMult (float[]) An array of multipliers used in calculation. Basically, the upper/lower bands are ranges multiplied by this.
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @returns (float[]) An array of Keltner Channels, where:
// index 1=basis; 2=basis+dev1; 3=basis-dev1; 4=basis+dev2, 5=basis-dev2, 6=basis+dev2, 7=basis-dev2, Nup=basis+devN, Nlow=basis-devN
// and dev1, dev2, devN are ```multiplier N * stdev```
export keltnerChannels(simple float[] aMult, float source, simple int length, float basis, simple string bandsStyle="True Range") =>
float[] aBands = array.new_float(1, basis)
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * _range
array.push(aBands, basis + _dev)
array.push(aBands, basis - _dev)
aBands
// @function Keltner Channels %B - or Percent Bandwidth (%B).
// This is the same as Bollinger Bands %B, but instead of Bollinger Bands, the logic of Keltner Channels is used to obtain the Percent Bandwidth (%B).
// Calculation:
// float kcb = (source - lower band)/(upper band - lower band)
// The Keltner Channels (KC) indicator is a banded indicator similar to Bollinger Bands
// and Moving Average Envelopes. They consist of an Upper Envelope above a Middle Line as well as a Lower Envelope below
// the Middle Line. The Middle Line is a moving average of price over a user-defined time period. Either a simple moving average or an
// exponential moving average are typically used. The Upper and Lower Envelopes are set a (user-defined multiple) of a
// range away from the Middle Line. This can be a multiple of the daily high/low range, or more commonly a multiple of the Average True Range.
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float) Percent Bandwidth (%B)
export keltnerChannelsB(float source, simple int length, float basis, simple string bandsStyle="True Range", float multiplier=2) =>
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
upperBand = basis + _range * multiplier
lowerBand = basis - _range * multiplier
kcB = (source - lowerBand)/(upperBand - lowerBand)
// @function Keltner Channels %B - or Percent Bandwidth (%B). Multiple bands version.
// This is the same as Bollinger Bands %B, but instead of Bollinger Bands, the logic of Keltner Channels is used to obtain the Percent Bandwidth (%B).
// Calculation:
// float kcb = (source - lower band)/(upper band - lower band)
// The Keltner Channels (KC) indicator is a banded indicator similar to Bollinger Bands
// and Moving Average Envelopes. They consist of an Upper Envelope above a Middle Line as well as a Lower Envelope below
// the Middle Line. The Middle Line is a moving average of price over a user-defined time period. Either a simple moving average or an
// exponential moving average are typically used. The Upper and Lower Envelopes are set a (user-defined multiple) of a
// range away from the Middle Line. This can be a multiple of the daily high/low range, or more commonly a multiple of the Average True Range.
// @param aMult (float[]) An array of multipliers used in calculation. Basically, the upper/lower bands are ranges multiplied by this.
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float) An array of Percent Bandwidth (%B)
export keltnerChannelsB(simple float[] aMult, float source, simple int length, float basis, simple string bandsStyle="True Range") =>
float[] aKCB = array.new_float(0)
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * _range
upperBand = basis + _dev
lowerBand = basis - _dev
kcB = (source - lowerBand)/(upperBand - lowerBand)
array.push(aKCB, kcB)
aKCB
// @function Keltner Channels Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands.
// Same as Bollinger Bands Width, but instead of Bollinger Bands, the logic of Keltner Channels is used to obtain the width.
// Calculation:
// Keltner Channels Width = (Upper Band - Lower Band) / Middle Band
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float) Percent Bandwidth (%B)
export keltnerChannelsW(float source, simple int length, float basis, simple string bandsStyle="True Range", float multiplier=2) =>
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
upperBand = basis + _range * multiplier
lowerBand = basis - _range * multiplier
kcW = (upperBand - lowerBand)/basis
// @function Keltner Channels Width. Serve as a way to quantitatively measure the width between the Upper and Lower Bands. Multiple bands version.
// Same as Bollinger Bands Width, but instead of Bollinger Bands, the logic of Keltner Channels is used to obtain the width.
// Calculation:
// Keltner Channels Width = (Upper Band - Lower Band) / Middle Band
// @param aMult (float[]) An array of multipliers used in calculation. Basically, the upper/lower bands are ranges multiplied by this.
// @param source (float) Source to calculate "Average True Range" and "Range"
// @param length (int) The time period to be used in calculating the "Average True Range" and "Range"
// @param basis (float) Basis of Keltner Channels (a moving average)
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range".
// @param multiplier (float) Multiplier used to calc the bands. Default is 2.
// @returns (float[]) An array of Percent Bandwidth (%B)
export keltnerChannelsW(simple float[] aMult, float source, simple int length, float basis, simple string bandsStyle="True Range") =>
float[] aKCW = array.new_float(0)
_high = ta.highest(source, 2)
_low = ta.lowest(source, 2)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(source, length)
"Range" => MAPROXY.rma(_high - _low, length)
for i = 0 to array.size(aMult) - 1
_dev = array.get(aMult, i) * _range
upperBand = basis + _dev
lowerBand = basis - _dev
kcW = (upperBand - lowerBand)/basis
array.push(aKCW, kcW)
aKCW
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Moving Average Envelopes
// @function Moving Average Envelopes. Moving Average Envelopes are percentage-based envelopes set above and
// below a moving average. The moving average, which forms the base for
// this indicator, can be a simple or exponential moving average. Each
// envelope is then set the same percentage above or below the moving average.
// This creates parallel bands that follow price action. With a moving average
// as the base, Moving Average Envelopes can be used as a trend following indicator.
// However, this indicator is not limited to just trend following. The envelopes
// can also be used to identify overbought and oversold levels when the trend is
// relatively flat.
// Calculation:
// Upper Band = moving average + (moving average x percent shift)
// Lower Band = moving average - (moving average x percent shift)
// @param ma (float) A moving average
// @param percentShift (float) Multiplier used to calculate the envelope (percent shift).
// This array of multipliers permit the use of various bands, not only 2.
// @returns (float) A tuple with envelope bands: [basis, upper band, lower band]
export movingAverageEnvelopes(float ma, simple float percentShift) =>
dev = ma * percentShift / 100
upperBand = ma + dev
lowerBand = ma - dev
[ma, upperBand, lowerBand]
// @function Moving Average Envelopes. Multiple bands version.
// Moving Average Envelopes are percentage-based envelopes set above and
// below a moving average. The moving average, which forms the base for
// this indicator, can be a simple or exponential moving average. Each
// envelope is then set the same percentage above or below the moving average.
// This creates parallel bands that follow price action. With a moving average
// as the base, Moving Average Envelopes can be used as a trend following indicator.
// However, this indicator is not limited to just trend following. The envelopes
// can also be used to identify overbought and oversold levels when the trend is
// relatively flat.
// Calculation:
// Upper Band = moving average + (moving average x percent shift)
// Lower Band = moving average - (moving average x percent shift)
// @param ma (float) A moving average
// @param aPercentShift (float[]) An array of multipliers used to calculate the envelope (percent shift).
// This array of multipliers permit the use of various bands, not only 2.
// @returns (float[]) An array of envelopes bands, where:
// index 1=basis; 2=basis+dev1; 3=basis-dev1; 4=basis+dev2, 5=basis-dev2, 6=basis+dev2, 7=basis-dev2, Nup=basis+devN, Nlow=basis-devN
// and dev1, dev2, devN are ```multiplier N * stdev```
export movingAverageEnvelopes(float ma, simple float[] aPercentShift) =>
float[] aEnvelopes = array.new_float(1, ma)
for i = 0 to array.size(aPercentShift) - 1
_dev = ma * array.get(aPercentShift, i) / 100
array.push(aEnvelopes, ma + _dev)
array.push(aEnvelopes, ma - _dev)
aEnvelopes
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// #region Donchian Channels
// @function Donchian Channels.
// The Donchian Channel is a useful indicator for seeing the volatility of a market price.
// If a price is stable the Donchian channel will be relatively narrow. If the price fluctuates a lot the Donchian Channel will be wider.
// It is formed by taking the highest high and the lowest low of the last n periods.
// The area between the high and the low is the channel for the period chosen.
// The upper channel line is the highest high of the last n periods.
// The lower channel line is the lowest low of the last n periods.
// @param sourceHigh (float) Source to calculate the highest high
// @param sourceLow (float) Source to calculate the lowest low
// @param length (int) The time period to be used in calculating the highest high and lowest low
// @returns (float) A tuple of Donchian Channels, where index 1=upper band; 2=lower band; 3=basis
export donchianChannels(float sourceHigh, float sourceLow, simple int length) =>
float upper = ta.highest(sourceHigh, length)
float lower = ta.lowest(sourceLow, length)
float basis = math.avg(upper, lower)
[upper, lower, basis]
// @function Donchian Channels with multiple bands.
// The Donchian Channel is a useful indicator for seeing the volatility of a market price.
// If a price is stable the Donchian channel will be relatively narrow. If the price fluctuates a lot the Donchian Channel will be wider.
// It is formed by taking the highest high and the lowest low of the last n periods.
// The area between the high and the low is the channel for the period chosen.
// The upper channel line is the highest high of the last n periods.
// The lower channel line is the lowest low of the last n periods.
// @param sourceHigh (float) Source to calculate the highest high
// @param sourceLow (float) Source to calculate the lowest low
// @param length (int) Time periods to be used in calculating the highest high and lowest low
// @param aMultiplier (float[]) An array of multipliers used in calculation.
// @param bandsStyle (string) Bands Style. Valid options: "True Range" (default), "Average True Range", "Range", "Standard Deviation".
// @param sourceRange (float) Source to calculate the range used in "Range"
// @returns (float[]) An array of Donchian Channels, where:
// index 1=upper band; 2=lower band; 3=basis;
// 4=upper band 2, 5=lower band 2, 6=basis 2 upper, 7=basis 2 lower,
// Nup=upper band N, Nlow=lower band N
export donchianChannels(float sourceHigh, float sourceLow, simple int length, simple float[] aMultiplier, simple string bandsStyle="True Range", float sourceRange) =>
float[] aDonchian = array.new_float(0)
float upper = ta.highest(sourceHigh, length)
float lower = ta.lowest(sourceLow, length)
float basis = math.avg(upper, lower)
array.push(aDonchian, upper)
array.push(aDonchian, lower)
array.push(aDonchian, basis)
_range = switch bandsStyle
"True Range" => ta.tr(true)
"Average True Range" => atr(sourceRange, length)
"Range" => MAPROXY.rma(upper - lower, length)
"Standard Deviation" => ta.stdev(sourceRange, length)
for i = 0 to array.size(aMultiplier) - 1
array.push(aDonchian, upper + (_range * array.get(aMultiplier, i)) )
array.push(aDonchian, lower - (_range * array.get(aMultiplier, i)) )
array.push(aDonchian, basis + (_range * array.get(aMultiplier, i)) )
array.push(aDonchian, basis - (_range * array.get(aMultiplier, i)) )
aDonchian
// #endregion
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// EXAMPLES
//@version=5
// indicator("Volatility Indicators (Examples)")
// import andre_007/VolatilityIndicators/2 as VOL
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Keltner Channels with multiple bands
// ma = ta.ema(hl2, 21)
// aMultipliers = array.from(3, 5, 8, 13, 21)
// aBands = keltnerChannels(aMult=aMultipliers, source=hl2, length=233, basis=ma, bandsStyle="Average True Range")
// plot(array.get(aBands, 0), 'Basis', color.white)
// plot(array.get(aBands, 1), 'Upper 1', color.blue)
// plot(array.get(aBands, 2), 'Lower 1', color.blue)
// plot(array.get(aBands, 3), 'Upper 2', color.yellow)
// plot(array.get(aBands, 4), 'Lower 2', color.yellow)
// plot(array.get(aBands, 5), 'Upper 3', color.red)
// plot(array.get(aBands, 6), 'Lower 3', color.red)
// plot(array.get(aBands, 7), 'Upper 4', color.purple)
// plot(array.get(aBands, 8), 'Lower 4', color.purple)
// plot(array.get(aBands, 9), 'Upper 5', color.fuchsia)
// plot(array.get(aBands, 10), 'Lower 5', color.fuchsia)
// Keltner Channels with 2 bands (traditional)
// ma = ta.ema(hl2, 200)
// [basis, upper, lower] = keltnerChannels(length=200, basis=ma, bandsStyle="Range", multiplier=2)
// plot(basis, 'Basis', color.white)
// plot(upper, 'Upper 1', color.blue)
// plot(lower, 'Lower 1', color.blue)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Moving Average Envelopes
// ma = ta.ema(hl2, 21)
// [basis, upperBand, lowerBand] = movingAverageEnvelopes(ma, 2)
// plot(basis, 'Basis', color.white)
// plot(upperBand, 'Upper 1', color.blue)
// plot(lowerBand, 'Lower 1', color.blue)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Donchian Channels
// float sourceHigh = input.source(defval=high, title="Source High")
// float sourceLow = input.source(defval=low, title="Source Low")
// int length = input.int(defval=21, title="Length")
// [upper, lower, basis] = donchianChannels(sourceHigh, sourceLow, length)
// plot(series=upper, title="Upper", color=color.blue)
// plot(series=lower, title="Lower", color=color.blue)
// plot(series=basis, title="Basis", color=color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Donchian Channels with multiple bands
// float sourceHigh = input.source(defval=high, title="Source High")
// float sourceLow = input.source(defval=low, title="Source Low")
// int length = input.int(defval=55, title="Length")
// float multiplier1 = input.float(defval = 0.618, title = 'Multipler')
// float multiplier2 = input.float(defval = 0.786, title = 'Multipler')
// float multiplier3 = input.float(defval = 1, title = 'Multipler')
// string rangeStyle = input.string(defval = "Average True Range", title = "Range Style", options = ["True Range", "Average True Range", "Range", "Standard Deviation"])
// float sourceRange = input.source(defval=hl2, title="Source Range")
// aMultipliers = array.from(multiplier1, multiplier2, multiplier3)
// aDonchian = donchianChannels(sourceHigh, sourceLow, length, aMultipliers, rangeStyle, sourceRange)
// plot(series=array.get(aDonchian, 0), title="Upper", color=color.yellow)
// plot(series=array.get(aDonchian, 1), title="Lower", color=color.yellow)
// plot(series=array.get(aDonchian, 2), title="Basis", color=color.white)
// plot(series=array.get(aDonchian, 3), title="Upper +1x", color=color.green)
// plot(series=array.get(aDonchian, 4), title="Lower -1x", color=color.green)
// plot(series=array.get(aDonchian, 5), title="Basis +1x", color=color.white)
// plot(series=array.get(aDonchian, 6), title="Basis -1x", color=color.white)
// plot(series=array.get(aDonchian, 7), title="Upper +2x", color=color.blue)
// plot(series=array.get(aDonchian, 8), title="Lower -2x", color=color.blue)
// plot(series=array.get(aDonchian, 9), title="Basis +2x", color=color.white)
// plot(series=array.get(aDonchian, 10), title="Basis -2x", color=color.white)
// plot(series=array.get(aDonchian, 11), title="Upper +3x", color=color.purple)
// plot(series=array.get(aDonchian, 12), title="Lower -3x", color=color.purple)
// plot(series=array.get(aDonchian, 13), title="Basis +3x", color=color.white)
// plot(series=array.get(aDonchian, 14), title="Basis -3x", color=color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Moving Average Envelopes
// ma = ta.ema(hl2, 21)
// aMultipliers = array.from(3, 5, 8)
// aBands = movingAverageEnvelopes(ma, aMultipliers)
// plot(array.get(aBands, 0), 'Basis', color.white)
// plot(array.get(aBands, 1), 'Upper 1', color.blue)
// plot(array.get(aBands, 2), 'Lower 1', color.blue)
// plot(array.get(aBands, 3), 'Upper 2', color.yellow)
// plot(array.get(aBands, 4), 'Lower 2', color.yellow)
// plot(array.get(aBands, 5), 'Upper 3', color.red)
// plot(array.get(aBands, 6), 'Lower 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Keltner Channel B%
// ma = ta.ema(hl2, 55)
// bPerc = keltnerChannelsB(source=hl2, length=55, basis=ma, bandsStyle="Average True Range", multiplier=2)
// plot(bPerc, 'KC B%', color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Keltner Channel B% with multiple bands
// ma = ta.ema(hl2, 55)
// aMultipliers = array.from(2, 3, 4)
// aPerc = keltnerChannelsB(aMult = aMultipliers, source=hl2, length=55, basis=ma, bandsStyle="Average True Range")
// plot(array.get(aPerc, 0), 'KC B% 1', color.white)
// plot(array.get(aPerc, 1), 'KC B% 2', color.yellow)
// plot(array.get(aPerc, 2), 'KC B% 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Keltner Channels Width
// ma = ta.ema(hl2, 55)
// kcW = keltnerChannelsW(source=hl2, length=55, basis=ma, bandsStyle="Average True Range", multiplier=2)
// plot(kcW, 'KC Width', color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Keltner Channels Width with multiple bands
// ma = ta.ema(hl2, 55)
// aMultipliers = array.from(2, 3, 4)
// akcW = keltnerChannelsW(aMult=aMultipliers, source=hl2, length=55, basis=ma, bandsStyle="Average True Range")
// plot(array.get(akcW, 0), 'KC Width 1', color.white)
// plot(array.get(akcW, 1), 'KC Width 2', color.yellow)
// plot(array.get(akcW, 2), 'KC Width 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Dinamic Zone
// [upper, lower, center] = VOL.dynamicZone(close, 55, 90, 90)
// plot(upper, 'Upper Line', color.green)
// plot(lower, 'Upper Line', color.red)
// plot(center, 'Upper Line', color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// ATR
// default_atr = ta.atr(13)
// new_atr = VOL.atr(hl2, 13)
// plot(default_atr, 'Default ATR', color.red)
// plot(new_atr, 'New ATR', color.green)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// ATRP
// default_atrp = VOL.atrp(13, close)
// atrp = VOL.atrp(close, 13, close)
// plot(default_atrp, 'Default ATRP', color.red)
// plot(atrp, 'New ATRP', color.green)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// historicalVolatility
// histo1 = VOL.historicalVolatility(13, 55)
// histo2 = VOL.historicalVolatility(hl2, 13, 55)
// plot(histo1, 'Histo without source', color.red)
// plot(histo2, 'Histo with custom source', color.green)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Normalization
// x1 = VOL.minMaxNormalization(hl2, 13)
// x2 = VOL.minMaxNormalization(hl2, 13, 0, 5)
// plot(x1, 'No limits', color.red)
// plot(x2, 'With limits', color.green)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// lsVolatilityIndex(float movingAverage, float sourceHvol, simple int lengthATR, simple int lengthHist) =>
// lsVolatilityIndex(float sourcePrice, float movingAverage, float sourceHvol, simple int lengthATR, simple int lengthHist) =>
// sma = ta.ema(hl2, 55)
// // With lower and upper limits
// ls1 = VOL.lsVolatilityIndex(movingAverage = sma, sourceHvol=hl2, lengthATR=55, lengthHist=55, lenNormal=89, lowerLimit=0, upperLimit=100)
// ls2 = VOL.lsVolatilityIndex(sourcePrice=hl2, movingAverage=sma, sourceHvol=hl2, lengthATR=55, lengthHist=55, lenNormal=89, lowerLimit=0, upperLimit=100)
// // Without lower and upper limits
// ls3 = VOL.lsVolatilityIndex(movingAverage = sma, sourceHvol=hl2, lengthATR=55, lengthHist=55)
// ls4 = VOL.lsVolatilityIndex(sourcePrice=hl2, movingAverage=sma, sourceHvol=hl2, lengthATR=55, lengthHist=55)
// plot(ls1, 'LS1', color.red)
// plot(ls2, 'LS2', color.blue)
// plot(ls3, 'LS1', color.yellow)
// plot(ls4, 'LS2', color.fuchsia)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Bollinger Bands with multiple bands (3 bands)
// ma = ta.ema(hl2, 233)
// aMultipliers = array.from(1, 2, 3)
// aBands = VOL.bollingerBands(hl2, 233, aMultipliers, ma)
// plotbar(open, high, low, close, title='Price', color = open < close ? color.green : color.red)
// // Arrays size = (Number of multipliers x 2) = 6
// plot(array.get(aBands, 0), 'Basis', color.white)
// plot(array.get(aBands, 1), 'Upper 1', color.blue)
// plot(array.get(aBands, 2), 'Lower 1', color.blue)
// plot(array.get(aBands, 3), 'Upper 2', color.yellow)
// plot(array.get(aBands, 4), 'Lower 2', color.yellow)
// plot(array.get(aBands, 5), 'Upper 3', color.red)
// plot(array.get(aBands, 6), 'Lower 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Bollinger Bands with multiple bands (6 bands)
// ma = ta.ema(hl2, 233)
// aMultipliers = array.from(1, 2, 3, 4, 5, 6)
// aBands = VOL.bollingerBands(hl2, 233, aMultipliers, ma)
// plotbar(open, high, low, close, title='Price', color = open < close ? color.green : color.red)
// // Arrays size = (Number of multipliers x 2) = 12
// plot(array.get(aBands, 0), 'Basis', color.white)
// plot(array.get(aBands, 1), 'Upper 1', color.blue)
// plot(array.get(aBands, 2), 'Lower 1', color.blue)
// plot(array.get(aBands, 3), 'Upper 2', color.green)
// plot(array.get(aBands, 4), 'Lower 2', color.green)
// plot(array.get(aBands, 5), 'Upper 3', color.yellow)
// plot(array.get(aBands, 6), 'Lower 3', color.yellow)
// plot(array.get(aBands, 7), 'Upper 4', color.red)
// plot(array.get(aBands, 8), 'Lower 4', color.red)
// plot(array.get(aBands, 9), 'Upper 5', color.fuchsia)
// plot(array.get(aBands, 10), 'Lower 5', color.fuchsia)
// plot(array.get(aBands, 11), 'Upper 6', color.purple)
// plot(array.get(aBands, 12), 'Lower 6', color.purple)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// Bollinger Bands with default number of bands (2 bands)
// ma = ta.ema(hl2, 233)
// [basis, upper, lower] = VOL.bollingerBands(hl2, 233, 2, ma)
// plotbar(open, high, low, close, title='Price', color = open < close ? color.green : color.red)
// plot(basis, 'Basis', color.white)
// plot(upper, 'Upper 1', color.blue)
// plot(lower, 'Lower 1', color.blue)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// Bollinger Bands B% (default version)
// ma = ta.ema(hl2, 233)
// bolllingerB = VOL.bollingerBandsB(src=hl2, length=233, mult=2.0, basis=ma)
// plot(bolllingerB, 'Bollinger B%', color.white)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// Bollinger Bands B% (multiples bands)
// aMultipliers = array.from(1, 2, 3)
// ma = ta.ema(hl2, 21)
// aBolllingerB = VOL.bollingerBandsB(src=hl2, length=21, aMult=aMultipliers, basis=ma)
// // Arrays size = Number of multipliers
// plot(array.get(aBolllingerB, 0), 'B% 1', color.blue)
// plot(array.get(aBolllingerB, 1), 'B% 2', color.yellow)
// plot(array.get(aBolllingerB, 2), 'B% 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Bollinger Bands Width (default version with 2 bands)
// ma = ta.ema(hl2, 233)
// bbw = VOL.bollingerBandsW(src=hl2, length=233, mult=2.0, basis=ma)
// plot(bbw, 'BBW', color.blue)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Bollinger Bands Width (version with multiple bands)
// aMultipliers = array.from(1, 2, 3)
// ma = ta.ema(hl2, 233)
// aBBW = VOL.bollingerBandsW(src=hl2, length=233, aMult=aMultipliers, basis=ma)
// // Arrays size = Number of multipliers
// plot(array.get(aBBW, 0), 'BBW 1', color.blue)
// plot(array.get(aBBW, 1), 'BBW 2', color.yellow)
// plot(array.get(aBBW, 2), 'BBW 3', color.red)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Difference between a source in relation to another source
// ma = ta.ema(hl2, 233)
// dev = VOL.dev(source=hl2, length=233, anotherSource=ma)
// plot(dev, 'DEV', color.blue)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Standard Deviation
// ma = ta.ema(hl2, 233)
// stdev1 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=true)
// stdev2 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=13)
// stdev3 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=12)
// stdev4 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=11)
// stdev5 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=10)
// stdev6 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=9)
// stdev7 = VOL.stDev(src=hl2, length = 14, mean=ma, biased=false, degreesOfFreedom=8)
// plot(stdev1, 'Std Dev 1 - Biased', color.blue)
// plot(stdev2, 'Std Dev 2 - Unbiased', color.yellow)
// plot(stdev3, 'Std Dev 3 - Unbiased (custom degree of freedom)', color.red)
// plot(stdev4, 'Std Dev 4 - Unbiased (custom degree of freedom)', color.fuchsia)
// plot(stdev5, 'Std Dev 5 - Unbiased (custom degree of freedom)', color.purple)
// plot(stdev6, 'Std Dev 6 - Unbiased (custom degree of freedom)', color.green)
// plot(stdev7, 'Std Dev 7 - Unbiased (custom degree of freedom)', color.aqua)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// Z-score
// ma = ta.sma(hl2, 14)
// zscore1 = VOL.zscore(src=hl2, mean=ma, length=14, biased=true)
// zscore2 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=13)
// zscore3 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=12)
// zscore4 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=11)
// zscore5 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=10)
// zscore6 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=9)
// zscore7 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=8)
// zscore8 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=7)
// zscore9 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=6)
// zscore10 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=7)
// zscore11 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=4)
// zscore12 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=3)
// zscore13 = VOL.zscore(src=hl2, mean=ma, length=14, biased=false, degreesOfFreedom=2)
// plot(zscore1, 'Z-score 1 - Biased', color.blue)
// plot(zscore2, 'Z-score 2 - Unbiased', color.blue)
// plot(zscore3, 'Z-score 3 - Unbiased', color.green)
// plot(zscore4, 'Z-score 4 - Unbiased', color.green)
// plot(zscore5, 'Z-score 5 - Unbiased', color.yellow)
// plot(zscore6, 'Z-score 6 - Unbiased', color.yellow)
// plot(zscore7, 'Z-score 7 - Unbiased', color.red)
// plot(zscore8, 'Z-score 8 - Unbiased', color.red)
// plot(zscore9, 'Z-score 9 - Unbiased', color.fuchsia)
// plot(zscore10, 'Z-score 10 - Unbiased', color.fuchsia)
// plot(zscore11, 'Z-score 11 - Unbiased', color.purple)
// plot(zscore12, 'Z-score 12 - Unbiased', color.purple)
// plot(zscore13, 'Z-score 13 - Unbiased', color.purple)
// [upper, lower, center] = VOL.dynamicZone(zscore1, 55, 90, 90)
// plot(series=upper, title='Upper Line', color=color.green, linewidth=2)
// plot(series=lower, title='Upper Line', color=color.red, linewidth=2)
// plot(series=center,title= 'Upper Line', color=color.white, linewidth=2)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— {
// T-Score
// indicator(title='T-Score (T-Student)', shorttitle="T-Score",
// format=format.price, precision=2, overlay = false)
// import andre_007/VolatilityIndicators/6 as VOLATILITY
// // Standard Deviation
// srcStd = input(close, title="Source for Standard Deviation", group="Standard Deviation")
// lengthStd = input.int(21, minval=1, title="Length of Standard Deviation", group="Standard Deviation")
// biasedStd = input.bool(true, title="Biased Standard Deviation", group="Standard Deviation")
// degreesOfFreedomStd = input.int(1, minval=1, title="Degrees of Freedom for Standard Deviation", group="Standard Deviation")
// lenghMAstd = input.int(21, minval=1, title="Length of MA for Standard Deviation", group="Standard Deviation")
// // Standard Error
// lenghError = input.int(21, minval=1, title='Length for Standard Error', group="Standard Error")
// maStd = ta.ema(srcStd, lenghMAstd)
// stdDev = VOLATILITY.stDev(src=srcStd, length=lengthStd, mean=maStd, biased=biasedStd, degreesOfFreedom=degreesOfFreedomStd)
// stdError = VOLATILITY.stErr(stdDev=stdDev, sampleSize=lenghError)
// float tscore = (srcStd - maStd) / stdError
// float zscore = VOLATILITY.zscore(src=srcStd, mean=maStd, length=lengthStd, biased=true, degreesOfFreedom=degreesOfFreedomStd)
// plot(tscore, title='T-Score', color=color.red, linewidth=2, style=plot.style_line)
// plot(zscore, title='Z-Score', color=color.blue, linewidth=2, style=plot.style_line)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————— }
|
lib_colors | https://www.tradingview.com/script/pxqvtXuL-lib-colors/ | robbatt | https://www.tradingview.com/u/robbatt/ | 0 | 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/
// © robbatt
//@version=5
// @description
library("lib_colors", overlay = true)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © robbatt
// @function get offset color
// @param original original color
// @param offset offset for new color
// @param transparency transparency for new color
// @returns offset color
export offset_mono(simple color original, float offset, float transparency = na) =>
var r = color.r(original)
var g = color.g(original)
var b = color.b(original)
var t = na(transparency) ? color.t(original) : transparency
// oscillating values between 0 and 256 with a rising input
r_off = int(127 * (math.sin(math.toradians(offset + r)) + 1))
g_off = int(127 * (math.sin(math.toradians(offset + g)) + 1))
b_off = int(127 * (math.sin(math.toradians(offset + b)) + 1))
color c_off = color.rgb(r_off, g_off, b_off, t)
//@description automatic detection of dark/light user layout
//@returns boolean status, true: dark mode, false: light mode
is_dark_mode() =>
var is_dark = color.r(chart.bg_color) < 128 or color.g(chart.bg_color) < 128 or color.b(chart.bg_color) < 128
is_dark
///////////////////////////////////////////////////////////
// TEST
///////////////////////////////////////////////////////////
var test_color = input.color(color.blue, 'base color')
color off_color = offset_mono(test_color, bar_index)
// plot(color.r(off_color) , 'offset color', off_color, linewidth = 4)
// plot(-255, 'fg color, offset -255', offset_mono(test_color, -255), linewidth = 4)
// plot(-224, 'fg color, offset -224', offset_mono(test_color, -224), linewidth = 4)
// plot(-192, 'fg color, offset -192', offset_mono(test_color, -192), linewidth = 4)
// plot(-160, 'fg color, offset -160', offset_mono(test_color, -160), linewidth = 4)
// plot(-128, 'fg color, offset -128', offset_mono(test_color, -128), linewidth = 4)
// plot(-96, 'fg color, offset -96', offset_mono(test_color, -96), linewidth = 4)
// plot(-64, 'fg color, offset -64', offset_mono(test_color, -64), linewidth = 4)
// plot(-32, 'fg color, offset -32', offset_mono(test_color, -32), linewidth = 4)
plot(128, 'fg color', test_color, linewidth = 4)
// plot(3, 'fg color, offset 0', offset_mono(test_color, 0), linewidth = 4)
// plot(32, 'fg color, offset 32', offset_mono(test_color, 32), linewidth = 4)
// plot(64, 'fg color, offset 64', offset_mono(test_color, 64), linewidth = 4)
// plot(96, 'fg color, offset 96', offset_mono(test_color, 96), linewidth = 4)
// plot(128, 'fg color, offset 128', offset_mono(test_color, 128), linewidth = 4)
// plot(160, 'fg color, offset 160', offset_mono(test_color, 160), linewidth = 4)
// plot(192, 'fg color, offset 192', offset_mono(test_color, 192), linewidth = 4)
// plot(224, 'fg color, offset 224', offset_mono(test_color, 224), linewidth = 4)
// plot(255, 'fg color, offset 255', offset_mono(test_color, 255), linewidth = 4)
plotshape(true, 'oscilating indefinite', shape.circle, location.bottom, offset_mono(test_color, bar_index), size = size.small)
plotshape(true, 'is dark mode', shape.circle, location.top, is_dark_mode() ? color.white : color.black, size = size.small) |
KNN ATR Dual Range Predictions [SS] | https://www.tradingview.com/script/fQnkocWk-KNN-ATR-Dual-Range-Predictions-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 56 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// © Steversteves
//@version=5
indicator("KNN ATR Dual Range Predictions [SS]", overlay=true, max_bars_back = 5000)
// Groups //
g1 = "Settings"
g2 = "Primary Targets"
g3 = "Secondary Targets"
// Settings
train = input.int(150, "Training Time", group = g1)
reg_type = input.string("Last Instance", "KNN Regression Type", ["Last Instance", "Cluster"], group = g1)
clust = input.int(3, "Clusters", group = g1)
tol = input.float(0.5, "Tolerance", group = g1)
stats = input.bool(true, "Show Regression Statistics", group = g1)
// Primary Targets
prim_tf = input.bool(true, "Show Primary Timeframe Targets", group = g2)
fill = input.bool(true, "Fill Primary Targets", group = g2)
// Secondary Targets
alt_tf = input.bool(true, "Show Secondary Timeframe Targets", group = g3)
timeframe = input.timeframe("D", "Secondary Timeframe", group = g3)
// Regression
knn_regression(float y, float x, int len, string last_instance_or_cluster_or_avg, int clusters, float tolerance) =>
int index_of = 0
float result = 0.0
float error = 0.0
int inst = 0
float y_result = 0.0
float cor = 0.0
float r2 = 0.0
y_in = y[1]
ed_y = math.abs(math.sqrt(math.pow(y[1] - x[1],2)))
ed_x = math.abs(math.sqrt(math.pow(y - x, 2)))
ed_array = array.new<float>()
y_array = array.new<float>()
cluster_array = array.new<float>()
cluster_avg = array.new<float>()
for i = 0 to len
array.push(ed_array, ed_y[i])
array.push(y_array, y_in[i])
// Find KNN
if last_instance_or_cluster_or_avg == "Last Instance"
if array.includes(ed_array, ed_x)
index_of := array.indexof(ed_array, ed_x)
result := array.get(y_array, index_of)
else if result[1] < 0
result := result[1]
else if result[2] < 0
result := result[2]
else if result[3] < 0
result := result[3]
else
na
else if last_instance_or_cluster_or_avg == "Avg"
for i = 0 to array.size(ed_array) - 1
if array.get(ed_array, i) == ed_x
y_result += array.get(y_array, i)
inst += 1
result := y_result / inst
else if last_instance_or_cluster_or_avg == "Cluster"
for i = 0 to array.size(ed_array) - 1
if array.get(ed_array, i) >= ed_x - tolerance and array.get(ed_array, i) <= ed_x + tolerance
array.push(cluster_array, array.get(y_array, i))
if array.size(cluster_array) - 1 > clusters
for i = 0 to clusters
array.push(cluster_avg, array.get(cluster_array, i))
result := array.avg(cluster_avg)
// Error
bool above_result = y > result
bool below_result = y < result
above_arr = array.new<float>()
below_arr = array.new<float>()
above_dif = y - result
below_dif = result - y
for i = 0 to len
if above_result[i]
array.push(above_arr, above_dif[i])
else if below_result[i]
array.push(below_arr, below_dif[i])
else
na
avg1 = array.avg(above_arr)
avg2 = array.avg(below_arr)
error := math.avg(avg1, avg2)
// Correlation
result_array = array.new<float>()
for i = 0 to array.size(y_array) - 1
array.push(result_array, result[i])
cov = array.covariance(result_array, y_array)
y_sd = array.stdev(y_array)
r_sd = array.stdev(result_array)
cor := cov / (y_sd * r_sd)
// R2
r2 := math.pow(cor, 2)
[result, error, cor, r2]
// Calcs
[hitoop_tf, optolo_tf, op_tf, ti] = request.security(syminfo.tickerid, timeframe, [high[1] - open[1], open[1] - low[1], open, time], lookahead = barmerge.lookahead_on)
hitoop = (high[1] - open[1])
optolo = (open[1] - low[1])
[h_r, h_er, h_cor, h_r2] = knn_regression(hitoop, hitoop[1], train, str.tostring(reg_type), clust, tol)
[l_r, l_er, l_cor, l_r2] = knn_regression(optolo, optolo[1], train, str.tostring(reg_type), clust, tol)
[h_tf_r, h_tf_er, h_tf_cor, h_tf_r2] = knn_regression(hitoop_tf, hitoop_tf[1], train, str.tostring(reg_type), clust, tol)
[l_tf_r, l_tf_er, l_tf_cor, l_tf_r2] = knn_regression(optolo_tf, optolo_tf[1], train, str.tostring(reg_type), clust, tol)
// Colours
color black = color.rgb(0, 0, 0)
color white = color.white
color gray = color.gray
color greenfill = color.new(color.lime, 90)
color redfill = color.new(color.red, 90)
// Plots
a = plot(prim_tf ? ta.sma(open + h_r, 14) : na, color=greenfill, linewidth=2)
b = plot(prim_tf ? ta.sma(open + h_r + h_er, 14) : na, color=greenfill, linewidth=2)
c = plot(prim_tf ? ta.sma(open - l_r, 14) : na, color=redfill, linewidth=2)
d = plot(prim_tf ? ta.sma(open - l_r - l_er, 14) : na, color=redfill, linewidth=2)
fill(a, b, color = fill ? greenfill : na)
fill(c, d, color = fill ? redfill : na)
// Secondary TF Plots
var line hitp_1 = na
var line hitp_2 = na
var line lotp_1 = na
var line lotp_2 = na
if barstate.isconfirmed and alt_tf
line.delete(hitp_1), line.delete(hitp_2), line.delete(lotp_1), line.delete(lotp_2)
hitp_1 := line.new(bar_index[10], op_tf + h_tf_r, bar_index, op_tf + h_tf_r, extend = extend.right, color = color.lime, width=3)
hitp_2 := line.new(bar_index[10], op_tf + h_tf_r + h_tf_er, bar_index, op_tf + h_tf_r + h_tf_er, extend = extend.right, color = color.lime, width=3)
lotp_1 := line.new(bar_index[10], op_tf - l_tf_r, bar_index, op_tf - l_tf_r, extend = extend.right, color = color.red, width=3)
lotp_2 := line.new(bar_index[10], op_tf - l_tf_r - l_tf_er, bar_index, op_tf - l_tf_r - l_tf_er, extend = extend.right, color = color.red, width=3)
// Stats
if stats
var table stats_tbl = table.new(position.middle_right, 3, 6, bgcolor = black, frame_color = color.aqua, frame_width = 3)
table.cell(stats_tbl, 1, 1, text = "Statistics Table", bgcolor = black, text_color = white)
table.cell(stats_tbl, 1, 2, text = "Primary Timeframe Data", bgcolor = gray, text_color = white)
table.cell(stats_tbl, 1, 3, text = "High Correlation: " + str.tostring(math.round(h_cor,2)) + "\n High R2: " + str.tostring(math.round(h_r2,2)) + "\n Low Correlation: " + str.tostring(math.round(l_cor,2)) + "\n Low R2: " + str.tostring(math.round(l_r2,2)), bgcolor = black, text_color = white)
table.cell(stats_tbl, 1, 4, text = "Secondary Timeframe Data", bgcolor = gray, text_color = white)
table.cell(stats_tbl, 1, 5, text = "High Correlation: " + str.tostring(math.round(h_tf_cor,2)) + "\n High R2: " + str.tostring(math.round(h_tf_r2,2)) + "\n Low Correlation: " + str.tostring(math.round(l_tf_cor,2)) + "\n Low R2: " + str.tostring(math.round(l_tf_r2,2)), bgcolor = black, text_color = white)
|
HDBhagat multi time frame box analysis | https://www.tradingview.com/script/fVoDObUV-HDBhagat-multi-time-frame-box-analysis/ | HDBhagat | https://www.tradingview.com/u/HDBhagat/ | 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/
// © HDBhagat
//@version=5
indicator("HDBhagat multi time frame", overlay = true,max_boxes_count=5000)
timeframeInput = input.timeframe("1W")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
drawBox(bar b, right) =>
bar s = bar.new()
color boxColor = b.c >= b.o ? color.rgb(82, 61, 220) : color.rgb(247, 63, 63)
box.new(b.t, b.h, right, b.l, boxColor, xloc = xloc.bar_time,border_style=line.style_dashed,border_width=2, bgcolor = color.new(boxColor, 99))
updateBox(box boxId, bar b) =>
color boxColor = b.c >= b.o ? color.rgb(72, 54, 239, 72) : color.rgb(245, 31, 31, 77)
box.set_border_color(boxId, boxColor)
box.set_bgcolor(boxId, color.new(boxColor, 99))
box.set_top(boxId, b.h)
box.set_bottom(boxId, b.l)
box.set_right(boxId, time)
secBar = request.security(syminfo.tickerid, timeframeInput, bar.new())
if not na(secBar)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox(secBar, time[1])
else
var box lastBox = na
if na(lastBox) or timeframe.change(timeframeInput)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox := drawBox(secBar, time)
else
// On other chart updates, use setters to modify the current box.
updateBox(lastBox, secBar)
//@version=5
//indicator("Multi Time Period Chart", overlay = true)
timeframeInput2 = input.timeframe("1D")
type barb
float ow = open
float hw = high
float lw = low
float cw = close
int tw = time
drawBox2(barb b2, right2) =>
barb s2 = barb.new()
color boxColor2 = b2.cw >= b2.ow ? color.rgb(94, 101, 249) : color.rgb(244, 96, 96)
box.new(b2.tw, b2.hw, right2, b2.lw, boxColor2, xloc = xloc.bar_time,border_style=line.style_dotted,border_width=1, bgcolor = color.new(boxColor2, 99))
updateBox2(box boxId2, barb b2) =>
color boxColor2 = b2.cw >= b2.ow ? color.rgb(76, 109, 255, 67) : color.rgb(255, 72, 72, 54)
box.set_border_color(boxId2, boxColor2)
box.set_bgcolor(boxId2, color.new(boxColor2, 99))
box.set_top(boxId2, b2.hw)
box.set_bottom(boxId2, b2.lw)
box.set_right(boxId2, time)
secBar2 = request.security(syminfo.tickerid, timeframeInput2, barb.new())
if not na(secBar2)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput2)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox2(secBar2, time[1])
else
var box lastBox2 = na
if na(lastBox2) or timeframe.change(timeframeInput2)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox2 := drawBox2(secBar2, time)
else
// On other chart updates, use setters to modify the current box.
updateBox2(lastBox2, secBar2)
//@version=5
//indicator("Multi Time Period Chart", overlay = true)
timeframeInput12 = input.timeframe("240")
type barb2
float od = open
float hd = high
float ld = low
float cd = close
int td = time
drawBox1(barb2 b12, right12) =>
barb2 s12 = barb2.new()
color boxColor12 = b12.cd >= b12.od ? color.rgb(131, 105, 210) : color.rgb(243, 79, 79)
box.new(b12.td, b12.hd, right12, b12.ld, boxColor12, xloc = xloc.bar_time, border_style=line.style_solid,border_width=2, bgcolor = color.new(boxColor12, 99))
updateBox1(box boxId12, barb2 b12) =>
color boxColor12 = b12.cd >= b12.od ? color.rgb(98, 98, 231, 70) : color.rgb(250, 34, 34, 72)
box.set_border_color(boxId12, boxColor12)
box.set_bgcolor(boxId12, color.new(boxColor12, 99))
box.set_top(boxId12, b12.hd)
box.set_bottom(boxId12, b12.ld)
box.set_right(boxId12, time)
secBar12 = request.security(syminfo.tickerid, timeframeInput12, barb2.new())
if not na(secBar12)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput12)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox1(secBar12, time[1])
else
var box lastBox12 = na
if na(lastBox12) or timeframe.change(timeframeInput12)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox12 := drawBox1(secBar12, time)
else
// On other chart updates, use setters to modify the current box.
updateBox1(lastBox12, secBar12)
//@version=5
//indicator("Multi Time Period Chart", overlay = true)
timeframeInput123 = input.timeframe("60")
type barb3
float o4 = open
float h4 = high
float l4 = low
float c4 = close
int t4 = time
drawBox3(barb3 b123, right123) =>
barb3 s123 = barb3.new()
color boxColor123 = b123.c4 >= b123.o4 ? color.rgb(88, 96, 255) : color.rgb(255, 48, 48)
box.new(b123.t4, b123.h4, right123, b123.l4, boxColor123, xloc = xloc.bar_time,border_style=line.style_solid,border_width=1, bgcolor = color.new(boxColor123, 99))
updateBox3(box boxId123, barb3 b123) =>
color boxColor123 = b123.c4 >= b123.o4 ? color.rgb(76, 101, 175) : color.rgb(250, 41, 41)
box.set_border_color(boxId123, boxColor123)
box.set_bgcolor(boxId123, color.new(boxColor123, 99))
box.set_top(boxId123, b123.h4)
box.set_bottom(boxId123, b123.l4)
box.set_right(boxId123, time)
secBar123 = request.security(syminfo.tickerid, timeframeInput123, barb3.new())
if not na(secBar123)
// To avoid a runtime error, only process data when an object exists.
if not barstate.islast
if timeframe.change(timeframeInput123)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox3(secBar123, time[1])
else
var box lastBox123 = na
if na(lastBox123) or timeframe.change(timeframeInput123)
// On the last bar, only draw a new current box the first time we get there or when HTF changes.
lastBox123 := drawBox3(secBar123, time)
else
// On other chart updates, use setters to modify the current box.
updateBox3(lastBox123, secBar123)
|
Curved Management (Zeiierman) | https://www.tradingview.com/script/VVBbYPt4-Curved-Management-Zeiierman/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 542 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman
//@version=5
indicator("Curved Management (Zeiierman)",overlay=true)
//~~}
// ~~ Tooltip {
t1="Select the trade direction"
t2="Sets the ratio for take profit relative to stop loss. Increasing this value will set your take profit further from the entry, and decreasing will bring it closer."
t3="Choose the curve style for take profit visualization. 'Rounded' gives a curved edge, 'Plane' gives a straight edge, and 'Rounded Intersection' combines Entry & TP. \n\nSelect the color of the take profit visualization. \n\nAdjust the transparency level of the take profit visualization. A higher value increases transparency, making it more see-through."
t4="Multiplier for calculating stop loss based on the ATR value. Increasing this makes your stop loss further from the entry, while decreasing brings it closer."
t5="Choose the curve style for stop loss visualization. 'Rounded' gives a curved edge, 'Plane' gives a straight edge, and 'Rounded Intersection' combines Entry & SL. \n\nSelect the color of the stop loss visualization. \n\nAdjust the transparency level of the stop loss visualization. A higher value increases transparency, making it more see-through."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
los = input.string("Long","Trade Direction",options=["Long","Short"],group="Trade Direction",tooltip=t1)
rr = input.float(1.5,"Reward Multiplier",step=.1,group="Take Profit",tooltip=t2)
tpc = input.string("Plane","",options=["Rounded","Plane","Rounded Intersection"],group="Take Profit",inline="tp")
tpcol = input.color(color.lime,"",group="Take Profit",inline="tp")
tptransp = input.int(75,"",group="Take Profit",inline="tp",tooltip=t3)
mult = input.float(1.5,"Risk Multiplier",step=.1,group="Trade",inline="mult",tooltip=t4)
slc = input.string("Rounded","",options=["Rounded","Plane","Rounded Intersection"],group="Trade",inline="sl")
slcol = input.color(color.red,"",group="Trade",inline="sl")
sltransp = input.int(75,"",group="Trade",inline="sl",tooltip=t5)
entLab = input.bool(true,"Entry Label",group="Appearance",inline="Appearance")
tpLab = input.bool(true,"TP Label",group="Appearance",inline="Appearance")
slLab = input.bool(true,"Stop Label",group="Appearance",inline="Appearance")
width = input.int(20,"Width of Trade Management",group="Appearance",inline="Appearance")
x = input.time(0, "Entry & Time Info",confirm=true,group="Entry & Time",inline="xy")
y = input.price(0,"Entry & Time Info",confirm=true,group="Entry & Time",inline="xy")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
atr = ta.atr(10)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Functions {
TimeToIndex()=>
d = 86400000
t = switch
timeframe.isseconds => 1000
timeframe.isminutes => 60000
timeframe.isdaily => d
timeframe.isweekly => d*7
timeframe.ismonthly => d*30
output = timeframe.multiplier*t
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate trade management {
if barstate.islastconfirmedhistory
var stop = array.new<chart.point>()
var tp = array.new<chart.point>()
t = TimeToIndex()*width
x1 = los=="Long"?x-t:x+t
x2 = los=="Long"?x+t:x-t
sly = los=="Long"?y-atr*mult:y+atr*mult
tpy = los=="Long"?y+(y-sly)*rr:y-(sly-y)*rr
stop.push(chart.point.from_time(x1,y))
stop.push(chart.point.from_time(x,sly))
stop.push(chart.point.from_time(x2,y))
tp.push(chart.point.from_time(x1,y))
tp.push(chart.point.from_time(x1,tpy))
tp.push(chart.point.from_time(x2,tpy))
tp.push(chart.point.from_time(x2,y))
polyline.new(stop,slc!="Plane"?true:false,slc=="Rounded Intersection"?true:false,xloc.bar_time,slcol,color.new(slcol,sltransp))
polyline.new(tp,tpc!="Plane"?true:false,tpc=="Rounded Intersection"?true:false,xloc.bar_time,tpcol,color.new(tpcol,tptransp))
//Labels
if entLab
label.new(chart.point.from_time(x+t*2,y),"Entry: "+str.tostring(y,format.mintick),xloc.bar_time,
style=label.style_label_right,color=na,textcolor=chart.fg_color)
if tpLab
label.new(chart.point.from_time(x+t*2,tpy),"TP: "+str.tostring(tpy,format.mintick),xloc.bar_time,
style=label.style_label_right,color=na,textcolor=chart.fg_color)
if slLab
label.new(chart.point.from_time(x+t*2,sly),"Stoploss: "+str.tostring(sly,format.mintick),xloc.bar_time,
style=label.style_label_right,color=na,textcolor=chart.fg_color)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Pivot Points | https://www.tradingview.com/script/x3QEg95k-Pivot-Points/ | agentsmith1337 | https://www.tradingview.com/u/agentsmith1337/ | 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/
// @agentsmith1337
//@version=5
indicator('Pivot Points', 'pivot-points', overlay = true)
///////////////////////////////////////////////////////////////////////////////
// inputs
i_leverage = input.int(1, "Leverage")
i_takeProfit = input.float(1.0, "Take Profit %") / i_leverage
i_dca = input.float(-1.0, "DCA when < %") / i_leverage *-1
i_pivotFactor = input.float(-1, "Pivot Factor")
i_pivotLength = input.int(60, "Pivot Length", minval = 0)
i_lookbackFactor = input.float(-1, "Lookback Factor")
///////////////////////////////////////////////////////////////////////////////
// variables
// Manually track the average entry price and position size
var float avg_entry_price = na
var int position_size = 0
int pause = 0
pause := nz(pause[1])
bool paused = time < pause
float fill = 0.0
fill := nz(fill[1])
float count = 0.0
count := nz(fill[1])
///////////////////////////////////////////////////////////////////////////////
// functions
update_position(avg_price, size, entry_price) =>
new_avg_price = size > 0 ? (avg_price * size + entry_price) / (size + 1) : entry_price
new_size = size + 1
[new_avg_price, new_size]
///////////////////////////////////////////////////////////////////////////////
// calculations
pivotHigh = ta.highest(i_pivotLength)
pivotHighAboveSMA = ta.dev(pivotHigh, i_pivotLength) > 0
hi = pivotHighAboveSMA ? na : pivotHigh
hPivot = ta.valuewhen(not na(hi), hi, 0)
pivotLow = ta.lowest(i_pivotLength)
pivotLowAboveSMA = ta.dev(pivotLow, i_pivotLength) > 0
lo = pivotLowAboveSMA ? na : pivotLow
lPivot = ta.valuewhen(not na(lo), lo, 0)
entry = ((((hPivot - lPivot)) * i_pivotFactor) + lPivot)
lookbackFactor = (((hPivot - lPivot) * i_lookbackFactor) + lPivot)
profit = avg_entry_price + avg_entry_price * (i_takeProfit / 100)
filled = count > 0 ? entry > fill - fill / 100 * i_dca : false
signal = nz(lookbackFactor[i_pivotLength]) > 0 and not paused and not filled ? 1 : 0
filledOrder = ta.crossunder(low[1], entry[1]) and signal[1] > 0
///////////////////////////////////////////////////////////////////////////////
// strategy
if filledOrder
fill := entry
count := count + 1
pause := time + 60000
[temp_avg_entry_price, temp_position_size] = update_position(avg_entry_price, position_size, close)
avg_entry_price := temp_avg_entry_price
position_size := temp_position_size
closeit = ta.crossover(high, profit) and position_size >= 1
if closeit
// reset position
avg_entry_price := na
position_size := 0
count := 0
fill := 0
///////////////////////////////////////////////////////////////////////////////
// plots
plotshape(filledOrder, 'Entry Signal', color = color.green, textcolor = color.white, location = location.belowbar, style = shape.labelup, text = 'ENTRY')
plotshape(closeit, 'Exit Signal', color = color.red, textcolor = color.white, location = location.abovebar, style = shape.labeldown, text = 'EXIT')
plot(filledOrder ? 1 : 0, 'Enter', color = color.green, editable = false)
plot(closeit ? 1 : 0, 'Exit', color = color.red, editable = false) |
ICT NWOG/NDOG [Source Code] (fadi) | https://www.tradingview.com/script/XY0niHGg-ICT-NWOG-NDOG-Source-Code-fadi/ | fadizeidan | https://www.tradingview.com/u/fadizeidan/ | 109 | 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/
// © fadizeidan
//@version=5
indicator(title="ICT NWOG/NDOG (fadi)", overlay=true, max_bars_back=5000, max_lines_count = 500)
// Helper type is a hack to group generic functions
type Helper
string name
type Settings
bool show
color color
color color_new
color ce_color
color ce_color_new
string extend
bool EH_show // Event Horizon
color EH_color
string EH_style
int EH_size
int max_count
bool label_show
string label_size
color label_color
color label_bgcolor
type Gap
string name
float open
float middle
float close
int open_time
int close_time
box box
line CE
label lbl_date
bool is_current = false
type OpenGap
Gap[] gaps
Settings settings
line EventHorizon = na
var nwog_gaps = array.new<Gap>()
var OpenGap NWOG = OpenGap.new()
NWOG.gaps := nwog_gaps
NWOG.settings := Settings.new()
var ndog_gaps = array.new<Gap>()
var OpenGap NDOG = OpenGap.new()
NDOG.gaps := ndog_gaps
NDOG.settings := Settings.new()
var Helper helper = Helper.new()
NWOG_Group = "New Week Open Gap (NWOG)"
NDOG_Group = "New Day Open Gap (NDOG)"
General_Group = "General Settings"
NWOG.settings.show := input.bool(true, "NWOG", group=NWOG_Group)
NWOG.settings.color_new := input.color(color.new(color.purple,85), 'Range ', group=NWOG_Group, inline='1')
NWOG.settings.color := input.color(color.new(color.black,85), '', group=NWOG_Group, inline='1')
NWOG.settings.ce_color_new := input.color(color.new(color.purple,20), 'Middle ', group=NWOG_Group, inline='3')
NWOG.settings.ce_color := input.color(color.new(color.black,20), '', group=NWOG_Group, inline='3')
NWOG.settings.label_show := input.bool(true, "Date ", group=NWOG_Group, inline='2')
NWOG.settings.label_color := input.color(color.black, "", group=NWOG_Group, inline='2')
NWOG.settings.label_bgcolor := input.color(color.new(color.orange, 100), "", group=NWOG_Group, inline='2')
NWOG.settings.label_size := input.string(size.small, "", [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group=NWOG_Group, inline='2')
NWOG.settings.EH_show := input.bool(true, "Event Horizon", group=NWOG_Group, inline="4", tooltip="Only applicable to Previous and Next, draws middle point Event Horizon.")
NWOG.settings.EH_color := input.color(color.new(color.purple,20), "", group=NWOG_Group, inline='4')
NWOG.settings.EH_style := input.string('----', '', options = ['⎯⎯⎯', '----', '····'], group=NWOG_Group, inline='4')
NWOG.settings.EH_size := input.int(1, '', options = [1,2,3,4], group=NWOG_Group, inline='4')
NWOG.settings.max_count := input.int(5, "Maximum number of NWOGs to use", 1, 50, group=NWOG_Group)
NWOG.settings.extend := input.string("Always", "Extend Gaps", options = ['Always', 'Above and below only', 'Any that is near current price'], group=NWOG_Group)
NDOG.settings.show := input.bool(true, "NDOG", group=NDOG_Group)
NDOG.settings.color_new := input.color(color.new(color.green,85), 'Range ', group=NDOG_Group, inline='1')
NDOG.settings.color := input.color(color.new(color.blue,85), '', group=NDOG_Group, inline='1')
NDOG.settings.label_show := input.bool(true, "Date ", group=NDOG_Group, inline='2')
NDOG.settings.label_color := input.color(color.black, "", group=NDOG_Group, inline='2')
NDOG.settings.label_bgcolor := input.color(color.new(color.orange, 100), "", group=NDOG_Group, inline='2')
NDOG.settings.label_size := input.string(size.small, "", [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group=NDOG_Group, inline='2')
NDOG.settings.ce_color_new := input.color(color.new(color.green,20), 'Middle ', group=NDOG_Group, inline='3')
NDOG.settings.ce_color := input.color(color.new(color.blue,20), '', group=NDOG_Group, inline='3')
NDOG.settings.max_count := input.int(1, "Maximum number of NDOGs to use", 1, 50, group=NDOG_Group)
NDOG.settings.extend := input.string("Always", "Extend Gaps", options = ['Always', 'Above and below only', 'Any that is near current price'], group=NDOG_Group)
distance = input.int(200, "Number of candles to use in calculation", group="Other")
factor = input.float(20, "Factor multiplier for distance test", group="Other")
buffer = input.int(1, "Buffer - Number of candles to extend by", minval=0, group="Other")+1
atrf = ta.atr(distance) + (ta.stdev(high - low, distance)*factor)
dt = time - time[1]
//+------------------------------------------------------------------------------------------------------------+//
//+--- Functions ---+//
//+------------------------------------------------------------------------------------------------------------+//
f_get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
//+------------------------------------------------------------------------------------------------------------+//
//+--- Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
method AbovePrice(Gap[] gaps, price) =>
float delta = -1
size = gaps.size()
Gap _return = na
if size > 0
for i= size-1 to 0
Gap ng = gaps.get(i)
float mark = math.max(ng.open, ng.close)
if price < mark
ndelta = math.abs(mark - price)
delta := delta == -1 ? ndelta : delta
if ndelta <= delta
delta := ndelta
_return := ng
_return
method BelowPrice(Gap[] gaps, price) =>
float delta = -1
size = gaps.size()
Gap _return = na
if size > 0
for i=0 to size-1
Gap ng = gaps.get(i)
float mark = math.min(ng.open, ng.close)
if price > mark
ndelta = math.abs(price - mark)
delta := delta == -1 ? ndelta : delta
if ndelta <= delta
delta := ndelta
_return := ng
_return
method GetExtendedValue(Helper helper, string extendby, Gap gap) =>
helper.name := "GetExtendedValue" // Dummy setting to make Helper type work
switch extendby
'Always' =>
time + (dt*buffer)
'Above and below only' =>
gap.close_time + (dt*buffer)
'Any that is near current price' =>
t = (math.min(gap.open, gap.close) - high)
l = (low - math.max(gap.open, gap.close))
if (t > 0 and t < atrf) or (l > 0 and l < atrf) or (t <= 0 and l <= 0)
time + dt*buffer
else
gap.close_time + (dt*buffer)
method RenderBox(Helper helper, box box, line line, label lbl, float top, float bottom, int left, int right, Settings settings, bool is_current) =>
helper.name := "RenderBox" //Dummy setting
if not na(box)
box.set_lefttop(box, left, top)
box.set_rightbottom(box, right, bottom)
box.set_bgcolor(box, is_current ? settings.color_new : settings.color)
box.set_border_color(box, is_current ? settings.color_new : settings.color)
if not na(line)
line.set_x2(line, right)
line.set_color(line, is_current ? settings.ce_color_new : settings.ce_color)
if not na(lbl) and settings.label_show
label.set_x(lbl, right)
method Add(OpenGap GAP, string name) =>
gap = Gap.new()
gap.name := name
gap.open := close[1]
gap.close := open
gap.middle := (open+close[1])/2
gap.open_time := time[1]
gap.close_time := time
gap.box := box.new(gap.open_time, gap.open, gap.close_time, gap.close, GAP.settings.color_new, 1, line.style_solid, extend.none, xloc.bar_time, GAP.settings.color_new)
gap.CE := line.new(gap.open_time, gap.middle, gap.close_time, gap.middle, xloc.bar_time, extend.none, GAP.settings.ce_color_new, line.style_dotted, 1)
if GAP.settings.label_show
gap.lbl_date := label.new(gap.close_time, gap.middle, str.format("({0, date, d MMM yyyy}) - {1}", gap.close_time, gap.name), style=label.style_label_left, xloc=xloc.bar_time, size=GAP.settings.label_size, color=GAP.settings.label_bgcolor, textcolor=GAP.settings.label_color)
GAP.gaps.unshift(gap)
if GAP.gaps.size() > GAP.settings.max_count
g = GAP.gaps.pop()
box.delete(g.box)
line.delete(g.CE)
label.delete(g.lbl_date)
GAP
method Redraw(OpenGap GAP) =>
if GAP.gaps.size() > 0
for i = 0 to GAP.gaps.size()-1
g = GAP.gaps.get(i)
g.is_current := i == 0
e = helper.GetExtendedValue(GAP.settings.extend, g)
helper.RenderBox(g.box, g.CE, g.lbl_date, math.max(g.open, g.close), math.min(g.open, g.close), g.open_time, e, GAP.settings, g.is_current)
if GAP.settings.extend == 'Above and below only' or GAP.settings.EH_show
prev = GAP.gaps.AbovePrice(close)
next = GAP.gaps.BelowPrice(close)
d = time + (time-time[1])*buffer
if GAP.settings.extend == 'Above and below only'
if not na(prev)
helper.RenderBox(prev.box, prev.CE, prev.lbl_date, math.max(prev.open, prev.close), math.min(prev.open, prev.close), prev.open_time, d, GAP.settings, prev.is_current)
if not na(next)
helper.RenderBox(next.box, next.CE, next.lbl_date, math.max(next.open, next.close), math.min(next.open, next.close), next.open_time, d, GAP.settings, next.is_current)
if GAP.settings.EH_show
if not na(prev) and not na(next)
if math.min(prev.open, prev.close) > math.max(next.open, next.close)
middle = (math.min(prev.open, prev.close) + math.max(next.open, next.close))/2
if na(GAP.EventHorizon)
GAP.EventHorizon := line.new(math.max(prev.open_time, next.open_time), middle, time+(time-time[1])*buffer, middle, xloc=xloc.bar_time, color=GAP.settings.EH_color, width = GAP.settings.EH_size, style=f_get_line_style(GAP.settings.EH_style))
else
line.set_xy1(GAP.EventHorizon, math.max(prev.open_time, next.open_time), middle)
line.set_xy2(GAP.EventHorizon, time+(time-time[1])*buffer, middle)
else
line.delete(GAP.EventHorizon)
else
line.delete(GAP.EventHorizon)
1
else
line.delete(GAP.EventHorizon)
1
GAP
//+------------------------------------------------------------------------------------------------------------+//
//+--- Main ---+//
//+------------------------------------------------------------------------------------------------------------+//
if barstate.isconfirmed
if NWOG.settings.show
is_sunday = dayofweek == dayofweek.sunday
if not is_sunday[1] and is_sunday //and open != close[1]
NWOG.Add("NWOG")
NWOG.Redraw()
if NDOG.settings.show
dailyBarTime = time('1D')
isNewDay = ta.change(dailyBarTime)
if isNewDay and open != close[1]
NDOG.Add("NDOG")
NDOG.Redraw()
|
Spice | https://www.tradingview.com/script/2ovY1KmA-Spice/ | Crypto_Chili_ | https://www.tradingview.com/u/Crypto_Chili_/ | 109 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author @Crypto_Chili_
// Thanks to Lij_MC MarketVision A indicator for inspiring me to add more features to this indicator. At first it was just the RSI Arrows and the BB reversals candles + Condition but then I found MarketVision A and loved the extra Leledc and 3 Line Strike features.
// Thank you to all the creators mentioned in this source code. Names will be above their indicator
// Hope you enjoy this
//@version=5
indicator('Spice', shorttitle='Spice',overlay=true)
//Toggles
ShowRecentSignalsIn = input.int(200, "Signals Shown in x No. of Bars", minval = 0, maxval = 100000000, step = 5, inline = "Signals")
show_BB = input.bool(defval=false, title='Show BB?')
show_bullish3strike = input.bool(defval=true, title='Show Bullish 3 Strike Candles')
show_bearish3strike = input.bool(defval=true, title='Show Bearish 3 Strike Candles')
ShowLeledcHigh = input.bool(defval=true, title='Show Leledc Exhaustion High')
ShowLeledcLow = input.bool(defval=true, title='Show Leledc Exhaustion Low')
show_topR = input.bool(defval=false, title='Show Top Reversals? ', inline='1', group='Top/Bot Reversal')
show_botR = input.bool(defval=false, title='Show Bottom Reversals?', inline='1', group='Top/Bot Reversal')
show_topbox = input.bool(defval=true, title='Show Confirmed First Bar ', inline='2', group='Top/Bot Reversal')
show_botbox = input.bool(defval=true, title='Show Confirmed First Bar', inline='2', group='Top/Bot Reversal')
show_topbox2 = input.bool(defval=true, title='Show Confirmed Second Bar ', inline='3', group='Top/Bot Reversal')
show_botbox2 = input.bool(defval=true, title='Show Confirmed Second Bar', inline='3', group='Top/Bot Reversal')
show_rsi = input.bool(defval=true, title='Show RSI Arrows?', group='RSI Timeframes')
remove_ema = input.bool(defval=true, title='Remove EMAs?', group='EMAs')
show_ema1 = input.bool(defval=true, title='Show EMA 1', group='EMAs', inline='3')
show_ema2 = input.bool(defval=true, title='Show EMA 2', group='EMAs', inline='4')
show_ema3 = input.bool(defval=true, title='Show EMA 3', group='EMAs', inline='5')
show_ema4 = input.bool(defval=true, title='Show EMA 4', group='EMAs', inline='6')
// EMAs
ema1Length = input(20, title = "- Length", group='EMAs', inline='3')
ema2Length = input(50, title = "- Length", group='EMAs', inline='4')
ema3Length = input(100, title = "- Length", group='EMAs', inline='5')
ema4Length = input(200, title = "- Length", group='EMAs', inline='6')
ema1 = ta.ema(close, ema1Length)
ema2 = ta.ema(close, ema2Length)
ema3 = ta.ema(close, ema3Length)
ema4 = ta.ema(close, ema4Length)
plot(not remove_ema and show_ema1 ? ema1:na, color=color.rgb(255, 0, 0, 30), linewidth=1, title="EMA 1")
plot(not remove_ema and show_ema2 ? ema2:na, color=color.rgb(255, 183, 77, 30), linewidth=1, title="EMA 2")
plot(not remove_ema and show_ema3 ? ema3:na, color=color.rgb(91, 156, 246, 30), linewidth=2, title="EMA 3")
plot(not remove_ema and show_ema4 ? ema4:na, color=color.rgb(255, 255, 255, 30), linewidth=3, title="EMA 4")
// Multi Timeframe RSI (LTF) by @millerrh, with my own touches to make it an overlay
rsi_mid = 50
rsiHigh = 70
rsiLow = 30
rsi_len = (6)
rsi_src = (close)
show1m = input(true, title='1m', group='RSI Timeframes')
show5m = input(true, title='5m', group='RSI Timeframes')
show15m = input(true, title='15m', group='RSI Timeframes')
show30m = input(true, title='30m', group='RSI Timeframes')
show1h = input(true, title='1h', group='RSI Timeframes')
show4h = input(true, title='4h', group='RSI Timeframes')
show1D = input(true, title='1D', group='RSI Timeframes')
rsiCurrent = ta.rsi(rsi_src, rsi_len)
rsi1m = request.security(syminfo.tickerid, '1', ta.rsi(rsi_src, rsi_len))
rsi5m = request.security(syminfo.tickerid, '5', ta.rsi(rsi_src, rsi_len))
rsi15m = request.security(syminfo.tickerid, '15', ta.rsi(rsi_src, rsi_len))
rsi30m = request.security(syminfo.tickerid, '30', ta.rsi(rsi_src, rsi_len))
rsi1h = request.security(syminfo.tickerid, '60', ta.rsi(rsi_src, rsi_len))
rsi4h = request.security(syminfo.tickerid, '240', ta.rsi(rsi_src, rsi_len))
rsi1D = request.security(syminfo.tickerid, 'D', ta.rsi(rsi_src, rsi_len))
redZone = (rsiCurrent > rsiHigh and (show5m and timeframe.multiplier < 5 ? rsi5m > rsiHigh : true) and (show15m and timeframe.multiplier < 15 ? rsi15m > rsiHigh : true) and (show30m and timeframe.multiplier < 30 ? rsi30m > rsiHigh : true) and (show1h and timeframe.multiplier < 60 ? rsi1h > rsiHigh : true) and (show4h and timeframe.multiplier < 240 ? rsi4h > rsiHigh : true) and (show1D and not timeframe.isdaily ? rsi1D > rsiHigh : true))
greenZone = (rsiCurrent < rsiLow and (show5m and timeframe.multiplier < 5 ? rsi5m < rsiLow : true) and (show15m and timeframe.multiplier < 15 ? rsi15m < rsiLow : true) and (show30m and timeframe.multiplier < 30 ? rsi30m < rsiHigh : true) and (show1h and timeframe.multiplier < 60 ? rsi1h < rsiLow : true) and (show4h and timeframe.multiplier < 240 ? rsi4h < rsiLow : true) and (show1D and not timeframe.isdaily ? rsi1D < rsiLow : true))
sinceRed = ta.barssince(redZone)
sinceGreen = ta.barssince(greenZone)
rsi_UpArrow = not greenZone and (sinceGreen < 2)
rsi_DownArrow = not redZone and (sinceRed < 2)
plotshape(show_rsi ? rsi_UpArrow:na, title='Up Arrow', style=shape.triangleup, location=location.belowbar, size=size.small, color=color.rgb(0, 187, 212, 50), show_last = ShowRecentSignalsIn)
plotshape(show_rsi ? rsi_DownArrow:na, title='Down Arrow', style=shape.triangledown, location=location.abovebar, size=size.small, color=color.rgb(103, 58, 183,50), show_last = ShowRecentSignalsIn)
//---------------------------------------------------------------------------------------------------------------------------------------------------------------//
// BB Reversals + specific candle condition met next bar by @Crypto_Chili_ - The way this should be used is by waiting for a 1 or 2 bar confirmation closed above/below the high/low of the Reversal candle.
// So if its a Top R, a yellow box will print as a confirmed 1 bar if it closed below the top R's low, then you can wait for the second bar to close also below the Top R's low. Vice versa with the Bot R.
bb_length = (20)
bb_src = (close)
mult = (2.0)
basis = ta.sma(bb_src, bb_length)
dev = mult * ta.stdev(bb_src, bb_length)
upper = basis + dev
lower = basis - dev
plot(show_BB ? basis:na, "Basis", color=#FF6D00)
p1 = plot(show_BB ? upper:na, "Upper", color=#2962FF)
p2 = plot(show_BB ? lower:na, "Lower", color=#2962FF)
fill(p1,p2, title = "Background", color=color.rgb(33, 150, 243, 95))
topR = ta.crossunder(close, upper)
botR = ta.crossover(close, lower)
plotchar(show_topR ? topR:na, title='Top Reversal', char='R', location=location.abovebar, color=#e6e600, size=size.tiny, show_last = ShowRecentSignalsIn)
plotchar(show_botR ? botR:na, title='Bot Reversal', char='R', location=location.belowbar, color=#f57c00, size=size.tiny, show_last = ShowRecentSignalsIn)
barcolor(show_topR and topR ? #e6e600 : na, editable=true, title='T Reversal Bar', show_last = ShowRecentSignalsIn)
barcolor(show_botR and botR ? #f57c00 : na, editable=true, title='B Reversal Bar', show_last = ShowRecentSignalsIn)
// Candle closing below top reversal
topR_low = ta.valuewhen(topR, low, 0)
topR_since = ta.barssince(topR) == 1
topR1 = close < topR_low and topR_since
plotshape(show_topbox ? topR1:na, title="Top Reversal bar1", location=location.abovebar, color=color.rgb(255, 235, 59, 50), style=shape.square, size=size.tiny, show_last = ShowRecentSignalsIn)
// Second Candle closing below top reversal
barsSinceTopR1 = ta.barssince(topR1) == 1
topR_low2 = ta.valuewhen(topR, low, 0)
topR_since2 = ta.barssince(topR) == 2
topR2 = close < topR_low2 and topR_since2 and barsSinceTopR1
plotshape(show_topbox2 ? topR2:na, title="Top Reversal bar2", location=location.abovebar, color=color.rgb(255, 0, 0, 50), style=shape.square, size=size.tiny, show_last = ShowRecentSignalsIn)
//Candle closing above bottom reversal
botR_high = ta.valuewhen(botR, high, 0)
botR_since = ta.barssince(botR) == 1
botR1 = close > botR_high and botR_since
plotshape(show_botbox ? botR1:na, title="Bottom Reversal bar1", location=location.belowbar, color=color.rgb(245, 123, 0, 50), style=shape.square, size=size.tiny, show_last = ShowRecentSignalsIn)
// Second Candle closing above bottom reversal
barsSinceBotR1 = ta.barssince(botR1) == 1
botR_high2 = ta.valuewhen(botR, high, 0)
botR_since2 = ta.barssince(botR) == 2
botR2 = close > botR_high2 and botR_since2 and barsSinceBotR1
plotshape(show_botbox2 ? botR2:na, title="Bottom Reversal bar2", location=location.belowbar, color=color.rgb(29, 245, 0, 50), style=shape.square, size=size.tiny, show_last = ShowRecentSignalsIn)
// 3 Line Strike from Lij_MC 'MarketVision A'. Awesome creator should check out the MarketVision B.
Bullish3LineStrike = close[3] < open[3] and close[2] < open[2] and close[1] < open[1] and close > open[1]
Bearish3LineStrike = close[3] > open[3] and close[2] > open[2] and close[1] > open[1] and close < open[1]
plotshape(show_bullish3strike ? Bullish3LineStrike:na, title='3 Line Strike', location=location.belowbar, style=shape.circle, color=color.new(color.green,70), size=size.tiny, show_last=ShowRecentSignalsIn)
plotshape(show_bearish3strike ? Bearish3LineStrike:na, title='3 Line Strike', location=location.abovebar, style=shape.circle, color=color.new(color.red,70), size=size.tiny, show_last=ShowRecentSignalsIn)
// Leledc Exhaustion Bar by glaz, used updated version by Joy_Bangla
src = close
majorBarCount = 6
majorBarLen = 30
minorBarCount = 5
minorBarLen = 5
bindexSindexInput = 1
closeValInput = 4
// Function for Leledec calculation
lele(qual, len) =>
bindex = 0
sindex = 0
bindex := nz(bindex[bindexSindexInput], 0)
sindex := nz(sindex[bindexSindexInput], 0)
ret = 0
if close > close[closeValInput]
bindex += 1
bindex
if close < close[closeValInput]
sindex += 1
sindex
if bindex > qual and close < open and high >= ta.highest(high, len)
bindex := 0
ret := -1
ret
if sindex > qual and close > open and low <= ta.lowest(low, len)
sindex := 0
ret := 1
ret
ret // return ret
// Major and Minor calculations
major = lele(majorBarCount, majorBarLen)
minor = lele(minorBarCount, minorBarLen)
major_high = major == -1 ? high:na
major_low = major == 1 ? low:na
plotchar(ShowLeledcHigh ? major_high:na, char='∘', location=location.absolute, color=color.new(color.red, 50), size=size.small, show_last=ShowRecentSignalsIn)
plotchar(ShowLeledcLow ? major_low:na, char='∘', location=location.absolute, color=color.new(color.lime, 50), size=size.small, show_last=ShowRecentSignalsIn)
// Alerts
alertcondition(rsi_UpArrow, title='RSI Up Arrow ', message='RSI Up Arrow')
alertcondition(rsi_DownArrow, title='RSI Down Arrow ', message='RSI Down Arrow')
alertcondition(topR, title='Reversal - Top', message='Top Reversal, candle bar closing back in BB')
alertcondition(botR, title='Reversal - Bottom', message='Bottom Reversal, candle bar closing back in BB')
alertcondition(topR1, title='R Top First Bar', message='Top R Confirmed First Bar')
alertcondition(botR1, title='R Bot First Bar', message='Bottom R Confirmed First Bar')
alertcondition(topR2, title='R Top Second Bar', message='Top R Confirmed Second Bar')
alertcondition(botR2, title='R Bot Second Bar', message='Bottom R Confirmed Second Bar')
alertcondition(Bullish3LineStrike, title='3 Line Strike - Bullish', message='Bullish 3 Line Strike')
alertcondition(Bearish3LineStrike, title='3 Line Strike - Bearish', message='Bearish 3 Line Strike')
alertcondition(major_high, title='Major Exhaustion - High', message='Leledc Major Exhaustion High')
alertcondition(major_low, title='Major Exhaustion - Low ', message='Leledc Major Exhaustion Low')
alertcondition(Bullish3LineStrike and major_low, title='Bullish Double trouble', message='Bullish 3 Line Strike - Major Exhuastion')
alertcondition(Bearish3LineStrike and major_high, title='Bearish Double Trouble', message='Bearish 3 Line Strike - Major Exhuastion')
alertcondition(Bullish3LineStrike and major_low and rsi_UpArrow, title='Bullish Triple Threat', message='Bullish 3 Line Strike - Major Exhuastion - RSI Up Arrow')
alertcondition(Bearish3LineStrike and major_high and rsi_DownArrow, title='Bearish Triple Threat', message='Bearish 3 Line Strike - Major Exhuastion - RSI Down Arrow')
alertcondition(ta.cross(close, ema1), title='EMA1 cross', message='Price is crossing EMA1')
alertcondition(ta.cross(close, ema2), title='EMA2 cross', message='Price is crossing EMA2')
alertcondition(ta.cross(close, ema3), title='EMA3 cross', message='Price is crossing EMA3')
alertcondition(ta.cross(close, ema4), title='EMA4 cross', message='Price is crossing EMA4') |
Session Breakout/Sweep with alerts | https://www.tradingview.com/script/SxnXL2QI-Session-Breakout-Sweep-with-alerts/ | a_guy_from_wall_street | https://www.tradingview.com/u/a_guy_from_wall_street/ | 130 | study | 5 | MPL-2.0 | //This source code is subject the terms of the Mozilla Public License at https://mozilla.org/MPL/2.0/
// © hiimannshu
//@version=5
indicator(title='Session Breakout', shorttitle='Sess Break', overlay=true, max_boxes_count=500, max_lines_count=500)
//--------------------------------- Inputs --------------------------------------------------------------//
show_session_box = input.bool(true, title='Show session time range box ?', group='Session Time Range')
box_infil_color = input.color(color.new(color.red, 70), 'Box Infill', inline='box_prop', group='Session Time Range')
box_border_color = input.color(color.new(color.black, 70), 'Box Border', inline='box_prop', group='Session Time Range')
sess = input.session('1800-0101',"Session Timing", group='Session Time Range',tooltip = "Add one extra minute in session end time, otherwise it won't add last candle in time range. e.g. if your session timing is '12:00 - 13:00'\nset it as '12:00 - 13:01'")
show_hl_levels = input.bool(title='Show breakout Levels?', defval=true, group='Breakout Levels')
use_close = input.bool(title='Use close as breakout confirmation ?', defval=false, group='Breakout Levels')
br_line_color = input.color(color.new(color.red, 70), 'Breakout Line Color', group='Breakout Levels')
extend_upto = input.int(defval=5,title='Extend breakout lines (in hours) ',minval=2,maxval=10, group='Breakout Levels')
ind_style = input.string("Fixed","Breakout indicator style",options = ["Don't show","Fixed","Moving"], group='Breakout Levels')
use_method = input.string("Breakout", title = "Use as",options = ["Breakout","Liquidity sweep"], group='Breakout Levels')
alerts = input.string(defval = "No alerts",title="Alerts",options = ["No alerts","On first breakout","Every Time breakout happens"],group='Alerts')
show_day = input.bool(false,"Show previos day high low?",inline="day",group = "Previous Levels")
day_col = input.color(color.new(color.blue, 70),"",inline="day",group = "Previous Levels")
show_week = input.bool(false,"Show previos week high low?",inline="week",group = "Previous Levels")
week_col = input.color(color.new(color.green, 70),"",inline="week",group = "Previous Levels")
//--------------------------------- Functions --------------------------------------------------------------//
in_session(sess) =>
not na(time(timeframe.period, sess))
start_time(sess) =>
int startTime = na
startTime := in_session(sess) and not in_session(sess)[1] ? time : startTime[1]
startTime
is_new_session(res, sess) =>
t = time(res, sess)
na(t[1]) and not na(t) or t[1] < t
candle_count(tf, hours) =>
float candles = na
in_min = hours * 60
candles := in_min / tf
candles
//--------------------------------- Variavles --------------------------------------------------------------/
var int count = na
var float hv = na
var float lv = na
// ---- Verify Timeframe-----//
current_tf = str.tonumber(timeframe.period)
bool valid_tf = current_tf <= 45
// ---- Candle Count-----//
candles_far = int(candle_count(current_tf, extend_upto))
// ---- Time Range High Low -----//
float sess_low = na
float sess_high = na
float confirmed_low = na
float confirmed_high = na
session_started = is_new_session('1440', sess)
inside_sess = in_session(sess)
session_ended = inside_sess[1] and not(inside_sess)
sess_low := session_started ? low : in_session(sess) ? math.min(low, sess_low[1]) : na
sess_high := session_started ? high : in_session(sess) ? math.max(high, sess_high[1]) : na
confirmed_low := session_ended ? math.min(low, sess_low)[1] : na
confirmed_high := session_ended ? math.max(high, sess_high)[1] : na
dayHigh = request.security(syminfo.tickerid,"D",high[1])
dayLow = request.security(syminfo.tickerid,"D",low[1])
weekHigh = request.security(syminfo.tickerid,"W",high[1])
weekLow = request.security(syminfo.tickerid,"W",low[1])
// ---- Lines-----//
bullish_breakout_level = line(na)
bearish_breakout_level = line(na)
bull_br = line(na)
bear_br = line(na)
day_high = line(na)
day_low = line(na)
week_high = line(na)
week_low = line(na)
month_high = line(na)
month_low = line(na)
// ---- Breakout Level Coordinates-----//
time_diffrence = time - time[1]
x1_val = time[1]
x2_val = time + candles_far * time_diffrence
yl_val = confirmed_low
yh_val = confirmed_high
// ---- Box -----//
sess_box = box(na)
// ---- Label -----//
message = label(na)
//--------------------------------- Conditions --------------------------------------------------------------//
condition_1 = inside_sess and valid_tf
condition_2 = session_ended and valid_tf
sess_start_time = start_time(sess)
//--------------------------------- Draw box and Levels --------------------------------------------------------------//
if condition_1
if in_session(sess)[1]
box.delete(sess_box[1])
if low < sess_low
sess_low := low
confirmed_low := sess_low
confirmed_low
if high > sess_high
sess_high := high
confirmed_high := sess_high
confirmed_high
if show_session_box
sess_box := box.new(sess_start_time, sess_high, time, sess_low, xloc=xloc.bar_time, bgcolor= box_infil_color, border_color=box_border_color, border_style=line.style_solid)
sess_box
if barstate.islast and not valid_tf
message := label.new(x=bar_index + 2, y=close, style=label.style_label_left, size=size.large, color=#ffeecc, textcolor=color.black, text='Shift to lower Timeframe ( < 45 min )')
message
if condition_2
if show_hl_levels
bearish_breakout_level := line.new(x1_val, yl_val, x2_val, yl_val, xloc.bar_time, color=br_line_color)
bullish_breakout_level := line.new(x1_val, yh_val, x2_val, yh_val, xloc.bar_time, color=br_line_color)
if show_day
day_high := line.new(x1_val, dayHigh, x2_val, dayHigh, xloc.bar_time, color=day_col)
day_low := line.new(x1_val, dayLow, x2_val, dayLow, xloc.bar_time, color=day_col)
if show_week
week_high := line.new(x1_val, weekHigh, x2_val, weekHigh, xloc.bar_time, color=week_col)
week_low := line.new(x1_val, weekLow, x2_val, weekLow, xloc.bar_time, color=week_col)
if not(inside_sess) and inside_sess[1]
count:=0
hv:= yh_val
lv:= yl_val
crossover = use_method =="Breakout"?(use_close?close[1]>hv : ((high[1]>hv and open[1]<hv) or close[1]>hv)):(low[1]<lv and close[1]>lv)
crossunder =use_method =="Breakout"?( use_close? close[1]<lv :((low[1]<lv and open[1]>lv) or close[1]<lv)):(high[1]>hv and close[1]<hv)
if count!=0 and inside_sess
hv:=0
lv:=0
count:=0
if count==0 and not(inside_sess)
if crossover
count:= 1
if crossunder
count:= 2
bullish_breakout = (count[1]==0 and count==1) and show_hl_levels and valid_tf
bearish_breakout = (count[1]==0 and count==2) and show_hl_levels and valid_tf
br_st = ind_style == "Fixed"?1:(ind_style == "Moving"?2:0)
if bullish_breakout and br_st == 2
bull_br:=line.new(bar_index[1], low[1], bar_index[1], high[1],extend=extend.left, color=color.green, style = line.style_dotted,width=1)
if bearish_breakout and br_st == 2
bull_br:=line.new(bar_index[1], low[1], bar_index[1], high[1],extend=extend.right, color=color.red, style = line.style_dotted,width=1)
plotshape(bullish_breakout and br_st==2 ,"Bullish breakout",shape.labelup,location.bottom,text="⬆️",color = color.new(color.white,100),size=size.tiny,offset = -1)
plotshape(bearish_breakout and br_st==2 ,"Bearishbreakout",shape.labeldown,location.top,text="⬇️",color = color.new(color.white,100),size=size.tiny,offset = -1)
plotshape(bullish_breakout and br_st==1 ,"Bullish breakout",shape.triangleup,location.belowbar,color = color.new(color.green,0),size=size.tiny,offset = -1)
plotshape(bearish_breakout and br_st==1 ,"Bearish breakout",shape.triangledown,location.abovebar,color = color.new(color.red,0),size=size.tiny,offset = -1)
bull_alert = alerts=="On first breakout"?bullish_breakout:(alerts=="Every Time breakout happens"?crossover:false)
bear_alert = alerts=="On first breakout"?bearish_breakout:(alerts=="Every Time breakout happens"?crossunder:false)
if bull_alert
alert("Bullish breakout on "+str.tostring(syminfo.tickerid), alert.freq_once_per_bar)
if bear_alert
alert("Bearish breakout on "+str.tostring(syminfo.tickerid), alert.freq_once_per_bar)
|
CNTLibrary | https://www.tradingview.com/script/2w52iGBh-CNTLibrary/ | CN_FX-999 | https://www.tradingview.com/u/CN_FX-999/ | 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/
// © CN_FX-999
// Coded By Christian Nataliano
// First Coded In 10/06/2023
// Last Edited In 02/08/2023
// Huge Shout Out To © ZenAndTheArtOfTrading and his ZenLibrary V5, Some Of The Custom Functions Were Heavlily Inspired By Matt's Work & His Pine Script Mastery Course
// Another Shout Out To The TradingView's Team Library ta V5
//@version=5
// @description Custom Functions To Help Code In Pinescript V5
library("CNTLibrary")
//Import Refrance Libraries
import TradingView/ta/5 as Tv
//======================================================================================================================================================================
// Custom Indicator Functions
//======================================================================================================================================================================
//== Calculate Kaufman's Adaptive Moving Average ==
// @function Calculates An Adaptive Moving Average Based On Perry J Kaufman's Calculations
// @param KAMA_lenght Is The KAMA Lenght
// @param Fast_KAMA Is The KAMA's Fastes Moving Average
// @param Slow_KAMA Is The KAMA's Slowest Moving Average
// @returns Float Of The KAMA's Current Calculations
export GetKAMA(int KAMA_lenght, int Fast_KAMA, int Slow_KAMA) =>
//Efficiency Ratio
Fast_Trend = 2 / (Fast_KAMA + 1)
Slow_Trend = 2 / (Slow_KAMA + 1)
Difference = math.abs(close - close[1])
Signal = math.abs(close - close[KAMA_lenght])
Noise = math.sum(Difference,KAMA_lenght)
ER = 1.0
if(Noise != 0)
ER := Signal/Noise
//Smoothing Constant
Smoothing_Const = math.pow(ER * (Fast_Trend-Slow_Trend) + Slow_Trend,2)
//KAMA Indicator
KAMA = 1.0
if barstate.isfirst
KAMA := close
else
KAMA := KAMA[1] + Smoothing_Const * (close - KAMA[1])
KAMA
//== Get Custom Moving Average Values ==
// @function Get Custom Moving Averages Values
// @param Source Of The Moving Average, Defval = close
// @param Lenght Of The Moving Average, Defval = 50
// @param Type Of The Moving Average, Defval = Exponential Moving Average
// @returns The Moving Average Calculation Based On Its Given Source, Lenght & Calculation Type (Please Call Function On Global Scope)
export GetMovingAverage(float Source = close, simple int Lenght = 50, string Type = "") =>
//Moving Average Export Value
float MovingAverage = 0
//Moving Average Type
MAValue = switch Type
"EMA" => ta.ema(Source,Lenght)
"SMA" => ta.sma(Source,Lenght)
"WMA" => ta.wma(Source,Lenght)
"RMA" => ta.rma(Source,Lenght)
"HMA" => ta.hma(Source,Lenght)
"VWMA" => ta.vwma(Source,Lenght)
"SWMA" => ta.swma(Source)
"VWAP" => ta.vwap
"DEMA" =>
e1 = ta.ema(Source,Lenght)
e2 = ta.ema(e1,Lenght)
2 * e1 - e2
=> ta.ema(Source,Lenght)
MovingAverage := MAValue
//== Get Decimals ==
// @function Calculates how many decimals are on the quote price of the current market © ZenAndTheArtOfTrading
// @returns The current decimal places on the market quote price
export GetDecimals() => math.abs(math.log(syminfo.mintick) / math.log(10))
//== Truncate Number ==
// @function Truncates (cuts) excess decimal places © ZenAndTheArtOfTrading
// @param float number The number to truncate
// @param float decimalPlaces (default=2) The number of decimal places to truncate to
// @returns The given number truncated to the given decimalPlaces
export Truncate(float number, simple float decimalPlaces = 2.0) =>
factor = math.pow(10, decimalPlaces)
int(number * factor) / factor
//== Convert To Whole Number ==
// @function Converts pips into whole numbers © ZenAndTheArtOfTrading
// @param float number The pip number to convert into a whole number
// @returns The converted number
export ToWhole(float number) =>
_return = number < 1.0 ? number / syminfo.mintick / (10 / syminfo.pointvalue) : number
_return := number >= 1.0 and number <= 100.0 ? _return * 100 : _return
//== Convert To Pips ==
// @function Converts whole numbers back into pips © ZenAndTheArtOfTrading
// @param float number The whole number to convert into pips
// @returns The converted number
export ToPips(float number) =>
number * syminfo.mintick * 10
//== Get Precentage Change
// @function Gets the percentage change between 2 float values over a given lookback period © ZenAndTheArtOfTrading
// @param float value1 The first value to reference
// @param float value2 The second value to reference
// @param int lookback The lookback period to analyze
export GetPctChange(float value1, float value2, int lookback) =>
vChange = value1 - value2
vDiff = vChange - vChange[lookback]
(vDiff / vChange) * 100
//== Prev Bars Above MA ==
// @function Counts how many candles are above the MA © ZenAndTheArtOfTrading
// @param int lookback The lookback period to look back over
// @param float ma The moving average to check
// @returns The bar count of how many recent bars are above the MA
export BarsAboveMA(int lookback, float ma) =>
counter = 0
for i = 1 to lookback by 1
if close[i] > ma[i]
counter := counter + 1
counter
//== Prev Bars Below MA ==
// @function Counts how many candles are below the MA © ZenAndTheArtOfTrading
// @param int lookback The lookback period to look back over
// @param float ma The moving average to reference
// @returns The bar count of how many recent bars are below the EMA
export BarsBelowMA(int lookback, float ma) =>
counter = 0
for i = 1 to lookback by 1
if close[i] < ma[i]
counter := counter + 1
counter
//== Prev Bars That Crossed MA ==
// @function Counts how many times the EMA was crossed recently © ZenAndTheArtOfTrading
// @param int lookback The lookback period to look back over
// @param float ma The moving average to reference
// @returns The bar count of how many times price recently crossed the EMA
export BarsCrossedMA(int lookback, float ma) =>
counter = 0
for i = 1 to lookback by 1
if open[i] > ma and close[i] < ma or open[i] < ma and close[i] > ma
counter := counter + 1
counter
//== Get Prev Pullback Bar Count ==
// @function Counts how many green & red bars have printed recently (ie. pullback count) © ZenAndTheArtOfTrading
// @param int lookback The lookback period to look back over
// @param int direction The color of the bar to count (1 = Green, -1 = Red)
// @returns The bar count of how many candles have retraced over the given lookback & direction
export GetPullbackBarCount(int lookback, int direction) =>
recentCandles = 0
for i = 1 to lookback by 1
if direction == 1 and close[i] > open[i] // Count green bars
recentCandles := recentCandles + 1
if direction == -1 and close[i] < open[i] // Count red bars
recentCandles := recentCandles + 1
recentCandles
//== Calculate Last Swing High ==
// @function Check If Price Has Made A Recent Swing High
// @param Lookback Is For The Swing High Lookback Period, Defval = 7
// @param SwingType Is For The Swing High Type Of Identification, Defval = 1
// @returns A Bool - True If Price Has Made A Recent Swing High
export GetSwingHigh(int Lookback = 7, int SwingType = 1) =>
bool SwingHigh = false
HighestHigh = high[0] == ta.highest(Lookback)
NewSwingHigh = switch SwingType
1 => HighestHigh[0]
2 => HighestHigh[0] or HighestHigh[1]
3 => HighestHigh[0] or HighestHigh[1] or HighestHigh[2]
=> HighestHigh[0]
SwingHigh := NewSwingHigh
//== Calculate Last Swing Low ==
// @function Check If Price Has Made A Recent Swing Low
// @param Lookback Is For The Swing Low Lookback Period, Defval = 7
// @param SwingType Is For The Swing Low Type Of Identification, Defval = 1
// @returns A Bool - True If Price Has Made A Recent Swing Low
export GetSwingLow(int Lookback = 7, int SwingType = 1) =>
bool SwingLow = false
LowestLow = low[0] == ta.lowest(Lookback)
NewSwingLow = switch SwingType
1 => LowestLow[0]
2 => LowestLow[0] or LowestLow[1]
3 => LowestLow[0] or LowestLow[1] or LowestLow[2]
=> LowestLow[0]
SwingLow := NewSwingLow
//======================================================================================================================================================================
// Custom Risk Management Functions
//======================================================================================================================================================================
//== Calculate StopLoss Level ==
// @function Calculate StopLoss Level
// @param OrderType Is To Determine A Long / Short Position, Defval = 1
// @param Entry Is The Entry Level Of The Order, Defval = na
// @param StopLoss Is The Custom StopLoss Distance, Defval = 2x ATR Below Close
// @returns Float - The StopLoss Level In Actual Price As A
export CalculateStopLossLevel(int OrderType = 1, float Entry = na, float StopLoss = na) =>
//Stop Loss Export & ATR Value
float StopLossLevel = na
ATR = ta.atr(20)
//Calculate Inputed SL Level
if(not na(Entry) and not na(StopLoss))
if(OrderType == 1)
StopLossLevel := Entry - StopLoss
else if (OrderType == -1)
StopLossLevel := Entry + StopLoss
else
StopLossLevel := na
//Calculate Default SL Level
else
ATR_SL = ATR * 2
if(OrderType == 1)
StopLossLevel := close[0] - ATR_SL
else if (OrderType == -1)
StopLossLevel := close[0] + ATR_SL
else
StopLossLevel := na
StopLossLevel
//== Calculate StopLoss Distance ==
// @function Calculate StopLoss Distance In Pips
// @param OrderType Is To Determine A Long / Short Position, Defval = 1
// @param Entry Is The Entry Level Of The Order, NEED TO INPUT PARAM
// @param StopLoss Level Based On Previous Calculation, NEED TO INPUT PARAM
// @returns Float - The StopLoss Value In Pips
export CalculateStopLossDistance(int OrderType = 1, float Entry, float StopLoss) =>
//Stop Loss Export Value
float StopLossDistance = na
//Calculate Inputed SL Level
if(not na(Entry) and not na(StopLoss))
if(OrderType == 1)
StopLossDistance := Entry - StopLoss
else if (OrderType == -1)
StopLossDistance := StopLoss - Entry
else
StopLossDistance := na
StopLossDistance
//== Calculate TakeProfit Level ==
// @function Calculate TakeProfit Level
// @param OrderType Is To Determine A Long / Short Position, Defval = 1
// @param Entry Is The Entry Level Of The Order, Defval = na
// @param TakeProfit Is The Custom TakeProfit Distance, Defval = 1 RRR Distance
// @returns Float - The TakeProfit Level In Actual Price
export CalculateTakeProfitLevel(int OrderType = 1, float Entry = na, float StopLossDistance = na, float RiskReward = na) =>
//Stop Loss Export & ATR Value
float TakeProfitLevel = na
ATR = ta.atr(20)
//Calculate Inputed SL Level
if(not na(Entry) and not na(StopLossDistance) and not na(RiskReward))
if(OrderType == 1)
TakeProfitLevel := Entry + (StopLossDistance * RiskReward)
else if (OrderType == -1)
TakeProfitLevel := Entry - (StopLossDistance * RiskReward)
else
TakeProfitLevel := na
//Calculate Default SL Level
else
ATR_SL = ATR * 2
if(OrderType == 1)
SLDistance = close[0] - (close[0] - ATR_SL)
TakeProfitLevel := close[0] + (SLDistance * 1)
else if (OrderType == -1)
SLDistance = (close[0] + ATR_SL) - close[0]
TakeProfitLevel := close[0] - (SLDistance * 1)
else
TakeProfitLevel := na
TakeProfitLevel
//== Calculate Take Profit Distance ==
// @function Get TakeProfit Distance In Pips
// @param OrderType Is To Determine A Long / Short Position, Defval = 1
// @param Entry Is The Entry Level Of The Order, NEED TO INPUT PARAM
// @param TakeProfit Level Based On Previous Calculation, NEED TO INPUT PARAM
// @returns Float - The TakeProfit Value In Pips
export CalculateTakeProfitDistance(int OrderType = 1, float Entry, float TakeProfit) =>
//Stop Loss Export Value
float TakeProfitDistance = na
//Calculate Inputed SL Level
if(not na(Entry) and not na(TakeProfit))
if(OrderType == 1)
TakeProfitDistance := TakeProfit - Entry
else if (OrderType == -1)
TakeProfitDistance := Entry - TakeProfit
else
TakeProfitDistance := na
TakeProfitDistance
//== Calculate Conversion Currency ==
// @function Get The Conversion Currecny Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
// @param AccountCurrency Is For The Account Currency Used
// @param SymbolCurrency Is For The Current Symbol Currency (Front Symbol)
// @param BaseCurrency Is For The Current Symbol Base Currency (Back Symbol)
// @returns Tuple Of A Bollean (Convert The Currency ?) And A String (Converted Currency)
export CalculateConversionCurrency(simple string AccountCurrency, simple string SymbolCurrency, simple string BaseCurrency) =>
AccountSameAsSymbol = AccountCurrency == SymbolCurrency
AccountSameAsBase = AccountCurrency == BaseCurrency
AccountNeither = not AccountSameAsSymbol and not AccountSameAsBase
ConversionCurrency = AccountSameAsBase ? syminfo.tickerid:AccountCurrency + SymbolCurrency
ConvertCurrency = AccountSameAsBase or AccountNeither
[ConvertCurrency,ConversionCurrency]
//== Calculate Conversion Currency Rate ==
// @function Get The Conversion Rate Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
// @param ConvertCurrency Is To Check If The Current Symbol Needs To Be Converted Or Not
// @param ConversionRate Is The Quoted Price Of The Conversion Currency (Input The request.security Function Here)
// @returns Float Price Of Conversion Rate (If In The Same Currency Than Return Value Will Be 1.0)
export CalculateConversionRate(bool ConvertCurrency, float ConversionRate) => ConversionCurrencyRate = ConvertCurrency ? ConversionRate:1.0
//== Calculate Lot Sizing ==
// @function Get Current Lot Size
// @param LotSizeSimple Is To Toggle Lot Sizing Calculation (Simple Is Good Enough For Stocks & Crypto, Whilst Complex Is For Forex)
// @param Balance Is For The Current Account Balance To Calculate The Lot Sizing Based Off
// @param Risk Is For The Current Risk Per Trade To Calculate The Lot Sizing Based Off
// @param SLDistance Is The Current Position StopLoss Distance From Its Entry Price
// @param ConversionRate Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
// @returns Float - Position Size In Units
export LotSize(bool LotSizeSimple = false, float Balance = 100000, float Risk = 1, float SLDistance, float ConversionRate = 0) =>
float LotSize = na
//Simple Lot Sizing
if((LotSizeSimple and ConversionRate == 0) or syminfo.type != "forex")
LotSize := math.floor((Balance * (Risk / 100)) / (SLDistance))
//Complex (FOREX) Lot Sizing
else if(not LotSizeSimple and ConversionRate != 0 and syminfo.type == "forex")
RiskPerTrade = (Risk / 100) * Balance * ConversionRate
SLDistance_Points = ToWhole(SLDistance) * 10
RiskPerPoint = SLDistance_Points * syminfo.pointvalue
LotSize := math.round(RiskPerTrade / RiskPerPoint / syminfo.mintick)
//Adjust LotSizing To Lots / Units
LotSize := LotSize
//== Convert Units To Lots ==
// @function Converts Units To Lots
// @param Units Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
// @returns Float - Position Size In Lots
export ToLots(float Units) => UnitsToLots = math.round(Units / 100000,2)
//== Convert Lots To Units ==
// @function Converts Lots To Units
// @param Lots Is For How Many Lots Need To Be Converted Into Units (Minimun 0.01 Units)
// @returns Int - Position Size In Units
export ToUnits(float Lots) => LotsToUnits = math.round(Lots * 100000,0)
//== Convert Units To Lots To Units ==
// @function Converts Units To Lots Than Back To Units
// @param Units Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
// @returns Float - Position Size In Lots That Were Rounded To Units
export ToLotsInUnits(float Units) => UnitsToLots = math.round(Units / 100000,2) * 100000
//== Calculate ATR Trailing Stop ==
// @function Calculate ATR Trailing Stop
// @param OrderType Is To Determine A Long / Short Position, Defval = 1
// @param SourceType Is To Determine Where To Calculate The ATR Trailing From, Defval = close
// @param ATRPeriod Is To Change Its ATR Period, Defval = 20
// @param ATRMultiplyer Is To Change Its ATR Trailing Distance, Defval = 1
// @param SwingLookback Is To Change Its Swing HiLo Lookback (Only From Source Type 5), Defval = 7
// @returns Float - Number Of The Current ATR Trailing
export ATRTrail(int OrderType = 1, int SourceType = 4,simple int ATRPeriod = 20, float ATRMultiplyer = 1, int SwingLookback = 7) =>
ATR = ta.atr(ATRPeriod) * ATRMultiplyer
SwingLow = ta.lowest(SwingLookback)
SwingHigh = ta.highest(SwingLookback)
float ATRTrailing = na
float NewATRTrailing = switch SourceType
1 => OrderType == 1 ? open - ATR : OrderType == -1 ? open + ATR : na
2 => OrderType == 1 ? high - ATR : OrderType == -1 ? high + ATR : na
3 => OrderType == 1 ? low - ATR : OrderType == -1 ? low + ATR : na
4 => OrderType == 1 ? close - ATR : OrderType == -1 ? close + ATR : na
5 => OrderType == 1 ? SwingLow - ATR : OrderType == -1 ? SwingHigh + ATR : na
=> OrderType == 1 ? close - ATR : OrderType == -1 ? close + ATR : na
ATRTrailing := NewATRTrailing
//== Calculate Danger Zone ==
// @function Calculate Danger Zone Of A Given Strategy
// @param WinRate Is The Strategy WinRate
// @param AvgRRR Is The Strategy Avg RRR
// @param Filter Is The Minimum Profit It Needs To Be Out Of BE Zone, Defval = 3
// @returns Int - Value, 1 If Out Of Danger Zone, 0 If BE, -1 If In Danger Zone
export DangerZone(float WinRate, float AvgRRR, float Filter = 3) =>
LossTrades = 100 - WinRate
WinTrades = WinRate * AvgRRR
DangerZone = WinTrades - LossTrades > Filter ? 1 : WinTrades - LossTrades < (Filter * -1) ? -1 : 0
//== Check For Questionable Trades ==
// @function Checks For Questionable Trades (Which Are Trades That Its TP & SL Level Got Hit At The Same Candle)
// @param TradeTP Is The Trade In Question Take Profit Level
// @param TradeSL Is The Trade In Question Stop Loss Level
// @returns Bool - True If The Last Trade Was A "Questionable Trade"
export IsQuestionableTrades(float TradeTP, float TradeSL) =>
PrevBuyTrade = strategy.position_size[0] == 0 and strategy.position_size[1] > 0
PrevSellTrade = strategy.position_size[0] == 0 and strategy.position_size[1] < 0
BuyTPSL = PrevBuyTrade and high[0] > TradeTP[1] and low < TradeSL[1]
SellTPSL = PrevSellTrade and high[0] > TradeSL[1] and low < TradeTP[1]
QuestionableTrades = BuyTPSL or SellTPSL ? true:false
//======================================================================================================================================================================
// Custom Strategy Functions
//======================================================================================================================================================================
//== Strategy Open Long ==
// @function Open A Long Order Based On The Given Params
// @param EntryID Is The Trade Entry ID, Defval = "Long"
// @param LotSize Is The Lot Size Of The Trade, Defval = 1
// @param LimitPrice Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
// @param StopPrice Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
// @param Comment Is The Order Comment, Defval = Long Entry Order
// @param CommentValue Is For Custom Values In The Order Comment, Defval = Na
// @returns Void
export OpenLong(string EntryID = "Long", float LotSize = 1, float LimitPrice = na, float StopPrice = na, string Comment = "Long Entry Order", string CommentValue = "") =>
strategy.entry(id = EntryID, direction = strategy.long, qty = LotSize, limit = LimitPrice, stop = StopPrice, comment = Comment + CommentValue)
//== Strategy Open Short ==
// @function Open A Short Order Based On The Given Params
// @param EntryID Is The Trade Entry ID, Defval = "Short"
// @param LotSize Is The Lot Size Of The Trade, Defval = 1
// @param LimitPrice Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
// @param StopPrice Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
// @param Comment Is The Order Comment, Defval = Short Entry Order
// @param CommentValue Is For Custom Values In The Order Comment, Defval = Na
// @returns Void
export OpenShort(string EntryID = "Short", float LotSize = 1, float LimitPrice = na, float StopPrice = na, string Comment = "Short Entry Order", string CommentValue = "") =>
strategy.entry(id = EntryID, direction = strategy.short, qty = LotSize, limit = LimitPrice, stop = StopPrice, comment = Comment + CommentValue)
//== Strategy Exit By TP / SL ==
// @function Exits Based On Predetermined TP & SL Levels
// @param FromID Is The Trade ID That The TP & SL Levels Be Palced
// @param TPLevel Is The Take Profit Level
// @param SLLevel Is The StopLoss Level
// @param PercentageClose Is The Amount To Close The Order At (In Percentage) Defval = 100
// @param Comment Is The Order Comment, Defval = Exit Order
// @param CommentValue Is For Custom Values In The Order Comment, Defval = Na
// @returns Void
export TP_SLExit(string FromID, float TPLevel, float SLLevel, float PercentageClose = 100, string Comment = "Exit Order", string CommentValue = "") =>
strategy.exit(id = TPLevel > SLLevel ? "Long Exit":"Short Exit", from_entry = FromID, limit = TPLevel, stop = SLLevel, qty_percent = PercentageClose, comment = Comment + CommentValue)
//== Strategy Exit Long On Condition ==
// @function Exits A Long Order Based On A Specified Condition
// @param ExitID Is The Trade ID That Will Be Closed, Defval = "Long"
// @param PercentageClose Is The Amount To Close The Order At (In Percentage) Defval = 100
// @param Comment Is The Order Comment, Defval = Exit Order
// @param CommentValue Is For Custom Values In The Order Comment, Defval = Na
// @param Instant Is For Exit Execution Type, Defval = false
// @returns Void
export CloseLong(string ExitID = "Long", float PercentageClose = 100, string Comment = "Long Exit Order", string CommentValue = "", bool Instant = false) =>
strategy.close(id = ExitID, qty_percent = PercentageClose, comment = Comment + CommentValue, immediately = Instant)
//== Strategy Exit Short On Condition ==
// @function Exits A Short Order Based On A Specified Condition
// @param ExitID Is The Trade ID That Will Be Closed, Defval = "Short"
// @param PercentageClose Is The Amount To Close The Order At (In Percentage) Defval = 100
// @param Comment Is The Order Comment, Defval = Exit Order
// @param CommentValue Is For Custom Values In The Order Comment, Defval = Na
// @param Instant Is For Exit Execution Type, Defval = false
// @returns Void
export CloseShort(string ExitID = "Short", float PercentageClose = 100, string Comment = "Short Exit Order", string CommentValue = "", bool Instant = false) =>
strategy.close(id = ExitID, qty_percent = PercentageClose, comment = Comment + CommentValue, immediately = Instant)
//== Broker Check ==
// @function Checks Traded Broker With Current Loaded Chart Broker
// @param Broker Is The Current Broker That Is Traded
// @returns Bool - True If Current Traded Broker Is Same As Loaded Chart Broker
export BrokerCheck(string Broker) => SameBroker = str.contains(syminfo.tickerid,Broker)
//== Pine Connector Open Position ==
// @function Compiles Given Parameters Into An Alert String Format To Open Trades Using Pine Connector
// @param LicenseID Is The Users PineConnector LicenseID
// @param OrderType Is The Desired OrderType To Open
// @param UseLimit Is If We Want To Enter Using A Limit Order
// @param UseStop Is If We Want To Enter Using A Stop Order
// @param Price Is The Limit Price Of The Trade (Only For Pending Orders)
// @param SymbolPrefix Is The Current Symbol Prefix (If Any)
// @param Symbol Is The Traded Symbol
// @param SymbolSuffix Is The Current Symbol Suffix (If Any)
// @param Risk Is The Trade Risk Per Trade / Fixed Lot Sizing
// @param SL Is The Trade SL In Price / In Pips
// @param TP Is The Trade TP In Price / In Pips
// @param OrderComment Is The Executed Trade Comment
// @param Spread is The Maximum Spread For Execution
// @returns String - Pine Connector Order Syntax Alert Message
export OpenPC(string LicenseID, int OrderType, bool UseLimit, bool UseStop, float Price, string SymbolPrefix, string Symbol, string SymbolSuffix, float Risk, float SL, float TP, string OrderComment, float Spread) =>
MarketOrder = OrderType == 1 ? "buy" : OrderType == -1 ? "sell" : na
PendingOrder = UseLimit ? MarketOrder + "limit" : UseStop ? MarketOrder + "stop" : MarketOrder
StringOrderType = PendingOrder
PendingPrice = UseLimit or UseStop ? ",price=" + str.tostring(Truncate(Price,GetDecimals())) : ""
CurrentSymbol = SymbolPrefix + Symbol + SymbolSuffix
PCAlert = LicenseID + "," + StringOrderType + "," + CurrentSymbol + PendingPrice + ",risk=" + str.tostring(Risk,'#.##') + ",sl=" + str.tostring(SL) + ",tp=" + str.tostring(TP) + ",comment=" + "\"" + OrderComment + "\"" + ",spread=" + str.tostring(Spread)
//== PineConnector Close Position ==
// @function Compiles Given Parameters Into An Alert String Format To Close Trades Using Pine Connector
// @param LicenseID Is The Users PineConnector LicenseID
// @param OrderType Is The Desired OrderType To Close
// @param SymbolPrefix Is The Current Symbol Prefix (If Any)
// @param Symbol Is The Traded Symbol
// @param SymbolSuffix Is The Current Symbol Suffix (If Any)
// @param OrderComment Is The Executed Trade Comment For Multi Strategy Implementation
// @returns String - Pine Connector Order Syntax Alert Message
export ClosePC(string LicenseID, int OrderType, string SymbolPrefix, string Symbol, string SymbolSuffix, string OrderComment = "")=>
StringOrderType = OrderType == 1 ? "closelong" : OrderType == -1 ? "closeshort" : na
CurrentSymbol = SymbolPrefix + Symbol + SymbolSuffix
AlertComment = OrderComment == "" ? na : ",comment=" + "\"" + OrderComment + "\""
PCAlert = LicenseID + "," + StringOrderType + "," + CurrentSymbol + AlertComment
//== PineConnector Cancel Position ==
// @function Compiles Given Parameters Into An Alert String Format To Cancel Trades Using Pine Connector
// @param LicenseID Is The Users PineConnector LicenseID
// @param OrderType Is The Desired OrderType To Close
// @param SymbolPrefix Is The Current Symbol Prefix (If Any)
// @param Symbol Is The Traded Symbol
// @param SymbolSuffix Is The Current Symbol Suffix (If Any)
// @param OrderComment Is The Executed Trade Comment For Multi Strategy Implementation
// @returns String - Pine Connector Order Syntax Alert Message
export CancelPC(string LicenseID, int OrderType, string SymbolPrefix, string Symbol, string SymbolSuffix, string OrderComment = "") =>
StringOrderType = OrderType == 1 ? "cancellong" : OrderType == -1 ? "cancelshort" : na
CurrentSymbol = SymbolPrefix + Symbol + SymbolSuffix
AlertComment = OrderComment == "" ? na : ",comment=" + "\"" + OrderComment + "\""
PCAlert = LicenseID + "," + StringOrderType + "," + CurrentSymbol + AlertComment
//======================================================================================================================================================================
// Custom Backtesting Calculation Functions
//======================================================================================================================================================================
//== Calculate Trade PNL ==
// @function Calculates Trade PNL Based On Entry, Eixt & Lot Size
// @param EntryPrice Is The Trade Entry
// @param ExitPrice Is The Trade Exit
// @param LotSize Is The Trade Sizing
// @param ConversionRate Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
// @returns Float - The Current Trade PNL
export CalculatePNL(float EntryPrice, float ExitPrice, float LotSize, float ConversionRate) => TradePNL = Truncate(Truncate((ExitPrice - EntryPrice) * LotSize,2) / ConversionRate,2)
//== Update Balance ==
// @function Updates The Previous Ginve Balance To The Next PNL
// @param PrevBalance Is The Previous Balance To Be Updated
// @param PNL Is The Current Trade PNL To Be Added
// @returns Float - The Current Updated PNL
export UpdateBalance(float PrevBalance, float PNL) => NewBalance = Truncate(PrevBalance + PNL,2)
//== Calculate Slippage & Commisions ==
// @function Calculates Random Slippage & Commisions Fees Based On The Parameters
// @param PNL Is The Current Trade PNL
// @param MaxRate Is The Upper Limit (In Percentage) Of The Randomized Fee
// @returns Float - A Percentage Fee Of The Current Trade PNL
export CalculateSlpComm(float PNL, float MaxRate = 0.025) =>
MaxRatePercent = MaxRate / 100
MinRatePercent = 0.005 / 100
RandomRate = math.random(MinRatePercent,MaxRate)
SlpComm = Truncate(math.abs(PNL * RandomRate))
//== Calculate & Than Update DD Statistics ==
// @function Calculates & Updates The DD Based On Its Given Parameters
// @param MaxBalance Is The Maximum Balance Ever Recorded
// @param Balance Is The Current Account Balance
// @returns Float - The Current Strategy DD
export UpdateDD(float MaxBalance, float Balance) => Drawdown = Truncate(((MaxBalance-Balance) / MaxBalance) * 100,2)
//== Calculate Total Trades, Long Trades, And Short Trades Win Rate ==
// @function Calculate The Total, Long & Short Trades Win Rate
// @param TotalTrades Are The Current Total Trades That The Strategy Has Taken
// @param LongID Is The Order ID Of The Long Trades Of The Strategy
// @param ShortID Is The Order ID Of The Short Trades Of The Strategy
// @returns Tuple Of Long WR%, Short WR%, Total WR%, Total Winning Trades, Total Losing Trades, Total Long Trades & Total Short Trades
export CalculateWR(int TotalTrades, string LongID, string ShortID) =>
//Declare Variables
LongTradeCount = 0
ShortTradeCount = 0
LongTradeWin = 0
LongTradeLoss = 0
ShortTradeWin = 0
ShortTradeLoss = 0
//Loop Through All Closed Trades
for i = 0 to TotalTrades
if strategy.closedtrades.entry_id(i - 1) == LongID
if strategy.closedtrades.profit(i - 1) > 0
LongTradeCount += 1
LongTradeWin += 1
else if strategy.closedtrades.profit(i - 1) < 0
LongTradeCount += 1
LongTradeLoss += 1
if strategy.closedtrades.entry_id(i - 1) == ShortID
if strategy.closedtrades.profit(i - 1) > 0
ShortTradeCount += 1
ShortTradeWin += 1
else if strategy.closedtrades.profit(i - 1) < 0
ShortTradeCount += 1
ShortTradeLoss += 1
//Calculate Each WR
LongWR = Truncate((LongTradeWin / LongTradeCount) * 100,2)
ShortWR = Truncate((ShortTradeWin / ShortTradeCount) * 100,2)
TotalWR = Truncate(((LongTradeWin + ShortTradeWin) / TotalTrades) * 100,2)
TotalWinTrades = LongTradeWin + ShortTradeWin
TotalLossTrades = TotalTrades - TotalWinTrades
[LongWR, ShortWR, TotalWR, TotalWinTrades, TotalLossTrades, LongTradeCount, ShortTradeCount]
//== Calculate The Avg RRR ==
// @function Calculates The Overall Strategy Avg Risk Reward Ratio
// @param WinTrades Are The Strategy Winning Trades
// @param LossTrades Are The Strategy Losing Trades
// @returns Float - The Average RRR Values
export CalculateAvgRRR(int WinTrades, int LossTrades) =>
AvgWinArray = array.new_float(WinTrades, 0)
AvgLossArray = array.new_float(LossTrades, 0)
for i = 0 to WinTrades + LossTrades
if strategy.closedtrades.profit(i - 1) > 0
array.push(AvgWinArray,strategy.closedtrades.profit(i - 1))
else if strategy.closedtrades.profit(i - 1) < 0
array.push(AvgLossArray,strategy.closedtrades.profit(i - 1))
AvgWin = array.avg(AvgWinArray)
AvgLoss = array.avg(AvgLossArray) * -1
AvgRRR = Truncate(AvgWin / AvgLoss,2)
//== Calculate CAGR ==
// @function Calculates The CAGR Over The Given Time Period © TradingView
// @param StartTime Is The Starting Time Of The Calculation
// @param StartPrice Is The Starting Price Of The Calculation
// @param EndTime Is The Ending Time Of The Calculation
// @param EndPrice Is The Ending Price Of The Calculation
// @returns Float - The CAGR Values
export CAGR(int StartTime, float StartPrice, int EndTime, float EndPrice) => Truncate(Tv.cagr(StartTime,StartPrice,EndTime,EndPrice) ,2)
//======================================================================================================================================================================
// Custom Plot Functions
//======================================================================================================================================================================
//== Modify Labels ==
// @function Edit / Delete Labels
// @param LabelID Is The ID Of The Selected Label
// @param X1 Is The X1 Coordinate IN BARINDEX Xloc
// @param Y1 Is The Y1 Coordinate IN PRICE Yloc
// @param Text Is The Text Than Wants To Be Written In The Label
// @param Color Is The Color Value Change Of The Label
// @param Color Is The Color Value Change Of The Label Text
// @param EditCondition Is The Edit Condition of The Line (Setting Location / Color)
// @param DeleteCondition Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
// @returns Void
export EditLabels(series label LabelID, int X1, float Y1, string Text, color Color, color TextColor, int EditCondition, bool DeleteCondition) =>
if(EditCondition == 1)
label.set_x(LabelID, X1)
label.set_y(LabelID, Y1)
else if(EditCondition == 2)
label.set_text(LabelID, Text)
else if(EditCondition == 3)
label.set_color(LabelID, Color)
else if(EditCondition == 4)
label.set_textcolor(LabelID, TextColor)
else if(DeleteCondition)
label.delete(LabelID[1])
//== Modify Lines ==
// @function Edit / Delete Lines
// @param LineID Is The ID Of The Selected Line
// @param X1 Is The X1 Coordinate IN BARINDEX Xloc
// @param Y1 Is The Y1 Coordinate IN PRICE Yloc
// @param X2 Is The X2 Coordinate IN BARINDEX Xloc
// @param Y2 Is The Y2 Coordinate IN PRICE Yloc
// @param Color Is The Color Value Change Of The Line
// @param EditCondition Is The Edit Condition of The Line (Setting Location / Color)
// @param DeleteCondition Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
// @returns Void
export EditLine(line LineID, int X1, float Y1, int X2, float Y2, color Color, int EditCondition, bool DeleteCondition) =>
if(EditCondition == 1)
line.set_x1(LineID, X1)
line.set_y1(LineID, Y1)
line.set_x2(LineID, X2)
line.set_y2(LineID, Y2)
else if(EditCondition == 2)
line.set_color(LineID, Color)
else if(DeleteCondition)
line.delete(LineID[1])
//======================================================================================================================================================================
// Custom Display Functions (Using Tables)
//======================================================================================================================================================================
//== Fill Table Function ==
// @function Filling The Selected Table With The Inputed Information
// @param TableID Is The Table ID That Wants To Be Edited
// @param Column Is The Current Column Of The Table That Wants To Be Edited
// @param Row Is The Current Row Of The Table That Wants To Be Edited
// @param Title Is The String Title Of The Current Cell Table
// @param Value Is The String Value Of The Current Cell Table
// @param BgColor Is The Selected Color For The Current Table
// @param TextColor Is The Selected Color For The Current Table
// @param ToolTip Is The ToolTip Of The Current Cell In The Table
// @returns Void
export FillTable(table TableID, int Column, int Row, string Title, string Value, color BgColor, color TextColor, string ToolTip) =>
CellText = Title + "\n" + Value
table.cell(table_id = TableID, column = Column, row = Row, text = CellText, bgcolor = BgColor, text_color = TextColor, tooltip = ToolTip)
//== Display Backtest Results Function ==
// @function Filling The Selected Table With The Inputed Information
// @param TableID Is The Table ID That Wants To Be Edited
// @param BgColor Is The Selected Color For The Current Table
// @param TextColor Is The Selected Color For The Current Table
// @param StartingBalance Is The Account Starting Balance
// @param DollarReturn Is The Account Dollar Reture
// @param TotalPips Is The Total Pips Gained / loss
// @param MaxDD Is The Maximum Drawdown Over The Backtesting Period
// @returns Void
export DisplayBTResults(table TableID, color BgColor, color TextColor, float StartingBalance, float Balance, float DollarReturn, float TotalPips, float MaxDD) =>
FillTable(TableID, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), BgColor, TextColor, "")
FillTable(TableID, 0, 1, "Win Rate:", str.tostring(Truncate(strategy.wintrades / strategy.closedtrades * 100)) + "%", BgColor, TextColor, "")
FillTable(TableID, 1, 0, "Starting Balance:", "$" + str.tostring(StartingBalance), BgColor, TextColor, "")
FillTable(TableID, 1, 1, "Ending Balance:", "$" + str.tostring(Truncate(Balance)), BgColor, TextColor, "")
FillTable(TableID, 2, 0, "Total Returns:", str.tostring((Truncate(DollarReturn))), BgColor, TextColor, "")
FillTable(TableID, 2, 1, "Total Pips:", (TotalPips > 0 ? "+" : "") + str.tostring(Truncate(TotalPips)), BgColor, TextColor, "")
FillTable(TableID, 3, 0, "Return In %:", (DollarReturn > 0 ? "+" : "") + str.tostring(Truncate(DollarReturn / StartingBalance * 100)) + "%", DollarReturn > 0 ? color.green : color.red, TextColor, "")
FillTable(TableID, 3, 1, "Max DD:", str.tostring(Truncate(MaxDD * 100)) + "%", color.red, TextColor, "")
//== Display Backtest Results Function Version 2==
// @function Filling The Selected Table With The Inputed Information
// @param TableID Is The Table ID That Wants To Be Edited
// @param BgColor Is The Selected Color For The Current Table
// @param TextColor Is The Selected Color For The Current Table
// @param TotalWR Is The Strategy Total WR In %
// @param QTCount Is The Strategy Questionable Trades Count
// @param LongWR Is The Strategy Total WR In %
// @param ShortWR Is The Strategy Total WR In %
// @param InitialCapital Is The Strategy Initial Starting Capital
// @param CumProfit Is The Strategy Ending Cumulative Profit
// @param CumFee Is The Strategy Ending Cumulative Fee (Based On Randomized Fee Assumptions)
// @param AvgRRR Is The Strategy Average Risk Reward Ratio
// @param MaxDD Is The Strategy Maximum DrawDown In Its Backtesting Period
// @param CAGR Is The Strategy Compounded Average GRowth In %
// @param MeanDD Is The Strategy Mean / Average Drawdown In The Backtesting Period
// @returns Void
export DisplayBTResultsV2(table TableID, color BgColor, color TextColor, float TotalWR, int QTCount, float LongWR, float ShortWR, float InitialCapital, float CumProfit, float CumFee, float AvgRRR, float MaxDD, float CAGR, float MeanDD) =>
//First Block
FillTable(TableID, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), BgColor, TextColor, "Questionable Trade Count : " + str.tostring(QTCount))
FillTable(TableID, 1, 0, "Total WR%:", str.tostring(TotalWR) + "%", DangerZone(TotalWR, AvgRRR) == 1 ? color.green:DangerZone(TotalWR, AvgRRR) == -1 ? color.red:color.orange, TextColor, "Total Trades Win Rate In %")
FillTable(TableID, 0, 1, "Long WR%:", str.tostring(LongWR) + "%", color.green, TextColor, "Long ONLY Trades Winning Rate In %")
FillTable(TableID, 1, 1, "Short WR%:", str.tostring(ShortWR) + "%", color.red, TextColor, "Short ONLY Trades Winning Rate In %")
//Second Block
FillTable(TableID, 2, 0, "Starting Balance:", "$" + str.tostring(InitialCapital), BgColor, TextColor, "Strategy Initial Starting Balance In Base Currency")
FillTable(TableID, 3, 0, "Return In %:", (CumProfit > 0 ? "+" : "") + str.tostring(Truncate(CumProfit / InitialCapital * 100)) + "%", CumProfit > 0 ? color.green:color.red, TextColor, "Strategy Total Returns In %")
FillTable(TableID, 2, 1, "Total Returns:", "$" + str.tostring(CumProfit), CumProfit > 0 ? color.green:color.red, TextColor, "Strategy Total Returns In Base Currency")
FillTable(TableID, 3, 1, "Total Fees:", "$" + str.tostring(CumFee), color.red, TextColor, "Total Approximate Slippage & Commisions Fees In Base Currency")
//Third Block
FillTable(TableID, 4, 0, "Avg RRR:", str.tostring(AvgRRR), DangerZone(TotalWR, AvgRRR) == 1 ? color.green:DangerZone(TotalWR, AvgRRR) == -1 ? color.red:color.orange, TextColor, "Average Risk Reward Ratio Of The Strategy")
FillTable(TableID, 5, 0, "MaxDD In %:", str.tostring(MaxDD) + "%", color.red, TextColor, "Max Draw Down Of The Current Strategy In %")
FillTable(TableID, 4, 1, "CAGR %:", (CAGR > 0 ? "+" : "") + str.tostring(CAGR) + "%", CAGR > 0 ? color.green:color.red, TextColor, "Compounded Average GRowth Of The Strategy In %")
FillTable(TableID, 5, 1, "CAGR/MeanDD :", str.tostring(Truncate(CAGR/MeanDD)), (CAGR/MeanDD) > 1 ? color.green:(CAGR/MeanDD) < -1 ?color.red:color.orange, TextColor, "Mean DD = " + str.tostring(MeanDD))
//======================================================================================================================================================================
// Custom Pattern Detection Functions
//======================================================================================================================================================================
//== Calculate Bullish Fibonacci Values ==
// @function Calculates A Bullish Fibonacci Value (From Swing Low To High) © ZenAndTheArtOfTrading
// @param PriceLow The Lowest Price Point
// @param PriceHigh The highest Price Point
// @param FibRatio The Fibonacci % Ratio To Calculate, Defval = 0.382
// @returns The Fibonacci Value Of The Given Ratio Between The Two Price Points
export BullFib(float priceLow, float priceHigh, float fibRatio = 0.382) => (priceLow - priceHigh) * fibRatio + priceHigh
//== Calculate Bearish Fibonacci Values ==
// @function Calculates A Bearish Fibonacci Value (From Swing High To Low) © ZenAndTheArtOfTrading
// @param PriceLow The Lowest Price Point
// @param PriceHigh The Highest Price Point
// @param FibRatio The Fibonacci % Ratio To Calculate
// @returns The Fibonacci Value Of The Given Ratio Between The Two Price Points
export BearFib(float priceLow, float priceHigh, float fibRatio = 0.382) => (priceHigh - priceLow) * fibRatio + priceLow
//== Calculate A Candle Body Size ==
// @function Gets The Current Candle Body Size IN POINTS © ZenAndTheArtOfTrading
// @returns The Current Candle Body Size IN POINTS
export GetBodySize() => math.abs(close - open) / syminfo.mintick
//== Calculate A Candle Upper Wick Size ==
// @function Gets The Current Candle Top Wick Size IN POINTS © ZenAndTheArtOfTrading
// @returns The Current Candle Top Wick Size IN POINTS
export GetTopWickSize() => math.abs(high - (close > open ? close : open)) / syminfo.mintick
//== Calculate A Candle Lower Wick Size ==
// @function Gets The Current Candle Bottom Wick Size IN POINTS © ZenAndTheArtOfTrading
// @returns The Current Candle Bottom Wick Size IN POINTS
export GetBottomWickSize() => math.abs((close < open ? close : open) - low) / syminfo.mintick
//== Calculate A Candle Body Percentage Size ==
// @function Gets The Current Candle Body Size As A Percentage Of Its Entire Size Including Its Wicks © ZenAndTheArtOfTrading
// @returns The Current Candle Body Size IN PERCENTAGE
export GetBodyPercent() => math.abs(open - close) / math.abs(high - low)
//== Calculate A Candle Upper Wick Percentage Size ==
// @function Gets The Current Top Wick Size As A Percentage Of Its Entire Body Size
// @returns Float - The Current Candle Top Wick Size IN PERCENTAGE
export GetTopWickPercent() => GetTopWickSize() / GetBodySize()
//== Calculate A Candle Lower Wick Percentage Size ==
// @function Gets The Current Bottom Wick Size As A Percentage Of Its Entire Bodu Size
// @returns Float - The Current Candle Bottom Size IN PERCENTAGE
export GetBottomWickPercent() => GetBottomWickSize() / GetBodySize()
//== Bullish Engulfing ==
// @function Checks If The Current Bar Is A Bullish Engulfing Candle
// @param Allowance To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bullsih Engulfing Pattern, Defval = na
// @param EngulfWick To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bullish Engulfing Candle
export BullishEC(int Allowance = 0, float RejectionWickSize = na, bool EngulfWick = false, bool NearSwings = true, int SwingLookBack = 10) =>
//Swing Low Detection
SwingLow = (low[0] == ta.lowest(SwingLookBack) or low[1] == ta.lowest(SwingLookBack)) or (not NearSwings)
//Engulfing Pattern Detection
Engulfing = open[1] > close[1] and open <= (close[1] + Allowance) and close >= (open[1] + Allowance)
//Also Check If Engulfing The Wick ?
Engulf_Wick = (close[0] > high[1] and open[0] < low[1]) or (not EngulfWick)
//Maximum Rejection Wick Size
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Bullish Engulfing
Bullish_Engulfing = Engulfing and Engulf_Wick and Rejection_Wick and SwingLow
Bullish_Engulfing
//== Bearish Engulfing ==
// @function Checks If The Current Bar Is A Bearish Engulfing Candle
// @param Allowance To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bearish Engulfing Pattern, Defval = na
// @param EngulfWick To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bearish Engulfing Candle
export BearishEC(int Allowance = 0, float RejectionWickSize = na, bool EngulfWick = false, bool NearSwings = true, int SwingLookBack = 10) =>
//Swing High Detection
SwingHigh = (high[0] == ta.highest(SwingLookBack) or high[1] == ta.highest(SwingLookBack)) or (not NearSwings)
//Engulfing Pattern Detection
Engulfing = open[1] < close[1] and open >= (close[1] - Allowance) and close <= (open[1] + Allowance)
//Also Check If Engulfing The Wick ?
Engulf_Wick = (close[0] < low[1] and open[0] > high[1]) or (not EngulfWick)
//Maximum Rejection Wick Size
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Bearish Engulfing
Bearish_Engulfing = Engulfing and Engulf_Wick and Rejection_Wick and SwingHigh
Bearish_Engulfing
//== Hammer Pattern ==
// @function Checks If The Current Bar Is A Hammer Candle
// @param Fib To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
// @param ColorMatch To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
// @param NearSwings To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
// @param ATRFilterCheck To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
// @param ATRPeriod To Change ATR Period Of The ATR Filter, Defval = 20
// @returns Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
export Hammer(float Fib = 0.382, bool ColorMatch = false, bool NearSwings = true, int SwingLookBack = 10, float ATRFilterCheck = 1, int ATRPeriod = 20) =>
//Swing HiLo & Lowest Body
SwingLow = (low[0] == ta.lowest(SwingLookBack)) or (not NearSwings)
LowestBody = (close > open ? open:close)
//ATR Filter Check
ATR = ta.atr(ATRPeriod)
CandleSize = high - low
ATRFilter = CandleSize >= (ATR * ATRFilterCheck)
//Color Match
ColorCandle = (not ColorMatch or close > open)
//Hammer Pattern
HammerPattern = LowestBody >= BullFib(low,high,Fib) and SwingLow and ATRFilter and ColorCandle
//== Stars Pattern ==
// @function Checks If The Current Bar Is A Hammer Candle
// @param Fib To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
// @param ColorMatch To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
// @param NearSwings To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
// @param ATRFilterCheck To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
// @param ATRPeriod To Change ATR Period Of The ATR Filter, Defval = 20
// @returns Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
export Star(float Fib = 0.382, bool ColorMatch = false, bool NearSwings = true, int SwingLookBack = 10, float ATRFilterCheck = 1, int ATRPeriod = 20) =>
//Swing HiLo & Lowest Body
SwingHigh = (high[0] == ta.highest(SwingLookBack)) or (not NearSwings)
HighestBody = (close > open ? close:open)
//ATR Filter Check
ATR = ta.atr(ATRPeriod)
CandleSize = high - low
ATRFilter = CandleSize >= (ATR * ATRFilterCheck)
//Color Match
ColorCandle = (not ColorMatch or close < open)
//Hammer Pattern
StarPattern = HighestBody <= BearFib(low,high,Fib) and SwingHigh and ATRFilter and ColorCandle
//== Doji Pattern ==
// @function Checks If The Current Bar Is A Doji Candle
// @param MaxWickSize To Specify The Maximum Lenght Of Its Upper & Lower Wick, Defval = 2
// @param MaxBodySize To Specify The Maximum Lenght Of Its Candle Body IN PERCENT, Defval = 0.05
// @param Doji Type To Specify The Type Of Doji That Want To Be Detected, Defval = Netral Doji
// @param NearSwings To Specify If We Want The Doji To Be Near A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Doji Candle
export Doji(float MaxWickSize = 2, float MaxBodySize = 0.05, int DojiType = 0, bool NearSwings = true, int SwingLookBack = 10) =>
//Swing HiLo
SwingHigh = (high[0] == ta.highest(SwingLookBack)) or (not NearSwings)
SwingLow = (low[0] == ta.lowest(SwingLookBack)) or (not NearSwings)
//Doji Detection
NetralDoji = GetTopWickSize() <= (GetBottomWickSize() * MaxWickSize) and GetBottomWickSize() <= (GetTopWickSize() * MaxWickSize) and GetBodyPercent() <= MaxBodySize
Dragonfly = GetTopWickSize() <= (GetBottomWickSize() * MaxWickSize) and GetBottomWickSize() >= (GetTopWickSize() * MaxWickSize) and GetBodyPercent() <= MaxBodySize
Gravestone = GetTopWickSize() >= (GetBottomWickSize() * MaxWickSize) and GetBottomWickSize() <= (GetTopWickSize() * MaxWickSize) and GetBodyPercent() <= MaxBodySize
//Export Value Doji
bool Doji_Candle = na
if(DojiType == 0)
Doji_Candle := NetralDoji
else if(DojiType == 1)
Doji_Candle := Dragonfly and SwingLow
else if(DojiType == -1)
Doji_Candle := Gravestone and SwingHigh
else
Doji_Candle := false
Doji_Candle
//== Bullish Harami Pattern ==
// @function Checks If The Current Bar Is A Bullish Harami Candle
// @param Allowance To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
// @param EngulfWick To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle
export BullishIB(int Allowance = 0, float RejectionWickSize = na, bool EngulfWick = false, bool NearSwings = true, int SwingLookBack = 10) =>
//Check Near Swing Low
SwingLow = (low[0] == ta.lowest(SwingLookBack) or low[1] == ta.lowest(SwingLookBack)) or (not NearSwings)
//Check Harami Candle
Harami = open[1] > close[1] and open[0] < close[0] and open >= (close[1] + Allowance) and close <= (open[1] + Allowance)
//Check Engulf Wick
Engulf_Wick = (open[1] > high[0] and close[1] < low[0]) or (not EngulfWick)
//Check Rejection Wick
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Check Bullish Harami
Bullish_Harami = Harami and Engulf_Wick and Rejection_Wick and SwingLow
Bullish_Harami
//== Bullish Harami Pattern Version 2==
// @function Checks If The Current Bar Is A Bullish Harami Candle
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
// @param IncludeBody To Specify If We Want The Pattern To Also Be "Inside" Its Previous Body Candle And Not Just HiLo Range, Defval = false
// @param ColorMatch To Have A Bullish & Bearish Variaton Similar To Bullish Engulfing, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle Version 2
export BullishIBV2(float RejectionWickSize = na, bool IncludeBody = false, bool ColorMatch = false,bool NearSwings = true, int SwingLookBack = 10) =>
//Check Near Swing Low
SwingLow = (low[0] == ta.lowest(SwingLookBack) or low[1] == ta.lowest(SwingLookBack)) or (not NearSwings)
//Check Harami Candle
Harami = high[1] > high[0] and low[1] < low[0]
//ColorMatch
BullBear = (open[1] > close[1] and open[0] < close[0]) or (not ColorMatch)
//Check If Use Body Calculation Instead
BodyCalculation = IncludeBody ? false : true
if IncludeBody and not BodyCalculation
HighestBody = open[0] > close[0] ? open[0] : close[0]
LowestBody = open[0] < close[0] ? open[0] : close[0]
PrevHighesttBody = open[1] > close[1] ? open[1] : close[1]
PrevLowestBody = open[1] < close[1] ? open[1] : close[1]
BodyCalculation := PrevHighesttBody >= HighestBody and PrevLowestBody <= LowestBody
//Check Rejection Wick
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Check Bullish Harami
Bullish_Harami = Harami and BullBear and BodyCalculation and Rejection_Wick and SwingLow
Bullish_Harami
//== Bearish Harami Pattern ==
// @function Checks If The Current Bar Is A Bullish Harami Candle
// @param Allowance To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
// @param EngulfWick To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle
export BearishIB(int Allowance = 0, float RejectionWickSize = na, bool EngulfWick = false, bool NearSwings = true, int SwingLookBack = 10) =>
//Check Near Swing High
SwingHigh = (high[0] == ta.highest(SwingLookBack) or high[1] == ta.highest(SwingLookBack)) or (not NearSwings)
//Check Bearish Harami
Harami = open[1] < close[1] and open[0] > close[0] and open <= (close[1] + Allowance) and close >= (open[1] + Allowance)
//Check Engulf Wick
Engulf_Wick = (open[1] < low[0] and close[1] > high[0]) or (not EngulfWick)
//Check Rejection Wick
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Check Bearish Harami
Bearish_Harami = Harami and Engulf_Wick and Rejection_Wick and SwingHigh
Bearish_Harami
//== Bearish Harami Pattern Version 2==
// @function Checks If The Current Bar Is A Bearish Harami Candle
// @param RejectionWickSize To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
// @param IncludeBody To Specify If We Want The Pattern To Also Be "Inside" Its Previous Body Candle And Not Just HiLo Range, Defval = false
// @param ColorMatch To Have A Bullish & Bearish Variaton Similar To Bullish Engulfing, Defval = false
// @param NearSwings To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
// @param SwingLookBack To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
// @returns Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle Version 2
export BearishIBV2(float RejectionWickSize = na, bool IncludeBody = false, bool ColorMatch = false,bool NearSwings = true, int SwingLookBack = 10) =>
//Check Near Swing High
SwingHigh = (high[0] == ta.highest(SwingLookBack) or high[1] == ta.highest(SwingLookBack)) or (not NearSwings)
//Check Harami Candle
Harami = high[1] > high[0] and low[1] < low[0]
//ColorMatch
BearBull = (open[1] < close[1] and open[0] > close[0]) or (not ColorMatch)
//Check If Use Body Calculation Instead
BodyCalculation = IncludeBody ? false : true
if IncludeBody and not BodyCalculation
HighestBody = open[0] > close[0] ? open[0] : close[0]
LowestBody = open[0] < close[0] ? open[0] : close[0]
PrevHighesttBody = open[1] > close[1] ? open[1] : close[1]
PrevLowestBody = open[1] < close[1] ? open[1] : close[1]
BodyCalculation := PrevHighesttBody >= HighestBody and PrevLowestBody <= LowestBody
//Check Rejection Wick
Rejection_Wick = (GetTopWickPercent() < RejectionWickSize and GetBottomWickPercent() < RejectionWickSize) or (na(RejectionWickSize))
//Check Bearish Harami
Bearish_Harami = Harami and BearBull and BodyCalculation and Rejection_Wick and SwingHigh
Bearish_Harami
//======================================================================================================================================================================
// Custom Time Functions
//======================================================================================================================================================================
//== Bar In Session Checker ==
// @function Determines if the current price bar falls inside the specified session © ZenAndTheArtOfTrading
// @param string sess The session to check
// @param bool useFilter (default=true) Whether or not to actually use this filter
// @returns A boolean - true if the current bar falls within the given time session
export BarInSession(simple string sess, bool useFilter = true) => na(time(timeframe.period, sess + ":1234567")) == false or not useFilter
//== Bar Out Of Session Checker ==
// @function Determines if the current price bar falls outside the specified session © ZenAndTheArtOfTrading
// @param string sess The session to check
// @param bool useFilter (default=true) Whether or not to actually use this filter
// @returns A boolean - true if the current bar falls outside the given time session
export BarOutSession(simple string sess, bool useFilter = true) => na(time(timeframe.period, sess + ":1234567")) or not useFilter
//== Date Checker ==
// @function Determines if this bar's time falls within date filter range © ZenAndTheArtOfTrading
// @param int startTime The UNIX date timestamp to begin searching from
// @param int endTime the UNIX date timestamp to stop searching from
// @returns A boolean - true if the current bar falls within the given dates
export DateFilter(int startTime, int endTime) => time >= startTime and time <= endTime
//== Get Day Of Week Function ==
// @function Checks if the current bar's day is in the list of given days to analyze © ZenAndTheArtOfTrading
// @param bool monday Should the script analyze this day? (true/false)
// @param bool tuesday Should the script analyze this day? (true/false)
// @param bool wednesday Should the script analyze this day? (true/false)
// @param bool thursday Should the script analyze this day? (true/false)
// @param bool friday Should the script analyze this day? (true/false)
// @param bool saturday Should the script analyze this day? (true/false)
// @param bool sunday Should the script analyze this day? (true/false)
// @returns A boolean - true if the current bar's day is one of the given days
export DayFilter(bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday, bool sunday) =>
dayofweek == dayofweek.monday and monday or
dayofweek == dayofweek.tuesday and tuesday or
dayofweek == dayofweek.wednesday and wednesday or
dayofweek == dayofweek.thursday and thursday or
dayofweek == dayofweek.friday and friday or
dayofweek == dayofweek.saturday and saturday or
dayofweek == dayofweek.sunday and sunday
//== Get Australian Session ==
// @function Checks If The Current Australian Forex Session In Running
// @returns Bool - True If Currently The Australian Session Is Running
export AUSSess() =>
var bool Australian_Session = na
if(str.tonumber(str.format_time(time,"HH","UTC+0")) == 21 and barstate.isconfirmed)
Australian_Session := true
if((str.tonumber(str.format_time(time,"HH","UTC+0")) == 6))
Australian_Session := false
Australian_Session
//== Get Asia Session ==
// @function Checks If The Current Asian Forex Session In Running
// @returns Bool - True If Currently The Asian Session Is Running
export ASIASess() =>
var bool Asian_Session = na
if(str.tonumber(str.format_time(time,"HH","UTC+0")) == 0 and barstate.isconfirmed)
Asian_Session := true
if((str.tonumber(str.format_time(time,"HH","UTC+0")) == 8))
Asian_Session := false
Asian_Session
//== Get European Session ==
// @function Checks If The Current European Forex Session In Running
// @returns Bool - True If Currently The European Session Is Running
export EURSess() =>
var bool European_Session = na
if(str.tonumber(str.format_time(time,"HH","UTC+0")) == 7 and barstate.isconfirmed)
European_Session := true
if((str.tonumber(str.format_time(time,"HH","UTC+0")) == 16))
European_Session := false
European_Session
//== Get US Session ==
// @function Checks If The Current US Forex Session In Running
// @returns Bool - True If Currently The US Session Is Running
export USSess() =>
var bool US_Session = na
if(str.tonumber(str.format_time(time,"HH","UTC+0")) == 12 and barstate.isconfirmed)
US_Session := true
if((str.tonumber(str.format_time(time,"HH","UTC+0")) == 21))
US_Session := false
US_Session
//== UNIX To Datetime ==
// @function Converts UNIX Time To Datetime
// @param Time Is The UNIX Time Input
// @param ConversionType Is The Datetime Output Format, Defval = DD-MM-YYYY
// @param TimeZone Is To Convert The Outputed Datetime Into The Specified Time Zone, Defval = Exchange Time Zone
// @returns String - String Of Datetime
export UNIXToDate(int Time, int ConversionType = 1, string TimeZone = na) =>
SelectedTimeZone = na(TimeZone) ? syminfo.timezone : TimeZone
ConvertedTime = switch ConversionType
1 => str.format_time(Time,"dd-MM-yyyy", SelectedTimeZone)
2 => str.format_time(Time,"MM-dd-yyyy", SelectedTimeZone)
3 => str.format_time(Time,"yyyy-MM-dd", SelectedTimeZone)
4 => str.format_time(Time,"dd-MM-yyyy HH:mm", SelectedTimeZone)
5 => str.format_time(Time,"MM-dd-yyyy HH:mm", SelectedTimeZone)
6 => str.format_time(Time,"yyyy-MM-ddd HH:mm", SelectedTimeZone)
7 => str.format_time(Time,"HH:mm:ss", SelectedTimeZone)
=> str.format_time(Time,"yyyy-MM-dd' 'HH:mm:ssZ", SelectedTimeZone)
ConvertedTime
//======================================================================================================================================================================
// End Of Library
//====================================================================================================================================================================== |
NewsEventsGbp | https://www.tradingview.com/script/m20TANXq-NewsEventsGbp/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the high impact news events on GBP. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("NewsEventsGbp")
// @function GBP high impact news date and time from 2015 to 2019
export gbpNews2015To2019() =>
array.from(
timestamp("2015-01-08T12:00:00"),
timestamp("2015-01-08T12:00:00"),
timestamp("2015-01-13T09:30:00"),
timestamp("2015-01-13T09:30:00"),
timestamp("2015-01-14T14:15:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-27T09:30:00"),
timestamp("2015-01-27T09:30:00"),
timestamp("2015-01-28T18:50:00"),
timestamp("2015-02-05T12:00:00"),
timestamp("2015-02-05T12:00:00"),
timestamp("2015-02-12T10:30:00"),
timestamp("2015-02-12T10:30:00"),
timestamp("2015-02-17T09:30:00"),
timestamp("2015-02-17T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-25T10:00:00"),
timestamp("2015-02-26T09:30:00"),
timestamp("2015-02-26T09:30:00"),
timestamp("2015-03-05T12:00:00"),
timestamp("2015-03-05T12:00:00"),
timestamp("2015-03-06T09:30:00"),
timestamp("2015-03-10T14:35:00"),
timestamp("2015-03-12T12:45:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-24T09:30:00"),
timestamp("2015-03-24T09:30:00"),
timestamp("2015-03-27T08:45:00"),
timestamp("2015-03-31T08:30:00"),
timestamp("2015-03-31T08:30:00"),
timestamp("2015-04-09T11:00:00"),
timestamp("2015-04-09T11:00:00"),
timestamp("2015-04-14T08:30:00"),
timestamp("2015-04-14T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-28T08:30:00"),
timestamp("2015-04-28T08:30:00"),
timestamp("2015-05-07T12:00:00"),
timestamp("2015-05-11T11:00:00"),
timestamp("2015-05-11T11:00:00"),
timestamp("2015-05-12T14:00:00"),
timestamp("2015-05-13T09:30:00"),
timestamp("2015-05-13T09:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-21T08:30:00"),
timestamp("2015-05-22T13:00:00"),
timestamp("2015-06-04T11:00:00"),
timestamp("2015-06-04T11:00:00"),
timestamp("2015-06-05T08:30:00"),
timestamp("2015-06-10T14:00:00"),
timestamp("2015-06-10T20:00:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-26T14:15:00"),
timestamp("2015-07-07T14:00:00"),
timestamp("2015-07-09T11:00:00"),
timestamp("2015-07-09T11:00:00"),
timestamp("2015-07-14T09:15:00"),
timestamp("2015-07-14T11:45:00"),
timestamp("2015-07-16T18:00:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:45:00"),
timestamp("2015-08-06T14:00:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-28T08:30:00"),
timestamp("2015-08-29T02:25:00"),
timestamp("2015-09-09T14:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-11T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-16T13:15:00"),
timestamp("2015-09-29T19:40:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T18:00:00"),
timestamp("2015-10-20T10:00:00"),
timestamp("2015-10-21T17:00:00"),
timestamp("2015-10-27T09:30:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:45:00"),
timestamp("2015-11-06T15:00:00"),
timestamp("2015-11-11T10:30:00"),
timestamp("2015-11-17T09:30:00"),
timestamp("2015-11-17T09:30:00"),
timestamp("2015-11-24T10:00:00"),
timestamp("2015-11-24T10:00:00"),
timestamp("2015-12-01T09:00:00"),
timestamp("2015-12-07T15:00:00"),
timestamp("2015-12-08T15:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T18:30:00"),
timestamp("2016-01-12T14:15:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-19T12:00:00"),
timestamp("2016-01-26T10:45:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:45:00"),
timestamp("2016-02-10T15:00:00"),
timestamp("2016-02-16T09:30:00"),
timestamp("2016-02-16T09:30:00"),
timestamp("2016-02-23T10:00:00"),
timestamp("2016-02-23T10:00:00"),
timestamp("2016-02-25T09:30:00"),
timestamp("2016-02-26T00:15:00"),
timestamp("2016-03-08T09:15:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-22T09:30:00"),
timestamp("2016-03-22T09:30:00"),
timestamp("2016-03-27T19:00:00"),
timestamp("2016-03-31T07:00:00"),
timestamp("2016-04-12T08:30:00"),
timestamp("2016-04-12T08:30:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-19T14:35:00"),
timestamp("2016-04-21T14:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:45:00"),
timestamp("2016-05-17T08:30:00"),
timestamp("2016-05-17T08:30:00"),
timestamp("2016-05-24T09:00:00"),
timestamp("2016-06-02T13:00:00"),
timestamp("2016-06-10T08:30:00"),
timestamp("2016-06-14T08:30:00"),
timestamp("2016-06-14T08:30:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T20:00:00"),
timestamp("2016-06-23T12:00:00"),
timestamp("2016-06-24T07:45:00"),
timestamp("2016-06-30T15:00:00"),
timestamp("2016-07-05T10:00:00"),
timestamp("2016-07-12T09:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-19T08:30:00"),
timestamp("2016-07-19T08:30:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:30:00"),
timestamp("2016-08-09T14:00:00"),
timestamp("2016-08-16T08:30:00"),
timestamp("2016-08-16T08:30:00"),
timestamp("2016-08-31T11:45:00"),
timestamp("2016-09-05T08:30:00"),
timestamp("2016-09-07T13:15:00"),
timestamp("2016-09-09T08:30:00"),
timestamp("2016-09-13T08:30:00"),
timestamp("2016-09-13T08:30:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-22T17:00:00"),
timestamp("2016-10-07T14:00:00"),
timestamp("2016-10-14T14:00:00"),
timestamp("2016-10-18T08:30:00"),
timestamp("2016-10-18T08:30:00"),
timestamp("2016-10-25T14:30:00"),
timestamp("2016-11-03T10:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:30:00"),
timestamp("2016-11-08T15:00:00"),
timestamp("2016-11-14T16:00:00"),
timestamp("2016-11-15T09:30:00"),
timestamp("2016-11-15T09:30:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-23T12:30:00"),
timestamp("2016-11-25T09:30:00"),
timestamp("2016-12-05T00:00:00"),
timestamp("2016-12-06T00:00:00"),
timestamp("2016-12-07T00:00:00"),
timestamp("2016-12-07T15:00:00"),
timestamp("2016-12-08T00:00:00"),
timestamp("2016-12-09T09:30:00"),
timestamp("2016-12-14T12:15:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2017-01-01T12:00:00"),
timestamp("2017-01-11T14:15:00"),
timestamp("2017-01-16T18:30:00"),
timestamp("2017-01-17T09:30:00"),
timestamp("2017-01-17T09:30:00"),
timestamp("2017-01-17T11:45:00"),
timestamp("2017-01-24T09:30:00"),
timestamp("2017-01-25T16:50:00"),
timestamp("2017-01-26T09:30:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:30:00"),
timestamp("2017-02-08T20:00:00"),
timestamp("2017-02-09T18:30:00"),
timestamp("2017-02-14T09:30:00"),
timestamp("2017-02-21T10:00:00"),
timestamp("2017-02-21T10:00:00"),
timestamp("2017-02-22T09:30:00"),
timestamp("2017-03-10T09:30:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-21T09:30:00"),
timestamp("2017-03-21T10:35:00"),
timestamp("2017-03-29T11:45:00"),
timestamp("2017-04-07T08:30:00"),
timestamp("2017-04-07T09:00:00"),
timestamp("2017-04-12T08:30:00"),
timestamp("2017-04-12T08:30:00"),
timestamp("2017-04-18T10:15:00"),
timestamp("2017-04-20T15:30:00"),
timestamp("2017-04-20T16:30:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:30:00"),
timestamp("2017-05-11T12:00:00"),
timestamp("2017-05-15T14:00:00"),
timestamp("2017-05-16T08:30:00"),
timestamp("2017-05-17T08:30:00"),
timestamp("2017-05-22T18:00:00"),
timestamp("2017-06-08T12:00:00"),
timestamp("2017-06-09T08:30:00"),
timestamp("2017-06-09T10:00:00"),
timestamp("2017-06-13T08:30:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-20T07:30:00"),
timestamp("2017-06-27T10:00:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-03T12:00:00"),
timestamp("2017-07-07T13:00:00"),
timestamp("2017-07-11T10:30:00"),
timestamp("2017-07-18T08:30:00"),
timestamp("2017-07-18T13:30:00"),
timestamp("2017-07-26T08:30:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:30:00"),
timestamp("2017-08-15T08:30:00"),
timestamp("2017-09-08T08:30:00"),
timestamp("2017-09-12T08:30:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-18T15:00:00"),
timestamp("2017-09-22T13:15:00"),
timestamp("2017-09-28T08:15:00"),
timestamp("2017-09-28T09:00:00"),
timestamp("2017-09-29T14:15:00"),
timestamp("2017-10-09T06:00:00"),
timestamp("2017-10-17T08:30:00"),
timestamp("2017-10-17T10:15:00"),
timestamp("2017-10-17T12:30:00"),
timestamp("2017-10-18T08:30:00"),
timestamp("2017-10-19T08:30:00"),
timestamp("2017-10-25T08:30:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:30:00"),
timestamp("2017-11-14T09:30:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-15T09:30:00"),
timestamp("2017-11-15T09:30:00"),
timestamp("2017-11-16T14:00:00"),
timestamp("2017-11-28T07:00:00"),
timestamp("2017-11-28T07:30:00"),
timestamp("2017-11-29T14:00:00"),
timestamp("2017-12-12T09:30:00"),
timestamp("2017-12-12T09:30:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-20T13:15:00"),
timestamp("2018-01-16T09:30:00"),
timestamp("2018-01-16T09:30:00"),
timestamp("2018-01-26T09:30:00"),
timestamp("2018-01-26T14:00:00"),
timestamp("2018-01-30T15:30:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:30:00"),
timestamp("2018-02-13T09:30:00"),
timestamp("2018-02-13T09:30:00"),
timestamp("2018-02-19T18:45:00"),
timestamp("2018-02-21T09:30:00"),
timestamp("2018-02-21T09:30:00"),
timestamp("2018-02-21T14:15:00"),
timestamp("2018-02-21T14:15:00"),
timestamp("2018-03-02T00:00:00"),
timestamp("2018-03-02T10:00:00"),
timestamp("2018-03-02T13:30:00"),
timestamp("2018-03-19T11:45:00"),
timestamp("2018-03-20T09:30:00"),
timestamp("2018-03-20T09:30:00"),
timestamp("2018-03-21T09:30:00"),
timestamp("2018-03-21T09:30:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-04-06T15:15:00"),
timestamp("2018-04-12T19:00:00"),
timestamp("2018-04-17T08:30:00"),
timestamp("2018-04-17T08:30:00"),
timestamp("2018-04-18T08:30:00"),
timestamp("2018-04-18T08:30:00"),
timestamp("2018-04-27T08:30:00"),
timestamp("2018-04-27T14:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:30:00"),
timestamp("2018-05-15T08:30:00"),
timestamp("2018-05-15T08:30:00"),
timestamp("2018-05-22T08:15:00"),
timestamp("2018-05-22T09:00:00"),
timestamp("2018-05-23T08:30:00"),
timestamp("2018-05-23T08:30:00"),
timestamp("2018-05-24T08:00:00"),
timestamp("2018-05-24T17:00:00"),
timestamp("2018-05-25T13:20:00"),
timestamp("2018-06-12T08:30:00"),
timestamp("2018-06-12T08:30:00"),
timestamp("2018-06-13T08:30:00"),
timestamp("2018-06-13T08:30:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T20:15:00"),
timestamp("2018-06-27T10:00:00"),
timestamp("2018-07-05T10:00:00"),
timestamp("2018-07-10T08:30:00"),
timestamp("2018-07-11T15:35:00"),
timestamp("2018-07-17T08:00:00"),
timestamp("2018-07-17T08:30:00"),
timestamp("2018-07-17T08:30:00"),
timestamp("2018-07-18T08:30:00"),
timestamp("2018-07-18T08:30:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:30:00"),
timestamp("2018-08-10T08:30:00"),
timestamp("2018-08-10T08:30:00"),
timestamp("2018-08-14T08:30:00"),
timestamp("2018-08-14T08:30:00"),
timestamp("2018-08-15T08:30:00"),
timestamp("2018-08-15T08:30:00"),
timestamp("2018-09-04T12:15:00"),
timestamp("2018-09-10T08:30:00"),
timestamp("2018-09-11T08:30:00"),
timestamp("2018-09-11T08:30:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-14T10:00:00"),
timestamp("2018-09-19T08:30:00"),
timestamp("2018-09-19T08:30:00"),
timestamp("2018-09-27T14:00:00"),
timestamp("2018-10-02T12:00:00"),
timestamp("2018-10-03T12:00:00"),
timestamp("2018-10-10T08:30:00"),
timestamp("2018-10-11T05:00:00"),
timestamp("2018-10-11T09:00:00"),
timestamp("2018-10-16T08:30:00"),
timestamp("2018-10-16T08:30:00"),
timestamp("2018-10-17T08:30:00"),
timestamp("2018-10-17T08:30:00"),
timestamp("2018-10-19T16:10:00"),
timestamp("2018-10-23T15:20:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:30:00"),
timestamp("2018-11-09T09:30:00"),
timestamp("2018-11-09T09:30:00"),
timestamp("2018-11-13T09:30:00"),
timestamp("2018-11-13T09:30:00"),
timestamp("2018-11-14T09:30:00"),
timestamp("2018-11-14T09:30:00"),
timestamp("2018-11-14T14:00:00"),
timestamp("2018-11-15T17:00:00"),
timestamp("2018-11-20T10:00:00"),
timestamp("2018-11-20T10:00:00"),
timestamp("2018-11-21T15:15:00"),
timestamp("2018-11-21T16:30:00"),
timestamp("2018-11-22T15:00:00"),
timestamp("2018-11-26T18:30:00"),
timestamp("2018-11-28T16:45:00"),
timestamp("2018-12-04T09:15:00"),
timestamp("2018-12-10T09:30:00"),
timestamp("2018-12-11T09:30:00"),
timestamp("2018-12-11T09:30:00"),
timestamp("2018-12-12T18:00:00"),
timestamp("2018-12-19T09:30:00"),
timestamp("2018-12-19T09:30:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2019-01-09T15:30:00"),
timestamp("2019-01-11T09:30:00"),
timestamp("2019-01-15T00:00:00"),
timestamp("2019-01-16T09:15:00"),
timestamp("2019-01-16T09:30:00"),
timestamp("2019-01-16T09:30:00"),
timestamp("2019-01-16T19:00:00"),
timestamp("2019-01-22T09:30:00"),
timestamp("2019-01-28T14:30:00"),
timestamp("2019-01-29T19:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:30:00"),
timestamp("2019-02-11T09:30:00"),
timestamp("2019-02-12T13:00:00"),
timestamp("2019-02-13T09:30:00"),
timestamp("2019-02-19T09:30:00"),
timestamp("2019-02-19T09:30:00"),
timestamp("2019-02-25T10:00:00"),
timestamp("2019-02-26T10:00:00"),
timestamp("2019-02-26T12:30:00"),
timestamp("2019-03-05T15:35:00"),
timestamp("2019-03-12T19:00:00"),
timestamp("2019-03-13T19:00:00"),
timestamp("2019-03-14T17:00:00"),
timestamp("2019-03-19T09:30:00"),
timestamp("2019-03-19T09:30:00"),
timestamp("2019-03-20T09:30:00"),
timestamp("2019-03-20T20:15:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-25T15:30:00"),
timestamp("2019-03-27T19:30:00"),
timestamp("2019-03-29T09:30:00"),
timestamp("2019-03-29T14:30:00"),
timestamp("2019-04-01T20:30:00"),
timestamp("2019-04-10T16:00:00"),
timestamp("2019-04-16T08:30:00"),
timestamp("2019-04-16T08:30:00"),
timestamp("2019-04-17T08:30:00"),
timestamp("2019-04-17T13:00:00"),
timestamp("2019-04-29T08:10:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:30:00"),
timestamp("2019-05-10T08:30:00"),
timestamp("2019-05-14T08:30:00"),
timestamp("2019-05-14T08:30:00"),
timestamp("2019-05-21T15:00:00"),
timestamp("2019-05-22T08:30:00"),
timestamp("2019-05-24T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-11T08:30:00"),
timestamp("2019-06-11T08:30:00"),
timestamp("2019-06-14T12:55:00"),
timestamp("2019-06-18T14:00:00"),
timestamp("2019-06-19T08:30:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T20:00:00"),
timestamp("2019-06-26T09:15:00"),
timestamp("2019-06-26T09:15:00"),
timestamp("2019-06-28T08:30:00"),
timestamp("2019-07-02T14:05:00"),
timestamp("2019-07-11T10:00:00"),
timestamp("2019-07-16T08:30:00"),
timestamp("2019-07-16T12:00:00"),
timestamp("2019-07-17T08:30:00"),
timestamp("2019-07-23T10:45:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:30:00"),
timestamp("2019-08-09T08:30:00"),
timestamp("2019-08-13T08:30:00"),
timestamp("2019-08-13T08:30:00"),
timestamp("2019-08-14T08:30:00"),
timestamp("2019-08-23T19:00:00"),
timestamp("2019-09-03T21:00:00"),
timestamp("2019-09-04T13:15:00"),
timestamp("2019-09-04T13:15:00"),
timestamp("2019-09-04T18:00:00"),
timestamp("2019-09-09T18:00:00"),
timestamp("2019-09-10T08:30:00"),
timestamp("2019-09-10T08:30:00"),
timestamp("2019-09-18T08:30:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-30T08:30:00"),
timestamp("2019-10-02T10:35:00"),
timestamp("2019-10-08T04:10:00"),
timestamp("2019-10-10T09:20:00"),
timestamp("2019-10-15T08:30:00"),
timestamp("2019-10-15T08:30:00"),
timestamp("2019-10-16T08:30:00"),
timestamp("2019-10-16T13:00:00"),
timestamp("2019-10-16T22:00:00"),
timestamp("2019-10-17T00:00:00"),
timestamp("2019-10-18T00:00:00"),
timestamp("2019-10-22T18:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:30:00"),
timestamp("2019-11-11T09:30:00"),
timestamp("2019-11-12T09:30:00"),
timestamp("2019-11-12T09:30:00"),
timestamp("2019-11-13T09:30:00"),
timestamp("2019-11-22T09:30:00"),
timestamp("2019-12-10T15:15:00"),
timestamp("2019-12-12T00:00:00"),
timestamp("2019-12-16T09:30:00"),
timestamp("2019-12-17T09:30:00"),
timestamp("2019-12-17T09:30:00"),
timestamp("2019-12-17T19:15:00"),
timestamp("2019-12-18T09:30:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-20T09:30:00"),
timestamp("2019-12-20T15:00:00")
)
// @function GBP high impact news date and time from 2020 to 2023
export gbpNews2020To2023() =>
array.from(
timestamp("2020-01-09T09:30:00"),
timestamp("2020-01-15T09:30:00"),
timestamp("2020-01-21T09:30:00"),
timestamp("2020-01-21T09:30:00"),
timestamp("2020-01-24T09:30:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:30:00"),
timestamp("2020-01-31T23:59:00"),
timestamp("2020-02-11T09:30:00"),
timestamp("2020-02-18T09:30:00"),
timestamp("2020-02-18T09:30:00"),
timestamp("2020-02-19T09:30:00"),
timestamp("2020-02-21T09:30:00"),
timestamp("2020-03-03T09:30:00"),
timestamp("2020-03-04T13:15:00"),
timestamp("2020-03-05T17:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T09:00:00"),
timestamp("2020-03-13T12:00:00"),
timestamp("2020-03-17T09:30:00"),
timestamp("2020-03-17T09:30:00"),
timestamp("2020-03-17T14:30:00"),
timestamp("2020-03-17T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-24T09:30:00"),
timestamp("2020-03-25T07:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-31T06:00:00"),
timestamp("2020-04-21T06:00:00"),
timestamp("2020-04-21T06:00:00"),
timestamp("2020-04-22T06:00:00"),
timestamp("2020-04-23T08:30:00"),
timestamp("2020-05-05T06:00:00"),
timestamp("2020-05-05T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T09:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-19T06:00:00"),
timestamp("2020-05-19T06:00:00"),
timestamp("2020-05-20T06:00:00"),
timestamp("2020-05-20T13:30:00"),
timestamp("2020-05-21T08:30:00"),
timestamp("2020-06-12T06:00:00"),
timestamp("2020-06-12T06:00:00"),
timestamp("2020-06-16T06:00:00"),
timestamp("2020-06-16T06:00:00"),
timestamp("2020-06-16T11:00:00"),
timestamp("2020-06-16T11:00:00"),
timestamp("2020-06-17T06:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-23T08:30:00"),
timestamp("2020-06-23T08:45:00"),
timestamp("2020-06-29T09:30:00"),
timestamp("2020-06-30T06:00:00"),
timestamp("2020-07-13T15:30:00"),
timestamp("2020-07-14T06:00:00"),
timestamp("2020-07-15T06:00:00"),
timestamp("2020-07-16T06:00:00"),
timestamp("2020-07-16T06:00:00"),
timestamp("2020-07-16T11:15:00"),
timestamp("2020-07-17T10:00:00"),
timestamp("2020-07-24T08:30:00"),
timestamp("2020-08-04T06:00:00"),
timestamp("2020-08-04T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T09:00:00"),
timestamp("2020-08-06T11:00:00"),
timestamp("2020-08-11T06:00:00"),
timestamp("2020-08-11T06:00:00"),
timestamp("2020-08-12T06:00:00"),
timestamp("2020-08-19T06:00:00"),
timestamp("2020-08-21T08:30:00"),
timestamp("2020-08-28T13:05:00"),
timestamp("2020-09-02T13:30:00"),
timestamp("2020-09-03T14:00:00"),
timestamp("2020-09-14T15:00:00"),
timestamp("2020-09-15T06:00:00"),
timestamp("2020-09-15T06:00:00"),
timestamp("2020-09-15T11:00:00"),
timestamp("2020-09-15T11:00:00"),
timestamp("2020-09-16T06:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-22T07:30:00"),
timestamp("2020-09-23T08:30:00"),
timestamp("2020-09-24T14:00:00"),
timestamp("2020-09-29T14:00:00"),
timestamp("2020-09-30T06:00:00"),
timestamp("2020-10-08T07:25:00"),
timestamp("2020-10-12T16:00:00"),
timestamp("2020-10-13T06:00:00"),
timestamp("2020-10-13T06:00:00"),
timestamp("2020-10-18T13:05:00"),
timestamp("2020-10-21T06:00:00"),
timestamp("2020-10-22T09:25:00"),
timestamp("2020-10-23T08:30:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T09:15:00"),
timestamp("2020-11-09T10:35:00"),
timestamp("2020-11-10T07:00:00"),
timestamp("2020-11-10T07:00:00"),
timestamp("2020-11-12T07:00:00"),
timestamp("2020-11-12T08:00:00"),
timestamp("2020-11-12T16:45:00"),
timestamp("2020-11-13T16:00:00"),
timestamp("2020-11-17T11:00:00"),
timestamp("2020-11-17T14:00:00"),
timestamp("2020-11-18T07:00:00"),
timestamp("2020-11-18T16:30:00"),
timestamp("2020-11-23T09:30:00"),
timestamp("2020-11-23T15:30:00"),
timestamp("2020-12-11T09:30:00"),
timestamp("2020-12-15T07:00:00"),
timestamp("2020-12-15T07:00:00"),
timestamp("2020-12-16T07:00:00"),
timestamp("2020-12-16T09:30:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-21T17:00:00"),
timestamp("2020-12-22T07:00:00"),
timestamp("2021-01-06T14:30:00"),
timestamp("2021-01-11T15:00:00"),
timestamp("2021-01-20T07:00:00"),
timestamp("2021-01-20T17:00:00"),
timestamp("2021-01-22T09:30:00"),
timestamp("2021-01-25T17:00:00"),
timestamp("2021-01-26T07:00:00"),
timestamp("2021-01-26T07:00:00"),
timestamp("2021-01-26T17:45:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T13:00:00"),
timestamp("2021-02-05T13:30:00"),
timestamp("2021-02-10T17:00:00"),
timestamp("2021-02-12T07:00:00"),
timestamp("2021-02-17T07:00:00"),
timestamp("2021-02-19T09:30:00"),
timestamp("2021-02-22T12:00:00"),
timestamp("2021-02-23T07:00:00"),
timestamp("2021-02-23T07:00:00"),
timestamp("2021-02-24T14:30:00"),
timestamp("2021-03-08T10:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-23T07:00:00"),
timestamp("2021-03-23T07:00:00"),
timestamp("2021-03-23T11:50:00"),
timestamp("2021-03-24T07:00:00"),
timestamp("2021-03-24T09:30:00"),
timestamp("2021-03-25T09:30:00"),
timestamp("2021-03-31T06:00:00"),
timestamp("2021-04-20T06:00:00"),
timestamp("2021-04-20T06:00:00"),
timestamp("2021-04-21T06:00:00"),
timestamp("2021-04-21T10:30:00"),
timestamp("2021-04-23T08:30:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T12:00:00"),
timestamp("2021-05-11T14:30:00"),
timestamp("2021-05-12T06:00:00"),
timestamp("2021-05-12T14:00:00"),
timestamp("2021-05-13T16:00:00"),
timestamp("2021-05-18T06:00:00"),
timestamp("2021-05-18T06:00:00"),
timestamp("2021-05-18T14:00:00"),
timestamp("2021-05-19T06:00:00"),
timestamp("2021-05-21T08:30:00"),
timestamp("2021-05-24T14:30:00"),
timestamp("2021-05-24T15:30:00"),
timestamp("2021-06-01T15:00:00"),
timestamp("2021-06-03T16:00:00"),
timestamp("2021-06-11T08:30:00"),
timestamp("2021-06-14T13:00:00"),
timestamp("2021-06-15T06:00:00"),
timestamp("2021-06-15T06:00:00"),
timestamp("2021-06-15T12:15:00"),
timestamp("2021-06-16T06:00:00"),
timestamp("2021-06-23T08:30:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-30T06:00:00"),
timestamp("2021-07-01T08:00:00"),
timestamp("2021-07-09T10:00:00"),
timestamp("2021-07-14T06:00:00"),
timestamp("2021-07-15T06:00:00"),
timestamp("2021-07-15T06:00:00"),
timestamp("2021-07-23T08:30:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T12:00:00"),
timestamp("2021-08-12T06:00:00"),
timestamp("2021-08-17T06:00:00"),
timestamp("2021-08-17T06:00:00"),
timestamp("2021-08-18T06:00:00"),
timestamp("2021-08-23T08:30:00"),
timestamp("2021-09-08T15:00:00"),
timestamp("2021-09-14T06:00:00"),
timestamp("2021-09-14T06:00:00"),
timestamp("2021-09-15T06:00:00"),
timestamp("2021-09-23T08:30:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-27T15:00:00"),
timestamp("2021-09-30T06:00:00"),
timestamp("2021-10-12T06:00:00"),
timestamp("2021-10-12T06:00:00"),
timestamp("2021-10-20T06:00:00"),
timestamp("2021-10-22T08:30:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:30:00"),
timestamp("2021-11-08T17:00:00"),
timestamp("2021-11-09T16:00:00"),
timestamp("2021-11-11T07:00:00"),
timestamp("2021-11-15T13:30:00"),
timestamp("2021-11-16T07:00:00"),
timestamp("2021-11-16T07:00:00"),
timestamp("2021-11-17T07:00:00"),
timestamp("2021-11-23T09:30:00"),
timestamp("2021-11-25T17:00:00"),
timestamp("2021-11-30T15:00:00"),
timestamp("2021-12-01T14:00:00"),
timestamp("2021-12-14T07:00:00"),
timestamp("2021-12-14T07:00:00"),
timestamp("2021-12-15T07:00:00"),
timestamp("2021-12-16T09:30:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-22T07:00:00"),
timestamp("2022-01-18T07:00:00"),
timestamp("2022-01-18T07:00:00"),
timestamp("2022-01-19T07:00:00"),
timestamp("2022-01-19T14:15:00"),
timestamp("2022-01-24T09:30:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:30:00"),
timestamp("2022-02-10T17:00:00"),
timestamp("2022-02-11T07:00:00"),
timestamp("2022-02-15T07:00:00"),
timestamp("2022-02-15T07:00:00"),
timestamp("2022-02-16T07:00:00"),
timestamp("2022-02-21T09:30:00"),
timestamp("2022-02-23T09:30:00"),
timestamp("2022-02-23T09:30:00"),
timestamp("2022-03-15T07:00:00"),
timestamp("2022-03-15T07:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-23T07:00:00"),
timestamp("2022-03-23T12:00:00"),
timestamp("2022-03-24T09:30:00"),
timestamp("2022-03-28T11:00:00"),
timestamp("2022-03-31T06:00:00"),
timestamp("2022-04-04T09:05:00"),
timestamp("2022-04-12T06:00:00"),
timestamp("2022-04-12T06:00:00"),
timestamp("2022-04-13T06:00:00"),
timestamp("2022-04-21T16:30:00"),
timestamp("2022-04-22T08:30:00"),
timestamp("2022-04-22T14:30:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:30:00"),
timestamp("2022-05-12T06:00:00"),
timestamp("2022-05-16T14:15:00"),
timestamp("2022-05-17T06:00:00"),
timestamp("2022-05-17T06:00:00"),
timestamp("2022-05-18T06:00:00"),
timestamp("2022-05-23T16:15:00"),
timestamp("2022-05-24T08:30:00"),
timestamp("2022-06-06T17:00:00"),
timestamp("2022-06-14T06:00:00"),
timestamp("2022-06-14T06:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-22T06:00:00"),
timestamp("2022-06-23T08:30:00"),
timestamp("2022-06-29T13:00:00"),
timestamp("2022-06-30T06:00:00"),
timestamp("2022-07-11T14:15:00"),
timestamp("2022-07-12T17:00:00"),
timestamp("2022-07-19T06:00:00"),
timestamp("2022-07-19T06:00:00"),
timestamp("2022-07-20T06:00:00"),
timestamp("2022-07-22T08:30:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:30:00"),
timestamp("2022-08-12T06:00:00"),
timestamp("2022-08-16T06:00:00"),
timestamp("2022-08-16T06:00:00"),
timestamp("2022-08-17T06:00:00"),
timestamp("2022-08-23T08:30:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-13T06:00:00"),
timestamp("2022-09-13T06:00:00"),
timestamp("2022-09-14T06:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-23T08:30:00"),
timestamp("2022-09-30T06:00:00"),
timestamp("2022-10-11T06:00:00"),
timestamp("2022-10-11T06:00:00"),
timestamp("2022-10-11T18:35:00"),
timestamp("2022-10-19T06:00:00"),
timestamp("2022-10-24T08:30:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:30:00"),
timestamp("2022-11-11T07:00:00"),
timestamp("2022-11-15T07:00:00"),
timestamp("2022-11-15T07:00:00"),
timestamp("2022-11-16T07:00:00"),
timestamp("2022-11-16T14:15:00"),
timestamp("2022-11-23T09:30:00"),
timestamp("2022-11-29T15:00:00"),
timestamp("2022-12-13T07:00:00"),
timestamp("2022-12-13T07:00:00"),
timestamp("2022-12-13T11:00:00"),
timestamp("2022-12-14T07:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-16T09:30:00"),
timestamp("2022-12-22T07:00:00"),
timestamp("2023-01-10T10:10:00"),
timestamp("2023-01-16T15:00:00"),
timestamp("2023-01-17T07:00:00"),
timestamp("2023-01-17T07:00:00"),
timestamp("2023-01-18T07:00:00"),
timestamp("2023-01-24T09:30:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:30:00"),
timestamp("2023-02-09T09:45:00"),
timestamp("2023-02-09T09:45:00"),
timestamp("2023-02-10T07:00:00"),
timestamp("2023-02-14T07:00:00"),
timestamp("2023-02-14T07:00:00"),
timestamp("2023-02-15T07:00:00"),
timestamp("2023-02-21T09:30:00"),
timestamp("2023-03-01T10:10:00"),
timestamp("2023-03-14T07:00:00"),
timestamp("2023-03-14T07:00:00"),
timestamp("2023-03-22T07:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-24T09:30:00"),
timestamp("2023-03-27T17:00:00"),
timestamp("2023-03-28T08:45:00"),
timestamp("2023-03-31T06:00:00"),
timestamp("2023-04-12T13:00:00"),
timestamp("2023-04-12T19:15:00"),
timestamp("2023-04-18T06:00:00"),
timestamp("2023-04-18T06:00:00"),
timestamp("2023-04-19T06:00:00"),
timestamp("2023-04-21T08:30:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:30:00"),
timestamp("2023-05-12T06:00:00"),
timestamp("2023-05-16T06:00:00"),
timestamp("2023-05-16T06:00:00"),
timestamp("2023-05-17T09:50:00"),
timestamp("2023-05-18T09:15:00"),
timestamp("2023-05-23T08:30:00"),
timestamp("2023-05-23T09:15:00"),
timestamp("2023-05-24T06:00:00"),
timestamp("2023-05-24T09:30:00"),
timestamp("2023-05-24T13:00:00"),
timestamp("2023-06-13T06:00:00"),
timestamp("2023-06-13T06:00:00"),
timestamp("2023-06-13T14:00:00"),
timestamp("2023-06-21T06:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-23T08:30:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-30T06:00:00"),
timestamp("2023-06-30T06:00:00"),
timestamp("2023-07-11T06:00:00"),
timestamp("2023-07-11T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-21T06:00:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:30:00"),
timestamp("2023-08-11T06:00:00"),
timestamp("2023-08-11T06:00:00"),
timestamp("2023-08-15T06:00:00"),
timestamp("2023-08-15T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-18T06:00:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-09-06T08:30:00"),
timestamp("2023-09-12T06:00:00"),
timestamp("2023-09-12T06:00:00"),
timestamp("2023-09-15T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-29T06:00:00"),
timestamp("2023-09-29T06:00:00"),
timestamp("2023-10-17T06:00:00"),
timestamp("2023-10-17T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-20T06:00:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-11-02T11:30:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-09T07:00:00"),
timestamp("2023-11-10T07:00:00"),
timestamp("2023-11-14T07:00:00"),
timestamp("2023-11-14T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T09:30:00"),
timestamp("2023-11-17T07:00:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-12-12T07:00:00"),
timestamp("2023-12-12T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-15T07:00:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-22T07:00:00"),
timestamp("2023-12-22T07:00:00")
)
|
CalendarJpy | https://www.tradingview.com/script/MdPz0N62-CalendarJpy/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the important events on JPY. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("CalendarJpy")
// @function JPY high impact news date and time from 2015 to 2023
export HighImpactNews2015To2023() =>
array.from(
timestamp("2015-01-21T06:30:00"),
timestamp("2015-01-29T23:30:00"),
timestamp("2015-02-15T23:50:00"),
timestamp("2015-02-18T06:30:00"),
timestamp("2015-02-26T23:30:00"),
timestamp("2015-03-08T23:50:00"),
timestamp("2015-03-17T06:30:00"),
timestamp("2015-03-26T23:30:00"),
timestamp("2015-04-08T03:36:00"),
timestamp("2015-04-30T04:05:34"),
timestamp("2015-04-30T23:30:00"),
timestamp("2015-05-15T03:40:00"),
timestamp("2015-05-19T23:50:00"),
timestamp("2015-05-21T00:00:00"),
timestamp("2015-05-22T03:00:00"),
timestamp("2015-05-22T03:00:00"),
timestamp("2015-05-23T13:30:00"),
timestamp("2015-06-04T00:00:00"),
timestamp("2015-06-07T23:50:00"),
timestamp("2015-06-18T00:00:00"),
timestamp("2015-06-19T03:00:00"),
timestamp("2015-06-19T06:30:00"),
timestamp("2015-07-15T03:00:00"),
timestamp("2015-07-15T06:30:00"),
timestamp("2015-08-07T03:00:00"),
timestamp("2015-08-07T03:00:00"),
timestamp("2015-08-07T06:00:00"),
timestamp("2015-08-27T23:30:00"),
timestamp("2015-09-15T03:00:00"),
timestamp("2015-09-15T03:00:00"),
timestamp("2015-09-15T03:00:00"),
timestamp("2015-09-17T06:35:00"),
timestamp("2015-10-01T01:00:00"),
timestamp("2015-10-07T03:00:00"),
timestamp("2015-10-07T03:02:18"),
timestamp("2015-10-07T06:30:00"),
timestamp("2015-10-16T06:35:00"),
timestamp("2015-10-29T23:30:00"),
timestamp("2015-10-30T03:24:00"),
timestamp("2015-10-30T03:24:34"),
timestamp("2015-10-30T06:30:00"),
timestamp("2015-11-06T04:00:00"),
timestamp("2015-11-15T23:50:00"),
timestamp("2015-11-19T03:00:00"),
timestamp("2015-11-19T03:00:00"),
timestamp("2015-11-19T06:00:00"),
timestamp("2015-11-20T07:00:00"),
timestamp("2015-11-30T01:00:00"),
timestamp("2015-12-07T03:45:00"),
timestamp("2015-12-07T23:50:00"),
timestamp("2015-12-07T23:50:00"),
timestamp("2015-12-07T23:50:00"),
timestamp("2015-12-18T03:00:00"),
timestamp("2015-12-18T03:50:00"),
timestamp("2015-12-18T05:00:00"),
timestamp("2015-12-24T04:00:00"),
timestamp("2016-01-12T10:30:00"),
timestamp("2016-01-29T03:00:00"),
timestamp("2016-01-29T03:00:00"),
timestamp("2016-01-29T06:30:00"),
timestamp("2016-02-03T02:30:00"),
timestamp("2016-03-07T03:40:00"),
timestamp("2016-03-15T03:00:00"),
timestamp("2016-03-15T03:00:00"),
timestamp("2016-03-15T06:30:00"),
timestamp("2016-04-07T00:30:00"),
timestamp("2016-04-20T00:00:00"),
timestamp("2016-04-28T03:00:00"),
timestamp("2016-04-28T03:00:00"),
timestamp("2016-04-28T05:30:00"),
timestamp("2016-05-08T23:50:00"),
timestamp("2016-05-13T03:30:00"),
timestamp("2016-06-16T02:45:00"),
timestamp("2016-06-16T02:45:17"),
timestamp("2016-06-16T06:00:00"),
timestamp("2016-07-07T00:30:00"),
timestamp("2016-07-28T23:30:00"),
timestamp("2016-07-29T00:00:00"),
timestamp("2016-07-29T01:00:00"),
timestamp("2016-07-29T06:30:00"),
timestamp("2016-08-23T04:00:00"),
timestamp("2016-08-27T04:25:00"),
timestamp("2016-09-05T02:30:00"),
timestamp("2016-09-21T04:19:05"),
timestamp("2016-09-21T04:21:00"),
timestamp("2016-09-21T06:00:00"),
timestamp("2016-09-29T06:35:00"),
timestamp("2016-09-30T04:30:00"),
timestamp("2016-10-21T03:00:00"),
timestamp("2016-11-01T03:00:00"),
timestamp("2016-11-01T03:00:00"),
timestamp("2016-11-01T03:00:00"),
timestamp("2016-11-06T23:50:00"),
timestamp("2016-12-20T03:00:00"),
timestamp("2016-12-20T03:00:00"),
timestamp("2016-12-20T06:00:00"),
timestamp("2016-12-26T04:00:00"),
timestamp("2017-01-31T03:00:00"),
timestamp("2017-01-31T03:00:00"),
timestamp("2017-01-31T06:30:00"),
timestamp("2017-02-02T23:50:00"),
timestamp("2017-03-16T02:55:00"),
timestamp("2017-03-16T02:55:00"),
timestamp("2017-03-16T05:30:00"),
timestamp("2017-03-21T23:50:00"),
timestamp("2017-04-17T06:15:00"),
timestamp("2017-04-27T03:15:00"),
timestamp("2017-04-27T03:15:00"),
timestamp("2017-04-27T06:30:00"),
timestamp("2017-05-01T23:50:00"),
timestamp("2017-05-02T00:20:00"),
timestamp("2017-05-24T00:00:00"),
timestamp("2017-06-16T02:00:00"),
timestamp("2017-06-16T02:00:00"),
timestamp("2017-06-16T06:30:00"),
timestamp("2017-06-20T23:50:00"),
timestamp("2017-06-21T06:35:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-20T03:12:00"),
timestamp("2017-07-20T03:12:00"),
timestamp("2017-07-20T06:30:00"),
timestamp("2017-07-24T23:50:00"),
timestamp("2017-09-21T03:18:00"),
timestamp("2017-09-21T03:18:00"),
timestamp("2017-09-21T06:30:00"),
timestamp("2017-09-25T05:35:00"),
timestamp("2017-09-25T23:50:00"),
timestamp("2017-09-28T06:35:00"),
timestamp("2017-10-22T00:00:00"),
timestamp("2017-10-31T03:00:00"),
timestamp("2017-10-31T03:07:55"),
timestamp("2017-10-31T06:30:00"),
timestamp("2017-11-05T23:50:00"),
timestamp("2017-11-06T01:00:00"),
timestamp("2017-11-13T17:45:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-12-21T02:00:00"),
timestamp("2017-12-21T02:00:00"),
timestamp("2017-12-21T06:30:00"),
timestamp("2017-12-25T23:50:00"),
timestamp("2018-01-23T03:00:00"),
timestamp("2018-01-23T03:14:00"),
timestamp("2018-01-23T06:30:00"),
timestamp("2018-01-25T23:50:00"),
timestamp("2018-03-01T23:30:00"),
timestamp("2018-03-09T02:00:00"),
timestamp("2018-03-09T02:46:00"),
timestamp("2018-03-09T06:30:00"),
timestamp("2018-03-13T23:50:00"),
timestamp("2018-03-29T23:30:00"),
timestamp("2018-04-26T23:30:00"),
timestamp("2018-04-27T02:00:00"),
timestamp("2018-04-27T03:05:14"),
timestamp("2018-04-27T06:30:00"),
timestamp("2018-05-06T23:50:00"),
timestamp("2018-05-24T23:30:00"),
timestamp("2018-06-15T04:00:00"),
timestamp("2018-06-15T04:00:00"),
timestamp("2018-06-15T04:00:00"),
timestamp("2018-06-19T23:50:00"),
timestamp("2018-06-20T13:30:00"),
timestamp("2018-06-28T23:30:00"),
timestamp("2018-07-09T00:30:00"),
timestamp("2018-07-26T23:30:00"),
timestamp("2018-07-31T02:00:00"),
timestamp("2018-07-31T02:00:00"),
timestamp("2018-07-31T05:00:00"),
timestamp("2018-08-02T23:50:00"),
timestamp("2018-08-30T23:30:00"),
timestamp("2018-09-03T05:40:00"),
timestamp("2018-09-19T02:59:00"),
timestamp("2018-09-19T02:59:16"),
timestamp("2018-09-19T06:00:00"),
timestamp("2018-09-24T23:50:00"),
timestamp("2018-09-25T05:35:00"),
timestamp("2018-09-27T06:35:00"),
timestamp("2018-09-27T23:30:00"),
timestamp("2018-10-18T00:30:00"),
timestamp("2018-10-19T06:35:00"),
timestamp("2018-10-25T23:30:00"),
timestamp("2018-10-31T02:00:00"),
timestamp("2018-10-31T03:09:17"),
timestamp("2018-10-31T06:00:00"),
timestamp("2018-11-04T23:50:00"),
timestamp("2018-11-05T01:00:00"),
timestamp("2018-11-19T03:30:00"),
timestamp("2018-11-29T23:30:00"),
timestamp("2018-12-09T23:50:00"),
timestamp("2018-12-20T02:52:00"),
timestamp("2018-12-20T02:52:00"),
timestamp("2018-12-20T04:00:00"),
timestamp("2018-12-25T23:50:00"),
timestamp("2018-12-26T04:00:00"),
timestamp("2018-12-27T23:30:00"),
timestamp("2019-01-17T03:20:00"),
timestamp("2019-01-23T03:00:00"),
timestamp("2019-01-23T03:00:00"),
timestamp("2019-01-23T06:00:00"),
timestamp("2019-01-24T23:30:00"),
timestamp("2019-01-27T23:50:00"),
timestamp("2019-02-13T23:50:00"),
timestamp("2019-02-28T23:30:00"),
timestamp("2019-03-07T23:50:00"),
timestamp("2019-03-15T02:00:00"),
timestamp("2019-03-15T02:00:00"),
timestamp("2019-03-15T06:00:00"),
timestamp("2019-03-15T08:55:00"),
timestamp("2019-03-19T23:50:00"),
timestamp("2019-03-28T23:30:00"),
timestamp("2019-04-10T06:15:00"),
timestamp("2019-04-25T03:00:00"),
timestamp("2019-04-25T03:00:00"),
timestamp("2019-04-25T06:00:00"),
timestamp("2019-04-25T23:30:00"),
timestamp("2019-05-07T23:50:00"),
timestamp("2019-05-19T23:50:00"),
timestamp("2019-05-27T03:00:00"),
timestamp("2019-05-29T00:00:00"),
timestamp("2019-05-30T23:30:00"),
timestamp("2019-06-06T03:50:00"),
timestamp("2019-06-07T03:50:00"),
timestamp("2019-06-08T06:20:00"),
timestamp("2019-06-09T23:50:00"),
timestamp("2019-06-20T02:00:00"),
timestamp("2019-06-20T02:00:00"),
timestamp("2019-06-20T06:00:00"),
timestamp("2019-06-24T23:50:00"),
timestamp("2019-06-27T23:30:00"),
timestamp("2019-07-08T00:30:00"),
timestamp("2019-07-19T20:30:00"),
timestamp("2019-07-22T15:00:00"),
timestamp("2019-07-25T23:30:00"),
timestamp("2019-07-30T02:00:00"),
timestamp("2019-07-30T02:00:00"),
timestamp("2019-07-30T06:30:00"),
timestamp("2019-08-01T23:50:00"),
timestamp("2019-08-08T23:50:00"),
timestamp("2019-08-29T23:30:00"),
timestamp("2019-09-08T23:50:00"),
timestamp("2019-09-19T03:00:00"),
timestamp("2019-09-19T03:00:00"),
timestamp("2019-09-19T06:30:00"),
timestamp("2019-09-24T05:30:00"),
timestamp("2019-09-24T23:50:00"),
timestamp("2019-09-26T23:30:00"),
timestamp("2019-10-15T00:30:00"),
timestamp("2019-10-28T23:30:00"),
timestamp("2019-10-31T03:00:00"),
timestamp("2019-10-31T03:00:00"),
timestamp("2019-10-31T06:00:00"),
timestamp("2019-11-05T23:50:00"),
timestamp("2019-11-13T23:50:00"),
timestamp("2019-11-28T23:30:00"),
timestamp("2019-12-08T23:50:00"),
timestamp("2019-12-19T03:00:00"),
timestamp("2019-12-19T03:00:00"),
timestamp("2019-12-19T06:00:00"),
timestamp("2019-12-23T23:50:00"),
timestamp("2019-12-26T00:00:00"),
timestamp("2019-12-26T23:30:00"),
timestamp("2020-01-15T00:30:00"),
timestamp("2020-01-21T03:00:00"),
timestamp("2020-01-21T03:00:00"),
timestamp("2020-01-21T06:00:00"),
timestamp("2020-01-23T23:50:00"),
timestamp("2020-01-30T23:30:00"),
timestamp("2020-02-16T23:50:00"),
timestamp("2020-02-27T23:30:00"),
timestamp("2020-03-08T23:50:00"),
timestamp("2020-03-16T03:00:00"),
timestamp("2020-03-16T03:00:00"),
timestamp("2020-03-16T07:00:00"),
timestamp("2020-03-18T23:50:00"),
timestamp("2020-03-26T23:30:00"),
timestamp("2020-04-09T00:30:00"),
timestamp("2020-04-27T03:00:00"),
timestamp("2020-04-27T03:00:00"),
timestamp("2020-04-27T06:30:00"),
timestamp("2020-04-29T23:50:00"),
timestamp("2020-04-30T23:30:00"),
timestamp("2020-04-30T23:50:00"),
timestamp("2020-05-17T23:50:00"),
timestamp("2020-05-22T03:00:00"),
timestamp("2020-05-22T03:00:00"),
timestamp("2020-05-28T23:30:00"),
timestamp("2020-05-28T23:50:00"),
timestamp("2020-06-07T23:50:00"),
timestamp("2020-06-16T03:00:00"),
timestamp("2020-06-16T03:00:00"),
timestamp("2020-06-16T06:00:00"),
timestamp("2020-06-18T23:50:00"),
timestamp("2020-06-25T23:30:00"),
timestamp("2020-07-15T03:00:00"),
timestamp("2020-07-15T03:00:00"),
timestamp("2020-07-15T06:00:00"),
timestamp("2020-07-19T23:50:00"),
timestamp("2020-08-02T23:50:00"),
timestamp("2020-08-05T12:00:00"),
timestamp("2020-08-16T23:50:00"),
timestamp("2020-09-07T23:50:00"),
timestamp("2020-09-17T03:00:00"),
timestamp("2020-09-17T03:00:00"),
timestamp("2020-09-17T06:00:00"),
timestamp("2020-09-23T05:35:00"),
timestamp("2020-09-23T23:50:00"),
timestamp("2020-09-30T23:50:00"),
timestamp("2020-10-05T06:40:00"),
timestamp("2020-10-29T03:00:00"),
timestamp("2020-10-29T03:00:00"),
timestamp("2020-10-29T06:00:00"),
timestamp("2020-11-03T23:50:00"),
timestamp("2020-11-15T23:50:00"),
timestamp("2020-11-24T12:05:00"),
timestamp("2020-12-07T23:50:00"),
timestamp("2020-12-13T23:50:00"),
timestamp("2020-12-18T03:00:00"),
timestamp("2020-12-18T03:00:00"),
timestamp("2020-12-18T06:00:00"),
timestamp("2020-12-22T23:50:00"),
timestamp("2020-12-24T00:00:00"),
timestamp("2021-01-21T03:00:00"),
timestamp("2021-01-21T03:00:00"),
timestamp("2021-01-21T06:00:00"),
timestamp("2021-01-25T23:50:00"),
timestamp("2021-02-14T23:50:00"),
timestamp("2021-03-08T23:50:00"),
timestamp("2021-03-16T04:05:00"),
timestamp("2021-03-19T03:00:00"),
timestamp("2021-03-19T03:00:00"),
timestamp("2021-03-19T06:00:00"),
timestamp("2021-03-23T23:50:00"),
timestamp("2021-03-25T11:20:00"),
timestamp("2021-03-31T23:50:00"),
timestamp("2021-04-14T06:17:00"),
timestamp("2021-04-15T01:00:00"),
timestamp("2021-04-27T03:00:00"),
timestamp("2021-04-27T03:00:00"),
timestamp("2021-04-27T06:00:00"),
timestamp("2021-05-05T23:50:00"),
timestamp("2021-05-17T23:50:00"),
timestamp("2021-05-24T11:05:00"),
timestamp("2021-06-07T23:50:00"),
timestamp("2021-06-18T03:00:00"),
timestamp("2021-06-18T03:00:00"),
timestamp("2021-06-18T06:00:00"),
timestamp("2021-06-22T23:50:00"),
timestamp("2021-06-24T06:45:00"),
timestamp("2021-06-30T23:50:00"),
timestamp("2021-07-16T03:00:00"),
timestamp("2021-07-16T03:00:00"),
timestamp("2021-07-16T06:00:00"),
timestamp("2021-07-20T23:50:00"),
timestamp("2021-07-27T07:30:00"),
timestamp("2021-08-15T23:50:00"),
timestamp("2021-09-07T23:50:00"),
timestamp("2021-09-22T03:00:00"),
timestamp("2021-09-22T03:00:00"),
timestamp("2021-09-22T06:00:00"),
timestamp("2021-09-27T23:50:00"),
timestamp("2021-09-30T07:10:00"),
timestamp("2021-09-30T23:50:00"),
timestamp("2021-10-07T01:00:00"),
timestamp("2021-10-28T03:00:00"),
timestamp("2021-10-28T03:00:00"),
timestamp("2021-10-28T06:00:00"),
timestamp("2021-11-01T23:50:00"),
timestamp("2021-11-14T23:50:00"),
timestamp("2021-11-29T08:30:00"),
timestamp("2021-12-07T23:50:00"),
timestamp("2021-12-12T23:50:00"),
timestamp("2021-12-17T03:00:00"),
timestamp("2021-12-17T03:00:00"),
timestamp("2021-12-17T06:00:00"),
timestamp("2021-12-21T23:50:00"),
timestamp("2022-01-12T01:00:00"),
timestamp("2022-01-18T03:00:00"),
timestamp("2022-01-18T03:00:00"),
timestamp("2022-01-18T06:00:00"),
timestamp("2022-01-20T23:50:00"),
timestamp("2022-02-14T23:50:00"),
timestamp("2022-03-08T23:50:00"),
timestamp("2022-03-18T03:00:00"),
timestamp("2022-03-18T03:00:00"),
timestamp("2022-03-18T06:00:00"),
timestamp("2022-03-23T23:50:00"),
timestamp("2022-03-31T23:50:00"),
timestamp("2022-04-11T01:00:00"),
timestamp("2022-04-13T06:15:00"),
timestamp("2022-04-28T03:00:00"),
timestamp("2022-04-28T03:00:00"),
timestamp("2022-04-28T06:00:00"),
timestamp("2022-05-08T23:50:00"),
timestamp("2022-05-17T23:50:00"),
timestamp("2022-05-25T11:05:00"),
timestamp("2022-06-07T23:50:00"),
timestamp("2022-06-17T03:00:00"),
timestamp("2022-06-17T03:00:00"),
timestamp("2022-06-17T06:00:00"),
timestamp("2022-06-21T23:50:00"),
timestamp("2022-06-30T23:50:00"),
timestamp("2022-07-11T01:00:00"),
timestamp("2022-07-21T03:00:00"),
timestamp("2022-07-21T03:00:00"),
timestamp("2022-07-21T06:30:00"),
timestamp("2022-07-25T23:50:00"),
timestamp("2022-08-14T23:50:00"),
timestamp("2022-09-07T23:50:00"),
timestamp("2022-09-22T03:00:00"),
timestamp("2022-09-22T03:00:00"),
timestamp("2022-09-22T06:00:00"),
timestamp("2022-09-26T05:35:00"),
timestamp("2022-09-27T23:50:00"),
timestamp("2022-10-02T23:50:00"),
timestamp("2022-10-28T03:00:00"),
timestamp("2022-10-28T03:00:00"),
timestamp("2022-10-28T06:00:00"),
timestamp("2022-11-01T23:50:00"),
timestamp("2022-11-14T23:50:00"),
timestamp("2022-12-02T01:30:00"),
timestamp("2022-12-07T23:50:00"),
timestamp("2022-12-13T23:50:00"),
timestamp("2022-12-20T03:00:00"),
timestamp("2022-12-20T03:00:00"),
timestamp("2022-12-20T06:00:00"),
timestamp("2022-12-22T23:50:00"),
timestamp("2022-12-26T00:00:00"),
timestamp("2023-01-10T10:10:00"),
timestamp("2023-01-18T02:30:00"),
timestamp("2023-01-18T02:30:00"),
timestamp("2023-01-18T06:30:00"),
timestamp("2023-01-22T23:50:00"),
timestamp("2023-02-13T23:50:00"),
timestamp("2023-02-24T05:00:00"),
timestamp("2023-02-27T05:00:00"),
timestamp("2023-03-08T23:50:00"),
timestamp("2023-03-10T02:33:42"),
timestamp("2023-03-10T03:00:00"),
timestamp("2023-03-10T06:00:00"),
timestamp("2023-03-14T23:50:00"),
timestamp("2023-03-28T04:00:00"),
timestamp("2023-04-02T23:50:00"),
timestamp("2023-04-10T10:15:00"),
timestamp("2023-04-28T03:00:00"),
timestamp("2023-04-28T04:00:31"),
timestamp("2023-04-28T06:00:00"),
timestamp("2023-05-07T23:50:00"),
timestamp("2023-05-16T23:50:00"),
timestamp("2023-06-07T23:50:00"),
timestamp("2023-06-16T02:45:00"),
timestamp("2023-06-16T03:00:00"),
timestamp("2023-06-16T06:00:00"),
timestamp("2023-06-20T23:50:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-29T23:30:00"),
timestamp("2023-06-29T23:30:00"),
timestamp("2023-07-02T23:50:00"),
timestamp("2023-07-27T23:30:00"),
timestamp("2023-07-27T23:30:00"),
timestamp("2023-07-28T03:00:00"),
timestamp("2023-07-28T03:00:00"),
timestamp("2023-07-28T06:00:00"),
timestamp("2023-08-10T23:50:00"),
timestamp("2023-08-31T23:30:00"),
timestamp("2023-08-31T23:30:00"),
timestamp("2023-09-06T23:50:00"),
timestamp("2023-09-22T03:00:00"),
timestamp("2023-09-22T03:00:00"),
timestamp("2023-09-22T06:00:00"),
timestamp("2023-09-28T23:30:00"),
timestamp("2023-09-28T23:30:00"),
timestamp("2023-10-01T23:50:00"),
timestamp("2023-10-31T03:00:00"),
timestamp("2023-10-31T03:00:00"),
timestamp("2023-10-31T06:00:00"),
timestamp("2023-11-02T23:30:00"),
timestamp("2023-11-02T23:30:00"),
timestamp("2023-11-14T23:50:00"),
timestamp("2023-11-30T23:30:00"),
timestamp("2023-11-30T23:30:00"),
timestamp("2023-12-07T23:50:00"),
timestamp("2023-12-14T23:50:00"),
timestamp("2023-12-15T03:00:00"),
timestamp("2023-12-15T03:00:00"),
timestamp("2023-12-15T06:00:00")
)
|
NewsEventsEur | https://www.tradingview.com/script/fmnJTiI0-NewsEventsEur/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 1 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the high impact news events on EUR. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("NewsEventsEur")
// @function EUR high impact news date and time from 2015 to 2019
export eurNews2015To2019() =>
array.from(
timestamp("2015-01-01T06:00:00"),
timestamp("2015-01-07T08:00:00"),
timestamp("2015-01-07T10:00:00"),
timestamp("2015-01-07T10:00:00"),
timestamp("2015-01-14T08:30:00"),
timestamp("2015-01-16T10:00:00"),
timestamp("2015-01-16T10:00:00"),
timestamp("2015-01-22T12:45:00"),
timestamp("2015-01-22T13:30:00"),
timestamp("2015-01-30T10:00:00"),
timestamp("2015-01-30T10:00:00"),
timestamp("2015-02-04T09:00:00"),
timestamp("2015-02-04T09:00:02"),
timestamp("2015-02-11T16:30:00"),
timestamp("2015-02-12T14:00:00"),
timestamp("2015-02-13T10:00:00"),
timestamp("2015-02-16T14:00:00"),
timestamp("2015-02-19T12:30:00"),
timestamp("2015-02-20T20:00:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-24T13:00:50"),
timestamp("2015-02-24T14:00:00"),
timestamp("2015-02-25T17:15:00"),
timestamp("2015-03-02T10:00:00"),
timestamp("2015-03-02T10:00:00"),
timestamp("2015-03-05T12:45:00"),
timestamp("2015-03-05T13:30:00"),
timestamp("2015-03-06T10:00:00"),
timestamp("2015-03-09T14:00:00"),
timestamp("2015-03-11T08:00:00"),
timestamp("2015-03-16T18:45:00"),
timestamp("2015-03-17T10:00:00"),
timestamp("2015-03-17T10:00:00"),
timestamp("2015-03-19T10:15:00"),
timestamp("2015-03-19T12:00:52"),
timestamp("2015-03-20T10:00:31"),
timestamp("2015-03-23T14:00:00"),
timestamp("2015-03-31T09:00:00"),
timestamp("2015-03-31T09:00:00"),
timestamp("2015-04-02T11:30:00"),
timestamp("2015-04-15T11:45:00"),
timestamp("2015-04-15T12:30:00"),
timestamp("2015-04-17T09:00:00"),
timestamp("2015-04-17T09:00:00"),
timestamp("2015-04-18T16:00:00"),
timestamp("2015-04-24T11:30:00"),
timestamp("2015-04-30T09:00:00"),
timestamp("2015-04-30T09:00:00"),
timestamp("2015-05-13T09:00:00"),
timestamp("2015-05-14T15:00:00"),
timestamp("2015-05-21T11:30:00"),
timestamp("2015-05-21T17:30:00"),
timestamp("2015-05-22T08:00:00"),
timestamp("2015-05-23T13:30:00"),
timestamp("2015-05-27T11:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-03T11:45:00"),
timestamp("2015-06-03T12:30:00"),
timestamp("2015-06-08T00:00:00"),
timestamp("2015-06-09T09:00:00"),
timestamp("2015-06-15T13:00:00"),
timestamp("2015-06-16T08:00:00"),
timestamp("2015-06-18T09:33:18"),
timestamp("2015-06-22T10:30:00"),
timestamp("2015-06-22T17:00:00"),
timestamp("2015-06-25T14:00:00"),
timestamp("2015-06-26T09:00:00"),
timestamp("2015-06-29T10:45:00"),
timestamp("2015-06-30T09:00:00"),
timestamp("2015-06-30T09:00:00"),
timestamp("2015-07-02T11:30:00"),
timestamp("2015-07-02T15:10:00"),
timestamp("2015-07-07T16:00:00"),
timestamp("2015-07-12T00:00:00"),
timestamp("2015-07-16T09:00:00"),
timestamp("2015-07-16T09:00:00"),
timestamp("2015-07-16T11:45:00"),
timestamp("2015-07-16T12:30:00"),
timestamp("2015-07-31T09:00:00"),
timestamp("2015-07-31T09:00:00"),
timestamp("2015-08-13T11:30:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T13:00:00"),
timestamp("2015-08-31T09:00:00"),
timestamp("2015-08-31T09:00:00"),
timestamp("2015-09-03T11:45:00"),
timestamp("2015-09-03T12:30:00"),
timestamp("2015-09-08T09:00:00"),
timestamp("2015-09-08T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-23T13:00:00"),
timestamp("2015-09-24T09:15:00"),
timestamp("2015-09-30T09:00:00"),
timestamp("2015-09-30T09:00:00"),
timestamp("2015-10-02T01:30:00"),
timestamp("2015-10-06T17:00:00"),
timestamp("2015-10-07T07:00:00"),
timestamp("2015-10-22T11:45:00"),
timestamp("2015-10-22T12:30:00"),
timestamp("2015-10-30T10:00:00"),
timestamp("2015-10-30T10:00:00"),
timestamp("2015-11-03T19:00:00"),
timestamp("2015-11-04T08:00:00"),
timestamp("2015-11-05T11:45:00"),
timestamp("2015-11-11T13:15:00"),
timestamp("2015-11-12T08:30:00"),
timestamp("2015-11-12T10:30:00"),
timestamp("2015-11-13T10:00:00"),
timestamp("2015-11-13T10:00:00"),
timestamp("2015-11-16T10:15:00"),
timestamp("2015-11-17T10:00:00"),
timestamp("2015-11-19T12:30:00"),
timestamp("2015-11-20T08:00:00"),
timestamp("2015-12-02T10:00:00"),
timestamp("2015-12-02T10:00:00"),
timestamp("2015-12-03T12:45:00"),
timestamp("2015-12-03T13:30:00"),
timestamp("2015-12-08T10:00:00"),
timestamp("2015-12-08T10:00:00"),
timestamp("2015-12-14T11:00:00"),
timestamp("2015-12-16T08:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2016-01-01T13:30:00"),
timestamp("2016-01-05T10:00:00"),
timestamp("2016-01-05T10:00:00"),
timestamp("2016-01-13T08:00:00"),
timestamp("2016-01-14T12:30:00"),
timestamp("2016-01-21T12:45:00"),
timestamp("2016-01-21T13:30:00"),
timestamp("2016-01-22T07:45:00"),
timestamp("2016-01-25T18:00:00"),
timestamp("2016-01-29T10:00:00"),
timestamp("2016-01-29T10:00:00"),
timestamp("2016-02-01T16:00:00"),
timestamp("2016-02-03T08:00:00"),
timestamp("2016-02-04T08:00:00"),
timestamp("2016-02-12T10:00:00"),
timestamp("2016-02-12T10:00:00"),
timestamp("2016-02-15T14:00:00"),
timestamp("2016-02-17T08:00:00"),
timestamp("2016-02-18T12:30:00"),
timestamp("2016-02-29T10:00:00"),
timestamp("2016-02-29T10:00:00"),
timestamp("2016-03-08T10:00:00"),
timestamp("2016-03-08T10:00:00"),
timestamp("2016-03-10T12:45:00"),
timestamp("2016-03-10T12:45:00"),
timestamp("2016-03-10T13:30:00"),
timestamp("2016-03-16T08:00:00"),
timestamp("2016-03-17T10:00:00"),
timestamp("2016-03-17T10:00:00"),
timestamp("2016-03-24T10:56:59"),
timestamp("2016-03-31T09:00:00"),
timestamp("2016-03-31T09:00:00"),
timestamp("2016-04-06T07:00:00"),
timestamp("2016-04-07T11:30:00"),
timestamp("2016-04-07T13:00:00"),
timestamp("2016-04-14T09:00:00"),
timestamp("2016-04-14T09:00:00"),
timestamp("2016-04-20T10:00:00"),
timestamp("2016-04-21T11:45:00"),
timestamp("2016-04-21T12:30:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-05-02T14:00:00"),
timestamp("2016-05-04T07:00:00"),
timestamp("2016-05-13T09:00:00"),
timestamp("2016-05-13T09:00:00"),
timestamp("2016-05-18T07:00:00"),
timestamp("2016-05-18T09:00:00"),
timestamp("2016-05-18T09:00:00"),
timestamp("2016-05-19T11:30:00"),
timestamp("2016-05-20T00:00:00"),
timestamp("2016-05-21T00:00:00"),
timestamp("2016-05-26T00:00:00"),
timestamp("2016-05-27T00:00:00"),
timestamp("2016-05-31T09:00:00"),
timestamp("2016-05-31T09:00:00"),
timestamp("2016-06-02T11:45:00"),
timestamp("2016-06-02T11:45:00"),
timestamp("2016-06-02T12:30:00"),
timestamp("2016-06-07T09:00:00"),
timestamp("2016-06-07T09:00:00"),
timestamp("2016-06-09T07:00:00"),
timestamp("2016-06-17T15:00:00"),
timestamp("2016-06-21T13:00:00"),
timestamp("2016-06-22T07:00:00"),
timestamp("2016-06-23T11:13:41"),
timestamp("2016-06-24T09:30:00"),
timestamp("2016-06-28T00:00:00"),
timestamp("2016-06-28T08:00:00"),
timestamp("2016-06-28T08:00:00"),
timestamp("2016-06-29T12:00:00"),
timestamp("2016-06-30T09:00:00"),
timestamp("2016-06-30T09:00:00"),
timestamp("2016-07-06T07:00:00"),
timestamp("2016-07-06T07:00:00"),
timestamp("2016-07-07T11:30:00"),
timestamp("2016-07-21T11:45:00"),
timestamp("2016-07-21T11:45:00"),
timestamp("2016-07-21T12:30:00"),
timestamp("2016-07-29T09:00:00"),
timestamp("2016-07-29T20:00:00"),
timestamp("2016-08-03T07:00:00"),
timestamp("2016-08-12T09:00:00"),
timestamp("2016-08-12T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T11:30:00"),
timestamp("2016-08-31T09:00:00"),
timestamp("2016-08-31T09:00:00"),
timestamp("2016-09-08T11:45:00"),
timestamp("2016-09-08T11:45:00"),
timestamp("2016-09-08T12:30:00"),
timestamp("2016-09-13T09:00:00"),
timestamp("2016-09-13T10:45:00"),
timestamp("2016-09-16T00:00:00"),
timestamp("2016-09-22T09:30:00"),
timestamp("2016-09-22T13:00:00"),
timestamp("2016-09-26T15:05:00"),
timestamp("2016-09-28T09:00:00"),
timestamp("2016-09-30T09:00:00"),
timestamp("2016-09-30T09:00:00"),
timestamp("2016-10-06T11:30:00"),
timestamp("2016-10-17T09:00:00"),
timestamp("2016-10-17T09:00:00"),
timestamp("2016-10-17T17:35:00"),
timestamp("2016-10-20T11:45:00"),
timestamp("2016-10-20T11:45:00"),
timestamp("2016-10-20T12:30:00"),
timestamp("2016-10-25T15:30:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-11-14T15:00:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-17T12:30:00"),
timestamp("2016-11-18T08:15:00"),
timestamp("2016-11-21T16:30:00"),
timestamp("2016-11-28T14:00:00"),
timestamp("2016-11-30T10:00:00"),
timestamp("2016-11-30T10:00:00"),
timestamp("2016-11-30T12:45:00"),
timestamp("2016-12-06T10:00:00"),
timestamp("2016-12-06T10:00:00"),
timestamp("2016-12-08T12:45:00"),
timestamp("2016-12-08T12:45:00"),
timestamp("2016-12-08T13:30:00"),
timestamp("2016-12-16T10:00:00"),
timestamp("2016-12-16T10:00:00"),
timestamp("2017-01-04T10:00:00"),
timestamp("2017-01-04T10:00:00"),
timestamp("2017-01-12T12:30:00"),
timestamp("2017-01-19T12:45:00"),
timestamp("2017-01-19T12:45:00"),
timestamp("2017-01-19T13:30:00"),
timestamp("2017-01-23T11:30:00"),
timestamp("2017-01-31T08:00:00"),
timestamp("2017-01-31T10:00:00"),
timestamp("2017-01-31T10:00:00"),
timestamp("2017-02-01T08:00:00"),
timestamp("2017-02-02T12:15:00"),
timestamp("2017-02-06T14:00:00"),
timestamp("2017-02-14T10:00:00"),
timestamp("2017-02-14T10:00:00"),
timestamp("2017-02-15T08:00:00"),
timestamp("2017-02-16T12:30:00"),
timestamp("2017-03-09T12:45:00"),
timestamp("2017-03-09T12:45:00"),
timestamp("2017-03-09T13:30:00"),
timestamp("2017-03-13T13:30:00"),
timestamp("2017-03-22T08:00:00"),
timestamp("2017-03-29T12:45:00"),
timestamp("2017-04-04T14:30:00"),
timestamp("2017-04-05T07:00:00"),
timestamp("2017-04-06T07:00:00"),
timestamp("2017-04-06T11:30:00"),
timestamp("2017-04-27T11:45:00"),
timestamp("2017-04-27T11:45:00"),
timestamp("2017-04-27T12:30:00"),
timestamp("2017-04-29T16:00:00"),
timestamp("2017-05-03T09:00:00"),
timestamp("2017-05-03T09:00:00"),
timestamp("2017-05-04T16:30:00"),
timestamp("2017-05-10T12:00:00"),
timestamp("2017-05-12T11:00:00"),
timestamp("2017-05-13T11:00:00"),
timestamp("2017-05-16T09:00:00"),
timestamp("2017-05-16T09:00:00"),
timestamp("2017-05-18T11:30:00"),
timestamp("2017-05-18T17:00:00"),
timestamp("2017-05-24T12:45:00"),
timestamp("2017-05-26T00:00:00"),
timestamp("2017-05-27T00:00:00"),
timestamp("2017-05-29T13:00:00"),
timestamp("2017-05-29T14:15:00"),
timestamp("2017-05-29T15:00:00"),
timestamp("2017-06-08T09:00:00"),
timestamp("2017-06-08T09:00:00"),
timestamp("2017-06-08T11:45:00"),
timestamp("2017-06-08T11:45:00"),
timestamp("2017-06-08T12:30:00"),
timestamp("2017-06-21T07:00:00"),
timestamp("2017-06-26T17:30:00"),
timestamp("2017-06-27T08:00:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-05T07:00:00"),
timestamp("2017-07-06T11:30:00"),
timestamp("2017-07-17T09:00:00"),
timestamp("2017-07-17T09:00:00"),
timestamp("2017-07-18T08:00:00"),
timestamp("2017-07-20T11:45:00"),
timestamp("2017-07-20T11:45:00"),
timestamp("2017-07-20T12:30:00"),
timestamp("2017-07-31T09:00:00"),
timestamp("2017-07-31T09:00:00"),
timestamp("2017-08-01T09:00:00"),
timestamp("2017-08-01T09:00:00"),
timestamp("2017-08-02T07:00:00"),
timestamp("2017-08-16T09:00:00"),
timestamp("2017-08-16T09:00:00"),
timestamp("2017-08-17T09:00:00"),
timestamp("2017-08-17T09:00:00"),
timestamp("2017-08-17T11:30:00"),
timestamp("2017-08-23T07:00:00"),
timestamp("2017-08-25T19:00:00"),
timestamp("2017-08-31T09:00:00"),
timestamp("2017-08-31T09:00:00"),
timestamp("2017-09-07T09:00:00"),
timestamp("2017-09-07T09:00:00"),
timestamp("2017-09-07T11:45:00"),
timestamp("2017-09-07T11:45:00"),
timestamp("2017-09-07T12:30:00"),
timestamp("2017-09-18T09:00:00"),
timestamp("2017-09-18T09:00:00"),
timestamp("2017-09-20T07:00:00"),
timestamp("2017-09-21T13:30:00"),
timestamp("2017-09-22T08:00:00"),
timestamp("2017-09-22T09:30:00"),
timestamp("2017-09-25T13:00:00"),
timestamp("2017-09-29T09:00:00"),
timestamp("2017-09-29T09:00:00"),
timestamp("2017-10-04T07:00:00"),
timestamp("2017-10-04T17:15:00"),
timestamp("2017-10-05T11:30:00"),
timestamp("2017-10-12T14:30:00"),
timestamp("2017-10-17T09:00:00"),
timestamp("2017-10-17T09:00:00"),
timestamp("2017-10-18T08:10:00"),
timestamp("2017-10-26T11:45:00"),
timestamp("2017-10-26T11:45:00"),
timestamp("2017-10-26T12:30:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-11-07T09:00:00"),
timestamp("2017-11-08T08:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-16T10:00:00"),
timestamp("2017-11-16T10:00:00"),
timestamp("2017-11-17T08:30:00"),
timestamp("2017-11-20T10:30:00"),
timestamp("2017-11-20T14:00:00"),
timestamp("2017-11-20T16:00:00"),
timestamp("2017-11-23T12:30:00"),
timestamp("2017-11-30T10:00:00"),
timestamp("2017-11-30T10:00:00"),
timestamp("2017-12-06T08:00:00"),
timestamp("2017-12-07T10:00:00"),
timestamp("2017-12-07T10:00:00"),
timestamp("2017-12-07T16:00:00"),
timestamp("2017-12-12T19:00:00"),
timestamp("2017-12-14T12:45:00"),
timestamp("2017-12-14T12:45:00"),
timestamp("2017-12-14T13:30:00"),
timestamp("2017-12-18T10:00:00"),
timestamp("2017-12-18T10:00:00"),
timestamp("2018-01-05T10:00:00"),
timestamp("2018-01-05T10:00:00"),
timestamp("2018-01-09T08:00:00"),
timestamp("2018-01-11T12:30:00"),
timestamp("2018-01-17T10:00:00"),
timestamp("2018-01-17T10:00:00"),
timestamp("2018-01-25T12:45:00"),
timestamp("2018-01-25T12:45:00"),
timestamp("2018-01-25T13:30:00"),
timestamp("2018-01-30T10:00:00"),
timestamp("2018-01-30T10:00:00"),
timestamp("2018-01-31T10:00:00"),
timestamp("2018-01-31T10:00:00"),
timestamp("2018-02-05T16:00:00"),
timestamp("2018-02-07T08:00:00"),
timestamp("2018-02-14T10:00:00"),
timestamp("2018-02-14T10:00:00"),
timestamp("2018-02-21T08:00:00"),
timestamp("2018-02-22T12:30:00"),
timestamp("2018-02-23T10:00:00"),
timestamp("2018-02-23T10:00:00"),
timestamp("2018-02-26T14:40:00"),
timestamp("2018-02-28T10:00:00"),
timestamp("2018-02-28T10:00:00"),
timestamp("2018-03-07T10:00:00"),
timestamp("2018-03-07T10:00:00"),
timestamp("2018-03-08T12:45:00"),
timestamp("2018-03-08T12:45:00"),
timestamp("2018-03-08T13:30:00"),
timestamp("2018-03-14T08:00:00"),
timestamp("2018-03-16T10:00:00"),
timestamp("2018-03-16T10:00:00"),
timestamp("2018-04-04T09:00:00"),
timestamp("2018-04-04T09:00:00"),
timestamp("2018-04-11T11:00:00"),
timestamp("2018-04-12T11:30:00"),
timestamp("2018-04-18T09:00:00"),
timestamp("2018-04-18T09:00:00"),
timestamp("2018-04-26T11:45:00"),
timestamp("2018-04-26T11:45:00"),
timestamp("2018-04-26T12:30:00"),
timestamp("2018-05-02T09:00:00"),
timestamp("2018-05-02T09:00:00"),
timestamp("2018-05-03T09:00:00"),
timestamp("2018-05-03T09:00:00"),
timestamp("2018-05-11T13:15:00"),
timestamp("2018-05-15T09:00:00"),
timestamp("2018-05-15T09:00:00"),
timestamp("2018-05-16T09:00:00"),
timestamp("2018-05-16T09:00:00"),
timestamp("2018-05-16T12:00:00"),
timestamp("2018-05-24T11:30:00"),
timestamp("2018-05-31T00:00:00"),
timestamp("2018-05-31T09:00:00"),
timestamp("2018-05-31T09:00:00"),
timestamp("2018-06-01T00:00:00"),
timestamp("2018-06-02T00:00:00"),
timestamp("2018-06-07T09:00:00"),
timestamp("2018-06-07T09:00:00"),
timestamp("2018-06-08T00:00:00"),
timestamp("2018-06-09T00:00:00"),
timestamp("2018-06-14T11:45:00"),
timestamp("2018-06-14T11:45:00"),
timestamp("2018-06-14T12:30:00"),
timestamp("2018-06-15T09:00:00"),
timestamp("2018-06-15T09:00:00"),
timestamp("2018-06-18T17:30:00"),
timestamp("2018-06-19T08:00:00"),
timestamp("2018-06-20T13:30:00"),
timestamp("2018-06-29T09:00:00"),
timestamp("2018-06-29T09:00:00"),
timestamp("2018-07-09T13:00:00"),
timestamp("2018-07-09T15:00:00"),
timestamp("2018-07-11T07:00:00"),
timestamp("2018-07-12T11:30:00"),
timestamp("2018-07-18T09:00:00"),
timestamp("2018-07-18T09:00:00"),
timestamp("2018-07-26T11:45:00"),
timestamp("2018-07-26T11:45:00"),
timestamp("2018-07-26T12:30:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-08-14T09:00:00"),
timestamp("2018-08-14T09:00:00"),
timestamp("2018-08-17T09:00:00"),
timestamp("2018-08-17T09:00:00"),
timestamp("2018-08-23T11:30:00"),
timestamp("2018-08-31T09:00:00"),
timestamp("2018-08-31T09:00:00"),
timestamp("2018-09-07T09:00:00"),
timestamp("2018-09-07T09:00:00"),
timestamp("2018-09-13T11:45:00"),
timestamp("2018-09-13T11:45:00"),
timestamp("2018-09-13T12:30:00"),
timestamp("2018-09-17T09:00:00"),
timestamp("2018-09-17T09:00:00"),
timestamp("2018-09-18T07:15:00"),
timestamp("2018-09-19T13:00:00"),
timestamp("2018-09-24T13:00:00"),
timestamp("2018-09-27T13:30:00"),
timestamp("2018-09-28T09:00:00"),
timestamp("2018-09-28T09:00:00"),
timestamp("2018-10-11T11:30:00"),
timestamp("2018-10-17T00:00:00"),
timestamp("2018-10-17T09:00:00"),
timestamp("2018-10-17T09:00:00"),
timestamp("2018-10-18T00:00:00"),
timestamp("2018-10-25T11:45:00"),
timestamp("2018-10-25T11:45:00"),
timestamp("2018-10-25T12:30:00"),
timestamp("2018-10-26T14:00:00"),
timestamp("2018-10-30T10:00:00"),
timestamp("2018-10-30T10:00:00"),
timestamp("2018-10-31T10:00:00"),
timestamp("2018-10-31T10:00:00"),
timestamp("2018-11-08T15:20:00"),
timestamp("2018-11-14T10:00:00"),
timestamp("2018-11-14T10:00:00"),
timestamp("2018-11-16T08:30:00"),
timestamp("2018-11-16T10:00:00"),
timestamp("2018-11-16T10:00:00"),
timestamp("2018-11-22T12:30:00"),
timestamp("2018-11-26T00:00:00"),
timestamp("2018-11-26T14:00:00"),
timestamp("2018-11-29T08:00:00"),
timestamp("2018-11-30T10:00:00"),
timestamp("2018-11-30T10:00:00"),
timestamp("2018-12-05T08:30:00"),
timestamp("2018-12-07T10:00:00"),
timestamp("2018-12-07T10:00:00"),
timestamp("2018-12-13T12:45:00"),
timestamp("2018-12-13T12:45:00"),
timestamp("2018-12-13T13:30:00"),
timestamp("2018-12-15T10:30:00"),
timestamp("2018-12-17T10:00:00"),
timestamp("2018-12-17T10:00:00"),
timestamp("2019-01-04T10:00:00"),
timestamp("2019-01-04T10:00:00"),
timestamp("2019-01-10T12:30:00"),
timestamp("2019-01-15T15:00:00"),
timestamp("2019-01-17T10:00:00"),
timestamp("2019-01-17T10:00:00"),
timestamp("2019-01-24T12:45:00"),
timestamp("2019-01-24T12:45:00"),
timestamp("2019-01-24T13:30:00"),
timestamp("2019-01-28T14:00:00"),
timestamp("2019-01-28T16:00:00"),
timestamp("2019-01-31T10:00:00"),
timestamp("2019-01-31T10:00:00"),
timestamp("2019-02-01T10:00:00"),
timestamp("2019-02-01T10:00:00"),
timestamp("2019-02-14T10:00:00"),
timestamp("2019-02-14T10:00:00"),
timestamp("2019-02-21T09:00:00"),
timestamp("2019-02-21T12:30:00"),
timestamp("2019-02-22T15:30:00"),
timestamp("2019-03-01T10:00:00"),
timestamp("2019-03-01T10:00:00"),
timestamp("2019-03-07T10:00:00"),
timestamp("2019-03-07T10:00:00"),
timestamp("2019-03-07T12:45:00"),
timestamp("2019-03-07T12:45:00"),
timestamp("2019-03-07T13:30:00"),
timestamp("2019-03-22T09:00:00"),
timestamp("2019-03-27T08:00:00"),
timestamp("2019-04-01T09:00:00"),
timestamp("2019-04-01T09:00:00"),
timestamp("2019-04-04T11:30:00"),
timestamp("2019-04-10T11:45:00"),
timestamp("2019-04-10T11:45:00"),
timestamp("2019-04-10T12:30:00"),
timestamp("2019-04-18T08:00:00"),
timestamp("2019-04-30T09:00:00"),
timestamp("2019-04-30T09:00:00"),
timestamp("2019-05-03T09:00:00"),
timestamp("2019-05-03T09:00:00"),
timestamp("2019-05-08T11:30:00"),
timestamp("2019-05-15T09:00:00"),
timestamp("2019-05-15T09:00:00"),
timestamp("2019-05-22T07:30:00"),
timestamp("2019-05-23T08:00:00"),
timestamp("2019-05-23T11:30:00"),
timestamp("2019-06-04T09:00:00"),
timestamp("2019-06-04T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-06T11:45:00"),
timestamp("2019-06-06T11:45:00"),
timestamp("2019-06-06T12:30:00"),
timestamp("2019-06-12T08:15:00"),
timestamp("2019-06-17T18:00:00"),
timestamp("2019-06-18T08:00:00"),
timestamp("2019-06-18T14:00:00"),
timestamp("2019-06-19T08:30:00"),
timestamp("2019-06-19T14:00:00"),
timestamp("2019-06-21T08:00:00"),
timestamp("2019-06-28T09:00:00"),
timestamp("2019-06-28T09:00:00"),
timestamp("2019-07-11T11:30:00"),
timestamp("2019-07-23T08:00:00"),
timestamp("2019-07-24T08:00:00"),
timestamp("2019-07-25T11:45:00"),
timestamp("2019-07-25T11:45:00"),
timestamp("2019-07-25T12:30:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-08-14T09:00:00"),
timestamp("2019-08-14T09:00:00"),
timestamp("2019-08-22T08:00:00"),
timestamp("2019-08-22T11:30:00"),
timestamp("2019-08-24T00:00:00"),
timestamp("2019-08-25T00:00:00"),
timestamp("2019-08-26T00:00:00"),
timestamp("2019-08-30T09:00:00"),
timestamp("2019-08-30T09:00:00"),
timestamp("2019-09-04T07:00:00"),
timestamp("2019-09-06T09:00:00"),
timestamp("2019-09-06T09:00:00"),
timestamp("2019-09-12T11:45:00"),
timestamp("2019-09-12T11:45:00"),
timestamp("2019-09-12T12:30:00"),
timestamp("2019-09-23T08:00:00"),
timestamp("2019-09-23T13:00:00"),
timestamp("2019-09-23T15:00:00"),
timestamp("2019-09-26T13:30:00"),
timestamp("2019-10-01T09:00:00"),
timestamp("2019-10-01T09:00:00"),
timestamp("2019-10-01T16:45:00"),
timestamp("2019-10-10T11:30:00"),
timestamp("2019-10-11T10:00:00"),
timestamp("2019-10-22T08:00:00"),
timestamp("2019-10-24T08:00:00"),
timestamp("2019-10-24T11:45:00"),
timestamp("2019-10-24T11:45:00"),
timestamp("2019-10-24T12:30:00"),
timestamp("2019-10-28T15:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-11-04T19:30:00"),
timestamp("2019-11-14T10:00:00"),
timestamp("2019-11-14T10:00:00"),
timestamp("2019-11-21T12:30:00"),
timestamp("2019-11-22T08:30:00"),
timestamp("2019-11-22T09:00:00"),
timestamp("2019-11-29T10:00:00"),
timestamp("2019-11-29T10:00:00"),
timestamp("2019-12-01T11:00:00"),
timestamp("2019-12-02T14:00:00"),
timestamp("2019-12-05T10:00:00"),
timestamp("2019-12-05T10:00:00"),
timestamp("2019-12-12T12:45:00"),
timestamp("2019-12-12T12:45:00"),
timestamp("2019-12-12T13:30:00"),
timestamp("2019-12-16T09:00:00"),
timestamp("2019-12-18T08:30:00")
)
// @function EUR high impact news date and time from 2020 to 2023
export eurNews2020To2023() =>
array.from(
timestamp("2020-01-07T10:00:00"),
timestamp("2020-01-07T10:00:00"),
timestamp("2020-01-16T12:30:00"),
timestamp("2020-01-16T18:00:00"),
timestamp("2020-01-20T18:30:00"),
timestamp("2020-01-21T09:00:00"),
timestamp("2020-01-23T12:45:00"),
timestamp("2020-01-23T12:45:00"),
timestamp("2020-01-23T13:30:00"),
timestamp("2020-01-24T09:00:00"),
timestamp("2020-01-24T10:30:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-02-05T12:15:00"),
timestamp("2020-02-06T08:00:00"),
timestamp("2020-02-11T14:00:00"),
timestamp("2020-02-14T10:00:00"),
timestamp("2020-02-14T10:00:00"),
timestamp("2020-02-20T12:30:00"),
timestamp("2020-02-21T09:00:00"),
timestamp("2020-02-26T13:30:00"),
timestamp("2020-02-27T09:45:00"),
timestamp("2020-03-03T00:00:00"),
timestamp("2020-03-03T10:00:00"),
timestamp("2020-03-03T10:00:00"),
timestamp("2020-03-10T10:00:00"),
timestamp("2020-03-10T10:00:00"),
timestamp("2020-03-12T12:45:00"),
timestamp("2020-03-12T12:45:00"),
timestamp("2020-03-12T13:30:00"),
timestamp("2020-03-16T00:00:00"),
timestamp("2020-03-16T12:00:00"),
timestamp("2020-03-24T00:00:00"),
timestamp("2020-03-24T09:00:00"),
timestamp("2020-03-31T09:00:00"),
timestamp("2020-03-31T09:00:00"),
timestamp("2020-04-09T11:30:00"),
timestamp("2020-04-14T00:00:00"),
timestamp("2020-04-23T00:00:00"),
timestamp("2020-04-23T08:00:00"),
timestamp("2020-04-28T08:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T11:45:00"),
timestamp("2020-04-30T11:45:00"),
timestamp("2020-04-30T12:30:00"),
timestamp("2020-05-08T11:00:00"),
timestamp("2020-05-15T09:00:00"),
timestamp("2020-05-15T09:00:00"),
timestamp("2020-05-19T00:00:00"),
timestamp("2020-05-21T08:00:00"),
timestamp("2020-05-22T11:30:00"),
timestamp("2020-05-27T07:30:00"),
timestamp("2020-05-29T09:00:00"),
timestamp("2020-05-29T09:00:00"),
timestamp("2020-06-03T00:00:00"),
timestamp("2020-06-03T09:00:00"),
timestamp("2020-06-04T11:45:00"),
timestamp("2020-06-04T11:45:00"),
timestamp("2020-06-04T12:30:00"),
timestamp("2020-06-08T13:45:00"),
timestamp("2020-06-08T15:45:00"),
timestamp("2020-06-09T09:00:00"),
timestamp("2020-06-09T09:00:00"),
timestamp("2020-06-23T08:00:00"),
timestamp("2020-06-25T11:30:00"),
timestamp("2020-06-26T07:00:00"),
timestamp("2020-06-30T09:00:00"),
timestamp("2020-06-30T09:00:00"),
timestamp("2020-07-04T10:40:00"),
timestamp("2020-07-14T08:00:00"),
timestamp("2020-07-16T11:45:00"),
timestamp("2020-07-16T11:45:00"),
timestamp("2020-07-16T12:30:00"),
timestamp("2020-07-17T00:00:00"),
timestamp("2020-07-22T13:15:00"),
timestamp("2020-07-24T08:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-08-05T09:00:00"),
timestamp("2020-08-14T09:00:00"),
timestamp("2020-08-14T09:00:00"),
timestamp("2020-08-17T00:00:00"),
timestamp("2020-08-21T08:00:00"),
timestamp("2020-09-01T09:00:00"),
timestamp("2020-09-01T09:00:00"),
timestamp("2020-09-03T09:00:00"),
timestamp("2020-09-08T09:00:00"),
timestamp("2020-09-08T09:00:00"),
timestamp("2020-09-10T11:45:00"),
timestamp("2020-09-10T11:45:00"),
timestamp("2020-09-10T12:30:00"),
timestamp("2020-09-10T17:00:00"),
timestamp("2020-09-21T12:25:00"),
timestamp("2020-09-23T08:00:00"),
timestamp("2020-09-28T13:45:00"),
timestamp("2020-09-30T07:20:00"),
timestamp("2020-10-01T00:00:00"),
timestamp("2020-10-02T00:00:00"),
timestamp("2020-10-02T09:00:00"),
timestamp("2020-10-02T09:00:00"),
timestamp("2020-10-05T09:00:00"),
timestamp("2020-10-06T13:00:00"),
timestamp("2020-10-07T12:10:00"),
timestamp("2020-10-12T11:00:00"),
timestamp("2020-10-14T08:00:00"),
timestamp("2020-10-15T00:00:00"),
timestamp("2020-10-15T16:00:00"),
timestamp("2020-10-16T00:00:00"),
timestamp("2020-10-18T13:05:00"),
timestamp("2020-10-19T12:40:00"),
timestamp("2020-10-19T12:45:00"),
timestamp("2020-10-21T07:30:00"),
timestamp("2020-10-23T08:00:00"),
timestamp("2020-10-27T09:00:00"),
timestamp("2020-10-29T12:45:00"),
timestamp("2020-10-29T12:45:00"),
timestamp("2020-10-29T13:30:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-11-05T10:00:00"),
timestamp("2020-11-09T09:25:00"),
timestamp("2020-11-11T13:00:00"),
timestamp("2020-11-12T16:45:00"),
timestamp("2020-11-13T10:00:00"),
timestamp("2020-11-13T10:00:00"),
timestamp("2020-11-16T13:00:00"),
timestamp("2020-11-17T16:00:00"),
timestamp("2020-11-19T08:00:00"),
timestamp("2020-11-19T15:15:00"),
timestamp("2020-11-20T08:35:00"),
timestamp("2020-11-23T09:00:00"),
timestamp("2020-11-24T14:00:00"),
timestamp("2020-11-30T10:30:00"),
timestamp("2020-12-01T10:00:00"),
timestamp("2020-12-01T10:00:00"),
timestamp("2020-12-01T17:00:00"),
timestamp("2020-12-03T10:00:00"),
timestamp("2020-12-07T00:00:00"),
timestamp("2020-12-08T10:00:00"),
timestamp("2020-12-08T10:00:00"),
timestamp("2020-12-09T19:00:00"),
timestamp("2020-12-10T00:00:00"),
timestamp("2020-12-10T12:45:00"),
timestamp("2020-12-10T12:45:00"),
timestamp("2020-12-10T13:30:00"),
timestamp("2020-12-11T00:00:00"),
timestamp("2020-12-16T09:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-11T14:40:00"),
timestamp("2021-01-13T09:00:00"),
timestamp("2021-01-19T09:00:00"),
timestamp("2021-01-21T12:45:00"),
timestamp("2021-01-21T12:45:00"),
timestamp("2021-01-21T13:30:00"),
timestamp("2021-01-22T09:00:00"),
timestamp("2021-01-25T08:45:00"),
timestamp("2021-01-25T16:15:00"),
timestamp("2021-02-02T10:00:00"),
timestamp("2021-02-02T10:00:00"),
timestamp("2021-02-03T10:00:00"),
timestamp("2021-02-03T10:00:00"),
timestamp("2021-02-04T10:00:00"),
timestamp("2021-02-12T00:00:00"),
timestamp("2021-02-16T10:00:00"),
timestamp("2021-02-16T10:00:00"),
timestamp("2021-02-18T12:30:00"),
timestamp("2021-02-19T09:00:00"),
timestamp("2021-02-22T14:30:00"),
timestamp("2021-03-01T16:10:00"),
timestamp("2021-03-02T10:00:00"),
timestamp("2021-03-02T10:00:00"),
timestamp("2021-03-04T10:00:00"),
timestamp("2021-03-09T10:00:00"),
timestamp("2021-03-09T10:00:00"),
timestamp("2021-03-11T12:45:00"),
timestamp("2021-03-11T12:45:00"),
timestamp("2021-03-11T13:30:00"),
timestamp("2021-03-18T08:00:00"),
timestamp("2021-03-18T11:00:00"),
timestamp("2021-03-24T09:00:00"),
timestamp("2021-03-24T15:40:00"),
timestamp("2021-03-25T00:00:00"),
timestamp("2021-03-25T09:30:00"),
timestamp("2021-03-26T00:00:00"),
timestamp("2021-03-31T09:00:00"),
timestamp("2021-03-31T09:00:00"),
timestamp("2021-04-12T09:00:00"),
timestamp("2021-04-14T14:00:00"),
timestamp("2021-04-20T08:00:00"),
timestamp("2021-04-22T11:45:00"),
timestamp("2021-04-22T11:45:00"),
timestamp("2021-04-22T12:30:00"),
timestamp("2021-04-23T08:00:00"),
timestamp("2021-04-23T14:30:00"),
timestamp("2021-04-28T14:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-05-06T09:00:00"),
timestamp("2021-05-06T11:25:00"),
timestamp("2021-05-07T10:00:00"),
timestamp("2021-05-18T09:00:00"),
timestamp("2021-05-18T09:00:00"),
timestamp("2021-05-18T14:00:00"),
timestamp("2021-05-20T12:00:00"),
timestamp("2021-05-21T08:00:00"),
timestamp("2021-05-21T11:00:00"),
timestamp("2021-06-01T09:00:00"),
timestamp("2021-06-01T09:00:00"),
timestamp("2021-06-02T17:10:00"),
timestamp("2021-06-04T09:00:00"),
timestamp("2021-06-08T09:00:00"),
timestamp("2021-06-08T09:00:00"),
timestamp("2021-06-10T11:45:00"),
timestamp("2021-06-10T11:45:00"),
timestamp("2021-06-10T12:30:00"),
timestamp("2021-06-11T00:00:00"),
timestamp("2021-06-12T00:00:00"),
timestamp("2021-06-13T00:00:00"),
timestamp("2021-06-21T12:30:00"),
timestamp("2021-06-21T14:15:00"),
timestamp("2021-06-23T08:00:00"),
timestamp("2021-06-23T18:00:00"),
timestamp("2021-06-24T00:00:00"),
timestamp("2021-06-25T00:00:00"),
timestamp("2021-06-29T13:40:00"),
timestamp("2021-06-30T09:00:00"),
timestamp("2021-06-30T09:00:00"),
timestamp("2021-07-01T07:00:00"),
timestamp("2021-07-02T12:30:00"),
timestamp("2021-07-06T09:00:00"),
timestamp("2021-07-08T11:00:00"),
timestamp("2021-07-08T12:30:00"),
timestamp("2021-07-09T10:00:00"),
timestamp("2021-07-11T12:10:00"),
timestamp("2021-07-20T08:00:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T12:30:00"),
timestamp("2021-07-23T08:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T14:00:00"),
timestamp("2021-08-04T09:00:00"),
timestamp("2021-08-17T09:00:00"),
timestamp("2021-08-17T09:00:00"),
timestamp("2021-08-23T08:00:00"),
timestamp("2021-08-25T08:30:00"),
timestamp("2021-08-31T09:00:00"),
timestamp("2021-08-31T09:00:00"),
timestamp("2021-09-03T09:00:00"),
timestamp("2021-09-07T09:00:00"),
timestamp("2021-09-07T09:00:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T12:30:00"),
timestamp("2021-09-10T09:30:00"),
timestamp("2021-09-13T13:30:00"),
timestamp("2021-09-16T12:00:00"),
timestamp("2021-09-23T08:00:00"),
timestamp("2021-09-27T11:45:00"),
timestamp("2021-09-28T12:00:00"),
timestamp("2021-09-29T15:45:00"),
timestamp("2021-09-29T16:30:00"),
timestamp("2021-10-01T09:00:00"),
timestamp("2021-10-01T09:00:00"),
timestamp("2021-10-05T15:00:00"),
timestamp("2021-10-06T09:00:00"),
timestamp("2021-10-08T12:10:00"),
timestamp("2021-10-16T14:00:00"),
timestamp("2021-10-21T00:00:00"),
timestamp("2021-10-22T08:00:00"),
timestamp("2021-10-26T08:00:00"),
timestamp("2021-10-27T15:20:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T12:30:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-11-03T10:15:00"),
timestamp("2021-11-04T13:00:00"),
timestamp("2021-11-05T10:00:00"),
timestamp("2021-11-09T13:00:00"),
timestamp("2021-11-15T10:00:00"),
timestamp("2021-11-16T10:00:00"),
timestamp("2021-11-16T10:00:00"),
timestamp("2021-11-16T16:10:00"),
timestamp("2021-11-17T01:20:00"),
timestamp("2021-11-19T08:30:00"),
timestamp("2021-11-19T18:45:00"),
timestamp("2021-11-23T09:00:00"),
timestamp("2021-11-25T13:30:00"),
timestamp("2021-11-26T08:00:00"),
timestamp("2021-11-29T08:00:00"),
timestamp("2021-11-30T10:00:00"),
timestamp("2021-11-30T10:00:00"),
timestamp("2021-12-03T08:30:00"),
timestamp("2021-12-03T10:00:00"),
timestamp("2021-12-07T10:00:00"),
timestamp("2021-12-07T10:00:00"),
timestamp("2021-12-10T09:05:00"),
timestamp("2021-12-16T00:00:00"),
timestamp("2021-12-16T09:00:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T13:30:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-11T10:20:00"),
timestamp("2022-01-14T13:15:00"),
timestamp("2022-01-21T12:30:00"),
timestamp("2022-01-24T09:00:00"),
timestamp("2022-01-31T10:00:00"),
timestamp("2022-01-31T10:00:00"),
timestamp("2022-02-01T09:00:00"),
timestamp("2022-02-02T10:00:00"),
timestamp("2022-02-02T10:00:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T13:30:00"),
timestamp("2022-02-04T10:00:00"),
timestamp("2022-02-07T15:45:00"),
timestamp("2022-02-14T16:15:00"),
timestamp("2022-02-15T10:00:00"),
timestamp("2022-02-15T10:00:00"),
timestamp("2022-02-21T09:00:00"),
timestamp("2022-02-25T14:00:00"),
timestamp("2022-02-28T15:50:00"),
timestamp("2022-03-01T13:00:00"),
timestamp("2022-03-02T10:00:00"),
timestamp("2022-03-02T10:00:00"),
timestamp("2022-03-02T14:30:00"),
timestamp("2022-03-04T10:00:00"),
timestamp("2022-03-08T10:00:00"),
timestamp("2022-03-08T10:00:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T13:30:00"),
timestamp("2022-03-15T15:15:00"),
timestamp("2022-03-17T09:30:00"),
timestamp("2022-03-21T07:30:00"),
timestamp("2022-03-22T13:15:00"),
timestamp("2022-03-24T09:00:00"),
timestamp("2022-03-30T08:00:00"),
timestamp("2022-04-01T09:00:00"),
timestamp("2022-04-01T09:00:00"),
timestamp("2022-04-07T09:00:00"),
timestamp("2022-04-12T08:00:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T12:30:00"),
timestamp("2022-04-21T17:00:00"),
timestamp("2022-04-22T08:00:00"),
timestamp("2022-04-22T13:00:00"),
timestamp("2022-04-27T16:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-05-03T13:00:00"),
timestamp("2022-05-04T09:00:00"),
timestamp("2022-05-11T08:00:00"),
timestamp("2022-05-17T09:00:00"),
timestamp("2022-05-17T09:00:00"),
timestamp("2022-05-17T17:00:00"),
timestamp("2022-05-24T08:00:00"),
timestamp("2022-05-24T18:00:00"),
timestamp("2022-05-25T08:00:00"),
timestamp("2022-05-31T09:00:00"),
timestamp("2022-05-31T09:00:00"),
timestamp("2022-06-01T11:00:00"),
timestamp("2022-06-03T09:00:00"),
timestamp("2022-06-08T09:00:00"),
timestamp("2022-06-08T09:00:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T12:30:00"),
timestamp("2022-06-15T09:00:00"),
timestamp("2022-06-15T16:20:00"),
timestamp("2022-06-20T13:00:00"),
timestamp("2022-06-23T08:00:00"),
timestamp("2022-06-27T18:30:00"),
timestamp("2022-06-28T08:00:00"),
timestamp("2022-06-29T13:00:00"),
timestamp("2022-06-29T15:00:00"),
timestamp("2022-07-01T09:00:00"),
timestamp("2022-07-01T09:00:00"),
timestamp("2022-07-06T09:00:00"),
timestamp("2022-07-08T11:55:00"),
timestamp("2022-07-19T08:00:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:45:00"),
timestamp("2022-07-21T14:15:00"),
timestamp("2022-07-22T08:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-08-03T09:00:00"),
timestamp("2022-08-17T09:00:00"),
timestamp("2022-08-17T09:00:00"),
timestamp("2022-08-23T08:00:00"),
timestamp("2022-08-31T09:00:00"),
timestamp("2022-08-31T09:00:00"),
timestamp("2022-09-05T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:45:00"),
timestamp("2022-09-08T14:15:00"),
timestamp("2022-09-09T09:30:00"),
timestamp("2022-09-14T10:00:00"),
timestamp("2022-09-16T08:30:00"),
timestamp("2022-09-20T17:00:00"),
timestamp("2022-09-23T08:00:00"),
timestamp("2022-09-26T13:00:00"),
timestamp("2022-09-27T11:30:00"),
timestamp("2022-09-28T07:15:00"),
timestamp("2022-09-30T09:00:00"),
timestamp("2022-09-30T09:00:00"),
timestamp("2022-10-04T15:00:00"),
timestamp("2022-10-06T09:00:00"),
timestamp("2022-10-12T13:30:00"),
timestamp("2022-10-22T09:00:00"),
timestamp("2022-10-24T08:00:00"),
timestamp("2022-10-25T08:00:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:45:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-11-03T08:05:00"),
timestamp("2022-11-04T09:30:00"),
timestamp("2022-11-07T08:40:00"),
timestamp("2022-11-08T10:00:00"),
timestamp("2022-11-15T10:00:00"),
timestamp("2022-11-15T10:00:00"),
timestamp("2022-11-16T17:00:00"),
timestamp("2022-11-18T08:30:00"),
timestamp("2022-11-23T09:00:00"),
timestamp("2022-11-28T14:00:00"),
timestamp("2022-11-30T10:00:00"),
timestamp("2022-11-30T10:00:00"),
timestamp("2022-12-02T02:40:00"),
timestamp("2022-12-03T02:30:00"),
timestamp("2022-12-05T10:00:00"),
timestamp("2022-12-07T10:00:00"),
timestamp("2022-12-07T10:00:00"),
timestamp("2022-12-08T12:00:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:45:00"),
timestamp("2022-12-16T09:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-19T10:30:00"),
timestamp("2023-01-20T10:00:00"),
timestamp("2023-01-23T17:45:00"),
timestamp("2023-01-24T09:00:00"),
timestamp("2023-01-24T09:45:00"),
timestamp("2023-01-31T09:00:00"),
timestamp("2023-01-31T10:00:00"),
timestamp("2023-01-31T10:00:00"),
timestamp("2023-02-01T10:00:00"),
timestamp("2023-02-01T10:00:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:45:00"),
timestamp("2023-02-02T18:30:00"),
timestamp("2023-02-06T10:00:00"),
timestamp("2023-02-06T18:00:00"),
timestamp("2023-02-14T10:00:00"),
timestamp("2023-02-14T10:00:00"),
timestamp("2023-02-15T14:00:00"),
timestamp("2023-02-21T09:00:00"),
timestamp("2023-02-21T15:00:00"),
timestamp("2023-03-02T07:55:00"),
timestamp("2023-03-02T10:00:00"),
timestamp("2023-03-02T10:00:00"),
timestamp("2023-03-06T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-10T15:00:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:45:00"),
timestamp("2023-03-20T14:00:00"),
timestamp("2023-03-20T16:00:00"),
timestamp("2023-03-21T12:30:00"),
timestamp("2023-03-22T08:45:00"),
timestamp("2023-03-24T09:00:00"),
timestamp("2023-03-28T13:15:00"),
timestamp("2023-03-31T09:00:00"),
timestamp("2023-03-31T09:00:00"),
timestamp("2023-04-11T09:00:00"),
timestamp("2023-04-17T17:00:00"),
timestamp("2023-04-20T12:00:00"),
timestamp("2023-04-21T08:00:00"),
timestamp("2023-04-28T09:00:00"),
timestamp("2023-04-28T09:00:00"),
timestamp("2023-05-02T08:00:00"),
timestamp("2023-05-02T09:00:00"),
timestamp("2023-05-02T09:00:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:45:00"),
timestamp("2023-05-05T09:00:00"),
timestamp("2023-05-11T12:00:00"),
timestamp("2023-05-16T09:00:00"),
timestamp("2023-05-16T09:00:00"),
timestamp("2023-05-16T14:00:00"),
timestamp("2023-05-18T09:00:00"),
timestamp("2023-05-23T08:00:00"),
timestamp("2023-05-24T17:45:00"),
timestamp("2023-05-31T12:30:00"),
timestamp("2023-06-01T09:00:00"),
timestamp("2023-06-01T09:00:00"),
timestamp("2023-06-01T09:30:00"),
timestamp("2023-06-05T13:00:00"),
timestamp("2023-06-06T09:00:00"),
timestamp("2023-06-08T09:00:00"),
timestamp("2023-06-08T09:00:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:45:00"),
timestamp("2023-06-23T07:00:00"),
timestamp("2023-06-23T08:00:00"),
timestamp("2023-06-26T19:00:00"),
timestamp("2023-06-27T08:00:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-07-06T09:00:00"),
timestamp("2023-07-18T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:45:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-08-04T09:00:00"),
timestamp("2023-08-16T09:00:00"),
timestamp("2023-08-16T09:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-09-06T09:00:00"),
timestamp("2023-09-07T09:00:00"),
timestamp("2023-09-07T09:00:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:45:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-10-04T09:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:45:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-11-08T10:00:00"),
timestamp("2023-11-14T10:00:00"),
timestamp("2023-11-14T10:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-12-06T10:00:00"),
timestamp("2023-12-07T10:00:00"),
timestamp("2023-12-07T10:00:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:45:00"),
timestamp("2023-12-20T09:00:00"),
timestamp("2023-12-20T09:00:00"),
timestamp("2023-12-20T09:00:00")
) |
CalendarUsd | https://www.tradingview.com/script/1ypFJG7Y-CalendarUsd/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the important events on USD. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("CalendarUsd")
// @function USD high impact news date and time from 2015 to 2019
export HighImpactNews2015To2019() =>
array.from(
timestamp("2015-01-02T15:00:00"),
timestamp("2015-01-06T15:00:00"),
timestamp("2015-01-07T19:00:00"),
timestamp("2015-01-09T13:30:00"),
timestamp("2015-01-09T13:30:00"),
timestamp("2015-01-14T13:30:00"),
timestamp("2015-01-16T13:30:00"),
timestamp("2015-01-16T13:30:00"),
timestamp("2015-01-27T13:30:00"),
timestamp("2015-01-27T15:00:00"),
timestamp("2015-01-28T19:00:00"),
timestamp("2015-01-28T19:00:00"),
timestamp("2015-01-30T13:30:00"),
timestamp("2015-02-02T15:00:00"),
timestamp("2015-02-04T15:00:00"),
timestamp("2015-02-06T13:30:00"),
timestamp("2015-02-06T13:30:00"),
timestamp("2015-02-12T13:30:00"),
timestamp("2015-02-18T19:00:00"),
timestamp("2015-02-24T15:00:00"),
timestamp("2015-02-24T15:00:00"),
timestamp("2015-02-25T15:00:00"),
timestamp("2015-02-26T13:30:00"),
timestamp("2015-02-26T13:30:00"),
timestamp("2015-02-26T13:30:00"),
timestamp("2015-02-27T13:30:00"),
timestamp("2015-03-02T15:00:00"),
timestamp("2015-03-04T15:00:00"),
timestamp("2015-03-06T13:30:00"),
timestamp("2015-03-06T13:30:00"),
timestamp("2015-03-11T20:30:00"),
timestamp("2015-03-12T12:30:00"),
timestamp("2015-03-18T18:00:00"),
timestamp("2015-03-18T18:00:00"),
timestamp("2015-03-18T18:30:00"),
timestamp("2015-03-24T12:30:00"),
timestamp("2015-03-24T12:30:00"),
timestamp("2015-03-25T12:30:00"),
timestamp("2015-03-27T12:30:00"),
timestamp("2015-03-31T14:00:00"),
timestamp("2015-04-01T14:00:00"),
timestamp("2015-04-03T12:30:00"),
timestamp("2015-04-03T12:30:00"),
timestamp("2015-04-06T14:00:00"),
timestamp("2015-04-08T18:00:00"),
timestamp("2015-04-14T12:30:00"),
timestamp("2015-04-17T12:30:00"),
timestamp("2015-04-17T12:30:00"),
timestamp("2015-04-24T12:30:00"),
timestamp("2015-04-28T14:00:00"),
timestamp("2015-04-29T12:30:00"),
timestamp("2015-04-29T18:00:00"),
timestamp("2015-05-01T14:00:00"),
timestamp("2015-05-05T14:00:00"),
timestamp("2015-05-08T12:30:00"),
timestamp("2015-05-08T12:30:00"),
timestamp("2015-05-13T12:30:00"),
timestamp("2015-05-13T12:30:00"),
timestamp("2015-05-20T18:00:00"),
timestamp("2015-05-22T12:30:00"),
timestamp("2015-05-22T12:30:00"),
timestamp("2015-05-22T17:00:00"),
timestamp("2015-05-26T12:30:00"),
timestamp("2015-05-26T12:30:00"),
timestamp("2015-05-29T12:30:00"),
timestamp("2015-06-01T14:00:00"),
timestamp("2015-06-05T12:30:00"),
timestamp("2015-06-05T12:30:00"),
timestamp("2015-06-11T12:30:00"),
timestamp("2015-06-11T12:30:00"),
timestamp("2015-06-17T18:00:00"),
timestamp("2015-06-17T18:00:00"),
timestamp("2015-06-17T18:30:00"),
timestamp("2015-06-18T12:30:00"),
timestamp("2015-06-18T12:30:00"),
timestamp("2015-06-23T12:30:00"),
timestamp("2015-06-23T12:30:00"),
timestamp("2015-06-24T12:30:00"),
timestamp("2015-06-24T12:30:00"),
timestamp("2015-07-01T14:00:00"),
timestamp("2015-07-02T12:30:00"),
timestamp("2015-07-02T12:30:00"),
timestamp("2015-07-08T18:00:00"),
timestamp("2015-07-14T12:30:00"),
timestamp("2015-07-14T12:30:00"),
timestamp("2015-07-16T18:30:00"),
timestamp("2015-07-17T12:30:00"),
timestamp("2015-07-17T12:30:00"),
timestamp("2015-07-27T12:30:00"),
timestamp("2015-07-27T12:30:00"),
timestamp("2015-07-29T18:00:00"),
timestamp("2015-07-29T18:00:00"),
timestamp("2015-07-30T12:30:00"),
timestamp("2015-07-30T12:30:00"),
timestamp("2015-08-03T14:00:00"),
timestamp("2015-08-03T14:00:00"),
timestamp("2015-08-07T12:30:00"),
timestamp("2015-08-07T12:30:00"),
timestamp("2015-08-13T12:30:00"),
timestamp("2015-08-13T12:30:00"),
timestamp("2015-08-19T12:30:00"),
timestamp("2015-08-19T12:30:00"),
timestamp("2015-08-19T18:00:00"),
timestamp("2015-08-26T12:30:00"),
timestamp("2015-08-27T00:00:00"),
timestamp("2015-08-27T12:30:00"),
timestamp("2015-08-27T12:30:00"),
timestamp("2015-08-27T12:30:00"),
timestamp("2015-08-27T12:30:00"),
timestamp("2015-08-28T00:00:00"),
timestamp("2015-08-29T00:00:00"),
timestamp("2015-08-29T04:25:00"),
timestamp("2015-09-04T12:30:00"),
timestamp("2015-09-04T12:30:00"),
timestamp("2015-09-04T12:30:00"),
timestamp("2015-09-15T12:30:00"),
timestamp("2015-09-15T12:30:00"),
timestamp("2015-09-16T12:30:00"),
timestamp("2015-09-16T12:30:00"),
timestamp("2015-09-17T18:00:00"),
timestamp("2015-09-17T18:30:00"),
timestamp("2015-09-25T12:30:00"),
timestamp("2015-09-28T12:30:00"),
timestamp("2015-10-01T14:00:00"),
timestamp("2015-10-01T14:00:00"),
timestamp("2015-10-02T12:30:00"),
timestamp("2015-10-02T12:30:00"),
timestamp("2015-10-08T18:00:00"),
timestamp("2015-10-14T12:30:00"),
timestamp("2015-10-14T12:30:00"),
timestamp("2015-10-15T12:30:00"),
timestamp("2015-10-15T12:30:00"),
timestamp("2015-10-16T14:00:00"),
timestamp("2015-10-27T12:30:00"),
timestamp("2015-10-27T14:00:00"),
timestamp("2015-10-28T18:00:00"),
timestamp("2015-10-28T18:00:00"),
timestamp("2015-10-29T12:30:00"),
timestamp("2015-10-29T12:30:00"),
timestamp("2015-10-29T12:30:00"),
timestamp("2015-11-02T15:00:00"),
timestamp("2015-11-04T15:00:00"),
timestamp("2015-11-06T13:30:00"),
timestamp("2015-11-06T13:30:00"),
timestamp("2015-11-13T13:30:00"),
timestamp("2015-11-13T13:30:00"),
timestamp("2015-11-17T13:30:00"),
timestamp("2015-11-17T13:30:00"),
timestamp("2015-11-18T19:00:00"),
timestamp("2015-11-25T13:30:00"),
timestamp("2015-11-25T13:30:00"),
timestamp("2015-12-03T15:00:00"),
timestamp("2015-12-04T13:30:00"),
timestamp("2015-12-04T13:30:00"),
timestamp("2015-12-11T13:30:00"),
timestamp("2015-12-11T13:30:00"),
timestamp("2015-12-15T13:30:00"),
timestamp("2015-12-15T13:30:00"),
timestamp("2015-12-16T19:00:00"),
timestamp("2015-12-16T19:30:00"),
timestamp("2015-12-22T13:30:00"),
timestamp("2015-12-22T13:30:00"),
timestamp("2015-12-23T13:30:00"),
timestamp("2015-12-23T13:30:00"),
timestamp("2016-01-04T15:00:00"),
timestamp("2016-01-04T15:00:00"),
timestamp("2016-01-06T19:00:00"),
timestamp("2016-01-08T13:30:00"),
timestamp("2016-01-08T13:30:00"),
timestamp("2016-01-15T13:30:00"),
timestamp("2016-01-20T13:30:00"),
timestamp("2016-01-20T13:30:00"),
timestamp("2016-01-27T19:00:00"),
timestamp("2016-01-27T19:00:00"),
timestamp("2016-01-28T13:30:00"),
timestamp("2016-01-28T13:30:00"),
timestamp("2016-01-29T13:30:00"),
timestamp("2016-01-29T13:30:00"),
timestamp("2016-02-05T13:30:00"),
timestamp("2016-02-05T13:30:00"),
timestamp("2016-02-10T14:00:00"),
timestamp("2016-02-11T15:00:00"),
timestamp("2016-02-12T13:30:00"),
timestamp("2016-02-12T13:30:00"),
timestamp("2016-02-12T13:30:00"),
timestamp("2016-02-17T19:00:00"),
timestamp("2016-02-19T13:30:00"),
timestamp("2016-02-19T13:30:00"),
timestamp("2016-02-23T15:00:00"),
timestamp("2016-02-25T13:30:00"),
timestamp("2016-02-25T13:30:00"),
timestamp("2016-02-26T13:30:00"),
timestamp("2016-02-26T13:30:00"),
timestamp("2016-02-26T13:30:00"),
timestamp("2016-02-26T15:00:00"),
timestamp("2016-03-01T15:00:00"),
timestamp("2016-03-01T15:00:00"),
timestamp("2016-03-04T13:30:00"),
timestamp("2016-03-04T13:30:00"),
timestamp("2016-03-15T12:30:00"),
timestamp("2016-03-16T18:00:00"),
timestamp("2016-03-16T18:00:00"),
timestamp("2016-03-16T18:30:00"),
timestamp("2016-03-28T12:30:00"),
timestamp("2016-03-29T14:00:00"),
timestamp("2016-04-01T12:30:00"),
timestamp("2016-04-01T12:30:00"),
timestamp("2016-04-01T14:00:00"),
timestamp("2016-04-01T14:00:00"),
timestamp("2016-04-06T18:00:00"),
timestamp("2016-04-11T13:30:00"),
timestamp("2016-04-13T12:30:00"),
timestamp("2016-04-26T12:30:00"),
timestamp("2016-04-27T18:00:00"),
timestamp("2016-04-27T18:00:00"),
timestamp("2016-05-02T14:00:00"),
timestamp("2016-05-06T12:30:00"),
timestamp("2016-05-06T12:30:00"),
timestamp("2016-05-13T12:30:00"),
timestamp("2016-05-18T18:00:00"),
timestamp("2016-05-26T12:30:00"),
timestamp("2016-05-26T12:30:00"),
timestamp("2016-06-01T14:00:00"),
timestamp("2016-06-01T14:00:00"),
timestamp("2016-06-03T12:30:00"),
timestamp("2016-06-03T12:30:00"),
timestamp("2016-06-14T12:30:00"),
timestamp("2016-06-14T12:30:00"),
timestamp("2016-06-14T12:30:00"),
timestamp("2016-06-15T18:00:00"),
timestamp("2016-06-15T18:00:00"),
timestamp("2016-06-15T18:00:00"),
timestamp("2016-06-15T18:30:00"),
timestamp("2016-06-21T14:00:00"),
timestamp("2016-06-22T14:00:00"),
timestamp("2016-06-29T20:30:00"),
timestamp("2016-07-01T14:00:00"),
timestamp("2016-07-06T18:00:00"),
timestamp("2016-07-08T12:30:00"),
timestamp("2016-07-08T12:30:00"),
timestamp("2016-07-15T12:30:00"),
timestamp("2016-07-27T12:30:00"),
timestamp("2016-07-27T18:00:00"),
timestamp("2016-07-27T18:00:00"),
timestamp("2016-07-29T12:30:00"),
timestamp("2016-07-29T12:30:00"),
timestamp("2016-08-01T14:00:00"),
timestamp("2016-08-01T14:00:00"),
timestamp("2016-08-05T12:30:00"),
timestamp("2016-08-05T12:30:00"),
timestamp("2016-08-12T12:30:00"),
timestamp("2016-08-17T18:00:00"),
timestamp("2016-08-25T00:00:00"),
timestamp("2016-08-26T00:00:00"),
timestamp("2016-08-26T12:30:00"),
timestamp("2016-08-26T14:00:00"),
timestamp("2016-09-01T14:00:00"),
timestamp("2016-09-01T14:00:00"),
timestamp("2016-09-02T12:30:00"),
timestamp("2016-09-02T12:30:00"),
timestamp("2016-09-06T14:00:00"),
timestamp("2016-09-15T12:30:00"),
timestamp("2016-09-16T12:30:00"),
timestamp("2016-09-16T12:30:00"),
timestamp("2016-09-16T14:00:00"),
timestamp("2016-09-21T18:00:00"),
timestamp("2016-09-21T18:00:00"),
timestamp("2016-09-21T18:00:00"),
timestamp("2016-09-21T18:30:00"),
timestamp("2016-09-28T12:30:00"),
timestamp("2016-09-28T14:00:00"),
timestamp("2016-09-28T14:30:00"),
timestamp("2016-09-29T12:30:00"),
timestamp("2016-09-29T20:00:00"),
timestamp("2016-10-03T14:00:00"),
timestamp("2016-10-03T14:00:00"),
timestamp("2016-10-07T12:30:00"),
timestamp("2016-10-07T12:30:00"),
timestamp("2016-10-12T18:00:00"),
timestamp("2016-10-14T12:30:00"),
timestamp("2016-10-14T14:00:00"),
timestamp("2016-10-14T17:30:00"),
timestamp("2016-10-27T12:30:00"),
timestamp("2016-10-27T12:30:00"),
timestamp("2016-10-28T12:30:00"),
timestamp("2016-11-01T14:00:00"),
timestamp("2016-11-01T14:00:00"),
timestamp("2016-11-02T18:00:00"),
timestamp("2016-11-02T18:00:00"),
timestamp("2016-11-04T12:30:00"),
timestamp("2016-11-04T12:30:00"),
timestamp("2016-11-08T13:00:00"),
timestamp("2016-11-11T15:00:00"),
timestamp("2016-11-15T13:30:00"),
timestamp("2016-11-15T13:30:00"),
timestamp("2016-11-15T13:30:00"),
timestamp("2016-11-16T15:30:00"),
timestamp("2016-11-17T15:00:00"),
timestamp("2016-11-23T13:30:00"),
timestamp("2016-11-23T13:30:00"),
timestamp("2016-11-23T15:30:00"),
timestamp("2016-11-23T19:00:00"),
timestamp("2016-11-29T13:30:00"),
timestamp("2016-11-30T16:00:00"),
timestamp("2016-12-01T15:00:00"),
timestamp("2016-12-02T13:30:00"),
timestamp("2016-12-02T13:30:00"),
timestamp("2016-12-02T13:30:00"),
timestamp("2016-12-14T13:30:00"),
timestamp("2016-12-14T19:00:00"),
timestamp("2016-12-14T19:00:00"),
timestamp("2016-12-14T19:00:00"),
timestamp("2016-12-14T19:30:00"),
timestamp("2016-12-15T13:30:00"),
timestamp("2016-12-15T13:30:00"),
timestamp("2016-12-19T18:30:00"),
timestamp("2016-12-21T15:30:00"),
timestamp("2016-12-22T13:30:00"),
timestamp("2016-12-22T13:30:00"),
timestamp("2016-12-22T13:30:00"),
timestamp("2016-12-22T13:30:00"),
timestamp("2017-01-03T15:00:00"),
timestamp("2017-01-03T15:00:00"),
timestamp("2017-01-04T19:00:00"),
timestamp("2017-01-06T13:30:00"),
timestamp("2017-01-06T13:30:00"),
timestamp("2017-01-06T13:30:00"),
timestamp("2017-01-11T16:00:00"),
timestamp("2017-01-13T13:30:00"),
timestamp("2017-01-17T15:00:00"),
timestamp("2017-01-18T13:30:00"),
timestamp("2017-01-18T13:30:00"),
timestamp("2017-01-20T18:00:00"),
timestamp("2017-01-27T13:30:00"),
timestamp("2017-01-27T15:00:00"),
timestamp("2017-02-01T15:00:00"),
timestamp("2017-02-01T15:00:00"),
timestamp("2017-02-01T19:00:00"),
timestamp("2017-02-01T19:00:00"),
timestamp("2017-02-03T13:30:00"),
timestamp("2017-02-03T13:30:00"),
timestamp("2017-02-15T13:30:00"),
timestamp("2017-02-15T13:30:00"),
timestamp("2017-02-15T15:00:00"),
timestamp("2017-02-22T19:00:00"),
timestamp("2017-02-27T13:30:00"),
timestamp("2017-02-27T13:30:00"),
timestamp("2017-02-28T13:30:00"),
timestamp("2017-03-01T02:00:00"),
timestamp("2017-03-01T15:00:00"),
timestamp("2017-03-03T18:00:00"),
timestamp("2017-03-10T13:30:00"),
timestamp("2017-03-10T13:30:00"),
timestamp("2017-03-15T12:30:00"),
timestamp("2017-03-15T12:30:00"),
timestamp("2017-03-15T12:30:00"),
timestamp("2017-03-15T18:00:00"),
timestamp("2017-03-15T18:00:00"),
timestamp("2017-03-15T18:00:00"),
timestamp("2017-03-15T18:30:00"),
timestamp("2017-03-17T16:30:00"),
timestamp("2017-03-23T12:45:00"),
timestamp("2017-03-24T20:15:00"),
timestamp("2017-03-30T12:30:00"),
timestamp("2017-04-03T14:00:00"),
timestamp("2017-04-03T14:00:00"),
timestamp("2017-04-05T18:00:00"),
timestamp("2017-04-06T22:00:00"),
timestamp("2017-04-07T12:30:00"),
timestamp("2017-04-07T12:30:00"),
timestamp("2017-04-07T14:00:00"),
timestamp("2017-04-10T20:10:00"),
timestamp("2017-04-12T10:00:00"),
timestamp("2017-04-14T12:30:00"),
timestamp("2017-04-14T12:30:00"),
timestamp("2017-04-14T12:30:00"),
timestamp("2017-04-20T17:15:00"),
timestamp("2017-04-22T20:15:00"),
timestamp("2017-04-27T12:30:00"),
timestamp("2017-04-27T12:30:00"),
timestamp("2017-04-28T12:30:00"),
timestamp("2017-04-28T12:30:00"),
timestamp("2017-05-01T14:00:00"),
timestamp("2017-05-01T14:00:00"),
timestamp("2017-05-01T14:45:00"),
timestamp("2017-05-03T18:00:00"),
timestamp("2017-05-03T18:00:00"),
timestamp("2017-05-05T12:30:00"),
timestamp("2017-05-05T12:30:00"),
timestamp("2017-05-05T17:30:00"),
timestamp("2017-05-12T12:30:00"),
timestamp("2017-05-12T12:30:00"),
timestamp("2017-05-12T12:30:00"),
timestamp("2017-05-18T14:00:00"),
timestamp("2017-05-24T18:00:00"),
timestamp("2017-05-25T12:00:00"),
timestamp("2017-05-25T15:00:00"),
timestamp("2017-05-26T12:30:00"),
timestamp("2017-05-26T12:30:00"),
timestamp("2017-05-26T12:30:00"),
timestamp("2017-06-01T14:00:00"),
timestamp("2017-06-01T14:00:00"),
timestamp("2017-06-02T12:30:00"),
timestamp("2017-06-02T12:30:00"),
timestamp("2017-06-02T12:30:00"),
timestamp("2017-06-14T12:30:00"),
timestamp("2017-06-14T12:30:00"),
timestamp("2017-06-14T12:30:00"),
timestamp("2017-06-14T18:00:00"),
timestamp("2017-06-14T18:00:00"),
timestamp("2017-06-14T18:00:00"),
timestamp("2017-06-14T18:30:00"),
timestamp("2017-06-22T20:30:00"),
timestamp("2017-06-26T12:30:00"),
timestamp("2017-06-26T12:30:00"),
timestamp("2017-06-27T17:00:00"),
timestamp("2017-06-29T12:30:00"),
timestamp("2017-07-03T14:00:00"),
timestamp("2017-07-03T14:00:00"),
timestamp("2017-07-05T18:00:00"),
timestamp("2017-07-06T11:00:00"),
timestamp("2017-07-07T11:00:00"),
timestamp("2017-07-07T12:30:00"),
timestamp("2017-07-07T12:30:00"),
timestamp("2017-07-07T12:30:00"),
timestamp("2017-07-12T14:00:00"),
timestamp("2017-07-13T14:00:00"),
timestamp("2017-07-13T15:00:00"),
timestamp("2017-07-14T12:30:00"),
timestamp("2017-07-14T12:30:00"),
timestamp("2017-07-14T12:30:00"),
timestamp("2017-07-19T14:30:00"),
timestamp("2017-07-26T18:00:00"),
timestamp("2017-07-26T18:00:00"),
timestamp("2017-07-28T12:30:00"),
timestamp("2017-08-01T14:00:00"),
timestamp("2017-08-01T14:00:00"),
timestamp("2017-08-04T12:30:00"),
timestamp("2017-08-04T12:30:00"),
timestamp("2017-08-11T12:30:00"),
timestamp("2017-08-11T12:30:00"),
timestamp("2017-08-15T12:30:00"),
timestamp("2017-08-15T12:30:00"),
timestamp("2017-08-16T18:00:00"),
timestamp("2017-08-24T08:00:00"),
timestamp("2017-08-25T00:00:00"),
timestamp("2017-08-25T14:00:00"),
timestamp("2017-08-26T00:00:00"),
timestamp("2017-08-30T12:30:00"),
timestamp("2017-08-30T12:30:00"),
timestamp("2017-08-31T12:30:00"),
timestamp("2017-08-31T12:30:00"),
timestamp("2017-09-01T12:30:00"),
timestamp("2017-09-01T12:30:00"),
timestamp("2017-09-01T12:30:00"),
timestamp("2017-09-01T14:00:00"),
timestamp("2017-09-01T14:00:00"),
timestamp("2017-09-13T12:30:00"),
timestamp("2017-09-14T12:30:00"),
timestamp("2017-09-14T12:30:00"),
timestamp("2017-09-15T12:30:00"),
timestamp("2017-09-20T18:00:00"),
timestamp("2017-09-20T18:00:00"),
timestamp("2017-09-20T18:30:00"),
timestamp("2017-09-26T16:45:00"),
timestamp("2017-09-27T19:00:00"),
timestamp("2017-09-28T12:30:00"),
timestamp("2017-09-28T12:30:00"),
timestamp("2017-09-29T12:30:00"),
timestamp("2017-09-29T12:30:00"),
timestamp("2017-10-02T14:00:00"),
timestamp("2017-10-02T14:00:00"),
timestamp("2017-10-04T19:15:00"),
timestamp("2017-10-06T12:30:00"),
timestamp("2017-10-06T12:30:00"),
timestamp("2017-10-06T12:30:00"),
timestamp("2017-10-11T18:00:00"),
timestamp("2017-10-13T12:30:00"),
timestamp("2017-10-13T12:30:00"),
timestamp("2017-10-13T12:30:00"),
timestamp("2017-10-20T23:30:00"),
timestamp("2017-10-27T12:30:00"),
timestamp("2017-10-27T12:30:00"),
timestamp("2017-10-30T12:30:00"),
timestamp("2017-10-30T12:30:00"),
timestamp("2017-11-01T14:00:00"),
timestamp("2017-11-01T14:00:00"),
timestamp("2017-11-01T18:00:00"),
timestamp("2017-11-01T18:00:00"),
timestamp("2017-11-02T19:00:00"),
timestamp("2017-11-03T12:30:00"),
timestamp("2017-11-03T12:30:00"),
timestamp("2017-11-07T19:30:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-15T13:30:00"),
timestamp("2017-11-15T13:30:00"),
timestamp("2017-11-15T13:30:00"),
timestamp("2017-11-22T19:00:00"),
timestamp("2017-11-28T20:45:00"),
timestamp("2017-11-29T13:30:00"),
timestamp("2017-11-29T13:30:00"),
timestamp("2017-11-29T15:00:00"),
timestamp("2017-11-30T13:30:00"),
timestamp("2017-11-30T13:30:00"),
timestamp("2017-12-01T15:00:00"),
timestamp("2017-12-01T15:00:00"),
timestamp("2017-12-08T13:30:00"),
timestamp("2017-12-08T13:30:00"),
timestamp("2017-12-13T13:30:00"),
timestamp("2017-12-13T13:30:00"),
timestamp("2017-12-13T19:00:00"),
timestamp("2017-12-13T19:00:00"),
timestamp("2017-12-13T19:30:00"),
timestamp("2017-12-14T13:30:00"),
timestamp("2017-12-21T13:30:00"),
timestamp("2017-12-21T13:30:00"),
timestamp("2017-12-22T00:00:00"),
timestamp("2017-12-22T13:30:00"),
timestamp("2017-12-22T13:30:00"),
timestamp("2017-12-22T13:30:00"),
timestamp("2018-01-03T15:00:00"),
timestamp("2018-01-03T15:00:00"),
timestamp("2018-01-03T19:00:00"),
timestamp("2018-01-05T13:30:00"),
timestamp("2018-01-05T13:30:00"),
timestamp("2018-01-12T13:30:00"),
timestamp("2018-01-12T13:30:00"),
timestamp("2018-01-12T13:30:00"),
timestamp("2018-01-26T13:30:00"),
timestamp("2018-01-26T13:30:00"),
timestamp("2018-01-29T13:30:00"),
timestamp("2018-01-29T13:30:00"),
timestamp("2018-01-31T02:00:00"),
timestamp("2018-01-31T19:00:00"),
timestamp("2018-01-31T19:00:00"),
timestamp("2018-02-01T15:00:00"),
timestamp("2018-02-01T15:00:00"),
timestamp("2018-02-02T13:30:00"),
timestamp("2018-02-02T13:30:00"),
timestamp("2018-02-02T13:30:00"),
timestamp("2018-02-14T13:30:00"),
timestamp("2018-02-14T13:30:00"),
timestamp("2018-02-14T13:30:00"),
timestamp("2018-02-21T19:00:00"),
timestamp("2018-02-27T13:30:00"),
timestamp("2018-02-27T13:30:00"),
timestamp("2018-02-28T13:30:00"),
timestamp("2018-02-28T13:30:00"),
timestamp("2018-03-01T13:30:00"),
timestamp("2018-03-01T13:30:00"),
timestamp("2018-03-01T15:00:00"),
timestamp("2018-03-01T15:00:00"),
timestamp("2018-03-01T15:00:00"),
timestamp("2018-03-09T13:30:00"),
timestamp("2018-03-09T13:30:00"),
timestamp("2018-03-13T12:30:00"),
timestamp("2018-03-14T12:30:00"),
timestamp("2018-03-14T12:30:00"),
timestamp("2018-03-21T18:00:00"),
timestamp("2018-03-21T18:00:00"),
timestamp("2018-03-21T18:00:00"),
timestamp("2018-03-21T18:00:00"),
timestamp("2018-03-21T18:30:00"),
timestamp("2018-03-23T13:30:00"),
timestamp("2018-03-28T12:30:00"),
timestamp("2018-03-28T12:30:00"),
timestamp("2018-03-29T12:30:00"),
timestamp("2018-04-02T14:00:00"),
timestamp("2018-04-06T12:30:00"),
timestamp("2018-04-06T12:30:00"),
timestamp("2018-04-06T17:30:00"),
timestamp("2018-04-11T12:30:00"),
timestamp("2018-04-11T18:00:00"),
timestamp("2018-04-16T12:30:00"),
timestamp("2018-04-16T12:30:00"),
timestamp("2018-04-26T13:30:00"),
timestamp("2018-04-27T12:30:00"),
timestamp("2018-04-27T12:30:00"),
timestamp("2018-04-30T12:30:00"),
timestamp("2018-05-01T14:00:00"),
timestamp("2018-05-02T18:00:00"),
timestamp("2018-05-02T18:00:00"),
timestamp("2018-05-04T12:30:00"),
timestamp("2018-05-04T12:30:00"),
timestamp("2018-05-08T07:15:00"),
timestamp("2018-05-08T18:00:00"),
timestamp("2018-05-10T12:30:00"),
timestamp("2018-05-15T12:30:00"),
timestamp("2018-05-15T12:30:00"),
timestamp("2018-05-23T18:00:00"),
timestamp("2018-05-25T12:30:00"),
timestamp("2018-05-25T13:20:00"),
timestamp("2018-05-30T12:30:00"),
timestamp("2018-05-30T12:30:00"),
timestamp("2018-05-31T12:30:00"),
timestamp("2018-06-01T12:30:00"),
timestamp("2018-06-01T12:30:00"),
timestamp("2018-06-01T14:00:00"),
timestamp("2018-06-12T01:00:00"),
timestamp("2018-06-12T12:30:00"),
timestamp("2018-06-13T18:00:00"),
timestamp("2018-06-13T18:00:00"),
timestamp("2018-06-13T18:00:00"),
timestamp("2018-06-13T18:30:00"),
timestamp("2018-06-14T12:30:00"),
timestamp("2018-06-14T12:30:00"),
timestamp("2018-06-20T13:30:00"),
timestamp("2018-06-21T20:30:00"),
timestamp("2018-06-26T12:30:00"),
timestamp("2018-06-28T12:30:00"),
timestamp("2018-06-28T12:30:00"),
timestamp("2018-06-29T12:30:00"),
timestamp("2018-07-02T14:00:00"),
timestamp("2018-07-05T18:00:00"),
timestamp("2018-07-06T12:30:00"),
timestamp("2018-07-06T12:30:00"),
timestamp("2018-07-12T12:30:00"),
timestamp("2018-07-12T17:30:00"),
timestamp("2018-07-16T10:15:00"),
timestamp("2018-07-16T12:30:00"),
timestamp("2018-07-16T12:30:00"),
timestamp("2018-07-17T14:00:00"),
timestamp("2018-07-18T14:00:00"),
timestamp("2018-07-25T17:30:00"),
timestamp("2018-07-26T12:30:00"),
timestamp("2018-07-27T12:30:00"),
timestamp("2018-07-27T12:30:00"),
timestamp("2018-07-31T12:30:00"),
timestamp("2018-08-01T14:00:00"),
timestamp("2018-08-01T18:00:00"),
timestamp("2018-08-01T18:00:00"),
timestamp("2018-08-03T12:30:00"),
timestamp("2018-08-03T12:30:00"),
timestamp("2018-08-10T12:30:00"),
timestamp("2018-08-15T12:30:00"),
timestamp("2018-08-15T12:30:00"),
timestamp("2018-08-22T18:00:00"),
timestamp("2018-08-23T00:00:00"),
timestamp("2018-08-24T00:00:00"),
timestamp("2018-08-24T12:30:00"),
timestamp("2018-08-24T14:00:00"),
timestamp("2018-08-25T00:00:00"),
timestamp("2018-08-29T12:30:00"),
timestamp("2018-08-29T12:30:00"),
timestamp("2018-08-30T12:30:00"),
timestamp("2018-09-04T14:00:00"),
timestamp("2018-09-07T12:30:00"),
timestamp("2018-09-07T12:30:00"),
timestamp("2018-09-13T12:30:00"),
timestamp("2018-09-14T12:30:00"),
timestamp("2018-09-14T12:30:00"),
timestamp("2018-09-26T18:00:00"),
timestamp("2018-09-26T18:00:00"),
timestamp("2018-09-26T18:00:00"),
timestamp("2018-09-26T18:30:00"),
timestamp("2018-09-27T12:30:00"),
timestamp("2018-09-27T12:30:00"),
timestamp("2018-09-27T12:30:00"),
timestamp("2018-09-27T20:30:00"),
timestamp("2018-09-28T12:30:00"),
timestamp("2018-10-01T14:00:00"),
timestamp("2018-10-02T16:45:00"),
timestamp("2018-10-03T20:00:00"),
timestamp("2018-10-05T12:30:00"),
timestamp("2018-10-05T12:30:00"),
timestamp("2018-10-11T12:30:00"),
timestamp("2018-10-15T12:30:00"),
timestamp("2018-10-15T12:30:00"),
timestamp("2018-10-17T18:00:00"),
timestamp("2018-10-25T12:30:00"),
timestamp("2018-10-26T12:30:00"),
timestamp("2018-10-26T12:30:00"),
timestamp("2018-10-29T12:30:00"),
timestamp("2018-11-01T14:00:00"),
timestamp("2018-11-02T12:30:00"),
timestamp("2018-11-02T12:30:00"),
timestamp("2018-11-07T16:30:00"),
timestamp("2018-11-08T19:00:00"),
timestamp("2018-11-08T19:00:00"),
timestamp("2018-11-14T13:30:00"),
timestamp("2018-11-14T23:00:00"),
timestamp("2018-11-15T13:30:00"),
timestamp("2018-11-15T13:30:00"),
timestamp("2018-11-15T16:30:00"),
timestamp("2018-11-21T13:30:00"),
timestamp("2018-11-28T13:30:00"),
timestamp("2018-11-28T13:30:00"),
timestamp("2018-11-28T17:00:00"),
timestamp("2018-11-29T13:30:00"),
timestamp("2018-11-29T19:00:00"),
timestamp("2018-12-03T15:00:00"),
timestamp("2018-12-06T23:45:00"),
timestamp("2018-12-07T13:30:00"),
timestamp("2018-12-07T13:30:00"),
timestamp("2018-12-12T13:30:00"),
timestamp("2018-12-14T13:30:00"),
timestamp("2018-12-14T13:30:00"),
timestamp("2018-12-19T19:00:00"),
timestamp("2018-12-19T19:00:00"),
timestamp("2018-12-19T19:00:00"),
timestamp("2018-12-19T19:30:00"),
timestamp("2018-12-21T13:30:00"),
timestamp("2018-12-21T13:30:00"),
timestamp("2018-12-21T13:30:00"),
timestamp("2018-12-21T15:00:00"),
timestamp("2019-01-03T15:00:00"),
timestamp("2019-01-04T13:30:00"),
timestamp("2019-01-04T13:30:00"),
timestamp("2019-01-04T15:15:00"),
timestamp("2019-01-09T02:00:00"),
timestamp("2019-01-09T19:00:00"),
timestamp("2019-01-10T17:45:00"),
timestamp("2019-01-11T13:30:00"),
timestamp("2019-01-30T19:00:00"),
timestamp("2019-01-30T19:00:00"),
timestamp("2019-01-30T19:30:00"),
timestamp("2019-02-01T13:30:00"),
timestamp("2019-02-01T13:30:00"),
timestamp("2019-02-01T15:00:00"),
timestamp("2019-02-04T15:00:00"),
timestamp("2019-02-05T15:00:00"),
timestamp("2019-02-07T00:00:00"),
timestamp("2019-02-12T16:45:00"),
timestamp("2019-02-13T13:30:00"),
timestamp("2019-02-13T13:30:00"),
timestamp("2019-02-14T13:30:00"),
timestamp("2019-02-14T13:30:00"),
timestamp("2019-02-15T15:00:00"),
timestamp("2019-02-15T15:30:00"),
timestamp("2019-02-20T19:00:00"),
timestamp("2019-02-21T13:30:00"),
timestamp("2019-02-26T14:45:00"),
timestamp("2019-02-27T14:00:00"),
timestamp("2019-02-28T11:30:00"),
timestamp("2019-02-28T13:30:00"),
timestamp("2019-03-01T01:15:00"),
timestamp("2019-03-01T15:00:00"),
timestamp("2019-03-05T15:00:00"),
timestamp("2019-03-08T13:30:00"),
timestamp("2019-03-08T13:30:00"),
timestamp("2019-03-09T03:00:00"),
timestamp("2019-03-11T12:30:00"),
timestamp("2019-03-11T23:00:00"),
timestamp("2019-03-12T12:30:00"),
timestamp("2019-03-12T12:30:00"),
timestamp("2019-03-13T12:30:00"),
timestamp("2019-03-15T14:00:00"),
timestamp("2019-03-20T18:00:00"),
timestamp("2019-03-20T18:00:00"),
timestamp("2019-03-20T18:00:00"),
timestamp("2019-03-20T18:30:00"),
timestamp("2019-03-28T12:30:00"),
timestamp("2019-04-01T12:30:00"),
timestamp("2019-04-01T14:00:00"),
timestamp("2019-04-02T12:30:00"),
timestamp("2019-04-03T14:00:00"),
timestamp("2019-04-05T12:30:00"),
timestamp("2019-04-05T12:30:00"),
timestamp("2019-04-10T12:30:00"),
timestamp("2019-04-10T12:30:00"),
timestamp("2019-04-10T18:00:00"),
timestamp("2019-04-12T14:00:00"),
timestamp("2019-04-18T12:30:00"),
timestamp("2019-04-25T12:30:00"),
timestamp("2019-04-26T12:30:00"),
timestamp("2019-05-01T14:00:00"),
timestamp("2019-05-01T18:00:00"),
timestamp("2019-05-01T18:00:00"),
timestamp("2019-05-01T18:30:00"),
timestamp("2019-05-03T12:30:00"),
timestamp("2019-05-03T12:30:00"),
timestamp("2019-05-03T14:00:00"),
timestamp("2019-05-09T12:30:00"),
timestamp("2019-05-10T12:30:00"),
timestamp("2019-05-10T12:30:00"),
timestamp("2019-05-15T12:30:00"),
timestamp("2019-05-17T14:00:00"),
timestamp("2019-05-20T23:00:00"),
timestamp("2019-05-22T18:00:00"),
timestamp("2019-05-24T12:30:00"),
timestamp("2019-05-30T12:30:00"),
timestamp("2019-06-03T14:00:00"),
timestamp("2019-06-04T13:45:00"),
timestamp("2019-06-05T14:00:00"),
timestamp("2019-06-07T12:30:00"),
timestamp("2019-06-07T12:30:00"),
timestamp("2019-06-12T12:30:00"),
timestamp("2019-06-12T12:30:00"),
timestamp("2019-06-14T12:30:00"),
timestamp("2019-06-14T14:00:00"),
timestamp("2019-06-19T18:00:00"),
timestamp("2019-06-19T18:00:00"),
timestamp("2019-06-19T18:00:00"),
timestamp("2019-06-19T18:30:00"),
timestamp("2019-06-25T17:00:00"),
timestamp("2019-06-26T12:30:00"),
timestamp("2019-06-27T12:30:00"),
timestamp("2019-07-01T14:00:00"),
timestamp("2019-07-03T14:00:00"),
timestamp("2019-07-05T12:30:00"),
timestamp("2019-07-05T12:30:00"),
timestamp("2019-07-09T12:45:00"),
timestamp("2019-07-10T14:00:00"),
timestamp("2019-07-10T18:00:00"),
timestamp("2019-07-11T12:30:00"),
timestamp("2019-07-11T12:30:00"),
timestamp("2019-07-11T14:00:00"),
timestamp("2019-07-16T12:30:00"),
timestamp("2019-07-16T17:00:00"),
timestamp("2019-07-19T14:00:00"),
timestamp("2019-07-25T12:30:00"),
timestamp("2019-07-26T12:30:00"),
timestamp("2019-07-31T18:00:00"),
timestamp("2019-07-31T18:00:00"),
timestamp("2019-07-31T18:30:00"),
timestamp("2019-08-01T14:00:00"),
timestamp("2019-08-02T12:30:00"),
timestamp("2019-08-02T12:30:00"),
timestamp("2019-08-05T14:00:00"),
timestamp("2019-08-13T12:30:00"),
timestamp("2019-08-13T12:30:00"),
timestamp("2019-08-15T12:30:00"),
timestamp("2019-08-16T14:00:00"),
timestamp("2019-08-21T18:00:00"),
timestamp("2019-08-22T00:00:00"),
timestamp("2019-08-23T00:00:00"),
timestamp("2019-08-23T14:00:00"),
timestamp("2019-08-24T00:00:00"),
timestamp("2019-08-26T12:30:00"),
timestamp("2019-08-29T12:30:00"),
timestamp("2019-09-03T14:00:00"),
timestamp("2019-09-05T14:00:00"),
timestamp("2019-09-06T12:30:00"),
timestamp("2019-09-06T12:30:00"),
timestamp("2019-09-06T16:30:00"),
timestamp("2019-09-12T12:30:00"),
timestamp("2019-09-12T12:30:00"),
timestamp("2019-09-13T12:30:00"),
timestamp("2019-09-13T14:00:00"),
timestamp("2019-09-18T18:00:00"),
timestamp("2019-09-18T18:00:00"),
timestamp("2019-09-18T18:00:00"),
timestamp("2019-09-18T18:30:00"),
timestamp("2019-09-26T12:30:00"),
timestamp("2019-09-27T12:30:00"),
timestamp("2019-10-01T14:00:00"),
timestamp("2019-10-03T14:00:00"),
timestamp("2019-10-04T12:30:00"),
timestamp("2019-10-04T12:30:00"),
timestamp("2019-10-04T18:00:00"),
timestamp("2019-10-07T17:00:00"),
timestamp("2019-10-08T18:30:00"),
timestamp("2019-10-09T15:00:00"),
timestamp("2019-10-09T18:00:00"),
timestamp("2019-10-10T12:30:00"),
timestamp("2019-10-10T12:30:00"),
timestamp("2019-10-11T14:00:00"),
timestamp("2019-10-16T12:30:00"),
timestamp("2019-10-24T12:30:00"),
timestamp("2019-10-30T12:30:00"),
timestamp("2019-10-30T18:00:00"),
timestamp("2019-10-30T18:00:00"),
timestamp("2019-10-30T18:30:00"),
timestamp("2019-11-01T12:30:00"),
timestamp("2019-11-01T12:30:00"),
timestamp("2019-11-01T14:00:00"),
timestamp("2019-11-05T15:00:00"),
timestamp("2019-11-08T15:00:00"),
timestamp("2019-11-12T17:00:00"),
timestamp("2019-11-13T13:30:00"),
timestamp("2019-11-13T13:30:00"),
timestamp("2019-11-13T16:00:00"),
timestamp("2019-11-14T15:00:00"),
timestamp("2019-11-15T13:30:00"),
timestamp("2019-11-20T19:00:00"),
timestamp("2019-11-26T00:00:00"),
timestamp("2019-11-27T13:30:00"),
timestamp("2019-11-27T13:30:00"),
timestamp("2019-12-02T15:00:00"),
timestamp("2019-12-04T15:00:00"),
timestamp("2019-12-06T13:30:00"),
timestamp("2019-12-06T13:30:00"),
timestamp("2019-12-06T15:00:00"),
timestamp("2019-12-11T13:30:00"),
timestamp("2019-12-11T13:30:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:00:00"),
timestamp("2019-12-11T19:30:00"),
timestamp("2019-12-13T13:30:00"),
timestamp("2019-12-20T13:30:00"),
timestamp("2019-12-23T13:30:00")
)
// @function USD high impact news date and time from 2020 to 2023
export HighImpactNews2020To2023() =>
array.from(
timestamp("2020-01-03T15:00:00"),
timestamp("2020-01-03T19:00:00"),
timestamp("2020-01-07T15:00:00"),
timestamp("2020-01-10T13:30:00"),
timestamp("2020-01-10T13:30:00"),
timestamp("2020-01-14T13:30:00"),
timestamp("2020-01-14T13:30:00"),
timestamp("2020-01-16T13:30:00"),
timestamp("2020-01-17T15:00:00"),
timestamp("2020-01-28T13:30:00"),
timestamp("2020-01-29T19:00:00"),
timestamp("2020-01-29T19:30:00"),
timestamp("2020-01-30T13:30:00"),
timestamp("2020-02-03T15:00:00"),
timestamp("2020-02-05T15:00:00"),
timestamp("2020-02-07T13:30:00"),
timestamp("2020-02-07T13:30:00"),
timestamp("2020-02-11T15:00:00"),
timestamp("2020-02-12T14:30:00"),
timestamp("2020-02-13T13:30:00"),
timestamp("2020-02-13T13:30:00"),
timestamp("2020-02-14T13:30:00"),
timestamp("2020-02-14T15:00:00"),
timestamp("2020-02-19T19:00:00"),
timestamp("2020-02-26T23:00:00"),
timestamp("2020-02-27T13:30:00"),
timestamp("2020-02-27T13:30:00"),
timestamp("2020-03-02T15:00:00"),
timestamp("2020-03-03T05:00:00"),
timestamp("2020-03-03T12:00:00"),
timestamp("2020-03-03T15:00:00"),
timestamp("2020-03-03T16:00:00"),
timestamp("2020-03-04T15:00:00"),
timestamp("2020-03-06T13:30:00"),
timestamp("2020-03-06T13:30:00"),
timestamp("2020-03-10T21:30:00"),
timestamp("2020-03-11T12:30:00"),
timestamp("2020-03-11T12:30:00"),
timestamp("2020-03-11T14:00:00"),
timestamp("2020-03-12T01:00:00"),
timestamp("2020-03-13T14:00:00"),
timestamp("2020-03-13T19:00:00"),
timestamp("2020-03-15T21:00:00"),
timestamp("2020-03-15T21:00:00"),
timestamp("2020-03-15T22:30:00"),
timestamp("2020-03-16T14:00:00"),
timestamp("2020-03-17T12:00:00"),
timestamp("2020-03-17T12:30:00"),
timestamp("2020-03-19T12:30:00"),
timestamp("2020-03-23T16:00:00"),
timestamp("2020-03-24T13:45:00"),
timestamp("2020-03-24T13:45:00"),
timestamp("2020-03-24T13:45:00"),
timestamp("2020-03-25T12:30:00"),
timestamp("2020-03-26T11:05:00"),
timestamp("2020-03-26T12:30:00"),
timestamp("2020-03-26T12:30:00"),
timestamp("2020-03-27T15:00:00"),
timestamp("2020-04-01T12:15:00"),
timestamp("2020-04-01T14:00:00"),
timestamp("2020-04-02T12:30:00"),
timestamp("2020-04-03T12:30:00"),
timestamp("2020-04-03T12:30:00"),
timestamp("2020-04-03T14:00:00"),
timestamp("2020-04-03T14:00:00"),
timestamp("2020-04-08T18:00:00"),
timestamp("2020-04-09T12:30:00"),
timestamp("2020-04-09T14:00:00"),
timestamp("2020-04-09T14:00:00"),
timestamp("2020-04-09T14:00:00"),
timestamp("2020-04-10T12:30:00"),
timestamp("2020-04-10T12:30:00"),
timestamp("2020-04-15T12:30:00"),
timestamp("2020-04-16T12:30:00"),
timestamp("2020-04-23T12:30:00"),
timestamp("2020-04-24T12:30:00"),
timestamp("2020-04-29T12:30:00"),
timestamp("2020-04-29T18:00:00"),
timestamp("2020-04-29T18:30:00"),
timestamp("2020-04-30T12:30:00"),
timestamp("2020-05-01T14:00:00"),
timestamp("2020-05-05T14:00:00"),
timestamp("2020-05-05T14:00:00"),
timestamp("2020-05-06T12:15:00"),
timestamp("2020-05-07T12:30:00"),
timestamp("2020-05-08T12:30:00"),
timestamp("2020-05-08T12:30:00"),
timestamp("2020-05-12T12:30:00"),
timestamp("2020-05-12T12:30:00"),
timestamp("2020-05-13T13:00:00"),
timestamp("2020-05-14T12:30:00"),
timestamp("2020-05-15T12:30:00"),
timestamp("2020-05-15T14:00:00"),
timestamp("2020-05-19T14:00:00"),
timestamp("2020-05-20T18:00:00"),
timestamp("2020-05-21T12:30:00"),
timestamp("2020-05-21T18:30:00"),
timestamp("2020-05-28T12:30:00"),
timestamp("2020-05-28T12:30:00"),
timestamp("2020-05-28T12:30:00"),
timestamp("2020-05-29T15:00:00"),
timestamp("2020-06-01T14:00:00"),
timestamp("2020-06-03T12:00:00"),
timestamp("2020-06-03T12:15:00"),
timestamp("2020-06-03T14:00:00"),
timestamp("2020-06-03T14:00:00"),
timestamp("2020-06-04T12:30:00"),
timestamp("2020-06-05T12:30:00"),
timestamp("2020-06-05T12:30:00"),
timestamp("2020-06-05T14:00:00"),
timestamp("2020-06-08T10:00:00"),
timestamp("2020-06-10T12:30:00"),
timestamp("2020-06-10T12:30:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:00:00"),
timestamp("2020-06-10T18:30:00"),
timestamp("2020-06-11T12:30:00"),
timestamp("2020-06-12T14:00:00"),
timestamp("2020-06-16T12:30:00"),
timestamp("2020-06-16T14:00:00"),
timestamp("2020-06-17T16:00:00"),
timestamp("2020-06-18T12:30:00"),
timestamp("2020-06-19T17:00:00"),
timestamp("2020-06-25T12:30:00"),
timestamp("2020-06-25T12:30:00"),
timestamp("2020-06-25T12:30:00"),
timestamp("2020-06-25T20:30:00"),
timestamp("2020-06-30T14:00:00"),
timestamp("2020-06-30T16:30:00"),
timestamp("2020-07-01T12:15:00"),
timestamp("2020-07-01T14:00:00"),
timestamp("2020-07-01T18:00:00"),
timestamp("2020-07-02T12:30:00"),
timestamp("2020-07-02T12:30:00"),
timestamp("2020-07-02T13:30:00"),
timestamp("2020-07-06T14:00:00"),
timestamp("2020-07-14T12:30:00"),
timestamp("2020-07-14T12:30:00"),
timestamp("2020-07-16T12:30:00"),
timestamp("2020-07-17T14:00:00"),
timestamp("2020-07-27T12:30:00"),
timestamp("2020-07-27T12:30:00"),
timestamp("2020-07-29T18:00:00"),
timestamp("2020-07-29T18:00:00"),
timestamp("2020-07-29T18:30:00"),
timestamp("2020-07-30T12:30:00"),
timestamp("2020-08-03T14:00:00"),
timestamp("2020-08-05T12:15:00"),
timestamp("2020-08-05T14:00:00"),
timestamp("2020-08-07T12:30:00"),
timestamp("2020-08-12T12:30:00"),
timestamp("2020-08-12T12:30:00"),
timestamp("2020-08-14T12:30:00"),
timestamp("2020-08-14T12:30:00"),
timestamp("2020-08-14T14:00:00"),
timestamp("2020-08-19T18:00:00"),
timestamp("2020-08-26T12:30:00"),
timestamp("2020-08-26T12:30:00"),
timestamp("2020-08-27T00:00:00"),
timestamp("2020-08-27T12:30:00"),
timestamp("2020-08-27T13:10:00"),
timestamp("2020-08-28T00:00:00"),
timestamp("2020-09-01T14:00:00"),
timestamp("2020-09-02T12:15:00"),
timestamp("2020-09-03T14:00:00"),
timestamp("2020-09-04T12:30:00"),
timestamp("2020-09-11T12:30:00"),
timestamp("2020-09-11T12:30:00"),
timestamp("2020-09-16T12:30:00"),
timestamp("2020-09-16T12:30:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:00:00"),
timestamp("2020-09-16T18:30:00"),
timestamp("2020-09-18T14:00:00"),
timestamp("2020-09-21T14:00:00"),
timestamp("2020-09-22T14:30:00"),
timestamp("2020-09-23T14:00:00"),
timestamp("2020-09-24T14:00:00"),
timestamp("2020-09-24T14:00:00"),
timestamp("2020-09-25T12:30:00"),
timestamp("2020-09-25T12:30:00"),
timestamp("2020-09-30T01:00:00"),
timestamp("2020-09-30T12:15:00"),
timestamp("2020-09-30T12:30:00"),
timestamp("2020-10-01T14:00:00"),
timestamp("2020-10-02T12:30:00"),
timestamp("2020-10-05T14:00:00"),
timestamp("2020-10-06T14:40:00"),
timestamp("2020-10-07T18:00:00"),
timestamp("2020-10-13T12:30:00"),
timestamp("2020-10-13T12:30:00"),
timestamp("2020-10-16T12:30:00"),
timestamp("2020-10-16T12:30:00"),
timestamp("2020-10-16T14:00:00"),
timestamp("2020-10-19T12:00:00"),
timestamp("2020-10-23T01:00:00"),
timestamp("2020-10-27T12:30:00"),
timestamp("2020-10-27T12:30:00"),
timestamp("2020-10-29T12:30:00"),
timestamp("2020-11-02T15:00:00"),
timestamp("2020-11-03T13:00:00"),
timestamp("2020-11-04T13:15:00"),
timestamp("2020-11-04T15:00:00"),
timestamp("2020-11-05T19:00:00"),
timestamp("2020-11-05T19:00:00"),
timestamp("2020-11-05T19:30:00"),
timestamp("2020-11-06T13:30:00"),
timestamp("2020-11-12T13:30:00"),
timestamp("2020-11-12T13:30:00"),
timestamp("2020-11-12T16:45:00"),
timestamp("2020-11-13T15:00:00"),
timestamp("2020-11-17T13:30:00"),
timestamp("2020-11-17T13:30:00"),
timestamp("2020-11-17T18:00:00"),
timestamp("2020-11-25T13:30:00"),
timestamp("2020-11-25T13:30:00"),
timestamp("2020-11-25T13:30:00"),
timestamp("2020-11-25T19:00:00"),
timestamp("2020-12-01T15:00:00"),
timestamp("2020-12-01T15:00:00"),
timestamp("2020-12-02T13:15:00"),
timestamp("2020-12-03T15:00:00"),
timestamp("2020-12-04T13:30:00"),
timestamp("2020-12-10T13:30:00"),
timestamp("2020-12-10T13:30:00"),
timestamp("2020-12-11T15:00:00"),
timestamp("2020-12-16T13:30:00"),
timestamp("2020-12-16T13:30:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:00:00"),
timestamp("2020-12-16T19:30:00"),
timestamp("2020-12-18T21:30:00"),
timestamp("2020-12-22T13:30:00"),
timestamp("2020-12-23T13:30:00"),
timestamp("2020-12-23T13:30:00"),
timestamp("2021-01-05T15:00:00"),
timestamp("2021-01-06T13:15:00"),
timestamp("2021-01-06T19:00:00"),
timestamp("2021-01-07T15:00:00"),
timestamp("2021-01-08T13:30:00"),
timestamp("2021-01-13T13:30:00"),
timestamp("2021-01-13T13:30:00"),
timestamp("2021-01-14T17:30:00"),
timestamp("2021-01-15T00:15:00"),
timestamp("2021-01-15T13:30:00"),
timestamp("2021-01-15T13:30:00"),
timestamp("2021-01-15T15:00:00"),
timestamp("2021-01-19T15:00:00"),
timestamp("2021-01-20T17:00:00"),
timestamp("2021-01-22T19:45:00"),
timestamp("2021-01-25T20:45:00"),
timestamp("2021-01-26T21:45:00"),
timestamp("2021-01-27T13:30:00"),
timestamp("2021-01-27T13:30:00"),
timestamp("2021-01-27T19:00:00"),
timestamp("2021-01-27T19:00:00"),
timestamp("2021-01-27T19:30:00"),
timestamp("2021-01-28T13:30:00"),
timestamp("2021-02-01T15:00:00"),
timestamp("2021-02-01T22:00:00"),
timestamp("2021-02-03T13:15:00"),
timestamp("2021-02-03T15:00:00"),
timestamp("2021-02-05T13:30:00"),
timestamp("2021-02-10T13:30:00"),
timestamp("2021-02-10T13:30:00"),
timestamp("2021-02-10T19:00:00"),
timestamp("2021-02-12T15:00:00"),
timestamp("2021-02-17T13:30:00"),
timestamp("2021-02-17T13:30:00"),
timestamp("2021-02-17T19:00:00"),
timestamp("2021-02-23T15:00:00"),
timestamp("2021-02-24T15:00:00"),
timestamp("2021-02-25T13:30:00"),
timestamp("2021-02-25T13:30:00"),
timestamp("2021-02-25T13:30:00"),
timestamp("2021-03-01T15:00:00"),
timestamp("2021-03-03T13:15:00"),
timestamp("2021-03-03T15:00:00"),
timestamp("2021-03-04T17:05:00"),
timestamp("2021-03-05T13:30:00"),
timestamp("2021-03-10T13:30:00"),
timestamp("2021-03-10T13:30:00"),
timestamp("2021-03-10T18:00:00"),
timestamp("2021-03-12T15:00:00"),
timestamp("2021-03-15T17:45:00"),
timestamp("2021-03-16T12:30:00"),
timestamp("2021-03-16T12:30:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:00:00"),
timestamp("2021-03-17T18:30:00"),
timestamp("2021-03-17T19:00:00"),
timestamp("2021-03-18T15:55:00"),
timestamp("2021-03-22T13:00:00"),
timestamp("2021-03-23T16:00:00"),
timestamp("2021-03-24T12:30:00"),
timestamp("2021-03-24T12:30:00"),
timestamp("2021-03-24T14:00:00"),
timestamp("2021-03-25T12:30:00"),
timestamp("2021-03-31T12:15:00"),
timestamp("2021-03-31T20:20:00"),
timestamp("2021-04-01T14:00:00"),
timestamp("2021-04-02T12:30:00"),
timestamp("2021-04-05T14:00:00"),
timestamp("2021-04-07T17:45:00"),
timestamp("2021-04-07T18:00:00"),
timestamp("2021-04-08T16:00:00"),
timestamp("2021-04-12T17:00:00"),
timestamp("2021-04-13T12:30:00"),
timestamp("2021-04-13T12:30:00"),
timestamp("2021-04-14T16:00:00"),
timestamp("2021-04-15T12:30:00"),
timestamp("2021-04-15T12:30:00"),
timestamp("2021-04-16T14:00:00"),
timestamp("2021-04-26T12:30:00"),
timestamp("2021-04-26T12:30:00"),
timestamp("2021-04-28T18:00:00"),
timestamp("2021-04-28T18:00:00"),
timestamp("2021-04-28T18:30:00"),
timestamp("2021-04-29T12:30:00"),
timestamp("2021-05-03T14:00:00"),
timestamp("2021-05-03T18:20:00"),
timestamp("2021-05-05T12:15:00"),
timestamp("2021-05-05T14:00:00"),
timestamp("2021-05-07T12:30:00"),
timestamp("2021-05-07T15:00:00"),
timestamp("2021-05-12T12:30:00"),
timestamp("2021-05-12T12:30:00"),
timestamp("2021-05-14T12:30:00"),
timestamp("2021-05-14T12:30:00"),
timestamp("2021-05-14T14:00:00"),
timestamp("2021-05-19T18:00:00"),
timestamp("2021-05-27T12:30:00"),
timestamp("2021-05-27T12:30:00"),
timestamp("2021-05-27T12:30:00"),
timestamp("2021-06-01T14:00:00"),
timestamp("2021-06-03T12:15:00"),
timestamp("2021-06-03T14:00:00"),
timestamp("2021-06-04T11:00:00"),
timestamp("2021-06-04T12:30:00"),
timestamp("2021-06-04T14:15:00"),
timestamp("2021-06-10T12:30:00"),
timestamp("2021-06-10T12:30:00"),
timestamp("2021-06-11T14:00:00"),
timestamp("2021-06-15T12:30:00"),
timestamp("2021-06-15T12:30:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:00:00"),
timestamp("2021-06-16T18:30:00"),
timestamp("2021-06-22T18:00:00"),
timestamp("2021-06-24T12:30:00"),
timestamp("2021-06-24T12:30:00"),
timestamp("2021-06-24T12:30:00"),
timestamp("2021-06-24T20:30:00"),
timestamp("2021-06-30T12:15:00"),
timestamp("2021-07-01T14:00:00"),
timestamp("2021-07-02T12:30:00"),
timestamp("2021-07-06T14:00:00"),
timestamp("2021-07-07T18:00:00"),
timestamp("2021-07-13T12:30:00"),
timestamp("2021-07-13T12:30:00"),
timestamp("2021-07-14T16:00:00"),
timestamp("2021-07-15T13:30:00"),
timestamp("2021-07-16T12:30:00"),
timestamp("2021-07-16T12:30:00"),
timestamp("2021-07-16T14:00:00"),
timestamp("2021-07-27T12:30:00"),
timestamp("2021-07-27T12:30:00"),
timestamp("2021-07-28T18:00:00"),
timestamp("2021-07-28T18:00:00"),
timestamp("2021-07-28T18:30:00"),
timestamp("2021-07-29T12:30:00"),
timestamp("2021-08-02T14:00:00"),
timestamp("2021-08-04T12:15:00"),
timestamp("2021-08-04T14:00:00"),
timestamp("2021-08-06T12:30:00"),
timestamp("2021-08-11T12:30:00"),
timestamp("2021-08-11T12:30:00"),
timestamp("2021-08-13T14:00:00"),
timestamp("2021-08-17T12:30:00"),
timestamp("2021-08-17T12:30:00"),
timestamp("2021-08-17T17:30:00"),
timestamp("2021-08-18T18:00:00"),
timestamp("2021-08-25T12:30:00"),
timestamp("2021-08-25T12:30:00"),
timestamp("2021-08-26T12:30:00"),
timestamp("2021-08-26T14:00:00"),
timestamp("2021-08-27T14:00:00"),
timestamp("2021-08-27T14:00:00"),
timestamp("2021-08-28T14:00:00"),
timestamp("2021-09-01T12:15:00"),
timestamp("2021-09-01T14:00:00"),
timestamp("2021-09-03T12:30:00"),
timestamp("2021-09-03T14:00:00"),
timestamp("2021-09-14T12:30:00"),
timestamp("2021-09-14T12:30:00"),
timestamp("2021-09-16T12:30:00"),
timestamp("2021-09-16T12:30:00"),
timestamp("2021-09-17T14:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:00:00"),
timestamp("2021-09-22T18:30:00"),
timestamp("2021-09-24T14:00:00"),
timestamp("2021-09-27T12:30:00"),
timestamp("2021-09-27T12:30:00"),
timestamp("2021-09-28T14:00:00"),
timestamp("2021-09-29T15:45:00"),
timestamp("2021-09-30T12:30:00"),
timestamp("2021-09-30T14:00:00"),
timestamp("2021-10-01T14:00:00"),
timestamp("2021-10-05T14:00:00"),
timestamp("2021-10-06T12:15:00"),
timestamp("2021-10-08T12:30:00"),
timestamp("2021-10-13T12:30:00"),
timestamp("2021-10-13T12:30:00"),
timestamp("2021-10-13T18:00:00"),
timestamp("2021-10-15T12:30:00"),
timestamp("2021-10-15T12:30:00"),
timestamp("2021-10-15T14:00:00"),
timestamp("2021-10-22T15:00:00"),
timestamp("2021-10-27T12:30:00"),
timestamp("2021-10-27T12:30:00"),
timestamp("2021-10-28T12:30:00"),
timestamp("2021-11-01T14:00:00"),
timestamp("2021-11-03T12:15:00"),
timestamp("2021-11-03T14:00:00"),
timestamp("2021-11-03T18:00:00"),
timestamp("2021-11-03T18:00:00"),
timestamp("2021-11-03T18:30:00"),
timestamp("2021-11-05T12:30:00"),
timestamp("2021-11-08T15:30:00"),
timestamp("2021-11-09T14:00:00"),
timestamp("2021-11-10T13:30:00"),
timestamp("2021-11-10T13:30:00"),
timestamp("2021-11-12T15:00:00"),
timestamp("2021-11-16T13:30:00"),
timestamp("2021-11-16T13:30:00"),
timestamp("2021-11-23T20:00:00"),
timestamp("2021-11-24T13:30:00"),
timestamp("2021-11-24T13:30:00"),
timestamp("2021-11-24T13:30:00"),
timestamp("2021-11-24T19:00:00"),
timestamp("2021-11-29T20:05:00"),
timestamp("2021-11-30T15:00:00"),
timestamp("2021-12-01T13:15:00"),
timestamp("2021-12-01T15:00:00"),
timestamp("2021-12-01T15:00:00"),
timestamp("2021-12-03T13:30:00"),
timestamp("2021-12-03T15:00:00"),
timestamp("2021-12-10T13:30:00"),
timestamp("2021-12-10T13:30:00"),
timestamp("2021-12-10T15:00:00"),
timestamp("2021-12-15T13:30:00"),
timestamp("2021-12-15T13:30:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:00:00"),
timestamp("2021-12-15T19:30:00"),
timestamp("2021-12-22T13:30:00"),
timestamp("2021-12-23T13:30:00"),
timestamp("2021-12-23T13:30:00"),
timestamp("2022-01-04T15:00:00"),
timestamp("2022-01-05T13:15:00"),
timestamp("2022-01-05T19:00:00"),
timestamp("2022-01-06T15:00:00"),
timestamp("2022-01-07T13:30:00"),
timestamp("2022-01-11T15:00:00"),
timestamp("2022-01-12T13:30:00"),
timestamp("2022-01-12T13:30:00"),
timestamp("2022-01-14T13:30:00"),
timestamp("2022-01-14T13:30:00"),
timestamp("2022-01-14T15:00:00"),
timestamp("2022-01-26T19:00:00"),
timestamp("2022-01-26T19:00:00"),
timestamp("2022-01-26T19:30:00"),
timestamp("2022-01-27T13:30:00"),
timestamp("2022-01-27T13:30:00"),
timestamp("2022-01-27T13:30:00"),
timestamp("2022-02-01T15:00:00"),
timestamp("2022-02-02T13:15:00"),
timestamp("2022-02-03T15:00:00"),
timestamp("2022-02-04T13:30:00"),
timestamp("2022-02-10T13:30:00"),
timestamp("2022-02-10T13:30:00"),
timestamp("2022-02-11T15:00:00"),
timestamp("2022-02-16T13:30:00"),
timestamp("2022-02-16T13:30:00"),
timestamp("2022-02-16T19:00:00"),
timestamp("2022-02-24T13:30:00"),
timestamp("2022-02-25T13:30:00"),
timestamp("2022-02-25T13:30:00"),
timestamp("2022-03-01T15:00:00"),
timestamp("2022-03-02T02:00:00"),
timestamp("2022-03-02T13:15:00"),
timestamp("2022-03-02T15:00:00"),
timestamp("2022-03-03T15:00:00"),
timestamp("2022-03-03T15:00:00"),
timestamp("2022-03-04T13:30:00"),
timestamp("2022-03-10T13:30:00"),
timestamp("2022-03-10T13:30:00"),
timestamp("2022-03-11T15:00:00"),
timestamp("2022-03-11T15:15:00"),
timestamp("2022-03-16T12:30:00"),
timestamp("2022-03-16T12:30:00"),
timestamp("2022-03-16T15:45:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:00:00"),
timestamp("2022-03-16T18:30:00"),
timestamp("2022-03-21T16:00:00"),
timestamp("2022-03-23T12:00:00"),
timestamp("2022-03-24T12:30:00"),
timestamp("2022-03-24T12:30:00"),
timestamp("2022-03-30T12:15:00"),
timestamp("2022-03-30T12:30:00"),
timestamp("2022-04-01T12:30:00"),
timestamp("2022-04-01T14:00:00"),
timestamp("2022-04-05T14:00:00"),
timestamp("2022-04-06T18:00:00"),
timestamp("2022-04-12T12:30:00"),
timestamp("2022-04-12T12:30:00"),
timestamp("2022-04-14T12:30:00"),
timestamp("2022-04-14T12:30:00"),
timestamp("2022-04-14T14:00:00"),
timestamp("2022-04-21T15:00:00"),
timestamp("2022-04-21T17:00:00"),
timestamp("2022-04-26T12:30:00"),
timestamp("2022-04-26T12:30:00"),
timestamp("2022-04-28T12:30:00"),
timestamp("2022-05-02T14:00:00"),
timestamp("2022-05-04T12:15:00"),
timestamp("2022-05-04T14:00:00"),
timestamp("2022-05-04T18:00:00"),
timestamp("2022-05-04T18:00:00"),
timestamp("2022-05-04T18:30:00"),
timestamp("2022-05-06T12:30:00"),
timestamp("2022-05-10T15:30:00"),
timestamp("2022-05-11T12:30:00"),
timestamp("2022-05-11T12:30:00"),
timestamp("2022-05-11T18:15:00"),
timestamp("2022-05-13T14:00:00"),
timestamp("2022-05-17T12:30:00"),
timestamp("2022-05-17T12:30:00"),
timestamp("2022-05-17T18:00:00"),
timestamp("2022-05-24T16:20:00"),
timestamp("2022-05-25T12:30:00"),
timestamp("2022-05-25T12:30:00"),
timestamp("2022-05-25T18:00:00"),
timestamp("2022-05-26T12:30:00"),
timestamp("2022-05-31T13:00:00"),
timestamp("2022-06-01T14:00:00"),
timestamp("2022-06-02T12:15:00"),
timestamp("2022-06-03T12:30:00"),
timestamp("2022-06-03T14:00:00"),
timestamp("2022-06-03T14:30:00"),
timestamp("2022-06-07T14:00:00"),
timestamp("2022-06-10T12:30:00"),
timestamp("2022-06-10T12:30:00"),
timestamp("2022-06-10T14:00:00"),
timestamp("2022-06-15T12:30:00"),
timestamp("2022-06-15T12:30:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:00:00"),
timestamp("2022-06-15T18:30:00"),
timestamp("2022-06-17T12:45:00"),
timestamp("2022-06-22T13:30:00"),
timestamp("2022-06-22T18:00:00"),
timestamp("2022-06-23T14:00:00"),
timestamp("2022-06-23T20:30:00"),
timestamp("2022-06-27T12:30:00"),
timestamp("2022-06-27T12:30:00"),
timestamp("2022-06-29T12:30:00"),
timestamp("2022-06-29T13:00:00"),
timestamp("2022-07-01T14:00:00"),
timestamp("2022-07-06T14:00:00"),
timestamp("2022-07-06T18:00:00"),
timestamp("2022-07-08T12:30:00"),
timestamp("2022-07-13T12:30:00"),
timestamp("2022-07-13T12:30:00"),
timestamp("2022-07-15T12:30:00"),
timestamp("2022-07-15T12:30:00"),
timestamp("2022-07-15T14:00:00"),
timestamp("2022-07-27T12:30:00"),
timestamp("2022-07-27T12:30:00"),
timestamp("2022-07-27T18:00:00"),
timestamp("2022-07-27T18:00:00"),
timestamp("2022-07-27T18:30:00"),
timestamp("2022-07-28T12:30:00"),
timestamp("2022-08-01T14:00:00"),
timestamp("2022-08-02T23:30:00"),
timestamp("2022-08-03T14:00:00"),
timestamp("2022-08-05T12:30:00"),
timestamp("2022-08-10T12:30:00"),
timestamp("2022-08-10T12:30:00"),
timestamp("2022-08-12T14:00:00"),
timestamp("2022-08-17T12:30:00"),
timestamp("2022-08-17T12:30:00"),
timestamp("2022-08-17T18:00:00"),
timestamp("2022-08-24T12:30:00"),
timestamp("2022-08-24T12:30:00"),
timestamp("2022-08-25T12:30:00"),
timestamp("2022-08-25T14:00:00"),
timestamp("2022-08-26T14:00:00"),
timestamp("2022-08-26T14:00:00"),
timestamp("2022-08-27T14:00:00"),
timestamp("2022-08-31T12:15:00"),
timestamp("2022-08-31T12:15:05"),
timestamp("2022-08-31T12:15:10"),
timestamp("2022-09-01T14:00:00"),
timestamp("2022-09-02T12:30:00"),
timestamp("2022-09-06T14:00:00"),
timestamp("2022-09-08T13:10:00"),
timestamp("2022-09-13T12:30:00"),
timestamp("2022-09-13T12:30:00"),
timestamp("2022-09-15T12:30:00"),
timestamp("2022-09-15T12:30:00"),
timestamp("2022-09-16T14:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:00:00"),
timestamp("2022-09-21T18:30:00"),
timestamp("2022-09-23T18:00:00"),
timestamp("2022-09-27T11:30:00"),
timestamp("2022-09-27T12:30:00"),
timestamp("2022-09-27T12:30:00"),
timestamp("2022-09-28T14:15:00"),
timestamp("2022-09-29T12:30:00"),
timestamp("2022-10-03T14:00:00"),
timestamp("2022-10-05T12:15:00"),
timestamp("2022-10-05T14:00:00"),
timestamp("2022-10-07T12:30:00"),
timestamp("2022-10-12T18:00:00"),
timestamp("2022-10-13T12:30:00"),
timestamp("2022-10-13T12:30:00"),
timestamp("2022-10-14T12:30:00"),
timestamp("2022-10-14T12:30:00"),
timestamp("2022-10-14T14:00:00"),
timestamp("2022-10-27T12:30:00"),
timestamp("2022-10-27T12:30:00"),
timestamp("2022-10-27T12:30:00"),
timestamp("2022-11-01T14:00:00"),
timestamp("2022-11-02T12:15:00"),
timestamp("2022-11-02T18:00:00"),
timestamp("2022-11-02T18:00:00"),
timestamp("2022-11-02T18:30:00"),
timestamp("2022-11-03T14:00:00"),
timestamp("2022-11-04T12:30:00"),
timestamp("2022-11-10T13:30:00"),
timestamp("2022-11-10T13:30:00"),
timestamp("2022-11-11T15:00:00"),
timestamp("2022-11-16T13:30:00"),
timestamp("2022-11-16T13:30:00"),
timestamp("2022-11-23T13:30:00"),
timestamp("2022-11-23T13:30:00"),
timestamp("2022-11-23T19:00:00"),
timestamp("2022-11-30T13:15:00"),
timestamp("2022-11-30T13:30:00"),
timestamp("2022-11-30T18:30:00"),
timestamp("2022-12-01T15:00:00"),
timestamp("2022-12-02T13:30:00"),
timestamp("2022-12-05T15:00:00"),
timestamp("2022-12-09T15:00:00"),
timestamp("2022-12-13T13:30:00"),
timestamp("2022-12-13T13:30:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:00:00"),
timestamp("2022-12-14T19:30:00"),
timestamp("2022-12-15T13:30:00"),
timestamp("2022-12-15T13:30:00"),
timestamp("2022-12-22T13:30:00"),
timestamp("2022-12-23T13:30:00"),
timestamp("2022-12-23T13:30:00"),
timestamp("2023-01-04T15:00:00"),
timestamp("2023-01-04T19:00:00"),
timestamp("2023-01-05T13:15:00"),
timestamp("2023-01-06T13:30:00"),
timestamp("2023-01-06T15:00:00"),
timestamp("2023-01-10T14:00:00"),
timestamp("2023-01-12T13:30:00"),
timestamp("2023-01-12T13:30:00"),
timestamp("2023-01-12T13:30:00"),
timestamp("2023-01-13T15:00:00"),
timestamp("2023-01-18T13:30:00"),
timestamp("2023-01-18T13:30:00"),
timestamp("2023-01-26T13:30:00"),
timestamp("2023-01-26T13:30:00"),
timestamp("2023-01-26T13:30:00"),
timestamp("2023-02-01T13:15:00"),
timestamp("2023-02-01T15:00:00"),
timestamp("2023-02-01T19:00:00"),
timestamp("2023-02-01T19:00:00"),
timestamp("2023-02-01T19:30:00"),
timestamp("2023-02-03T13:30:00"),
timestamp("2023-02-03T15:00:00"),
timestamp("2023-02-07T17:40:00"),
timestamp("2023-02-08T02:00:00"),
timestamp("2023-02-10T15:00:00"),
timestamp("2023-02-14T13:30:00"),
timestamp("2023-02-14T13:30:00"),
timestamp("2023-02-15T13:30:00"),
timestamp("2023-02-15T13:30:00"),
timestamp("2023-02-22T19:00:00"),
timestamp("2023-02-23T13:30:00"),
timestamp("2023-02-27T13:30:00"),
timestamp("2023-02-27T13:30:00"),
timestamp("2023-03-01T15:00:00"),
timestamp("2023-03-03T15:00:00"),
timestamp("2023-03-07T15:00:00"),
timestamp("2023-03-08T13:15:00"),
timestamp("2023-03-08T15:00:00"),
timestamp("2023-03-10T13:30:00"),
timestamp("2023-03-13T13:00:00"),
timestamp("2023-03-14T12:30:00"),
timestamp("2023-03-14T12:30:00"),
timestamp("2023-03-15T12:30:00"),
timestamp("2023-03-15T12:30:00"),
timestamp("2023-03-17T14:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:00:00"),
timestamp("2023-03-22T18:30:00"),
timestamp("2023-03-24T12:30:00"),
timestamp("2023-03-24T12:30:00"),
timestamp("2023-03-30T12:30:00"),
timestamp("2023-04-03T14:00:00"),
timestamp("2023-04-05T12:15:00"),
timestamp("2023-04-05T14:00:00"),
timestamp("2023-04-07T12:30:00"),
timestamp("2023-04-12T12:30:00"),
timestamp("2023-04-12T12:30:00"),
timestamp("2023-04-12T18:00:00"),
timestamp("2023-04-14T12:30:00"),
timestamp("2023-04-14T12:30:00"),
timestamp("2023-04-14T14:00:00"),
timestamp("2023-04-26T12:30:00"),
timestamp("2023-04-26T12:30:00"),
timestamp("2023-04-27T12:30:00"),
timestamp("2023-05-01T14:00:00"),
timestamp("2023-05-03T12:15:00"),
timestamp("2023-05-03T14:00:00"),
timestamp("2023-05-03T18:00:00"),
timestamp("2023-05-03T18:00:00"),
timestamp("2023-05-03T18:30:00"),
timestamp("2023-05-05T12:30:00"),
timestamp("2023-05-10T12:30:00"),
timestamp("2023-05-10T12:30:00"),
timestamp("2023-05-12T14:00:00"),
timestamp("2023-05-16T12:30:00"),
timestamp("2023-05-16T12:30:00"),
timestamp("2023-05-19T15:00:00"),
timestamp("2023-05-24T18:00:00"),
timestamp("2023-05-25T12:30:00"),
timestamp("2023-05-26T12:30:00"),
timestamp("2023-05-26T12:30:00"),
timestamp("2023-06-01T12:15:00"),
timestamp("2023-06-01T14:00:00"),
timestamp("2023-06-02T12:30:00"),
timestamp("2023-06-05T14:00:00"),
timestamp("2023-06-13T12:30:00"),
timestamp("2023-06-13T12:30:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:00:00"),
timestamp("2023-06-14T18:30:00"),
timestamp("2023-06-15T12:30:00"),
timestamp("2023-06-15T12:30:00"),
timestamp("2023-06-16T14:00:00"),
timestamp("2023-06-21T14:00:00"),
timestamp("2023-06-22T14:00:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-28T20:30:00"),
timestamp("2023-06-29T06:30:00"),
timestamp("2023-06-29T12:30:00"),
timestamp("2023-06-30T12:30:00"),
timestamp("2023-06-30T12:30:00"),
timestamp("2023-07-03T14:00:00"),
timestamp("2023-07-05T18:00:00"),
timestamp("2023-07-06T12:15:00"),
timestamp("2023-07-06T14:00:00"),
timestamp("2023-07-07T12:30:00"),
timestamp("2023-07-07T12:30:00"),
timestamp("2023-07-07T12:30:00"),
timestamp("2023-07-12T12:30:00"),
timestamp("2023-07-12T12:30:00"),
timestamp("2023-07-12T12:30:00"),
timestamp("2023-07-12T12:30:00"),
timestamp("2023-07-13T12:30:00"),
timestamp("2023-07-14T14:00:00"),
timestamp("2023-07-18T12:30:00"),
timestamp("2023-07-18T12:30:00"),
timestamp("2023-07-24T13:45:00"),
timestamp("2023-07-24T13:45:00"),
timestamp("2023-07-26T18:00:00"),
timestamp("2023-07-26T18:00:00"),
timestamp("2023-07-26T18:30:00"),
timestamp("2023-07-27T12:30:00"),
timestamp("2023-07-28T12:30:00"),
timestamp("2023-07-28T12:30:00"),
timestamp("2023-08-01T14:00:00"),
timestamp("2023-08-02T12:15:00"),
timestamp("2023-08-03T14:00:00"),
timestamp("2023-08-04T12:30:00"),
timestamp("2023-08-04T12:30:00"),
timestamp("2023-08-04T12:30:00"),
timestamp("2023-08-10T12:30:00"),
timestamp("2023-08-10T12:30:00"),
timestamp("2023-08-10T12:30:00"),
timestamp("2023-08-10T12:30:00"),
timestamp("2023-08-11T12:30:00"),
timestamp("2023-08-11T14:00:00"),
timestamp("2023-08-15T12:30:00"),
timestamp("2023-08-15T12:30:00"),
timestamp("2023-08-16T18:00:00"),
timestamp("2023-08-23T13:45:00"),
timestamp("2023-08-23T13:45:00"),
timestamp("2023-08-24T12:30:00"),
timestamp("2023-08-31T12:30:00"),
timestamp("2023-08-31T12:30:00"),
timestamp("2023-09-01T12:30:00"),
timestamp("2023-09-01T12:30:00"),
timestamp("2023-09-01T12:30:00"),
timestamp("2023-09-01T14:00:00"),
timestamp("2023-09-04T14:00:00"),
timestamp("2023-09-06T12:15:00"),
timestamp("2023-09-13T12:30:00"),
timestamp("2023-09-13T12:30:00"),
timestamp("2023-09-13T12:30:00"),
timestamp("2023-09-13T12:30:00"),
timestamp("2023-09-14T12:30:00"),
timestamp("2023-09-14T12:30:00"),
timestamp("2023-09-14T12:30:00"),
timestamp("2023-09-15T14:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:00:00"),
timestamp("2023-09-20T18:30:00"),
timestamp("2023-09-22T13:45:00"),
timestamp("2023-09-22T13:45:00"),
timestamp("2023-09-28T12:30:00"),
timestamp("2023-09-29T12:30:00"),
timestamp("2023-09-29T12:30:00"),
timestamp("2023-10-02T14:00:00"),
timestamp("2023-10-04T12:15:00"),
timestamp("2023-10-04T14:00:00"),
timestamp("2023-10-06T12:30:00"),
timestamp("2023-10-06T12:30:00"),
timestamp("2023-10-06T12:30:00"),
timestamp("2023-10-11T12:30:00"),
timestamp("2023-10-11T18:00:00"),
timestamp("2023-10-12T12:30:00"),
timestamp("2023-10-12T12:30:00"),
timestamp("2023-10-12T12:30:00"),
timestamp("2023-10-12T12:30:00"),
timestamp("2023-10-13T14:00:00"),
timestamp("2023-10-17T12:30:00"),
timestamp("2023-10-17T12:30:00"),
timestamp("2023-10-24T13:45:00"),
timestamp("2023-10-24T13:45:00"),
timestamp("2023-10-26T12:30:00"),
timestamp("2023-10-27T12:30:00"),
timestamp("2023-10-27T12:30:00"),
timestamp("2023-11-01T12:15:00"),
timestamp("2023-11-01T14:00:00"),
timestamp("2023-11-01T18:00:00"),
timestamp("2023-11-01T18:00:00"),
timestamp("2023-11-01T18:30:00"),
timestamp("2023-11-03T12:30:00"),
timestamp("2023-11-03T12:30:00"),
timestamp("2023-11-03T12:30:00"),
timestamp("2023-11-03T15:00:00"),
timestamp("2023-11-10T15:00:00"),
timestamp("2023-11-14T13:30:00"),
timestamp("2023-11-14T13:30:00"),
timestamp("2023-11-14T13:30:00"),
timestamp("2023-11-14T13:30:00"),
timestamp("2023-11-15T13:30:00"),
timestamp("2023-11-16T13:30:00"),
timestamp("2023-11-16T13:30:00"),
timestamp("2023-11-22T19:00:00"),
timestamp("2023-11-23T14:45:00"),
timestamp("2023-11-23T14:45:00"),
timestamp("2023-11-29T13:30:00"),
timestamp("2023-11-30T13:30:00"),
timestamp("2023-11-30T13:30:00"),
timestamp("2023-12-01T13:30:00"),
timestamp("2023-12-01T13:30:00"),
timestamp("2023-12-01T15:00:00"),
timestamp("2023-12-06T13:15:00"),
timestamp("2023-12-06T15:00:00"),
timestamp("2023-12-08T13:30:00"),
timestamp("2023-12-08T15:00:00"),
timestamp("2023-12-12T13:30:00"),
timestamp("2023-12-12T13:30:00"),
timestamp("2023-12-12T13:30:00"),
timestamp("2023-12-13T13:30:00"),
timestamp("2023-12-13T13:30:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:00:00"),
timestamp("2023-12-13T19:30:00"),
timestamp("2023-12-14T13:30:00"),
timestamp("2023-12-14T13:30:00"),
timestamp("2023-12-18T14:45:00"),
timestamp("2023-12-18T14:45:00"),
timestamp("2023-12-21T13:30:00"),
timestamp("2023-12-22T13:30:00"),
timestamp("2023-12-22T13:30:00")
)
|
lib_drawing_composite_types | https://www.tradingview.com/script/3UnLbMnV-lib-drawing-composite-types/ | robbatt | https://www.tradingview.com/u/robbatt/ | 0 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// credits to Trendoscope Pty Ltd (https://www.tradingview.com/script/63c8VXSa-DrawingTypes/)
//@version=5
import HeWhoMustNotBeNamed/DrawingTypes/2 as D
// @description User Defined Types for basic drawing structure. Other types and methods will be built on these. (added type Triangle and Polygon to https://www.tradingview.com/script/63c8VXSa-DrawingTypes/)
library("lib_drawing_composite_types", overlay = true)
// @type TriangleProperties object
// @field border_color Box border color. Default is color.blue
// @field fill_color Fill color
// @field transparency Fill transparency range from 0 to 100
// @field border_width Box border width. Default is 1
// @field border_style Box border style. Default is line.style_solid
// @field extend Extend property of box. default is extend.none
// @field xloc defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
// @field object linefill object created from wrapper
export type TriangleProperties
color border_color = chart.fg_color
color fill_color = chart.fg_color
int fill_transparency = 80
int border_width = 1
string border_style = line.style_solid
string xloc = xloc.bar_index
// @type Triangle object
// @field p1 point one
// @field p2 point two
// @field p3 point three
// @field properties Triangle properties
// @field l12 line object created
// @field l23 line object created
// @field l31 line object created
export type Triangle
D.Point p1
D.Point p2
D.Point p3
TriangleProperties properties
line l12
line l23
line l31
// @type Trianglefill object
// @field triangle to create a linefill for
// @field fill_color Fill color
// @field transparency Fill transparency range from 0 to 100
// @field object linefill object created
export type Trianglefill
Triangle triangle
color fill_color = chart.fg_color
int transparency = 80
linefill object
// @type Polygon object
// @field center Point that triangles are using as common center
// @field triangles an array of triangles that form the Polygon
export type Polygon
D.Point center
array<Triangle> triangles
// @type Polygonfill object
// @field _polygon to create a fill for
// @field _fills an array of Trianglefill objects that match the array of triangles in _polygon
export type Polygonfill
Polygon _polygon
array<Trianglefill> _fills
|
RSI Heatmap Screener [ChartPrime] | https://www.tradingview.com/script/mMn35YVE-RSI-Heatmap-Screener-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 332 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("RSI Heatmap Screener [ChartPrime]")
import TradingView/TechnicalRating/1 as TechnN
color OffGrey = color.rgb(68, 63, 63, 50)
color Offwhite = color.rgb(255, 255, 255, 19)
color Alpha = color.new(color.black,100)
int BarTime = time - time[1]
string SYM = "➞ Symbols🔸"
// -- { Inputs
int RSILen = input.int(14,"RSI Length")
bool ShowAvg = input.bool(true,"Show Average RSI")
bool ShowMark = input.bool(true,"Show Market Avg RSI")
bool Which = input.string("Detailed","HeatMap Type",options = ["Detailed", "Colorful"]) == "Detailed"
//-- }
// -- { Storage room
type RSI
array<string> str
array<int> position
array<label> Labels
int Right
int Left
array<int> Xbars
var array<label> LL = array.new_label()
type data
array<string> names
array<bool> USEbool
array<float> rsiArray
array<string> Tips
Data = data.new(array.new_string(0),array.new_bool(0), array.new_float(0),array.new_string(0))
RRSI = RSI.new(array.from("OVERBOUGHT","STRONG","NEUTRAL","WEAK","OVERSOLD"),
array.from(74,64,49,34,24),
array.new_label(5),
chart.right_visible_bar_time,
chart.left_visible_bar_time,
array.new_int())
// -- }
/// -{ Functions
Clearname(pair)=>
string str = pair
str := str.replace_all(str,"USDT","")
str := str.replace_all(str,"BUSD","")
str
Colz(float val)=>
switch
val > 85 => #ff2525
val > 70 => color.new(color.rgb(198, 194, 8),70)
val < 70 and val > 60 => color.new(color.rgb(125, 5, 5),70)
val > 40 and val < 60 => color.new(color.rgb(121, 119, 119),70)
val > 30 and val < 40 => color.new(#00e677, 58)
val < 30 and val > 20 => color.new(#089089, 56)
=> color.new(color.fuchsia,70)
GetBars(RSI self )=>
var int Rand = 0
var AA = self.Xbars.copy()
if time > chart.left_visible_bar_time and time < chart.right_visible_bar_time
AA.push(time)
Rand := int(math.random((AA.min() + (BarTime * 5)) ,(AA.max() - (BarTime * 10))))
Rand
method normalize(float _src, int _min, int _max) =>
var min_src = 10e10
var max_src = -10e10
min_src := math.min(nz(_src, min_src), min_src)
max_src := math.max(nz(_src, max_src), max_src)
_min + (_max - _min) * (_src - min_src) / math.max(max_src - min_src, 10e-10)
// -- }
//---{ Detailed HeatMap
method Prt(RSI self,data x)=>
var box avg = na , box.delete(avg)
if barstate.islast
for i = 0 to self.str.size() -1
label.delete(self.Labels.get(i))
self.Labels.set(i,label.new(
self.Right - (BarTime * 7 ),self.position.get(i),
self.str.get(i),
style = label.style_none,
textcolor = Offwhite,xloc = xloc.bar_time))
if ShowAvg
avg:=box.new(
self.Left,x.rsiArray.avg()+2,
self.Right,x.rsiArray.avg()-2,
bgcolor = color.rgb(102, 102, 105, 85),border_color = color.rgb(60, 60, 61, 85),extend = extend.both,
text = "Average RSI " + str.tostring(x.rsiArray.avg(),"0.##"),
text_size = size.normal,text_halign = text.align_center,text_color= color.orange,text_valign = text.align_center,
xloc = xloc.bar_time)
method PrtRSI(data self) =>
RSICGBAE = ta.change(fixnan(self.rsiArray.get(0)))
if barstate.isconfirmed
for i = 0 to self.USEbool.size() -1
Tip = self.Tips.get(i)
Bar_index = GetBars(RRSI)
LL.push(label.new(
Bar_index,self.rsiArray.get(i),
Clearname(self.names.get(i)),style = label.style_circle,
textcolor = color.white,color = Colz(self.rsiArray.get(i)),
size = size.tiny,tooltip = Tip,xloc = xloc.bar_time))
if LL.size()> self.USEbool.size()
for i = 0 to self.USEbool.size() -1
label.delete(LL.shift())
// -- }
// { ColorHeap
method Nameslabels(RSI rsi, data self)=>
var array<float> Levels = array.new_float(self.names.size())
step = 100 / self.names.size()
for i = 0 to self.names.size() -1 by 1
Pos = 20 + step * i
Levels.set(i,Pos)
label.new(rsi.Right + (BarTime * 2 ),Pos,Clearname(self.names.get(i)),style = label.style_none,textcolor = color.rgb(255, 255, 255, 57),xloc = xloc.bar_time)
Levels
// }
// { Worker
initialize(x,y)=>
if Which
PrtRSI(y)
Prt(x,y)
if (not Which)
Lev = Nameslabels(x, y)
Lev
//-- }
// --- { Screener
bool T01 = input.bool(true, title = "" , group = SYM , inline = 's01')
bool T02 = input.bool(true, title = "" , group = SYM , inline = 's02')
bool T03 = input.bool(true, title = "" , group = SYM , inline = 's03')
bool T04 = input.bool(true, title = "" , group = SYM , inline = 's04')
bool T05 = input.bool(true, title = "" , group = SYM , inline = 's05')
bool T06 = input.bool(true, title = "" , group = SYM , inline = 's06')
bool T07 = input.bool(true, title = "" , group = SYM , inline = 's07')
bool T08 = input.bool(true, title = "" , group = SYM , inline = 's08')
bool T09 = input.bool(true, title = "" , group = SYM , inline = 's09')
bool T10 = input.bool(true, title = "" , group = SYM , inline = 's10')
bool T11 = input.bool(true, title = "" , group = SYM , inline = 's11')
bool T12 = input.bool(true, title = "" , group = SYM , inline = 's12')
bool T13 = input.bool(true, title = "" , group = SYM , inline = 's13')
bool T14 = input.bool(true, title = "" , group = SYM , inline = 's14')
bool T15 = input.bool(true, title = "" , group = SYM , inline = 's15')
bool T16 = input.bool(true, title = "" , group = SYM , inline = 's16')
bool T17 = input.bool(true, title = "" , group = SYM , inline = 's17')
bool T18 = input.bool(true, title = "" , group = SYM , inline = 's18')
bool T19 = input.bool(true, title = "" , group = SYM , inline = 's19')
bool T20 = input.bool(true, title = "" , group = SYM , inline = 's20')
bool T21 = input.bool(true, title = "" , group = SYM , inline = 's21')
bool T22 = input.bool(true, title = "" , group = SYM , inline = 's22')
bool T23 = input.bool(true, title = "" , group = SYM , inline = 's23')
bool T24 = input.bool(true, title = "" , group = SYM , inline = 's24')
bool T25 = input.bool(true, title = "" , group = SYM , inline = 's25')
bool T26 = input.bool(true, title = "" , group = SYM , inline = 's26')
bool T27 = input.bool(true, title = "" , group = SYM , inline = 's27')
bool T28 = input.bool(true, title = "" , group = SYM , inline = 's28')
bool T29 = input.bool(true, title = "" , group = SYM , inline = 's29')
bool T30 = input.bool(true, title = "" , group = SYM , inline = 's30')
string s01 = input.symbol('BTCUSDT' , group = SYM , inline = 's01' , title = "Sym 1")
string s02 = input.symbol('ETHUSDT' , group = SYM , inline = 's02' , title = "Sym 2")
string s03 = input.symbol('BNBUSDT' , group = SYM , inline = 's03' , title = "Sym 3")
string s04 = input.symbol('SOLUSDT' , group = SYM , inline = 's04' , title = "Sym 4")
string s05 = input.symbol('LDOUSDT' , group = SYM , inline = 's05' , title = "Sym 5")
string s06 = input.symbol('ADAUSDT' , group = SYM , inline = 's06' , title = "Sym 6")
string s07 = input.symbol('MATICUSDT' , group = SYM , inline = 's07' , title = "Sym 7")
string s08 = input.symbol('WAVESUSDT' , group = SYM , inline = 's08' , title = "Sym 8")
string s09 = input.symbol('TRXUSDT' , group = SYM , inline = 's09' , title = "Sym 9")
string s10 = input.symbol('FTMUSDT' , group = SYM , inline = 's10' , title = "Sym 10")
string s11 = input.symbol('SANDUSDT' , group = SYM , inline = 's11' , title = "Sym 11")
string s12 = input.symbol('LINKUSDT' , group = SYM , inline = 's12' , title = "Sym 12")
string s13 = input.symbol('VETUSDT' , group = SYM , inline = 's13' , title = "Sym 13")
string s14 = input.symbol('GALAUSDT' , group = SYM , inline = 's14' , title = "Sym 14")
string s15 = input.symbol('AVAXUSDT' , group = SYM , inline = 's15' , title = "Sym 15")
string s16 = input.symbol('EOSUSDT' , group = SYM , inline = 's16' , title = "Sym 16")
string s17 = input.symbol('XLMUSDT' , group = SYM , inline = 's17' , title = "Sym 17")
string s18 = input.symbol('LTCUSDT' , group = SYM , inline = 's18' , title = "Sym 18")
string s19 = input.symbol('APTUSDT' , group = SYM , inline = 's19' , title = "Sym 19")
string s20 = input.symbol('WINUSDT' , group = SYM , inline = 's20' , title = "Sym 20")
string s21 = input.symbol('DOTUSDT' , group = SYM , inline = 's21' , title = "Sym 21")
string s22 = input.symbol('BTTUSDT' , group = SYM , inline = 's22' , title = "Sym 22")
string s23 = input.symbol('BCHUSDT' , group = SYM , inline = 's23' , title = "Sym 23")
string s24 = input.symbol('OPUSDT' , group = SYM , inline = 's24' , title = "Sym 24")
string s25 = input.symbol('IOSTUSDT' , group = SYM , inline = 's25' , title = "Sym 25")
string s26 = input.symbol('CHZUSDT' , group = SYM , inline = 's26' , title = "Sym 26")
string s27 = input.symbol('LINKUSDT' , group = SYM , inline = 's27' , title = "Sym 27")
string s28 = input.symbol('LTCUSDT' , group = SYM , inline = 's28' , title = "Sym 28")
string s29 = input.symbol('AXSUSDT' , group = SYM , inline = 's29' , title = "Sym 29")
string s30 = input.symbol('MANAUSDT' , group = SYM , inline = 's30' , title = "Sym 30")
_requestData() =>
rsi = ta.rsi(close,RSILen)
VWAP = ta.vwap(hlc3)
SMA10 = ta.sma(close,10)
SMA20 = ta.sma(close,20)
SMA50 = ta.sma(close,50)
SMA100 = ta.sma(close,100)
[ratingTotal, _, _] = TechnN.calcRatingAll()
TVrating = TechnN.ratingStatus(ratingTotal,0.5,0.1)
Stoch = ta.sma(ta.stoch(close, high, low, 8), 5)
StochK = ta.sma(Stoch, 5)
Volume = volume
Vol = ta.sma(volume,10)
CLOSE = close
[ rsi , VWAP , SMA10 , SMA20 , SMA50 , SMA100, TVrating , Stoch , StochK , Volume ,Vol ,CLOSE ]
GetData(pair)=>
[ rsi , VWAP , SMA10 , SMA20 , SMA50 , SMA100, TVrating , Stoch , StochK , Volume ,Vol, CLOSE ] = request.security(pair,"",_requestData())
string TIP = ""
Rsi = str.tostring(rsi,"0.##")
SMA100con = SMA100 < CLOSE ? "✅" : "❌"
StochCon = Stoch > StochK ? "✅" : "❌"
SMA10con = SMA10 < CLOSE ? "✅" : "❌"
SMA20con = SMA20 < CLOSE ? "✅" : "❌"
SMA50con = SMA50 < CLOSE ? "✅" : "❌"
VWAPcon = VWAP < CLOSE ? "✅" : "❌"
VolCon = Volume > Vol ? "✅" : "❌"
TVCon = switch TVrating
"Strong\nSell" => "❌ 🔥"
"Strong\nBuy " => "✅ 🔥"
"Neutral" => "〰️"
"Sell" => "❌"
"Buy" => "✅"
TIP += "RSI: " + Rsi + "\n"
TIP += "VWAP: " + VWAPcon + "\n"
TIP += "SMA10: " + SMA10con + "\n"
TIP += "SMA20: " + SMA20con + "\n"
TIP += "SMA50: " + SMA50con + "\n"
TIP += "SMA100: " + SMA100con + "\n"
TIP += "Stoch: " + StochCon + "\n"
TIP += "Volume Rating : " + VolCon + "\n"
TIP += "TradingView Rating " + TVCon + "\n"
[rsi , TIP]
///
[RSI01, TIP01 ] = GetData(s01) , [RSI02, TIP02 ] = GetData(s02) , [RSI03, TIP03 ] = GetData(s03) , [RSI04, TIP04 ] = GetData(s04)
[RSI05, TIP05 ] = GetData(s05) , [RSI06, TIP06 ] = GetData(s06) , [RSI07, TIP07 ] = GetData(s07) , [RSI08, TIP08 ] = GetData(s08)
[RSI09, TIP09 ] = GetData(s09) , [RSI10, TIP10 ] = GetData(s10) , [RSI11, TIP11 ] = GetData(s11) , [RSI12, TIP12 ] = GetData(s12)
[RSI13, TIP13 ] = GetData(s13) , [RSI14, TIP14 ] = GetData(s14) , [RSI15, TIP15 ] = GetData(s15) , [RSI16, TIP16 ] = GetData(s16)
[RSI17, TIP17 ] = GetData(s17) , [RSI18, TIP18 ] = GetData(s18) , [RSI19, TIP19 ] = GetData(s19) , [RSI20, TIP20 ] = GetData(s20)
[RSI21, TIP21 ] = GetData(s21) , [RSI22, TIP22 ] = GetData(s22) , [RSI23, TIP23 ] = GetData(s23) , [RSI24, TIP24 ] = GetData(s24)
[RSI25, TIP25 ] = GetData(s25) , [RSI26, TIP26 ] = GetData(s26) , [RSI27, TIP27 ] = GetData(s27) , [RSI28, TIP28 ] = GetData(s28)
[RSI29, TIP29 ] = GetData(s29) , [RSI30, TIP30 ] = GetData(s30)
plot(RSI01,display = display.data_window,title = "RSI")
array<string> raw_names =
array.from(
s01,s02,s03,s04,s05,s06,s07,s08,s09,s10,
s11,s12,s13,s14,s15,s16,s17,s18,s19,s20,
s21,s22,s23,s24,s25,s26,s27,s28,s29,s30
)
array<bool> raw_bools =
array.from(
T01,T02,T03,T04,T05,T06,T07,T08,T09,T10,
T11,T12,T13,T14,T15,T16,T17,T18,T19,T20,
T21,T22,T23,T24,T25,T26,T27,T28,T29,T30
)
array<float> raw_RSI =
array.from(
RSI01,RSI02,RSI03,RSI04,RSI05,
RSI06,RSI07,RSI08,RSI09,RSI10,
RSI11,RSI12,RSI13,RSI14,RSI15,
RSI16,RSI17,RSI18,RSI19,RSI20,
RSI21,RSI22,RSI23,RSI24,RSI25,
RSI26,RSI27,RSI28,RSI29,RSI30
)
array<string> raw_TIP =
array.from(
TIP01,TIP02,TIP03,TIP04,TIP05,
TIP06,TIP07,TIP08,TIP09,TIP10,
TIP11,TIP12,TIP13,TIP14,TIP15,
TIP16,TIP17,TIP18,TIP19,TIP20,
TIP21,TIP22,TIP23,TIP24,TIP25,
TIP26,TIP27,TIP28,TIP29,TIP30
)
for _bool in raw_bools
Data.USEbool.push(_bool)
for i = 0 to Data.USEbool.size() -1
if Data.USEbool.get(i)
Data.names.push(syminfo.ticker(raw_names.get(i)))
Data.rsiArray.push(raw_RSI.get(i))
Data.Tips.push(raw_TIP.get(i))
// --- }
// { Detailed Plotting
upper1 = hline(Which ? 85 : na,color = color.new(OffGrey,70))
upper2 = hline(Which ? 70 : na,color = color.new(OffGrey,70))
upper3 = hline(Which ? 60 : na,color = color.new(OffGrey,70))
Middle = hline(Which ? 50 : na,color = color.new(OffGrey,70))
lower1 = hline(Which ? 40 : na,color = color.new(OffGrey,70))
lower2 = hline(Which ? 30 : na,color = color.new(OffGrey,70))
lower3 = hline(Which ? 15 : na,color = color.new(OffGrey,70))
AVG = plot(Which ? ShowMark ? normalize(Data.rsiArray.avg(),0,15) : na: na ,style = plot.style_line,color = OffGrey)
Zero = plot(Which ? ShowMark ? 0: na : na ,display = display.data_window,color = color.new(color.black,100))
fill(upper1, upper2, top_value = 85, bottom_value = 71, bottom_color = color.new(#8d050c, 95), top_color = color.new(#e56b08, 0), editable = true)
fill(upper2, upper3, top_value = 71, bottom_value = 60, bottom_color = color.new(#8d050c, 85) , top_color = color.new(#8d050c, 95), editable = true)
fill(lower1, lower2, top_value = 40, bottom_value = 30, bottom_color = color.new(#045322, 90), top_color = color.new(#045623, 75), editable = true)
fill(lower2, lower3, top_value = 27, bottom_value = 15, bottom_color = color.new(#04a49f, 0), top_color = color.new(#04a140, 95), editable = true)
fill(AVG,Zero,color.from_gradient(Data.rsiArray.avg(),30,70,color.new(#09b8b2, 41),color.new(color.rgb(141, 7, 7),60)))
fill(upper3,lower1,color = color.rgb(57, 54, 54, 78))
// }
lev = initialize(RRSI,Data)
// -- { Colorful Build
COOOL(ints)=>
color.from_gradient(ints,15,80,color.new(#f3b14f, 48),color.new(#4c1457, 24))
plotchar(not Which ? lev.get(0) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(0)),offset = -5)
plotchar(not Which ? lev.get(1) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(1)),offset = -5)
plotchar(not Which ? lev.get(2) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(2)),offset = -5)
plotchar(not Which ? lev.get(3) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(3)),offset = -5)
plotchar(not Which ? lev.get(4) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(4)),offset = -5)
plotchar(not Which ? lev.get(5) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(5)),offset = -5)
plotchar(not Which ? lev.get(6) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(6)),offset = -5)
plotchar(not Which ? lev.get(7) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(7)),offset = -5)
plotchar(not Which ? lev.get(8) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(8)),offset = -5)
plotchar(not Which ? lev.get(9) : na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(9)),offset = -5)
plotchar(not Which ? lev.get(10): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(10)),offset = -5)
plotchar(not Which ? lev.get(11): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(11)),offset = -5)
plotchar(not Which ? lev.get(12): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(12)),offset = -5)
plotchar(not Which ? lev.get(13): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(13)),offset = -5)
plotchar(not Which ? lev.get(14): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(14)),offset = -5)
plotchar(not Which ? lev.get(15): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(15)),offset = -5)
plotchar(not Which ? lev.get(16): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(16)),offset = -5)
plotchar(not Which ? lev.get(17): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(17)),offset = -5)
plotchar(not Which ? lev.get(18): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(18)),offset = -5)
plotchar(not Which ? lev.get(19): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(19)),offset = -5)
plotchar(not Which ? lev.get(20): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(20)),offset = -5)
plotchar(not Which ? lev.get(21): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(21)),offset = -5)
plotchar(not Which ? lev.get(22): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(22)),offset = -5)
plotchar(not Which ? lev.get(23): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(23)),offset = -5)
plotchar(not Which ? lev.get(24): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(24)),offset = -5)
plotchar(not Which ? lev.get(25): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(25)),offset = -5)
plotchar(not Which ? lev.get(26): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(26)),offset = -5)
plotchar(not Which ? lev.get(27): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(27)),offset = -5)
plotchar(not Which ? lev.get(28): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(28)),offset = -5)
plotchar(not Which ? lev.get(29): na ,location = location.absolute,char = "☐" ,size = size.tiny,color = Colz(Data.rsiArray.get(29)),offset = -5)
// }
|
CalendarGbp | https://www.tradingview.com/script/64zlZL2D-CalendarGbp/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the important events on GBP. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("CalendarGbp")
// @function GBP high impact news date and time from 2015 to 2019
export HighImpactNews2015To2019() =>
array.from(
timestamp("2015-01-08T12:00:00"),
timestamp("2015-01-08T12:00:00"),
timestamp("2015-01-13T09:30:00"),
timestamp("2015-01-13T09:30:00"),
timestamp("2015-01-14T14:15:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-21T09:30:00"),
timestamp("2015-01-27T09:30:00"),
timestamp("2015-01-27T09:30:00"),
timestamp("2015-01-28T18:50:00"),
timestamp("2015-02-05T12:00:00"),
timestamp("2015-02-05T12:00:00"),
timestamp("2015-02-12T10:30:00"),
timestamp("2015-02-12T10:30:00"),
timestamp("2015-02-17T09:30:00"),
timestamp("2015-02-17T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-18T09:30:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-25T10:00:00"),
timestamp("2015-02-26T09:30:00"),
timestamp("2015-02-26T09:30:00"),
timestamp("2015-03-05T12:00:00"),
timestamp("2015-03-05T12:00:00"),
timestamp("2015-03-06T09:30:00"),
timestamp("2015-03-10T14:35:00"),
timestamp("2015-03-12T12:45:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-18T09:30:00"),
timestamp("2015-03-24T09:30:00"),
timestamp("2015-03-24T09:30:00"),
timestamp("2015-03-27T08:45:00"),
timestamp("2015-03-31T08:30:00"),
timestamp("2015-03-31T08:30:00"),
timestamp("2015-04-09T11:00:00"),
timestamp("2015-04-09T11:00:00"),
timestamp("2015-04-14T08:30:00"),
timestamp("2015-04-14T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-22T08:30:00"),
timestamp("2015-04-28T08:30:00"),
timestamp("2015-04-28T08:30:00"),
timestamp("2015-05-07T12:00:00"),
timestamp("2015-05-11T11:00:00"),
timestamp("2015-05-11T11:00:00"),
timestamp("2015-05-12T14:00:00"),
timestamp("2015-05-13T09:30:00"),
timestamp("2015-05-13T09:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-20T08:30:00"),
timestamp("2015-05-21T08:30:00"),
timestamp("2015-05-22T13:00:00"),
timestamp("2015-06-04T11:00:00"),
timestamp("2015-06-04T11:00:00"),
timestamp("2015-06-05T08:30:00"),
timestamp("2015-06-10T14:00:00"),
timestamp("2015-06-10T20:00:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-16T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-17T08:30:00"),
timestamp("2015-06-26T14:15:00"),
timestamp("2015-07-07T14:00:00"),
timestamp("2015-07-09T11:00:00"),
timestamp("2015-07-09T11:00:00"),
timestamp("2015-07-14T09:15:00"),
timestamp("2015-07-14T11:45:00"),
timestamp("2015-07-16T18:00:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-07-22T08:30:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:00:00"),
timestamp("2015-08-06T11:45:00"),
timestamp("2015-08-06T14:00:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-18T08:30:00"),
timestamp("2015-08-28T08:30:00"),
timestamp("2015-08-29T02:25:00"),
timestamp("2015-09-09T14:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-10T11:00:00"),
timestamp("2015-09-11T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-15T08:30:00"),
timestamp("2015-09-16T13:15:00"),
timestamp("2015-09-29T19:40:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T11:00:00"),
timestamp("2015-10-08T18:00:00"),
timestamp("2015-10-20T10:00:00"),
timestamp("2015-10-21T17:00:00"),
timestamp("2015-10-27T09:30:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:00:00"),
timestamp("2015-11-05T12:45:00"),
timestamp("2015-11-06T15:00:00"),
timestamp("2015-11-11T10:30:00"),
timestamp("2015-11-17T09:30:00"),
timestamp("2015-11-17T09:30:00"),
timestamp("2015-11-24T10:00:00"),
timestamp("2015-11-24T10:00:00"),
timestamp("2015-12-01T09:00:00"),
timestamp("2015-12-07T15:00:00"),
timestamp("2015-12-08T15:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T12:00:00"),
timestamp("2015-12-10T18:30:00"),
timestamp("2016-01-12T14:15:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-14T12:00:00"),
timestamp("2016-01-19T12:00:00"),
timestamp("2016-01-26T10:45:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:00:00"),
timestamp("2016-02-04T12:45:00"),
timestamp("2016-02-10T15:00:00"),
timestamp("2016-02-16T09:30:00"),
timestamp("2016-02-16T09:30:00"),
timestamp("2016-02-23T10:00:00"),
timestamp("2016-02-23T10:00:00"),
timestamp("2016-02-25T09:30:00"),
timestamp("2016-02-26T00:15:00"),
timestamp("2016-03-08T09:15:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-17T12:00:00"),
timestamp("2016-03-22T09:30:00"),
timestamp("2016-03-22T09:30:00"),
timestamp("2016-03-27T19:00:00"),
timestamp("2016-03-31T07:00:00"),
timestamp("2016-04-12T08:30:00"),
timestamp("2016-04-12T08:30:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-14T11:00:00"),
timestamp("2016-04-19T14:35:00"),
timestamp("2016-04-21T14:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:00:00"),
timestamp("2016-05-12T11:45:00"),
timestamp("2016-05-17T08:30:00"),
timestamp("2016-05-17T08:30:00"),
timestamp("2016-05-24T09:00:00"),
timestamp("2016-06-02T13:00:00"),
timestamp("2016-06-10T08:30:00"),
timestamp("2016-06-14T08:30:00"),
timestamp("2016-06-14T08:30:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T11:00:00"),
timestamp("2016-06-16T20:00:00"),
timestamp("2016-06-23T12:00:00"),
timestamp("2016-06-24T07:45:00"),
timestamp("2016-06-30T15:00:00"),
timestamp("2016-07-05T10:00:00"),
timestamp("2016-07-12T09:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-14T11:00:00"),
timestamp("2016-07-19T08:30:00"),
timestamp("2016-07-19T08:30:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:00:00"),
timestamp("2016-08-04T11:30:00"),
timestamp("2016-08-09T14:00:00"),
timestamp("2016-08-16T08:30:00"),
timestamp("2016-08-16T08:30:00"),
timestamp("2016-08-31T11:45:00"),
timestamp("2016-09-05T08:30:00"),
timestamp("2016-09-07T13:15:00"),
timestamp("2016-09-09T08:30:00"),
timestamp("2016-09-13T08:30:00"),
timestamp("2016-09-13T08:30:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-15T11:00:00"),
timestamp("2016-09-22T17:00:00"),
timestamp("2016-10-07T14:00:00"),
timestamp("2016-10-14T14:00:00"),
timestamp("2016-10-18T08:30:00"),
timestamp("2016-10-18T08:30:00"),
timestamp("2016-10-25T14:30:00"),
timestamp("2016-11-03T10:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:00:00"),
timestamp("2016-11-03T12:30:00"),
timestamp("2016-11-08T15:00:00"),
timestamp("2016-11-14T16:00:00"),
timestamp("2016-11-15T09:30:00"),
timestamp("2016-11-15T09:30:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-23T12:30:00"),
timestamp("2016-11-25T09:30:00"),
timestamp("2016-12-05T00:00:00"),
timestamp("2016-12-06T00:00:00"),
timestamp("2016-12-07T00:00:00"),
timestamp("2016-12-07T15:00:00"),
timestamp("2016-12-08T00:00:00"),
timestamp("2016-12-09T09:30:00"),
timestamp("2016-12-14T12:15:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2016-12-15T12:00:00"),
timestamp("2017-01-01T12:00:00"),
timestamp("2017-01-11T14:15:00"),
timestamp("2017-01-16T18:30:00"),
timestamp("2017-01-17T09:30:00"),
timestamp("2017-01-17T09:30:00"),
timestamp("2017-01-17T11:45:00"),
timestamp("2017-01-24T09:30:00"),
timestamp("2017-01-25T16:50:00"),
timestamp("2017-01-26T09:30:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:00:00"),
timestamp("2017-02-02T12:30:00"),
timestamp("2017-02-08T20:00:00"),
timestamp("2017-02-09T18:30:00"),
timestamp("2017-02-14T09:30:00"),
timestamp("2017-02-21T10:00:00"),
timestamp("2017-02-21T10:00:00"),
timestamp("2017-02-22T09:30:00"),
timestamp("2017-03-10T09:30:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-16T12:00:00"),
timestamp("2017-03-21T09:30:00"),
timestamp("2017-03-21T10:35:00"),
timestamp("2017-03-29T11:45:00"),
timestamp("2017-04-07T08:30:00"),
timestamp("2017-04-07T09:00:00"),
timestamp("2017-04-12T08:30:00"),
timestamp("2017-04-12T08:30:00"),
timestamp("2017-04-18T10:15:00"),
timestamp("2017-04-20T15:30:00"),
timestamp("2017-04-20T16:30:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:00:00"),
timestamp("2017-05-11T11:30:00"),
timestamp("2017-05-11T12:00:00"),
timestamp("2017-05-15T14:00:00"),
timestamp("2017-05-16T08:30:00"),
timestamp("2017-05-17T08:30:00"),
timestamp("2017-05-22T18:00:00"),
timestamp("2017-06-08T12:00:00"),
timestamp("2017-06-09T08:30:00"),
timestamp("2017-06-09T10:00:00"),
timestamp("2017-06-13T08:30:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-15T11:00:00"),
timestamp("2017-06-20T07:30:00"),
timestamp("2017-06-27T10:00:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-03T12:00:00"),
timestamp("2017-07-07T13:00:00"),
timestamp("2017-07-11T10:30:00"),
timestamp("2017-07-18T08:30:00"),
timestamp("2017-07-18T13:30:00"),
timestamp("2017-07-26T08:30:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:00:00"),
timestamp("2017-08-03T11:30:00"),
timestamp("2017-08-15T08:30:00"),
timestamp("2017-09-08T08:30:00"),
timestamp("2017-09-12T08:30:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-14T11:00:00"),
timestamp("2017-09-18T15:00:00"),
timestamp("2017-09-22T13:15:00"),
timestamp("2017-09-28T08:15:00"),
timestamp("2017-09-28T09:00:00"),
timestamp("2017-09-29T14:15:00"),
timestamp("2017-10-09T06:00:00"),
timestamp("2017-10-17T08:30:00"),
timestamp("2017-10-17T10:15:00"),
timestamp("2017-10-17T12:30:00"),
timestamp("2017-10-18T08:30:00"),
timestamp("2017-10-19T08:30:00"),
timestamp("2017-10-25T08:30:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:00:00"),
timestamp("2017-11-02T12:30:00"),
timestamp("2017-11-14T09:30:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-15T09:30:00"),
timestamp("2017-11-15T09:30:00"),
timestamp("2017-11-16T14:00:00"),
timestamp("2017-11-28T07:00:00"),
timestamp("2017-11-28T07:30:00"),
timestamp("2017-11-29T14:00:00"),
timestamp("2017-12-12T09:30:00"),
timestamp("2017-12-12T09:30:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-14T12:00:00"),
timestamp("2017-12-20T13:15:00"),
timestamp("2018-01-16T09:30:00"),
timestamp("2018-01-16T09:30:00"),
timestamp("2018-01-26T09:30:00"),
timestamp("2018-01-26T14:00:00"),
timestamp("2018-01-30T15:30:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:00:00"),
timestamp("2018-02-08T12:30:00"),
timestamp("2018-02-13T09:30:00"),
timestamp("2018-02-13T09:30:00"),
timestamp("2018-02-19T18:45:00"),
timestamp("2018-02-21T09:30:00"),
timestamp("2018-02-21T09:30:00"),
timestamp("2018-02-21T14:15:00"),
timestamp("2018-02-21T14:15:00"),
timestamp("2018-03-02T00:00:00"),
timestamp("2018-03-02T10:00:00"),
timestamp("2018-03-02T13:30:00"),
timestamp("2018-03-19T11:45:00"),
timestamp("2018-03-20T09:30:00"),
timestamp("2018-03-20T09:30:00"),
timestamp("2018-03-21T09:30:00"),
timestamp("2018-03-21T09:30:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-03-22T12:00:00"),
timestamp("2018-04-06T15:15:00"),
timestamp("2018-04-12T19:00:00"),
timestamp("2018-04-17T08:30:00"),
timestamp("2018-04-17T08:30:00"),
timestamp("2018-04-18T08:30:00"),
timestamp("2018-04-18T08:30:00"),
timestamp("2018-04-27T08:30:00"),
timestamp("2018-04-27T14:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:00:00"),
timestamp("2018-05-10T11:30:00"),
timestamp("2018-05-15T08:30:00"),
timestamp("2018-05-15T08:30:00"),
timestamp("2018-05-22T08:15:00"),
timestamp("2018-05-22T09:00:00"),
timestamp("2018-05-23T08:30:00"),
timestamp("2018-05-23T08:30:00"),
timestamp("2018-05-24T08:00:00"),
timestamp("2018-05-24T17:00:00"),
timestamp("2018-05-25T13:20:00"),
timestamp("2018-06-12T08:30:00"),
timestamp("2018-06-12T08:30:00"),
timestamp("2018-06-13T08:30:00"),
timestamp("2018-06-13T08:30:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T11:00:00"),
timestamp("2018-06-21T20:15:00"),
timestamp("2018-06-27T10:00:00"),
timestamp("2018-07-05T10:00:00"),
timestamp("2018-07-10T08:30:00"),
timestamp("2018-07-11T15:35:00"),
timestamp("2018-07-17T08:00:00"),
timestamp("2018-07-17T08:30:00"),
timestamp("2018-07-17T08:30:00"),
timestamp("2018-07-18T08:30:00"),
timestamp("2018-07-18T08:30:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:00:00"),
timestamp("2018-08-02T11:30:00"),
timestamp("2018-08-10T08:30:00"),
timestamp("2018-08-10T08:30:00"),
timestamp("2018-08-14T08:30:00"),
timestamp("2018-08-14T08:30:00"),
timestamp("2018-08-15T08:30:00"),
timestamp("2018-08-15T08:30:00"),
timestamp("2018-09-04T12:15:00"),
timestamp("2018-09-10T08:30:00"),
timestamp("2018-09-11T08:30:00"),
timestamp("2018-09-11T08:30:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-13T11:00:00"),
timestamp("2018-09-14T10:00:00"),
timestamp("2018-09-19T08:30:00"),
timestamp("2018-09-19T08:30:00"),
timestamp("2018-09-27T14:00:00"),
timestamp("2018-10-02T12:00:00"),
timestamp("2018-10-03T12:00:00"),
timestamp("2018-10-10T08:30:00"),
timestamp("2018-10-11T05:00:00"),
timestamp("2018-10-11T09:00:00"),
timestamp("2018-10-16T08:30:00"),
timestamp("2018-10-16T08:30:00"),
timestamp("2018-10-17T08:30:00"),
timestamp("2018-10-17T08:30:00"),
timestamp("2018-10-19T16:10:00"),
timestamp("2018-10-23T15:20:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:00:00"),
timestamp("2018-11-01T12:30:00"),
timestamp("2018-11-09T09:30:00"),
timestamp("2018-11-09T09:30:00"),
timestamp("2018-11-13T09:30:00"),
timestamp("2018-11-13T09:30:00"),
timestamp("2018-11-14T09:30:00"),
timestamp("2018-11-14T09:30:00"),
timestamp("2018-11-14T14:00:00"),
timestamp("2018-11-15T17:00:00"),
timestamp("2018-11-20T10:00:00"),
timestamp("2018-11-20T10:00:00"),
timestamp("2018-11-21T15:15:00"),
timestamp("2018-11-21T16:30:00"),
timestamp("2018-11-22T15:00:00"),
timestamp("2018-11-26T18:30:00"),
timestamp("2018-11-28T16:45:00"),
timestamp("2018-12-04T09:15:00"),
timestamp("2018-12-10T09:30:00"),
timestamp("2018-12-11T09:30:00"),
timestamp("2018-12-11T09:30:00"),
timestamp("2018-12-12T18:00:00"),
timestamp("2018-12-19T09:30:00"),
timestamp("2018-12-19T09:30:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2018-12-20T12:00:00"),
timestamp("2019-01-09T15:30:00"),
timestamp("2019-01-11T09:30:00"),
timestamp("2019-01-15T00:00:00"),
timestamp("2019-01-16T09:15:00"),
timestamp("2019-01-16T09:30:00"),
timestamp("2019-01-16T09:30:00"),
timestamp("2019-01-16T19:00:00"),
timestamp("2019-01-22T09:30:00"),
timestamp("2019-01-28T14:30:00"),
timestamp("2019-01-29T19:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:00:00"),
timestamp("2019-02-07T12:30:00"),
timestamp("2019-02-11T09:30:00"),
timestamp("2019-02-12T13:00:00"),
timestamp("2019-02-13T09:30:00"),
timestamp("2019-02-19T09:30:00"),
timestamp("2019-02-19T09:30:00"),
timestamp("2019-02-25T10:00:00"),
timestamp("2019-02-26T10:00:00"),
timestamp("2019-02-26T12:30:00"),
timestamp("2019-03-05T15:35:00"),
timestamp("2019-03-12T19:00:00"),
timestamp("2019-03-13T19:00:00"),
timestamp("2019-03-14T17:00:00"),
timestamp("2019-03-19T09:30:00"),
timestamp("2019-03-19T09:30:00"),
timestamp("2019-03-20T09:30:00"),
timestamp("2019-03-20T20:15:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-21T12:00:00"),
timestamp("2019-03-25T15:30:00"),
timestamp("2019-03-27T19:30:00"),
timestamp("2019-03-29T09:30:00"),
timestamp("2019-03-29T14:30:00"),
timestamp("2019-04-01T20:30:00"),
timestamp("2019-04-10T16:00:00"),
timestamp("2019-04-16T08:30:00"),
timestamp("2019-04-16T08:30:00"),
timestamp("2019-04-17T08:30:00"),
timestamp("2019-04-17T13:00:00"),
timestamp("2019-04-29T08:10:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:00:00"),
timestamp("2019-05-02T11:30:00"),
timestamp("2019-05-10T08:30:00"),
timestamp("2019-05-14T08:30:00"),
timestamp("2019-05-14T08:30:00"),
timestamp("2019-05-21T15:00:00"),
timestamp("2019-05-22T08:30:00"),
timestamp("2019-05-24T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-11T08:30:00"),
timestamp("2019-06-11T08:30:00"),
timestamp("2019-06-14T12:55:00"),
timestamp("2019-06-18T14:00:00"),
timestamp("2019-06-19T08:30:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T11:00:00"),
timestamp("2019-06-20T20:00:00"),
timestamp("2019-06-26T09:15:00"),
timestamp("2019-06-26T09:15:00"),
timestamp("2019-06-28T08:30:00"),
timestamp("2019-07-02T14:05:00"),
timestamp("2019-07-11T10:00:00"),
timestamp("2019-07-16T08:30:00"),
timestamp("2019-07-16T12:00:00"),
timestamp("2019-07-17T08:30:00"),
timestamp("2019-07-23T10:45:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:00:00"),
timestamp("2019-08-01T11:30:00"),
timestamp("2019-08-09T08:30:00"),
timestamp("2019-08-13T08:30:00"),
timestamp("2019-08-13T08:30:00"),
timestamp("2019-08-14T08:30:00"),
timestamp("2019-08-23T19:00:00"),
timestamp("2019-09-03T21:00:00"),
timestamp("2019-09-04T13:15:00"),
timestamp("2019-09-04T13:15:00"),
timestamp("2019-09-04T18:00:00"),
timestamp("2019-09-09T18:00:00"),
timestamp("2019-09-10T08:30:00"),
timestamp("2019-09-10T08:30:00"),
timestamp("2019-09-18T08:30:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-19T11:00:00"),
timestamp("2019-09-30T08:30:00"),
timestamp("2019-10-02T10:35:00"),
timestamp("2019-10-08T04:10:00"),
timestamp("2019-10-10T09:20:00"),
timestamp("2019-10-15T08:30:00"),
timestamp("2019-10-15T08:30:00"),
timestamp("2019-10-16T08:30:00"),
timestamp("2019-10-16T13:00:00"),
timestamp("2019-10-16T22:00:00"),
timestamp("2019-10-17T00:00:00"),
timestamp("2019-10-18T00:00:00"),
timestamp("2019-10-22T18:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:00:00"),
timestamp("2019-11-07T12:30:00"),
timestamp("2019-11-11T09:30:00"),
timestamp("2019-11-12T09:30:00"),
timestamp("2019-11-12T09:30:00"),
timestamp("2019-11-13T09:30:00"),
timestamp("2019-11-22T09:30:00"),
timestamp("2019-12-10T15:15:00"),
timestamp("2019-12-12T00:00:00"),
timestamp("2019-12-16T09:30:00"),
timestamp("2019-12-17T09:30:00"),
timestamp("2019-12-17T09:30:00"),
timestamp("2019-12-17T19:15:00"),
timestamp("2019-12-18T09:30:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-19T12:00:00"),
timestamp("2019-12-20T09:30:00"),
timestamp("2019-12-20T15:00:00")
)
// @function GBP high impact news date and time from 2020 to 2023
export HighImpactNews2020To2023() =>
array.from(
timestamp("2020-01-09T09:30:00"),
timestamp("2020-01-15T09:30:00"),
timestamp("2020-01-21T09:30:00"),
timestamp("2020-01-21T09:30:00"),
timestamp("2020-01-24T09:30:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:00:00"),
timestamp("2020-01-30T12:30:00"),
timestamp("2020-01-31T23:59:00"),
timestamp("2020-02-11T09:30:00"),
timestamp("2020-02-18T09:30:00"),
timestamp("2020-02-18T09:30:00"),
timestamp("2020-02-19T09:30:00"),
timestamp("2020-02-21T09:30:00"),
timestamp("2020-03-03T09:30:00"),
timestamp("2020-03-04T13:15:00"),
timestamp("2020-03-05T17:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T07:00:00"),
timestamp("2020-03-11T09:00:00"),
timestamp("2020-03-13T12:00:00"),
timestamp("2020-03-17T09:30:00"),
timestamp("2020-03-17T09:30:00"),
timestamp("2020-03-17T14:30:00"),
timestamp("2020-03-17T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-19T14:30:00"),
timestamp("2020-03-24T09:30:00"),
timestamp("2020-03-25T07:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-26T12:00:00"),
timestamp("2020-03-31T06:00:00"),
timestamp("2020-04-21T06:00:00"),
timestamp("2020-04-21T06:00:00"),
timestamp("2020-04-22T06:00:00"),
timestamp("2020-04-23T08:30:00"),
timestamp("2020-05-05T06:00:00"),
timestamp("2020-05-05T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T06:00:00"),
timestamp("2020-05-07T09:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-13T06:00:00"),
timestamp("2020-05-19T06:00:00"),
timestamp("2020-05-19T06:00:00"),
timestamp("2020-05-20T06:00:00"),
timestamp("2020-05-20T13:30:00"),
timestamp("2020-05-21T08:30:00"),
timestamp("2020-06-12T06:00:00"),
timestamp("2020-06-12T06:00:00"),
timestamp("2020-06-16T06:00:00"),
timestamp("2020-06-16T06:00:00"),
timestamp("2020-06-16T11:00:00"),
timestamp("2020-06-16T11:00:00"),
timestamp("2020-06-17T06:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-18T11:00:00"),
timestamp("2020-06-23T08:30:00"),
timestamp("2020-06-23T08:45:00"),
timestamp("2020-06-29T09:30:00"),
timestamp("2020-06-30T06:00:00"),
timestamp("2020-07-13T15:30:00"),
timestamp("2020-07-14T06:00:00"),
timestamp("2020-07-15T06:00:00"),
timestamp("2020-07-16T06:00:00"),
timestamp("2020-07-16T06:00:00"),
timestamp("2020-07-16T11:15:00"),
timestamp("2020-07-17T10:00:00"),
timestamp("2020-07-24T08:30:00"),
timestamp("2020-08-04T06:00:00"),
timestamp("2020-08-04T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T06:00:00"),
timestamp("2020-08-06T09:00:00"),
timestamp("2020-08-06T11:00:00"),
timestamp("2020-08-11T06:00:00"),
timestamp("2020-08-11T06:00:00"),
timestamp("2020-08-12T06:00:00"),
timestamp("2020-08-19T06:00:00"),
timestamp("2020-08-21T08:30:00"),
timestamp("2020-08-28T13:05:00"),
timestamp("2020-09-02T13:30:00"),
timestamp("2020-09-03T14:00:00"),
timestamp("2020-09-14T15:00:00"),
timestamp("2020-09-15T06:00:00"),
timestamp("2020-09-15T06:00:00"),
timestamp("2020-09-15T11:00:00"),
timestamp("2020-09-15T11:00:00"),
timestamp("2020-09-16T06:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-17T11:00:00"),
timestamp("2020-09-22T07:30:00"),
timestamp("2020-09-23T08:30:00"),
timestamp("2020-09-24T14:00:00"),
timestamp("2020-09-29T14:00:00"),
timestamp("2020-09-30T06:00:00"),
timestamp("2020-10-08T07:25:00"),
timestamp("2020-10-12T16:00:00"),
timestamp("2020-10-13T06:00:00"),
timestamp("2020-10-13T06:00:00"),
timestamp("2020-10-18T13:05:00"),
timestamp("2020-10-21T06:00:00"),
timestamp("2020-10-22T09:25:00"),
timestamp("2020-10-23T08:30:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T07:00:00"),
timestamp("2020-11-05T09:15:00"),
timestamp("2020-11-09T10:35:00"),
timestamp("2020-11-10T07:00:00"),
timestamp("2020-11-10T07:00:00"),
timestamp("2020-11-12T07:00:00"),
timestamp("2020-11-12T08:00:00"),
timestamp("2020-11-12T16:45:00"),
timestamp("2020-11-13T16:00:00"),
timestamp("2020-11-17T11:00:00"),
timestamp("2020-11-17T14:00:00"),
timestamp("2020-11-18T07:00:00"),
timestamp("2020-11-18T16:30:00"),
timestamp("2020-11-23T09:30:00"),
timestamp("2020-11-23T15:30:00"),
timestamp("2020-12-11T09:30:00"),
timestamp("2020-12-15T07:00:00"),
timestamp("2020-12-15T07:00:00"),
timestamp("2020-12-16T07:00:00"),
timestamp("2020-12-16T09:30:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-17T12:00:00"),
timestamp("2020-12-21T17:00:00"),
timestamp("2020-12-22T07:00:00"),
timestamp("2021-01-06T14:30:00"),
timestamp("2021-01-11T15:00:00"),
timestamp("2021-01-20T07:00:00"),
timestamp("2021-01-20T17:00:00"),
timestamp("2021-01-22T09:30:00"),
timestamp("2021-01-25T17:00:00"),
timestamp("2021-01-26T07:00:00"),
timestamp("2021-01-26T07:00:00"),
timestamp("2021-01-26T17:45:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T12:00:00"),
timestamp("2021-02-04T13:00:00"),
timestamp("2021-02-05T13:30:00"),
timestamp("2021-02-10T17:00:00"),
timestamp("2021-02-12T07:00:00"),
timestamp("2021-02-17T07:00:00"),
timestamp("2021-02-19T09:30:00"),
timestamp("2021-02-22T12:00:00"),
timestamp("2021-02-23T07:00:00"),
timestamp("2021-02-23T07:00:00"),
timestamp("2021-02-24T14:30:00"),
timestamp("2021-03-08T10:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-18T12:00:00"),
timestamp("2021-03-23T07:00:00"),
timestamp("2021-03-23T07:00:00"),
timestamp("2021-03-23T11:50:00"),
timestamp("2021-03-24T07:00:00"),
timestamp("2021-03-24T09:30:00"),
timestamp("2021-03-25T09:30:00"),
timestamp("2021-03-31T06:00:00"),
timestamp("2021-04-20T06:00:00"),
timestamp("2021-04-20T06:00:00"),
timestamp("2021-04-21T06:00:00"),
timestamp("2021-04-21T10:30:00"),
timestamp("2021-04-23T08:30:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T11:00:00"),
timestamp("2021-05-06T12:00:00"),
timestamp("2021-05-11T14:30:00"),
timestamp("2021-05-12T06:00:00"),
timestamp("2021-05-12T14:00:00"),
timestamp("2021-05-13T16:00:00"),
timestamp("2021-05-18T06:00:00"),
timestamp("2021-05-18T06:00:00"),
timestamp("2021-05-18T14:00:00"),
timestamp("2021-05-19T06:00:00"),
timestamp("2021-05-21T08:30:00"),
timestamp("2021-05-24T14:30:00"),
timestamp("2021-05-24T15:30:00"),
timestamp("2021-06-01T15:00:00"),
timestamp("2021-06-03T16:00:00"),
timestamp("2021-06-11T08:30:00"),
timestamp("2021-06-14T13:00:00"),
timestamp("2021-06-15T06:00:00"),
timestamp("2021-06-15T06:00:00"),
timestamp("2021-06-15T12:15:00"),
timestamp("2021-06-16T06:00:00"),
timestamp("2021-06-23T08:30:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-24T11:00:00"),
timestamp("2021-06-30T06:00:00"),
timestamp("2021-07-01T08:00:00"),
timestamp("2021-07-09T10:00:00"),
timestamp("2021-07-14T06:00:00"),
timestamp("2021-07-15T06:00:00"),
timestamp("2021-07-15T06:00:00"),
timestamp("2021-07-23T08:30:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T11:00:00"),
timestamp("2021-08-05T12:00:00"),
timestamp("2021-08-12T06:00:00"),
timestamp("2021-08-17T06:00:00"),
timestamp("2021-08-17T06:00:00"),
timestamp("2021-08-18T06:00:00"),
timestamp("2021-08-23T08:30:00"),
timestamp("2021-09-08T15:00:00"),
timestamp("2021-09-14T06:00:00"),
timestamp("2021-09-14T06:00:00"),
timestamp("2021-09-15T06:00:00"),
timestamp("2021-09-23T08:30:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-23T11:00:00"),
timestamp("2021-09-27T15:00:00"),
timestamp("2021-09-30T06:00:00"),
timestamp("2021-10-12T06:00:00"),
timestamp("2021-10-12T06:00:00"),
timestamp("2021-10-20T06:00:00"),
timestamp("2021-10-22T08:30:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:00:00"),
timestamp("2021-11-04T12:30:00"),
timestamp("2021-11-08T17:00:00"),
timestamp("2021-11-09T16:00:00"),
timestamp("2021-11-11T07:00:00"),
timestamp("2021-11-15T13:30:00"),
timestamp("2021-11-16T07:00:00"),
timestamp("2021-11-16T07:00:00"),
timestamp("2021-11-17T07:00:00"),
timestamp("2021-11-23T09:30:00"),
timestamp("2021-11-25T17:00:00"),
timestamp("2021-11-30T15:00:00"),
timestamp("2021-12-01T14:00:00"),
timestamp("2021-12-14T07:00:00"),
timestamp("2021-12-14T07:00:00"),
timestamp("2021-12-15T07:00:00"),
timestamp("2021-12-16T09:30:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-16T12:00:00"),
timestamp("2021-12-22T07:00:00"),
timestamp("2022-01-18T07:00:00"),
timestamp("2022-01-18T07:00:00"),
timestamp("2022-01-19T07:00:00"),
timestamp("2022-01-19T14:15:00"),
timestamp("2022-01-24T09:30:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:00:00"),
timestamp("2022-02-03T12:30:00"),
timestamp("2022-02-10T17:00:00"),
timestamp("2022-02-11T07:00:00"),
timestamp("2022-02-15T07:00:00"),
timestamp("2022-02-15T07:00:00"),
timestamp("2022-02-16T07:00:00"),
timestamp("2022-02-21T09:30:00"),
timestamp("2022-02-23T09:30:00"),
timestamp("2022-02-23T09:30:00"),
timestamp("2022-03-15T07:00:00"),
timestamp("2022-03-15T07:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-17T12:00:00"),
timestamp("2022-03-23T07:00:00"),
timestamp("2022-03-23T12:00:00"),
timestamp("2022-03-24T09:30:00"),
timestamp("2022-03-28T11:00:00"),
timestamp("2022-03-31T06:00:00"),
timestamp("2022-04-04T09:05:00"),
timestamp("2022-04-12T06:00:00"),
timestamp("2022-04-12T06:00:00"),
timestamp("2022-04-13T06:00:00"),
timestamp("2022-04-21T16:30:00"),
timestamp("2022-04-22T08:30:00"),
timestamp("2022-04-22T14:30:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:00:00"),
timestamp("2022-05-05T11:30:00"),
timestamp("2022-05-12T06:00:00"),
timestamp("2022-05-16T14:15:00"),
timestamp("2022-05-17T06:00:00"),
timestamp("2022-05-17T06:00:00"),
timestamp("2022-05-18T06:00:00"),
timestamp("2022-05-23T16:15:00"),
timestamp("2022-05-24T08:30:00"),
timestamp("2022-06-06T17:00:00"),
timestamp("2022-06-14T06:00:00"),
timestamp("2022-06-14T06:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-16T11:00:00"),
timestamp("2022-06-22T06:00:00"),
timestamp("2022-06-23T08:30:00"),
timestamp("2022-06-29T13:00:00"),
timestamp("2022-06-30T06:00:00"),
timestamp("2022-07-11T14:15:00"),
timestamp("2022-07-12T17:00:00"),
timestamp("2022-07-19T06:00:00"),
timestamp("2022-07-19T06:00:00"),
timestamp("2022-07-20T06:00:00"),
timestamp("2022-07-22T08:30:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:00:00"),
timestamp("2022-08-04T11:30:00"),
timestamp("2022-08-12T06:00:00"),
timestamp("2022-08-16T06:00:00"),
timestamp("2022-08-16T06:00:00"),
timestamp("2022-08-17T06:00:00"),
timestamp("2022-08-23T08:30:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-13T06:00:00"),
timestamp("2022-09-13T06:00:00"),
timestamp("2022-09-14T06:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-22T11:00:00"),
timestamp("2022-09-23T08:30:00"),
timestamp("2022-09-30T06:00:00"),
timestamp("2022-10-11T06:00:00"),
timestamp("2022-10-11T06:00:00"),
timestamp("2022-10-11T18:35:00"),
timestamp("2022-10-19T06:00:00"),
timestamp("2022-10-24T08:30:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:00:00"),
timestamp("2022-11-03T12:30:00"),
timestamp("2022-11-11T07:00:00"),
timestamp("2022-11-15T07:00:00"),
timestamp("2022-11-15T07:00:00"),
timestamp("2022-11-16T07:00:00"),
timestamp("2022-11-16T14:15:00"),
timestamp("2022-11-23T09:30:00"),
timestamp("2022-11-29T15:00:00"),
timestamp("2022-12-13T07:00:00"),
timestamp("2022-12-13T07:00:00"),
timestamp("2022-12-13T11:00:00"),
timestamp("2022-12-14T07:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-15T12:00:00"),
timestamp("2022-12-16T09:30:00"),
timestamp("2022-12-22T07:00:00"),
timestamp("2023-01-10T10:10:00"),
timestamp("2023-01-16T15:00:00"),
timestamp("2023-01-17T07:00:00"),
timestamp("2023-01-17T07:00:00"),
timestamp("2023-01-18T07:00:00"),
timestamp("2023-01-24T09:30:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:00:00"),
timestamp("2023-02-02T12:30:00"),
timestamp("2023-02-09T09:45:00"),
timestamp("2023-02-09T09:45:00"),
timestamp("2023-02-10T07:00:00"),
timestamp("2023-02-14T07:00:00"),
timestamp("2023-02-14T07:00:00"),
timestamp("2023-02-15T07:00:00"),
timestamp("2023-02-21T09:30:00"),
timestamp("2023-03-01T10:10:00"),
timestamp("2023-03-14T07:00:00"),
timestamp("2023-03-14T07:00:00"),
timestamp("2023-03-22T07:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-23T12:00:00"),
timestamp("2023-03-24T09:30:00"),
timestamp("2023-03-27T17:00:00"),
timestamp("2023-03-28T08:45:00"),
timestamp("2023-03-31T06:00:00"),
timestamp("2023-04-12T13:00:00"),
timestamp("2023-04-12T19:15:00"),
timestamp("2023-04-18T06:00:00"),
timestamp("2023-04-18T06:00:00"),
timestamp("2023-04-19T06:00:00"),
timestamp("2023-04-21T08:30:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:00:00"),
timestamp("2023-05-11T11:30:00"),
timestamp("2023-05-12T06:00:00"),
timestamp("2023-05-16T06:00:00"),
timestamp("2023-05-16T06:00:00"),
timestamp("2023-05-17T09:50:00"),
timestamp("2023-05-18T09:15:00"),
timestamp("2023-05-23T08:30:00"),
timestamp("2023-05-23T09:15:00"),
timestamp("2023-05-24T06:00:00"),
timestamp("2023-05-24T09:30:00"),
timestamp("2023-05-24T13:00:00"),
timestamp("2023-06-13T06:00:00"),
timestamp("2023-06-13T06:00:00"),
timestamp("2023-06-13T14:00:00"),
timestamp("2023-06-21T06:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-22T11:00:00"),
timestamp("2023-06-23T08:30:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-30T06:00:00"),
timestamp("2023-06-30T06:00:00"),
timestamp("2023-07-11T06:00:00"),
timestamp("2023-07-11T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-19T06:00:00"),
timestamp("2023-07-21T06:00:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-07-24T08:30:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:00:00"),
timestamp("2023-08-03T11:30:00"),
timestamp("2023-08-11T06:00:00"),
timestamp("2023-08-11T06:00:00"),
timestamp("2023-08-15T06:00:00"),
timestamp("2023-08-15T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-16T06:00:00"),
timestamp("2023-08-18T06:00:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-08-23T08:30:00"),
timestamp("2023-09-06T08:30:00"),
timestamp("2023-09-12T06:00:00"),
timestamp("2023-09-12T06:00:00"),
timestamp("2023-09-15T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-20T06:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-21T11:00:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-22T08:30:00"),
timestamp("2023-09-29T06:00:00"),
timestamp("2023-09-29T06:00:00"),
timestamp("2023-10-17T06:00:00"),
timestamp("2023-10-17T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-18T06:00:00"),
timestamp("2023-10-20T06:00:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-10-24T08:30:00"),
timestamp("2023-11-02T11:30:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-02T12:00:00"),
timestamp("2023-11-09T07:00:00"),
timestamp("2023-11-10T07:00:00"),
timestamp("2023-11-14T07:00:00"),
timestamp("2023-11-14T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T07:00:00"),
timestamp("2023-11-15T09:30:00"),
timestamp("2023-11-17T07:00:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-11-21T09:30:00"),
timestamp("2023-12-12T07:00:00"),
timestamp("2023-12-12T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-13T07:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-14T12:00:00"),
timestamp("2023-12-15T07:00:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-20T09:30:00"),
timestamp("2023-12-22T07:00:00"),
timestamp("2023-12-22T07:00:00")
)
|
Harmonic Patterns | https://www.tradingview.com/script/95HpZaAR-Harmonic-Patterns/ | Sharad_Gaikwad | https://www.tradingview.com/u/Sharad_Gaikwad/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sharad_Gaikwad
//#region General functions
var tab = table.new(position=position.top_right, columns=7, rows=30,frame_color = color.yellow, frame_width = 1)
msg(int row, int col, string msg_str, clr=color.blue) =>
if(barstate.islast)
table.cell(table_id=tab, column=col, row=row, text=msg_str, text_color=clr)
t(val) => str.tostring(val)
method f(float f) => str.tostring(f)
method f(int i) => str.tostring(i)
method f(bool b) => str.tostring(b)
method f(string s) => str.tostring(s)
method fd(int t, string format = "dd-MM-yy HH:mm") => str.format_time(t, format, syminfo.timezone)
dt(val, format = "dd-MM-yy HH:mm") => str.format_time(val, format, syminfo.timezone)
var debug = array.new<string>(1, "")
method clear_log(string [] s) =>
s.clear()
s.unshift("")
method log(string [] s, string msg, bool on_last_bar = false) =>
if((not on_last_bar) or (on_last_bar and barstate.islast))
if(str.length(s.get(0)) + str.length(msg) < 4095)
s.set(0, s.get(0) + msg + "\n")
method display(string [] s, where = 'B') =>
if(not na(s.get(0)))
if(where == 'B')
label.new(bar_index, low, yloc = yloc.belowbar, style = label.style_diamond, tooltip = s.get(0), size = size.tiny)
else
label.new(bar_index, high, yloc = yloc.abovebar, style = label.style_diamond, tooltip = s.get(0), size = size.tiny)
debug.clear_log()
//#endregion General functions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type class_p_visuals
bool plot_fl
string line_style
color line_color
color bg_color
var fixed_tt = "Fiexd value leg (mostly XD leg) patterns are rare, This % value is used to derive the range for such values. Set the % to 0.001% which is very close to fixed value"
//@version=5
indicator('Harmonic Patterns', overlay=true, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100)
//#region Input Parameters
start_time = input.time(timestamp("01 Jan 1900"))
g1 = 'Zigzag Setup'
lb = input.int(title = 'Left bars', defval = 10, group = g1, inline = 'g11')
rb = input.int(title = 'Right bars', defval = 10, group = g1, inline = 'g11')
color_ctf = input.color(title = 'Zigzag color', defval =color.new(color.blue, 95), group = g1, inline = 'g21')
width_ctf = input.int(title = 'Width', defval = 1, group = g1, inline = 'g21')
plot_ctf_zigzag = input.bool(title = 'Plot Zigzag', defval = true, group = g1, inline = 'g22')
plot_ctf_hhll_labels = input.bool(title = 'Plot HHLL labels', defval = false, group = g1, inline = 'g22')
g2 = 'Harmonic Pattern Setup'
ignore_xd_leg = input.bool(title = 'Ignore XD leg calculations', defval = false, group = g2)
apply_xd = ignore_xd_leg ? false : true
xd_offset_percent = input.float(title = 'Fixed value leg offset %', defval = 10, minval = 0.001, tooltip = fixed_tt)/100
show_pattern_label = input.bool(title = '', defval = true, inline = '90')
pattern_name_color = input.color(title = 'Pattern name label color', defval = color.purple, inline = '90')
var bull_bat = class_p_visuals.new()
bull_bat.plot_fl := input.bool(title = '', defval = true, inline = '100')
bull_bat.line_style := input.string(title = 'Bullish Bat => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '100')
bull_bat.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '100')
bull_bat.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '100')
var bear_bat = class_p_visuals.new()
bear_bat.plot_fl := input.bool(title = '', defval = true, inline = '110')
bear_bat.line_style := input.string(title = 'Bearish Bat => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '110')
bear_bat.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '110')
bear_bat.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '110')
var bull_abat = class_p_visuals.new()
bull_abat.plot_fl := input.bool(title = '', defval = true, inline = '120')
bull_abat.line_style := input.string(title = 'ALT Bullish Bat => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '120')
bull_abat.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '120')
bull_abat.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '120')
var bear_abat = class_p_visuals.new()
bear_abat.plot_fl := input.bool(title = '', defval = true, inline = '130')
bear_abat.line_style := input.string(title = 'ALT Bearish Bat => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '130')
bear_abat.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '130')
bear_abat.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '130')
var bull_bfly = class_p_visuals.new()
bull_bfly.plot_fl := input.bool(title = '', defval = true, inline = '140')
bull_bfly.line_style := input.string(title = 'Bullish Butterfly => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '140')
bull_bfly.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '140')
bull_bfly.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '140')
var bear_bfly = class_p_visuals.new()
bear_bfly.plot_fl := input.bool(title = '', defval = true, inline = '150')
bear_bfly.line_style := input.string(title = 'Bearish Butterfly => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '150')
bear_bfly.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '150')
bear_bfly.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '150')
var bull_crab = class_p_visuals.new()
bull_crab.plot_fl := input.bool(title = '', defval = true, inline = '160')
bull_crab.line_style := input.string(title = 'Bullish CRAB => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '160')
bull_crab.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '160')
bull_crab.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '160')
var bear_crab = class_p_visuals.new()
bear_crab.plot_fl := input.bool(title = '', defval = true, inline = '170')
bear_crab.line_style := input.string(title = 'Bearish CRAB => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '170')
bear_crab.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '170')
bear_crab.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '170')
var bull_dcrab = class_p_visuals.new()
bull_dcrab.plot_fl := input.bool(title = '', defval = true, inline = '180')
bull_dcrab.line_style := input.string(title = 'Bullish Deep CRAB => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '180')
bull_dcrab.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '180')
bull_dcrab.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '180')
var bear_dcrab = class_p_visuals.new()
bear_dcrab.plot_fl := input.bool(title = '', defval = true, inline = '190')
bear_dcrab.line_style := input.string(title = 'Bearish Deep CRAB => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '190')
bear_dcrab.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '190')
bear_dcrab.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '190')
var bull_gartley = class_p_visuals.new()
bull_gartley.plot_fl := input.bool(title = '', defval = true, inline = '200')
bull_gartley.line_style := input.string(title = 'Bullish Gartley => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '200')
bull_gartley.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '200')
bull_gartley.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '200')
var bear_gartley = class_p_visuals.new()
bear_gartley.plot_fl := input.bool(title = '', defval = true, inline = '210')
bear_gartley.line_style := input.string(title = 'Berish Gartley => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '210')
bear_gartley.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '210')
bear_gartley.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '210')
var bull_shark = class_p_visuals.new()
bull_shark.plot_fl := input.bool(title = '', defval = true, inline = '220')
bull_shark.line_style := input.string(title = 'Bullish Shark => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '220')
bull_shark.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '220')
bull_shark.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '220')
var bear_shark = class_p_visuals.new()
bear_shark.plot_fl := input.bool(title = '', defval = true, inline = '230')
bear_shark.line_style := input.string(title = 'Berish Shark => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '230')
bear_shark.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '230')
bear_shark.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '230')
var bull_cypher = class_p_visuals.new()
bull_cypher.plot_fl := input.bool(title = '', defval = true, inline = '240')
bull_cypher.line_style := input.string(title = 'Bullish Cypher => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '240')
bull_cypher.line_color := input.color(title = 'Color', defval = color.new(color.green, 0), inline = '240')
bull_cypher.bg_color := input.color(title = 'BG', defval = color.new(color.green, 85), inline = '240')
var bear_cypher = class_p_visuals.new()
bear_cypher.plot_fl := input.bool(title = '', defval = true, inline = '250')
bear_cypher.line_style := input.string(title = 'Berish Cypher => Style', defval = line.style_solid, options = [line.style_solid, line.style_dotted, line.style_dashed], inline = '250')
bear_cypher.line_color := input.color(title = 'Color', defval = color.new(color.red, 0), inline = '250')
bear_cypher.bg_color := input.color(title = 'BG', defval = color.new(color.red, 85), inline = '250')
//#endregion Input Parameters
var ctf = t(timeframe.period)
var v_map = map.new<string, class_p_visuals>()
if(bar_index == 0)
v_map.put("BULL-BAT", bull_bat)
v_map.put("BEAR-BAT", bear_bat)
v_map.put("BULL-ABAT", bull_abat)
v_map.put("BEAR-ABAT", bear_abat)
v_map.put("BULL-BFLY", bull_bfly)
v_map.put("BEAR-BFLY", bear_bfly)
v_map.put("BULL-CRAB", bull_crab)
v_map.put("BEAR-CRAB", bear_crab)
v_map.put("BULL-DCRAB", bull_dcrab)
v_map.put("BEAR-DCRAB", bear_dcrab)
v_map.put("BULL-GARTLEY", bull_gartley)
v_map.put("BEAR-GARTLEY", bear_gartley)
v_map.put("BULL-SHARK", bull_shark)
v_map.put("BEAR-SHARK", bear_shark)
v_map.put("BULL-CYPHER", bull_cypher)
v_map.put("BEAR-CYPHER", bear_cypher)
type class_visuals
bool plot_line = false
bool plot_label = false
color clr
int width
var visuals = map.new<string, class_visuals>()
if(bar_index == 0)
visuals.put('CTF', class_visuals.new(plot_ctf_zigzag, plot_ctf_hhll_labels, color_ctf, width_ctf))
//objects
type class_hhll
string group //H or l
string sub_group // HH, LL, LH, HL
int bar_id
int bar_time
float pivot_pp
line ln
label lbl
string tf
bool is_new = false
var array<class_hhll> hhll_ctf = array.new<class_hhll>()
type class_ohlc
bool pivot
float pp
int bar_id
int bar_time
type class_fib_levels
float f_382
float f_382u
float f_382l
float f_50
float f_618
float f_618u
float f_618l
float f_886
float f_886u
float f_886l
float f_1618
float f_1618u
float f_1618l
float f_2618
float f_3618
float f_200
float f_113
float f_113u
float f_113l
float f_786
float f_786u
float f_786l
float f_224
float f_127
float f_141
float f_fake1
float f_fake2
type class_legs
string l1_key
float l1_val
string l2_key
float l2_val
type class_xabcd
string name
class_legs xb
class_legs ac
class_legs bd
class_legs xd
bool bull_fl
bool bear_fl
int bull_cnt = 0
int bear_cnt = 0
int last_bull
int last_bear
var array<class_xabcd> p_xabcd = array.new<class_xabcd>()
if(bar_index == 0)
p_xabcd.push(class_xabcd.new(name = "BAT"
, xb = class_legs.new(l1_key = 'F_382', l2_key = 'F_50')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_1618', l2_key = 'F_2618')
, xd = class_legs.new(l1_key = 'F_886L', l2_key = 'F_886U')
))
p_xabcd.push(class_xabcd.new(name = "ABAT"
, xb = class_legs.new(l1_key = 'F_382L', l2_key = 'F_382U')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_200', l2_key = 'F_3618')
, xd = class_legs.new(l1_key = 'F_113L', l2_key = 'F_113U')
))
p_xabcd.push(class_xabcd.new(name = "BFLY"
, xb = class_legs.new(l1_key = 'F_786L', l2_key = 'F_786U')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_1618', l2_key = 'F_224')
, xd = class_legs.new(l1_key = 'F_127', l2_key = 'F_141')
))
p_xabcd.push(class_xabcd.new(name = "CRAB"
, xb = class_legs.new(l1_key = 'F_382', l2_key = 'F_618')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_2618', l2_key = 'F_3618')
, xd = class_legs.new(l1_key = 'F_1618L', l2_key = 'F_1618U')
))
p_xabcd.push(class_xabcd.new(name = "DCRAB"
, xb = class_legs.new(l1_key = 'F_886L', l2_key = 'F_886U')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_200', l2_key = 'F_3618')
, xd = class_legs.new(l1_key = 'F_1618L', l2_key = 'F_1618U')
))
p_xabcd.push(class_xabcd.new(name = "GARTLEY"
, xb = class_legs.new(l1_key = 'F_618L', l2_key = 'F_618U')
, ac = class_legs.new(l1_key = 'F_382', l2_key = 'F_886')
, bd = class_legs.new(l1_key = 'F_113', l2_key = 'F_1618')
, xd = class_legs.new(l1_key = 'F_786L', l2_key = 'F_786U')
))
p_xabcd.push(class_xabcd.new(name = "SHARK"
, xb = class_legs.new(l1_key = 'F_FAKE1', l2_key = 'F_FAKE2')
, ac = class_legs.new(l1_key = 'F_113', l2_key = 'F_1618')
, bd = class_legs.new(l1_key = 'F_1618', l2_key = 'F_224')
, xd = class_legs.new(l1_key = 'F_886', l2_key = 'F_113')
))
p_xabcd.push(class_xabcd.new(name = "CYPHER"
, xb = class_legs.new(l1_key = 'F_382', l2_key = 'F_618')
, ac = class_legs.new(l1_key = 'F_113', l2_key = 'F_141')
, bd = class_legs.new(l1_key = 'F_127', l2_key = 'F_200')
, xd = class_legs.new(l1_key = 'F_786L', l2_key = 'F_786U')
))
//
get_ph_pl(i) =>
ph = class_ohlc.new(pivot = false)
pl = class_ohlc.new(pivot = false)
_ph = ta.pivothigh(high[i], lb, rb)
_pl = ta.pivotlow(low[i], lb, rb)
if((_ph > 0 or _pl > 0) and time >= start_time)
rec = class_ohlc.new(
pivot = true,
pp = _ph > 0 ? high[rb+i] : low[rb+i],
bar_id = bar_index[rb+i],
bar_time = time[rb+i])
ph := not na(_ph) ? rec : ph
pl := not na(_pl) ? rec : pl
[ph, pl]
//
method get(array<class_hhll> hhll, id) => hhll.size() > id ? hhll.get(id) : class_hhll.new()
//
method add_ph(array<class_hhll> hhll, class_ohlc ph, class_visuals v, tf) =>
if(ph.pivot)
pp = ph.pp
bar_id = ph.bar_id
bar_time = ph.bar_time
class_hhll prev = hhll.get(0)
rec_deleted = false
if(prev.group == 'H')
if(pp > prev.pivot_pp)
rec_deleted := true
prev.ln.delete()
prev.lbl.delete()
hhll.shift()
prev := hhll.get(0)
if(prev.group != 'H')
move = math.round((pp - nz(prev.pivot_pp, 0)) / pp * 100, 2)
change = math.round_to_mintick(pp - nz(prev.pivot_pp))
new_rec = class_hhll.new(group = 'H', bar_id = bar_id, bar_time = bar_time, pivot_pp = pp, tf = t(tf), is_new = true)
if(na(prev.group))
new_rec.sub_group := 'HH'
if(v.plot_line)
new_rec.ln := line.new(bar_time, pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = "" //new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny,
color = v.clr, tooltip = tt)
else
class_hhll prev_ph = hhll.get(1)
new_rec.sub_group := pp > prev_ph.pivot_pp ? 'HH' : 'LH'
if(v.plot_line)
new_rec.ln := line.new(prev.bar_time, prev.pivot_pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = "" //new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny, color = v.clr, tooltip = tt)
hhll.unshift(new_rec)
true
//
method add_pl(array<class_hhll> hhll, class_ohlc pl, class_visuals v, tf) =>
if(pl.pivot)
pp = pl.pp
bar_id = pl.bar_id
bar_time = pl.bar_time
class_hhll prev = hhll.get(0)
rec_deleted = false
if(prev.group == 'L')
if(pp < prev.pivot_pp)
rec_deleted := true
prev.ln.delete()
prev.lbl.delete()
hhll.shift()
prev := hhll.get(0)
if(prev.group != 'L')
move = math.round((pp - nz(prev.pivot_pp, 0)) / pp * 100, 2)
change = math.round_to_mintick(pp - nz(prev.pivot_pp))
new_rec = class_hhll.new(group = 'L', bar_id = bar_id, bar_time = bar_time, pivot_pp = pp, tf = t(tf), is_new = true)
if(na(prev.group))
new_rec.sub_group := 'LL'
if(v.plot_line)
new_rec.ln := line.new(bar_time, pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = "" //new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny, color = v.clr, tooltip = tt)
else
class_hhll prev_pl = hhll.get(1)
new_rec.sub_group := pp < prev_pl.pivot_pp ? 'LL' : 'HL'
if(v.plot_line)
new_rec.ln := line.new(prev.bar_time, prev.pivot_pp, bar_time, pp, xloc = xloc.bar_time, color = v.clr, width = v.width)
if(v.plot_label)
tt = "" //new_rec.get_tt()
new_rec.lbl := label.new(bar_time, pp, text = new_rec.sub_group, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny, color = v.clr, tooltip = tt)
hhll.unshift(new_rec)
true
//
fib_levels(class_hhll pp1, class_hhll pp2, log = false) =>
class_fib_levels fib = class_fib_levels.new()
diff = math.abs(pp1.pivot_pp - pp2.pivot_pp)
minus = pp2.pivot_pp > pp1.pivot_pp
fib.f_382 := minus ? pp2.pivot_pp - (diff * 0.382) : pp2.pivot_pp + (diff * 0.382)
fib.f_382u := minus ? pp2.pivot_pp - (diff * (0.382 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (0.382*(1+xd_offset_percent)))
fib.f_382l := minus ? pp2.pivot_pp - (diff * (0.382 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (0.382*(1-xd_offset_percent)))
fib.f_50 := minus ? pp2.pivot_pp - (diff * 0.5) : pp2.pivot_pp + (diff * 0.5)
fib.f_618 := minus ? pp2.pivot_pp - (diff * 0.618) : pp2.pivot_pp + (diff * 0.618)
fib.f_618u := minus ? pp2.pivot_pp - (diff * (0.618 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (0.618*(1+xd_offset_percent)))
fib.f_618l := minus ? pp2.pivot_pp - (diff * (0.618 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (0.618*(1-xd_offset_percent)))
fib.f_886 := minus ? pp2.pivot_pp - (diff * 0.886) : pp2.pivot_pp + (diff * 0.886)
fib.f_886u := minus ? pp2.pivot_pp - (diff * (0.886 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (0.886*(1+xd_offset_percent)))
fib.f_886l := minus ? pp2.pivot_pp - (diff * (0.886 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (0.886*(1-xd_offset_percent)))
fib.f_1618 := minus ? pp2.pivot_pp - (diff * 1.618) : pp2.pivot_pp + (diff * 1.618)
fib.f_1618u := minus ? pp2.pivot_pp - (diff * (1.618 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (1.618*(1+xd_offset_percent)))
fib.f_1618l := minus ? pp2.pivot_pp - (diff * (1.618 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (1.618*(1-xd_offset_percent)))
fib.f_2618 := minus ? pp2.pivot_pp - (diff * 2.618) : pp2.pivot_pp + (diff * 2.618)
fib.f_3618 := minus ? pp2.pivot_pp - (diff * 3.618) : pp2.pivot_pp + (diff * 3.618)
fib.f_200 := minus ? pp2.pivot_pp - (diff * 2.00) : pp2.pivot_pp + (diff * 2.00)
fib.f_113 := minus ? pp2.pivot_pp - (diff * 1.13) : pp2.pivot_pp + (diff * 1.13)
fib.f_113u := minus ? pp2.pivot_pp - (diff * (1.13 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (1.13*(1+xd_offset_percent)))
fib.f_113l := minus ? pp2.pivot_pp - (diff * (1.13 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (1.13*(1-xd_offset_percent)))
fib.f_786 := minus ? pp2.pivot_pp - (diff * 0.786) : pp2.pivot_pp + (diff * 0.786)
fib.f_786u := minus ? pp2.pivot_pp - (diff * (0.786 * (1+xd_offset_percent))) : pp2.pivot_pp + (diff * (0.786*(1+xd_offset_percent)))
fib.f_786l := minus ? pp2.pivot_pp - (diff * (0.786 * (1-xd_offset_percent))) : pp2.pivot_pp + (diff * (0.786*(1-xd_offset_percent)))
fib.f_224 := minus ? pp2.pivot_pp - (diff * 2.24) : pp2.pivot_pp + (diff * 2.24)
fib.f_127 := minus ? pp2.pivot_pp - (diff * 1.27) : pp2.pivot_pp + (diff * 1.27)
fib.f_141 := minus ? pp2.pivot_pp - (diff * 1.41) : pp2.pivot_pp + (diff * 1.41)
fib.f_fake1 := minus ? pp2.pivot_pp - (diff * 0.00001) : pp2.pivot_pp + (diff * 0.00001)
fib.f_fake2 := minus ? pp2.pivot_pp - (diff * 100) : pp2.pivot_pp + (diff * 100)
fib
//
get_val(string key, class_fib_levels fib) =>
result = switch(key)
'F_382' => fib.f_382
'F_382U' => fib.f_382u
'F_382L' => fib.f_382l
'F_50' => fib.f_50
'F_618' => fib.f_618
'F_618U' => fib.f_618u
'F_618L' => fib.f_618l
'F_886' => fib.f_886
'F_886U' => fib.f_886u
'F_886L' => fib.f_886l
'F_1618' => fib.f_1618
'F_1618U' => fib.f_1618u
'F_1618L' => fib.f_1618l
'F_2618' => fib.f_2618
'F_3618' => fib.f_3618
'F_200' => fib.f_200
'F_113' => fib.f_113
'F_113U' => fib.f_113u
'F_113L' => fib.f_113l
'F_786' => fib.f_786
'F_786U' => fib.f_786u
'F_786L' => fib.f_786l
'F_224' => fib.f_224
'F_127' => fib.f_127
'F_141' => fib.f_141
'F_FAKE1' => fib.f_fake1
'F_FAKE2' => fib.f_fake2
=> -1
if(result == -1)
runtime.error("Key = "+ key + " Not found")
result
//
method set(class_legs leg, class_fib_levels fib) =>
leg.l1_val := get_val(leg.l1_key, fib)
leg.l2_val := get_val(leg.l2_key, fib)
//
method get_v_prop(map<string, class_p_visuals> v, class_xabcd rec) =>
class_p_visuals result = na
if(rec.bull_fl)
result := v.get("BULL-" + rec.name)
else
result := v.get("BEAR-" + rec.name)
result
//
method xabcd_patterns(array<class_hhll> hhll, array<class_xabcd> xabcd, map<string, class_p_visuals> v) =>
d = hhll.get(0)
c = hhll.get(1)
b = hhll.get(2)
a = hhll.get(3)
x = hhll.get(4)
points = array.new<chart.point>()
size = xabcd.size()
for i = 0 to size - 1
rec = xabcd.get(i)
fib_xb = fib_levels(x, a)
rec.xb.set(fib_xb)
rec.bull_fl := b.pivot_pp <= rec.xb.l1_val and b.pivot_pp >= rec.xb.l2_val
rec.bear_fl := b.pivot_pp >= rec.xb.l1_val and b.pivot_pp <= rec.xb.l2_val
if(not rec.bull_fl and not rec.bear_fl)
continue
fib_ac = fib_levels(a, b)
rec.ac.set(fib_ac)
rec.bull_fl := c.pivot_pp >= rec.ac.l1_val and c.pivot_pp <= rec.ac.l2_val
rec.bear_fl := c.pivot_pp <= rec.ac.l1_val and c.pivot_pp >= rec.ac.l2_val
if(not rec.bull_fl and not rec.bear_fl)
continue
fib_bd = fib_levels(b, c)
rec.bd.set(fib_bd)
rec.bull_fl := d.pivot_pp <= rec.bd.l1_val and d.pivot_pp >= rec.bd.l2_val
rec.bear_fl := d.pivot_pp >= rec.bd.l1_val and d.pivot_pp <= rec.bd.l2_val
if(not rec.bull_fl and not rec.bear_fl)
continue
if(apply_xd)
fib_xd = fib_levels(x, a)
rec.xd.set(fib_xd)
rec.bull_fl := d.pivot_pp <= rec.xd.l1_val and d.pivot_pp >= rec.xd.l2_val
rec.bear_fl := d.pivot_pp >= rec.xd.l1_val and d.pivot_pp <= rec.xd.l2_val
if(not rec.bull_fl and not rec.bear_fl)
continue
rec.bull_cnt := rec.bull_fl ? rec.bull_cnt + 1 : rec.bull_cnt
rec.bear_cnt := rec.bear_fl ? rec.bear_cnt + 1 : rec.bear_cnt
rec.last_bull := rec.bull_fl ? time : rec.last_bull
rec.last_bear := rec.bear_fl ? time : rec.last_bear
class_p_visuals visual = v.get_v_prop(rec) //v.get(v_prop)
if(visual.plot_fl)
ln_style = visual.line_style
ln_color = visual.line_color
bg_color = visual.bg_color
points.push(chart.point.from_time(x.bar_time, x.pivot_pp))
points.push(chart.point.from_time(a.bar_time, a.pivot_pp))
points.push(chart.point.from_time(b.bar_time, b.pivot_pp))
points.push(chart.point.from_time(x.bar_time, x.pivot_pp))
points.push(chart.point.from_time(b.bar_time, b.pivot_pp))
points.push(chart.point.from_time(c.bar_time, c.pivot_pp))
points.push(chart.point.from_time(d.bar_time, d.pivot_pp))
points.push(chart.point.from_time(b.bar_time, b.pivot_pp))
polyline.new(points, curved = false, closed = false, xloc = xloc.bar_time, line_style = ln_style, line_color = ln_color, fill_color = bg_color)
if(show_pattern_label)
lbl_txt = rec.bull_fl ? "Bullish " + rec.name : "Bearish " + rec.name
label.new(a.bar_time, a.pivot_pp, style = label.style_none, text = lbl_txt, xloc = xloc.bar_time, textcolor = pattern_name_color)
//#endregion Definitions and functios
//#region Main
//main code
[ph_ctf, pl_ctf] = get_ph_pl(0)
pre_size = hhll_ctf.size()
hhll_ctf.add_ph(ph_ctf, visuals.get('CTF'), ctf)
hhll_ctf.add_pl(pl_ctf, visuals.get('CTF'), ctf)
post_size = hhll_ctf.size()
if(post_size > pre_size)
hhll_ctf.xabcd_patterns(p_xabcd, v_map)
sz = p_xabcd.size()
if(sz > 0 and barstate.islast)
debug.log("Pattern name, Count, Latest Pattern Date")
debug.log("========================================")
for i = 0 to sz - 1
rec = p_xabcd.get(i)
debug.log(str.format("BULL {0} patterns = {1}", rec.name, rec.bull_cnt) + " " + (na(rec.last_bull) ? "-NA-" : dt(rec.last_bull)))
debug.log(str.format("BEAR {0} patterns = {1}", rec.name, rec.bear_cnt) + " " + (na(rec.last_bear) ? "-NA-" : dt(rec.last_bear)))
debug.display()
//#endregion Main
|
Top/Bottom Detector | https://www.tradingview.com/script/BBUKdH9z-Top-Bottom-Detector/ | lirre8 | https://www.tradingview.com/u/lirre8/ | 91 | 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/
// © lirre8
//
// Don't hesitate to send me a message if you have questions, noticed any bugs or have suggestions on improvements.
//@version=5
indicator(title='Top/Bottom Detector', shorttitle='TBD', overlay=true, precision=0)
// SETTINGS
BullCandlesBack = input(defval=4, title='Candles back', group='Bull count criteria', tooltip='Number of candles back in history that the current candle is compared to')
BullSourceCurrent = input(defval=close, title='Current candle source', group='Bull count criteria', tooltip='Price of the current candle')
BullSourceHistory = input(defval=close, title='History candle source', group='Bull count criteria', tooltip='Price of the historic candle that the current candle is compared with')
BullMaxCount = input(defval=9, title='Max count', group='Bull count criteria', tooltip='The count that will mark a top')
BearCandlesBack = input(defval=4, title='Candles back', group='Bear count criteria', tooltip='Number of candles back in history that the current candle is compared to')
BearSourceCurrent = input(defval=close, title='Current candle source', group='Bear count criteria', tooltip='Price of the current candle')
BearSourceHistory = input(defval=close, title='History candle source', group='Bear count criteria', tooltip='Price of the historic candle that the current candle is compared with')
BearMaxCount = input(defval=9, title='Max count', group='Bear count criteria', tooltip='The count that will mark a bottom')
ShowMtt = input(defval=true, title='Show multi timeframe table', group='Multi Timeframe Table')
FirstTimeframe = input.timeframe(title="", defval="30", inline="timeframes1", group="Multi Timeframe Table", display=display.none)
SecondTimeframe = input.timeframe(title="", defval="60", inline="timeframes1", group="Multi Timeframe Table", display=display.none)
ThirdTimeframe = input.timeframe(title="", defval="240", inline="timeframes1", group="Multi Timeframe Table", display=display.none)
FourthTimeframe = input.timeframe(title="", defval="1D", inline="timeframes2", group="Multi Timeframe Table", display=display.none)
FifthTimeframe = input.timeframe(title="", defval="1W", inline="timeframes2", group="Multi Timeframe Table", display=display.none)
SixthTimeframe = input.timeframe(title="", defval="1M", inline="timeframes2", group="Multi Timeframe Table", display=display.none)
TableColumns = input.int(title="Columns", defval=3, minval=1, maxval=3, inline="columnsrows", group="Multi Timeframe Table", display=display.none)
TableRows = input.int(title="Rows", defval=2, minval=1, maxval=2, inline="columnsrows", group="Multi Timeframe Table", display=display.none)
TablePosition = input.string(title="Position", defval=position.top_right, group="Multi Timeframe Table", display=display.none, options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
TableBorderWidth = input.int(title="Border width", defval=3, group="Multi Timeframe Table", display=display.none)
ShowCount = input(defval=false, title='Show count numbers', group='Misc')
Transp = input(defval=0, title='Transparency', group='Misc', display=display.none)
// VALUES
bearCount() =>
_bearCount = 0
_bearCount := BearSourceCurrent < BearSourceHistory[BearCandlesBack] ? _bearCount[1] + (_bearCount[1] == BearMaxCount ? 0 : 1) : 0
bullCount() =>
_bullCount = 0
_bullCount := BullSourceCurrent > BullSourceHistory[BullCandlesBack] ? _bullCount[1] + (_bullCount[1] == BullMaxCount ? 0 : 1) : 0
bullCount = bullCount()
bearCount = bearCount()
// PLOT
plotchar(ShowCount and bullCount == 1 and BullMaxCount > 1, char='1', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 2 and BullMaxCount > 2, char='2', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 3 and BullMaxCount > 3, char='3', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 4 and BullMaxCount > 4, char='4', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 5 and BullMaxCount > 5, char='5', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 6 and BullMaxCount > 6, char='6', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 7 and BullMaxCount > 7, char='7', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 8 and BullMaxCount > 8, char='8', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bullCount == 9 and BullMaxCount > 9, char='9', color=color.new(color.green, Transp), location=location.abovebar, editable=false)
plotchar(ShowCount and bearCount == 1 and BearMaxCount > 1, char='1', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 2 and BearMaxCount > 2, char='2', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 3 and BearMaxCount > 3, char='3', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 4 and BearMaxCount > 4, char='4', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 5 and BearMaxCount > 5, char='5', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 6 and BearMaxCount > 6, char='6', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 7 and BearMaxCount > 7, char='7', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 8 and BearMaxCount > 8, char='8', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotchar(ShowCount and bearCount == 9 and BearMaxCount > 9, char='9', color=color.new(color.red, Transp), location=location.belowbar, editable=false)
plotarrow(bullCount >= BullMaxCount ? -1 : bearCount >= BearMaxCount ? 1 : na, colorup=color.green, colordown=color.red, maxheight=15, editable=false)
// ALERTS
if bullCount >= BullMaxCount
alert("Top detected")
if bearCount >= BearMaxCount
alert("Bottom detected")
alertcondition(bullCount >= BullMaxCount, "Top", "TBD top detected")
alertcondition(bearCount >= BearMaxCount, "Bottom", "TBD bottom detected")
// MULTI TIMEFRAME TABLE
f_fillCell(_table, _column, _row, _value, _timeframe) =>
_c_color = na(_value) ? color.new(color.gray, 50) : _value == 0 ? color.gray : _value > 0 ? color.rgb(38, 166, 154) : color.rgb(240, 83, 80)
_valueText = na(_value) ? "N/A" : _value == 0 ? '-' : _value == BullMaxCount ? "Top" : _value == -BearMaxCount ? "Bottom" : str.tostring(math.abs(_value))
_cellText = _timeframe + "\n" + _valueText
table.cell(_table, _column, _row, _cellText, bgcolor = color.new(_c_color, 70), text_color = _c_color, width = 6)
f_isLowerTimeframe(_timeframe) =>
_timeframeNbr = str.tonumber(_timeframe)
not na(_timeframeNbr) and _timeframe != "1D" ? (timeframe.isdwm ? true : timeframe.multiplier > _timeframeNbr)
: _timeframe == "1D" ? timeframe.isweekly or timeframe.ismonthly
: _timeframe == "1W" ? timeframe.ismonthly
: false
mttCandleCount() =>
_bullCount = bullCount()
_bearCount = bearCount()
_bullCount > 0 ?_bullCount : -_bearCount
f_setupCountForTimeframe(_timeframe) =>
f_isLowerTimeframe(_timeframe) ? na : request.security(syminfo.tickerid, _timeframe, mttCandleCount())
f_labelForTimeframe(_timeframe) =>
_timeframeNbr = str.tonumber(_timeframe)
na(_timeframeNbr) or _timeframe == "1D" ? _timeframe
: _timeframeNbr % 60 == 0 ? str.tostring(_timeframeNbr/60) + "h" : _timeframe + "m"
if ShowMtt
var table mttTable = table.new(TablePosition, TableColumns, TableRows, border_width=TableBorderWidth)
f_fillCell(mttTable, 0, 0, f_setupCountForTimeframe(FirstTimeframe), f_labelForTimeframe(FirstTimeframe))
if TableColumns > 1
f_fillCell(mttTable, 1, 0, f_setupCountForTimeframe(SecondTimeframe), f_labelForTimeframe(SecondTimeframe))
if TableColumns > 2
f_fillCell(mttTable, 2, 0, f_setupCountForTimeframe(ThirdTimeframe), f_labelForTimeframe(ThirdTimeframe))
if TableRows > 1
f_fillCell(mttTable, 0, 1, f_setupCountForTimeframe(FourthTimeframe), f_labelForTimeframe(FourthTimeframe))
if TableColumns > 1
f_fillCell(mttTable, 1, 1, f_setupCountForTimeframe(FifthTimeframe), f_labelForTimeframe(FifthTimeframe))
if TableColumns > 2
f_fillCell(mttTable, 2, 1, f_setupCountForTimeframe(SixthTimeframe), f_labelForTimeframe(SixthTimeframe)) |
Bull Bear Power with Optional Normalization Function | https://www.tradingview.com/script/Zrc0KWJ5-Bull-Bear-Power-with-Optional-Normalization-Function/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 151 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo
//@version=5
indicator("Bull/Bear Power with Normalization Function", shorttitle="NBBP")
// Inputs
lengthInput = input.int(50, title="BBP Length")
maLength = input.int(50, title='Moving Average Length')
isNormalized = input.bool(true, title='Use Normalization Function?')
// Math
bullPower = high - ta.ema(close, lengthInput)
bearPower = low - ta.ema(close, lengthInput)
bbP = bullPower + bearPower
bbP_h = ta.max(bbP)
bbP_l = ta.min(bbP)
bbP_n = ((bbP - bbP_l) / (bbP_h - bbP_l) - 0.5) * 2
bbP_final = isNormalized ? bbP_n : bbP
zeroLine = 0
upCondition = ta.crossover(bbP_final, zeroLine)
downCondition = ta.crossunder(bbP_final, zeroLine)
movingAverage = ta.ema(bbP_final, maLength)
// Coloration
bbpColor = bbP_final > 0 ? color.green : color.red
fillColor = bbP_final > 0 ? color.new(color.lime, 50) : color.new(color.fuchsia, 50)
barcolor(bbpColor)
// Plotting
bbP_n_plot = plot(bbP_final, title='Bull/Bear Power', color=bbpColor, linewidth = 4)
zeroLineplot = plot(zeroLine, title = 'Zero Line', linewidth = 3)
plot(movingAverage, title = 'Exponential MA', color=color.white, linewidth = 3)
fill(bbP_n_plot, zeroLineplot, color=fillColor)
|
CalendarEur | https://www.tradingview.com/script/0Aeulp3S-CalendarEur/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the important events on EUR. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("CalendarEur")
// @function EUR high impact news date and time from 2015 to 2019
export HighImpactNews2015To2019() =>
array.from(
timestamp("2015-01-01T06:00:00"),
timestamp("2015-01-07T08:00:00"),
timestamp("2015-01-07T10:00:00"),
timestamp("2015-01-07T10:00:00"),
timestamp("2015-01-14T08:30:00"),
timestamp("2015-01-16T10:00:00"),
timestamp("2015-01-16T10:00:00"),
timestamp("2015-01-22T12:45:00"),
timestamp("2015-01-22T13:30:00"),
timestamp("2015-01-30T10:00:00"),
timestamp("2015-01-30T10:00:00"),
timestamp("2015-02-04T09:00:00"),
timestamp("2015-02-04T09:00:02"),
timestamp("2015-02-11T16:30:00"),
timestamp("2015-02-12T14:00:00"),
timestamp("2015-02-13T10:00:00"),
timestamp("2015-02-16T14:00:00"),
timestamp("2015-02-19T12:30:00"),
timestamp("2015-02-20T20:00:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-24T10:00:00"),
timestamp("2015-02-24T13:00:50"),
timestamp("2015-02-24T14:00:00"),
timestamp("2015-02-25T17:15:00"),
timestamp("2015-03-02T10:00:00"),
timestamp("2015-03-02T10:00:00"),
timestamp("2015-03-05T12:45:00"),
timestamp("2015-03-05T13:30:00"),
timestamp("2015-03-06T10:00:00"),
timestamp("2015-03-09T14:00:00"),
timestamp("2015-03-11T08:00:00"),
timestamp("2015-03-16T18:45:00"),
timestamp("2015-03-17T10:00:00"),
timestamp("2015-03-17T10:00:00"),
timestamp("2015-03-19T10:15:00"),
timestamp("2015-03-19T12:00:52"),
timestamp("2015-03-20T10:00:31"),
timestamp("2015-03-23T14:00:00"),
timestamp("2015-03-31T09:00:00"),
timestamp("2015-03-31T09:00:00"),
timestamp("2015-04-02T11:30:00"),
timestamp("2015-04-15T11:45:00"),
timestamp("2015-04-15T12:30:00"),
timestamp("2015-04-17T09:00:00"),
timestamp("2015-04-17T09:00:00"),
timestamp("2015-04-18T16:00:00"),
timestamp("2015-04-24T11:30:00"),
timestamp("2015-04-30T09:00:00"),
timestamp("2015-04-30T09:00:00"),
timestamp("2015-05-13T09:00:00"),
timestamp("2015-05-14T15:00:00"),
timestamp("2015-05-21T11:30:00"),
timestamp("2015-05-21T17:30:00"),
timestamp("2015-05-22T08:00:00"),
timestamp("2015-05-23T13:30:00"),
timestamp("2015-05-27T11:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-02T09:00:00"),
timestamp("2015-06-03T11:45:00"),
timestamp("2015-06-03T12:30:00"),
timestamp("2015-06-08T00:00:00"),
timestamp("2015-06-09T09:00:00"),
timestamp("2015-06-15T13:00:00"),
timestamp("2015-06-16T08:00:00"),
timestamp("2015-06-18T09:33:18"),
timestamp("2015-06-22T10:30:00"),
timestamp("2015-06-22T17:00:00"),
timestamp("2015-06-25T14:00:00"),
timestamp("2015-06-26T09:00:00"),
timestamp("2015-06-29T10:45:00"),
timestamp("2015-06-30T09:00:00"),
timestamp("2015-06-30T09:00:00"),
timestamp("2015-07-02T11:30:00"),
timestamp("2015-07-02T15:10:00"),
timestamp("2015-07-07T16:00:00"),
timestamp("2015-07-12T00:00:00"),
timestamp("2015-07-16T09:00:00"),
timestamp("2015-07-16T09:00:00"),
timestamp("2015-07-16T11:45:00"),
timestamp("2015-07-16T12:30:00"),
timestamp("2015-07-31T09:00:00"),
timestamp("2015-07-31T09:00:00"),
timestamp("2015-08-13T11:30:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T09:00:00"),
timestamp("2015-08-14T13:00:00"),
timestamp("2015-08-31T09:00:00"),
timestamp("2015-08-31T09:00:00"),
timestamp("2015-09-03T11:45:00"),
timestamp("2015-09-03T12:30:00"),
timestamp("2015-09-08T09:00:00"),
timestamp("2015-09-08T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-16T09:00:00"),
timestamp("2015-09-23T13:00:00"),
timestamp("2015-09-24T09:15:00"),
timestamp("2015-09-30T09:00:00"),
timestamp("2015-09-30T09:00:00"),
timestamp("2015-10-02T01:30:00"),
timestamp("2015-10-06T17:00:00"),
timestamp("2015-10-07T07:00:00"),
timestamp("2015-10-22T11:45:00"),
timestamp("2015-10-22T12:30:00"),
timestamp("2015-10-30T10:00:00"),
timestamp("2015-10-30T10:00:00"),
timestamp("2015-11-03T19:00:00"),
timestamp("2015-11-04T08:00:00"),
timestamp("2015-11-05T11:45:00"),
timestamp("2015-11-11T13:15:00"),
timestamp("2015-11-12T08:30:00"),
timestamp("2015-11-12T10:30:00"),
timestamp("2015-11-13T10:00:00"),
timestamp("2015-11-13T10:00:00"),
timestamp("2015-11-16T10:15:00"),
timestamp("2015-11-17T10:00:00"),
timestamp("2015-11-19T12:30:00"),
timestamp("2015-11-20T08:00:00"),
timestamp("2015-12-02T10:00:00"),
timestamp("2015-12-02T10:00:00"),
timestamp("2015-12-03T12:45:00"),
timestamp("2015-12-03T13:30:00"),
timestamp("2015-12-08T10:00:00"),
timestamp("2015-12-08T10:00:00"),
timestamp("2015-12-14T11:00:00"),
timestamp("2015-12-16T08:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2015-12-16T10:00:00"),
timestamp("2016-01-01T13:30:00"),
timestamp("2016-01-05T10:00:00"),
timestamp("2016-01-05T10:00:00"),
timestamp("2016-01-13T08:00:00"),
timestamp("2016-01-14T12:30:00"),
timestamp("2016-01-21T12:45:00"),
timestamp("2016-01-21T13:30:00"),
timestamp("2016-01-22T07:45:00"),
timestamp("2016-01-25T18:00:00"),
timestamp("2016-01-29T10:00:00"),
timestamp("2016-01-29T10:00:00"),
timestamp("2016-02-01T16:00:00"),
timestamp("2016-02-03T08:00:00"),
timestamp("2016-02-04T08:00:00"),
timestamp("2016-02-12T10:00:00"),
timestamp("2016-02-12T10:00:00"),
timestamp("2016-02-15T14:00:00"),
timestamp("2016-02-17T08:00:00"),
timestamp("2016-02-18T12:30:00"),
timestamp("2016-02-29T10:00:00"),
timestamp("2016-02-29T10:00:00"),
timestamp("2016-03-08T10:00:00"),
timestamp("2016-03-08T10:00:00"),
timestamp("2016-03-10T12:45:00"),
timestamp("2016-03-10T12:45:00"),
timestamp("2016-03-10T13:30:00"),
timestamp("2016-03-16T08:00:00"),
timestamp("2016-03-17T10:00:00"),
timestamp("2016-03-17T10:00:00"),
timestamp("2016-03-24T10:56:59"),
timestamp("2016-03-31T09:00:00"),
timestamp("2016-03-31T09:00:00"),
timestamp("2016-04-06T07:00:00"),
timestamp("2016-04-07T11:30:00"),
timestamp("2016-04-07T13:00:00"),
timestamp("2016-04-14T09:00:00"),
timestamp("2016-04-14T09:00:00"),
timestamp("2016-04-20T10:00:00"),
timestamp("2016-04-21T11:45:00"),
timestamp("2016-04-21T12:30:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-04-29T09:00:00"),
timestamp("2016-05-02T14:00:00"),
timestamp("2016-05-04T07:00:00"),
timestamp("2016-05-13T09:00:00"),
timestamp("2016-05-13T09:00:00"),
timestamp("2016-05-18T07:00:00"),
timestamp("2016-05-18T09:00:00"),
timestamp("2016-05-18T09:00:00"),
timestamp("2016-05-19T11:30:00"),
timestamp("2016-05-20T00:00:00"),
timestamp("2016-05-21T00:00:00"),
timestamp("2016-05-26T00:00:00"),
timestamp("2016-05-27T00:00:00"),
timestamp("2016-05-31T09:00:00"),
timestamp("2016-05-31T09:00:00"),
timestamp("2016-06-02T11:45:00"),
timestamp("2016-06-02T11:45:00"),
timestamp("2016-06-02T12:30:00"),
timestamp("2016-06-07T09:00:00"),
timestamp("2016-06-07T09:00:00"),
timestamp("2016-06-09T07:00:00"),
timestamp("2016-06-17T15:00:00"),
timestamp("2016-06-21T13:00:00"),
timestamp("2016-06-22T07:00:00"),
timestamp("2016-06-23T11:13:41"),
timestamp("2016-06-24T09:30:00"),
timestamp("2016-06-28T00:00:00"),
timestamp("2016-06-28T08:00:00"),
timestamp("2016-06-28T08:00:00"),
timestamp("2016-06-29T12:00:00"),
timestamp("2016-06-30T09:00:00"),
timestamp("2016-06-30T09:00:00"),
timestamp("2016-07-06T07:00:00"),
timestamp("2016-07-06T07:00:00"),
timestamp("2016-07-07T11:30:00"),
timestamp("2016-07-21T11:45:00"),
timestamp("2016-07-21T11:45:00"),
timestamp("2016-07-21T12:30:00"),
timestamp("2016-07-29T09:00:00"),
timestamp("2016-07-29T20:00:00"),
timestamp("2016-08-03T07:00:00"),
timestamp("2016-08-12T09:00:00"),
timestamp("2016-08-12T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T09:00:00"),
timestamp("2016-08-18T11:30:00"),
timestamp("2016-08-31T09:00:00"),
timestamp("2016-08-31T09:00:00"),
timestamp("2016-09-08T11:45:00"),
timestamp("2016-09-08T11:45:00"),
timestamp("2016-09-08T12:30:00"),
timestamp("2016-09-13T09:00:00"),
timestamp("2016-09-13T10:45:00"),
timestamp("2016-09-16T00:00:00"),
timestamp("2016-09-22T09:30:00"),
timestamp("2016-09-22T13:00:00"),
timestamp("2016-09-26T15:05:00"),
timestamp("2016-09-28T09:00:00"),
timestamp("2016-09-30T09:00:00"),
timestamp("2016-09-30T09:00:00"),
timestamp("2016-10-06T11:30:00"),
timestamp("2016-10-17T09:00:00"),
timestamp("2016-10-17T09:00:00"),
timestamp("2016-10-17T17:35:00"),
timestamp("2016-10-20T11:45:00"),
timestamp("2016-10-20T11:45:00"),
timestamp("2016-10-20T12:30:00"),
timestamp("2016-10-25T15:30:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-10-31T10:00:00"),
timestamp("2016-11-14T15:00:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-15T10:00:00"),
timestamp("2016-11-17T12:30:00"),
timestamp("2016-11-18T08:15:00"),
timestamp("2016-11-21T16:30:00"),
timestamp("2016-11-28T14:00:00"),
timestamp("2016-11-30T10:00:00"),
timestamp("2016-11-30T10:00:00"),
timestamp("2016-11-30T12:45:00"),
timestamp("2016-12-06T10:00:00"),
timestamp("2016-12-06T10:00:00"),
timestamp("2016-12-08T12:45:00"),
timestamp("2016-12-08T12:45:00"),
timestamp("2016-12-08T13:30:00"),
timestamp("2016-12-16T10:00:00"),
timestamp("2016-12-16T10:00:00"),
timestamp("2017-01-04T10:00:00"),
timestamp("2017-01-04T10:00:00"),
timestamp("2017-01-12T12:30:00"),
timestamp("2017-01-19T12:45:00"),
timestamp("2017-01-19T12:45:00"),
timestamp("2017-01-19T13:30:00"),
timestamp("2017-01-23T11:30:00"),
timestamp("2017-01-31T08:00:00"),
timestamp("2017-01-31T10:00:00"),
timestamp("2017-01-31T10:00:00"),
timestamp("2017-02-01T08:00:00"),
timestamp("2017-02-02T12:15:00"),
timestamp("2017-02-06T14:00:00"),
timestamp("2017-02-14T10:00:00"),
timestamp("2017-02-14T10:00:00"),
timestamp("2017-02-15T08:00:00"),
timestamp("2017-02-16T12:30:00"),
timestamp("2017-03-09T12:45:00"),
timestamp("2017-03-09T12:45:00"),
timestamp("2017-03-09T13:30:00"),
timestamp("2017-03-13T13:30:00"),
timestamp("2017-03-22T08:00:00"),
timestamp("2017-03-29T12:45:00"),
timestamp("2017-04-04T14:30:00"),
timestamp("2017-04-05T07:00:00"),
timestamp("2017-04-06T07:00:00"),
timestamp("2017-04-06T11:30:00"),
timestamp("2017-04-27T11:45:00"),
timestamp("2017-04-27T11:45:00"),
timestamp("2017-04-27T12:30:00"),
timestamp("2017-04-29T16:00:00"),
timestamp("2017-05-03T09:00:00"),
timestamp("2017-05-03T09:00:00"),
timestamp("2017-05-04T16:30:00"),
timestamp("2017-05-10T12:00:00"),
timestamp("2017-05-12T11:00:00"),
timestamp("2017-05-13T11:00:00"),
timestamp("2017-05-16T09:00:00"),
timestamp("2017-05-16T09:00:00"),
timestamp("2017-05-18T11:30:00"),
timestamp("2017-05-18T17:00:00"),
timestamp("2017-05-24T12:45:00"),
timestamp("2017-05-26T00:00:00"),
timestamp("2017-05-27T00:00:00"),
timestamp("2017-05-29T13:00:00"),
timestamp("2017-05-29T14:15:00"),
timestamp("2017-05-29T15:00:00"),
timestamp("2017-06-08T09:00:00"),
timestamp("2017-06-08T09:00:00"),
timestamp("2017-06-08T11:45:00"),
timestamp("2017-06-08T11:45:00"),
timestamp("2017-06-08T12:30:00"),
timestamp("2017-06-21T07:00:00"),
timestamp("2017-06-26T17:30:00"),
timestamp("2017-06-27T08:00:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-05T07:00:00"),
timestamp("2017-07-06T11:30:00"),
timestamp("2017-07-17T09:00:00"),
timestamp("2017-07-17T09:00:00"),
timestamp("2017-07-18T08:00:00"),
timestamp("2017-07-20T11:45:00"),
timestamp("2017-07-20T11:45:00"),
timestamp("2017-07-20T12:30:00"),
timestamp("2017-07-31T09:00:00"),
timestamp("2017-07-31T09:00:00"),
timestamp("2017-08-01T09:00:00"),
timestamp("2017-08-01T09:00:00"),
timestamp("2017-08-02T07:00:00"),
timestamp("2017-08-16T09:00:00"),
timestamp("2017-08-16T09:00:00"),
timestamp("2017-08-17T09:00:00"),
timestamp("2017-08-17T09:00:00"),
timestamp("2017-08-17T11:30:00"),
timestamp("2017-08-23T07:00:00"),
timestamp("2017-08-25T19:00:00"),
timestamp("2017-08-31T09:00:00"),
timestamp("2017-08-31T09:00:00"),
timestamp("2017-09-07T09:00:00"),
timestamp("2017-09-07T09:00:00"),
timestamp("2017-09-07T11:45:00"),
timestamp("2017-09-07T11:45:00"),
timestamp("2017-09-07T12:30:00"),
timestamp("2017-09-18T09:00:00"),
timestamp("2017-09-18T09:00:00"),
timestamp("2017-09-20T07:00:00"),
timestamp("2017-09-21T13:30:00"),
timestamp("2017-09-22T08:00:00"),
timestamp("2017-09-22T09:30:00"),
timestamp("2017-09-25T13:00:00"),
timestamp("2017-09-29T09:00:00"),
timestamp("2017-09-29T09:00:00"),
timestamp("2017-10-04T07:00:00"),
timestamp("2017-10-04T17:15:00"),
timestamp("2017-10-05T11:30:00"),
timestamp("2017-10-12T14:30:00"),
timestamp("2017-10-17T09:00:00"),
timestamp("2017-10-17T09:00:00"),
timestamp("2017-10-18T08:10:00"),
timestamp("2017-10-26T11:45:00"),
timestamp("2017-10-26T11:45:00"),
timestamp("2017-10-26T12:30:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-10-31T10:00:00"),
timestamp("2017-11-07T09:00:00"),
timestamp("2017-11-08T08:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-14T10:00:00"),
timestamp("2017-11-16T10:00:00"),
timestamp("2017-11-16T10:00:00"),
timestamp("2017-11-17T08:30:00"),
timestamp("2017-11-20T10:30:00"),
timestamp("2017-11-20T14:00:00"),
timestamp("2017-11-20T16:00:00"),
timestamp("2017-11-23T12:30:00"),
timestamp("2017-11-30T10:00:00"),
timestamp("2017-11-30T10:00:00"),
timestamp("2017-12-06T08:00:00"),
timestamp("2017-12-07T10:00:00"),
timestamp("2017-12-07T10:00:00"),
timestamp("2017-12-07T16:00:00"),
timestamp("2017-12-12T19:00:00"),
timestamp("2017-12-14T12:45:00"),
timestamp("2017-12-14T12:45:00"),
timestamp("2017-12-14T13:30:00"),
timestamp("2017-12-18T10:00:00"),
timestamp("2017-12-18T10:00:00"),
timestamp("2018-01-05T10:00:00"),
timestamp("2018-01-05T10:00:00"),
timestamp("2018-01-09T08:00:00"),
timestamp("2018-01-11T12:30:00"),
timestamp("2018-01-17T10:00:00"),
timestamp("2018-01-17T10:00:00"),
timestamp("2018-01-25T12:45:00"),
timestamp("2018-01-25T12:45:00"),
timestamp("2018-01-25T13:30:00"),
timestamp("2018-01-30T10:00:00"),
timestamp("2018-01-30T10:00:00"),
timestamp("2018-01-31T10:00:00"),
timestamp("2018-01-31T10:00:00"),
timestamp("2018-02-05T16:00:00"),
timestamp("2018-02-07T08:00:00"),
timestamp("2018-02-14T10:00:00"),
timestamp("2018-02-14T10:00:00"),
timestamp("2018-02-21T08:00:00"),
timestamp("2018-02-22T12:30:00"),
timestamp("2018-02-23T10:00:00"),
timestamp("2018-02-23T10:00:00"),
timestamp("2018-02-26T14:40:00"),
timestamp("2018-02-28T10:00:00"),
timestamp("2018-02-28T10:00:00"),
timestamp("2018-03-07T10:00:00"),
timestamp("2018-03-07T10:00:00"),
timestamp("2018-03-08T12:45:00"),
timestamp("2018-03-08T12:45:00"),
timestamp("2018-03-08T13:30:00"),
timestamp("2018-03-14T08:00:00"),
timestamp("2018-03-16T10:00:00"),
timestamp("2018-03-16T10:00:00"),
timestamp("2018-04-04T09:00:00"),
timestamp("2018-04-04T09:00:00"),
timestamp("2018-04-11T11:00:00"),
timestamp("2018-04-12T11:30:00"),
timestamp("2018-04-18T09:00:00"),
timestamp("2018-04-18T09:00:00"),
timestamp("2018-04-26T11:45:00"),
timestamp("2018-04-26T11:45:00"),
timestamp("2018-04-26T12:30:00"),
timestamp("2018-05-02T09:00:00"),
timestamp("2018-05-02T09:00:00"),
timestamp("2018-05-03T09:00:00"),
timestamp("2018-05-03T09:00:00"),
timestamp("2018-05-11T13:15:00"),
timestamp("2018-05-15T09:00:00"),
timestamp("2018-05-15T09:00:00"),
timestamp("2018-05-16T09:00:00"),
timestamp("2018-05-16T09:00:00"),
timestamp("2018-05-16T12:00:00"),
timestamp("2018-05-24T11:30:00"),
timestamp("2018-05-31T00:00:00"),
timestamp("2018-05-31T09:00:00"),
timestamp("2018-05-31T09:00:00"),
timestamp("2018-06-01T00:00:00"),
timestamp("2018-06-02T00:00:00"),
timestamp("2018-06-07T09:00:00"),
timestamp("2018-06-07T09:00:00"),
timestamp("2018-06-08T00:00:00"),
timestamp("2018-06-09T00:00:00"),
timestamp("2018-06-14T11:45:00"),
timestamp("2018-06-14T11:45:00"),
timestamp("2018-06-14T12:30:00"),
timestamp("2018-06-15T09:00:00"),
timestamp("2018-06-15T09:00:00"),
timestamp("2018-06-18T17:30:00"),
timestamp("2018-06-19T08:00:00"),
timestamp("2018-06-20T13:30:00"),
timestamp("2018-06-29T09:00:00"),
timestamp("2018-06-29T09:00:00"),
timestamp("2018-07-09T13:00:00"),
timestamp("2018-07-09T15:00:00"),
timestamp("2018-07-11T07:00:00"),
timestamp("2018-07-12T11:30:00"),
timestamp("2018-07-18T09:00:00"),
timestamp("2018-07-18T09:00:00"),
timestamp("2018-07-26T11:45:00"),
timestamp("2018-07-26T11:45:00"),
timestamp("2018-07-26T12:30:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-07-31T09:00:00"),
timestamp("2018-08-14T09:00:00"),
timestamp("2018-08-14T09:00:00"),
timestamp("2018-08-17T09:00:00"),
timestamp("2018-08-17T09:00:00"),
timestamp("2018-08-23T11:30:00"),
timestamp("2018-08-31T09:00:00"),
timestamp("2018-08-31T09:00:00"),
timestamp("2018-09-07T09:00:00"),
timestamp("2018-09-07T09:00:00"),
timestamp("2018-09-13T11:45:00"),
timestamp("2018-09-13T11:45:00"),
timestamp("2018-09-13T12:30:00"),
timestamp("2018-09-17T09:00:00"),
timestamp("2018-09-17T09:00:00"),
timestamp("2018-09-18T07:15:00"),
timestamp("2018-09-19T13:00:00"),
timestamp("2018-09-24T13:00:00"),
timestamp("2018-09-27T13:30:00"),
timestamp("2018-09-28T09:00:00"),
timestamp("2018-09-28T09:00:00"),
timestamp("2018-10-11T11:30:00"),
timestamp("2018-10-17T00:00:00"),
timestamp("2018-10-17T09:00:00"),
timestamp("2018-10-17T09:00:00"),
timestamp("2018-10-18T00:00:00"),
timestamp("2018-10-25T11:45:00"),
timestamp("2018-10-25T11:45:00"),
timestamp("2018-10-25T12:30:00"),
timestamp("2018-10-26T14:00:00"),
timestamp("2018-10-30T10:00:00"),
timestamp("2018-10-30T10:00:00"),
timestamp("2018-10-31T10:00:00"),
timestamp("2018-10-31T10:00:00"),
timestamp("2018-11-08T15:20:00"),
timestamp("2018-11-14T10:00:00"),
timestamp("2018-11-14T10:00:00"),
timestamp("2018-11-16T08:30:00"),
timestamp("2018-11-16T10:00:00"),
timestamp("2018-11-16T10:00:00"),
timestamp("2018-11-22T12:30:00"),
timestamp("2018-11-26T00:00:00"),
timestamp("2018-11-26T14:00:00"),
timestamp("2018-11-29T08:00:00"),
timestamp("2018-11-30T10:00:00"),
timestamp("2018-11-30T10:00:00"),
timestamp("2018-12-05T08:30:00"),
timestamp("2018-12-07T10:00:00"),
timestamp("2018-12-07T10:00:00"),
timestamp("2018-12-13T12:45:00"),
timestamp("2018-12-13T12:45:00"),
timestamp("2018-12-13T13:30:00"),
timestamp("2018-12-15T10:30:00"),
timestamp("2018-12-17T10:00:00"),
timestamp("2018-12-17T10:00:00"),
timestamp("2019-01-04T10:00:00"),
timestamp("2019-01-04T10:00:00"),
timestamp("2019-01-10T12:30:00"),
timestamp("2019-01-15T15:00:00"),
timestamp("2019-01-17T10:00:00"),
timestamp("2019-01-17T10:00:00"),
timestamp("2019-01-24T12:45:00"),
timestamp("2019-01-24T12:45:00"),
timestamp("2019-01-24T13:30:00"),
timestamp("2019-01-28T14:00:00"),
timestamp("2019-01-28T16:00:00"),
timestamp("2019-01-31T10:00:00"),
timestamp("2019-01-31T10:00:00"),
timestamp("2019-02-01T10:00:00"),
timestamp("2019-02-01T10:00:00"),
timestamp("2019-02-14T10:00:00"),
timestamp("2019-02-14T10:00:00"),
timestamp("2019-02-21T09:00:00"),
timestamp("2019-02-21T12:30:00"),
timestamp("2019-02-22T15:30:00"),
timestamp("2019-03-01T10:00:00"),
timestamp("2019-03-01T10:00:00"),
timestamp("2019-03-07T10:00:00"),
timestamp("2019-03-07T10:00:00"),
timestamp("2019-03-07T12:45:00"),
timestamp("2019-03-07T12:45:00"),
timestamp("2019-03-07T13:30:00"),
timestamp("2019-03-22T09:00:00"),
timestamp("2019-03-27T08:00:00"),
timestamp("2019-04-01T09:00:00"),
timestamp("2019-04-01T09:00:00"),
timestamp("2019-04-04T11:30:00"),
timestamp("2019-04-10T11:45:00"),
timestamp("2019-04-10T11:45:00"),
timestamp("2019-04-10T12:30:00"),
timestamp("2019-04-18T08:00:00"),
timestamp("2019-04-30T09:00:00"),
timestamp("2019-04-30T09:00:00"),
timestamp("2019-05-03T09:00:00"),
timestamp("2019-05-03T09:00:00"),
timestamp("2019-05-08T11:30:00"),
timestamp("2019-05-15T09:00:00"),
timestamp("2019-05-15T09:00:00"),
timestamp("2019-05-22T07:30:00"),
timestamp("2019-05-23T08:00:00"),
timestamp("2019-05-23T11:30:00"),
timestamp("2019-06-04T09:00:00"),
timestamp("2019-06-04T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-06T09:00:00"),
timestamp("2019-06-06T11:45:00"),
timestamp("2019-06-06T11:45:00"),
timestamp("2019-06-06T12:30:00"),
timestamp("2019-06-12T08:15:00"),
timestamp("2019-06-17T18:00:00"),
timestamp("2019-06-18T08:00:00"),
timestamp("2019-06-18T14:00:00"),
timestamp("2019-06-19T08:30:00"),
timestamp("2019-06-19T14:00:00"),
timestamp("2019-06-21T08:00:00"),
timestamp("2019-06-28T09:00:00"),
timestamp("2019-06-28T09:00:00"),
timestamp("2019-07-11T11:30:00"),
timestamp("2019-07-23T08:00:00"),
timestamp("2019-07-24T08:00:00"),
timestamp("2019-07-25T11:45:00"),
timestamp("2019-07-25T11:45:00"),
timestamp("2019-07-25T12:30:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-07-31T09:00:00"),
timestamp("2019-08-14T09:00:00"),
timestamp("2019-08-14T09:00:00"),
timestamp("2019-08-22T08:00:00"),
timestamp("2019-08-22T11:30:00"),
timestamp("2019-08-24T00:00:00"),
timestamp("2019-08-25T00:00:00"),
timestamp("2019-08-26T00:00:00"),
timestamp("2019-08-30T09:00:00"),
timestamp("2019-08-30T09:00:00"),
timestamp("2019-09-04T07:00:00"),
timestamp("2019-09-06T09:00:00"),
timestamp("2019-09-06T09:00:00"),
timestamp("2019-09-12T11:45:00"),
timestamp("2019-09-12T11:45:00"),
timestamp("2019-09-12T12:30:00"),
timestamp("2019-09-23T08:00:00"),
timestamp("2019-09-23T13:00:00"),
timestamp("2019-09-23T15:00:00"),
timestamp("2019-09-26T13:30:00"),
timestamp("2019-10-01T09:00:00"),
timestamp("2019-10-01T09:00:00"),
timestamp("2019-10-01T16:45:00"),
timestamp("2019-10-10T11:30:00"),
timestamp("2019-10-11T10:00:00"),
timestamp("2019-10-22T08:00:00"),
timestamp("2019-10-24T08:00:00"),
timestamp("2019-10-24T11:45:00"),
timestamp("2019-10-24T11:45:00"),
timestamp("2019-10-24T12:30:00"),
timestamp("2019-10-28T15:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-10-31T10:00:00"),
timestamp("2019-11-04T19:30:00"),
timestamp("2019-11-14T10:00:00"),
timestamp("2019-11-14T10:00:00"),
timestamp("2019-11-21T12:30:00"),
timestamp("2019-11-22T08:30:00"),
timestamp("2019-11-22T09:00:00"),
timestamp("2019-11-29T10:00:00"),
timestamp("2019-11-29T10:00:00"),
timestamp("2019-12-01T11:00:00"),
timestamp("2019-12-02T14:00:00"),
timestamp("2019-12-05T10:00:00"),
timestamp("2019-12-05T10:00:00"),
timestamp("2019-12-12T12:45:00"),
timestamp("2019-12-12T12:45:00"),
timestamp("2019-12-12T13:30:00"),
timestamp("2019-12-16T09:00:00"),
timestamp("2019-12-18T08:30:00")
)
// @function EUR high impact news date and time from 2020 to 2023
export HighImpactNews2020To2023() =>
array.from(
timestamp("2020-01-07T10:00:00"),
timestamp("2020-01-07T10:00:00"),
timestamp("2020-01-16T12:30:00"),
timestamp("2020-01-16T18:00:00"),
timestamp("2020-01-20T18:30:00"),
timestamp("2020-01-21T09:00:00"),
timestamp("2020-01-23T12:45:00"),
timestamp("2020-01-23T12:45:00"),
timestamp("2020-01-23T13:30:00"),
timestamp("2020-01-24T09:00:00"),
timestamp("2020-01-24T10:30:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-01-31T10:00:00"),
timestamp("2020-02-05T12:15:00"),
timestamp("2020-02-06T08:00:00"),
timestamp("2020-02-11T14:00:00"),
timestamp("2020-02-14T10:00:00"),
timestamp("2020-02-14T10:00:00"),
timestamp("2020-02-20T12:30:00"),
timestamp("2020-02-21T09:00:00"),
timestamp("2020-02-26T13:30:00"),
timestamp("2020-02-27T09:45:00"),
timestamp("2020-03-03T00:00:00"),
timestamp("2020-03-03T10:00:00"),
timestamp("2020-03-03T10:00:00"),
timestamp("2020-03-10T10:00:00"),
timestamp("2020-03-10T10:00:00"),
timestamp("2020-03-12T12:45:00"),
timestamp("2020-03-12T12:45:00"),
timestamp("2020-03-12T13:30:00"),
timestamp("2020-03-16T00:00:00"),
timestamp("2020-03-16T12:00:00"),
timestamp("2020-03-24T00:00:00"),
timestamp("2020-03-24T09:00:00"),
timestamp("2020-03-31T09:00:00"),
timestamp("2020-03-31T09:00:00"),
timestamp("2020-04-09T11:30:00"),
timestamp("2020-04-14T00:00:00"),
timestamp("2020-04-23T00:00:00"),
timestamp("2020-04-23T08:00:00"),
timestamp("2020-04-28T08:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T09:00:00"),
timestamp("2020-04-30T11:45:00"),
timestamp("2020-04-30T11:45:00"),
timestamp("2020-04-30T12:30:00"),
timestamp("2020-05-08T11:00:00"),
timestamp("2020-05-15T09:00:00"),
timestamp("2020-05-15T09:00:00"),
timestamp("2020-05-19T00:00:00"),
timestamp("2020-05-21T08:00:00"),
timestamp("2020-05-22T11:30:00"),
timestamp("2020-05-27T07:30:00"),
timestamp("2020-05-29T09:00:00"),
timestamp("2020-05-29T09:00:00"),
timestamp("2020-06-03T00:00:00"),
timestamp("2020-06-03T09:00:00"),
timestamp("2020-06-04T11:45:00"),
timestamp("2020-06-04T11:45:00"),
timestamp("2020-06-04T12:30:00"),
timestamp("2020-06-08T13:45:00"),
timestamp("2020-06-08T15:45:00"),
timestamp("2020-06-09T09:00:00"),
timestamp("2020-06-09T09:00:00"),
timestamp("2020-06-23T08:00:00"),
timestamp("2020-06-25T11:30:00"),
timestamp("2020-06-26T07:00:00"),
timestamp("2020-06-30T09:00:00"),
timestamp("2020-06-30T09:00:00"),
timestamp("2020-07-04T10:40:00"),
timestamp("2020-07-14T08:00:00"),
timestamp("2020-07-16T11:45:00"),
timestamp("2020-07-16T11:45:00"),
timestamp("2020-07-16T12:30:00"),
timestamp("2020-07-17T00:00:00"),
timestamp("2020-07-22T13:15:00"),
timestamp("2020-07-24T08:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-07-31T09:00:00"),
timestamp("2020-08-05T09:00:00"),
timestamp("2020-08-14T09:00:00"),
timestamp("2020-08-14T09:00:00"),
timestamp("2020-08-17T00:00:00"),
timestamp("2020-08-21T08:00:00"),
timestamp("2020-09-01T09:00:00"),
timestamp("2020-09-01T09:00:00"),
timestamp("2020-09-03T09:00:00"),
timestamp("2020-09-08T09:00:00"),
timestamp("2020-09-08T09:00:00"),
timestamp("2020-09-10T11:45:00"),
timestamp("2020-09-10T11:45:00"),
timestamp("2020-09-10T12:30:00"),
timestamp("2020-09-10T17:00:00"),
timestamp("2020-09-21T12:25:00"),
timestamp("2020-09-23T08:00:00"),
timestamp("2020-09-28T13:45:00"),
timestamp("2020-09-30T07:20:00"),
timestamp("2020-10-01T00:00:00"),
timestamp("2020-10-02T00:00:00"),
timestamp("2020-10-02T09:00:00"),
timestamp("2020-10-02T09:00:00"),
timestamp("2020-10-05T09:00:00"),
timestamp("2020-10-06T13:00:00"),
timestamp("2020-10-07T12:10:00"),
timestamp("2020-10-12T11:00:00"),
timestamp("2020-10-14T08:00:00"),
timestamp("2020-10-15T00:00:00"),
timestamp("2020-10-15T16:00:00"),
timestamp("2020-10-16T00:00:00"),
timestamp("2020-10-18T13:05:00"),
timestamp("2020-10-19T12:40:00"),
timestamp("2020-10-19T12:45:00"),
timestamp("2020-10-21T07:30:00"),
timestamp("2020-10-23T08:00:00"),
timestamp("2020-10-27T09:00:00"),
timestamp("2020-10-29T12:45:00"),
timestamp("2020-10-29T12:45:00"),
timestamp("2020-10-29T13:30:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-10-30T10:00:00"),
timestamp("2020-11-05T10:00:00"),
timestamp("2020-11-09T09:25:00"),
timestamp("2020-11-11T13:00:00"),
timestamp("2020-11-12T16:45:00"),
timestamp("2020-11-13T10:00:00"),
timestamp("2020-11-13T10:00:00"),
timestamp("2020-11-16T13:00:00"),
timestamp("2020-11-17T16:00:00"),
timestamp("2020-11-19T08:00:00"),
timestamp("2020-11-19T15:15:00"),
timestamp("2020-11-20T08:35:00"),
timestamp("2020-11-23T09:00:00"),
timestamp("2020-11-24T14:00:00"),
timestamp("2020-11-30T10:30:00"),
timestamp("2020-12-01T10:00:00"),
timestamp("2020-12-01T10:00:00"),
timestamp("2020-12-01T17:00:00"),
timestamp("2020-12-03T10:00:00"),
timestamp("2020-12-07T00:00:00"),
timestamp("2020-12-08T10:00:00"),
timestamp("2020-12-08T10:00:00"),
timestamp("2020-12-09T19:00:00"),
timestamp("2020-12-10T00:00:00"),
timestamp("2020-12-10T12:45:00"),
timestamp("2020-12-10T12:45:00"),
timestamp("2020-12-10T13:30:00"),
timestamp("2020-12-11T00:00:00"),
timestamp("2020-12-16T09:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-07T10:00:00"),
timestamp("2021-01-11T14:40:00"),
timestamp("2021-01-13T09:00:00"),
timestamp("2021-01-19T09:00:00"),
timestamp("2021-01-21T12:45:00"),
timestamp("2021-01-21T12:45:00"),
timestamp("2021-01-21T13:30:00"),
timestamp("2021-01-22T09:00:00"),
timestamp("2021-01-25T08:45:00"),
timestamp("2021-01-25T16:15:00"),
timestamp("2021-02-02T10:00:00"),
timestamp("2021-02-02T10:00:00"),
timestamp("2021-02-03T10:00:00"),
timestamp("2021-02-03T10:00:00"),
timestamp("2021-02-04T10:00:00"),
timestamp("2021-02-12T00:00:00"),
timestamp("2021-02-16T10:00:00"),
timestamp("2021-02-16T10:00:00"),
timestamp("2021-02-18T12:30:00"),
timestamp("2021-02-19T09:00:00"),
timestamp("2021-02-22T14:30:00"),
timestamp("2021-03-01T16:10:00"),
timestamp("2021-03-02T10:00:00"),
timestamp("2021-03-02T10:00:00"),
timestamp("2021-03-04T10:00:00"),
timestamp("2021-03-09T10:00:00"),
timestamp("2021-03-09T10:00:00"),
timestamp("2021-03-11T12:45:00"),
timestamp("2021-03-11T12:45:00"),
timestamp("2021-03-11T13:30:00"),
timestamp("2021-03-18T08:00:00"),
timestamp("2021-03-18T11:00:00"),
timestamp("2021-03-24T09:00:00"),
timestamp("2021-03-24T15:40:00"),
timestamp("2021-03-25T00:00:00"),
timestamp("2021-03-25T09:30:00"),
timestamp("2021-03-26T00:00:00"),
timestamp("2021-03-31T09:00:00"),
timestamp("2021-03-31T09:00:00"),
timestamp("2021-04-12T09:00:00"),
timestamp("2021-04-14T14:00:00"),
timestamp("2021-04-20T08:00:00"),
timestamp("2021-04-22T11:45:00"),
timestamp("2021-04-22T11:45:00"),
timestamp("2021-04-22T12:30:00"),
timestamp("2021-04-23T08:00:00"),
timestamp("2021-04-23T14:30:00"),
timestamp("2021-04-28T14:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-04-30T09:00:00"),
timestamp("2021-05-06T09:00:00"),
timestamp("2021-05-06T11:25:00"),
timestamp("2021-05-07T10:00:00"),
timestamp("2021-05-18T09:00:00"),
timestamp("2021-05-18T09:00:00"),
timestamp("2021-05-18T14:00:00"),
timestamp("2021-05-20T12:00:00"),
timestamp("2021-05-21T08:00:00"),
timestamp("2021-05-21T11:00:00"),
timestamp("2021-06-01T09:00:00"),
timestamp("2021-06-01T09:00:00"),
timestamp("2021-06-02T17:10:00"),
timestamp("2021-06-04T09:00:00"),
timestamp("2021-06-08T09:00:00"),
timestamp("2021-06-08T09:00:00"),
timestamp("2021-06-10T11:45:00"),
timestamp("2021-06-10T11:45:00"),
timestamp("2021-06-10T12:30:00"),
timestamp("2021-06-11T00:00:00"),
timestamp("2021-06-12T00:00:00"),
timestamp("2021-06-13T00:00:00"),
timestamp("2021-06-21T12:30:00"),
timestamp("2021-06-21T14:15:00"),
timestamp("2021-06-23T08:00:00"),
timestamp("2021-06-23T18:00:00"),
timestamp("2021-06-24T00:00:00"),
timestamp("2021-06-25T00:00:00"),
timestamp("2021-06-29T13:40:00"),
timestamp("2021-06-30T09:00:00"),
timestamp("2021-06-30T09:00:00"),
timestamp("2021-07-01T07:00:00"),
timestamp("2021-07-02T12:30:00"),
timestamp("2021-07-06T09:00:00"),
timestamp("2021-07-08T11:00:00"),
timestamp("2021-07-08T12:30:00"),
timestamp("2021-07-09T10:00:00"),
timestamp("2021-07-11T12:10:00"),
timestamp("2021-07-20T08:00:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T11:45:00"),
timestamp("2021-07-22T12:30:00"),
timestamp("2021-07-23T08:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T09:00:00"),
timestamp("2021-07-30T14:00:00"),
timestamp("2021-08-04T09:00:00"),
timestamp("2021-08-17T09:00:00"),
timestamp("2021-08-17T09:00:00"),
timestamp("2021-08-23T08:00:00"),
timestamp("2021-08-25T08:30:00"),
timestamp("2021-08-31T09:00:00"),
timestamp("2021-08-31T09:00:00"),
timestamp("2021-09-03T09:00:00"),
timestamp("2021-09-07T09:00:00"),
timestamp("2021-09-07T09:00:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T11:45:00"),
timestamp("2021-09-09T12:30:00"),
timestamp("2021-09-10T09:30:00"),
timestamp("2021-09-13T13:30:00"),
timestamp("2021-09-16T12:00:00"),
timestamp("2021-09-23T08:00:00"),
timestamp("2021-09-27T11:45:00"),
timestamp("2021-09-28T12:00:00"),
timestamp("2021-09-29T15:45:00"),
timestamp("2021-09-29T16:30:00"),
timestamp("2021-10-01T09:00:00"),
timestamp("2021-10-01T09:00:00"),
timestamp("2021-10-05T15:00:00"),
timestamp("2021-10-06T09:00:00"),
timestamp("2021-10-08T12:10:00"),
timestamp("2021-10-16T14:00:00"),
timestamp("2021-10-21T00:00:00"),
timestamp("2021-10-22T08:00:00"),
timestamp("2021-10-26T08:00:00"),
timestamp("2021-10-27T15:20:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T11:45:00"),
timestamp("2021-10-28T12:30:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-10-29T09:00:00"),
timestamp("2021-11-03T10:15:00"),
timestamp("2021-11-04T13:00:00"),
timestamp("2021-11-05T10:00:00"),
timestamp("2021-11-09T13:00:00"),
timestamp("2021-11-15T10:00:00"),
timestamp("2021-11-16T10:00:00"),
timestamp("2021-11-16T10:00:00"),
timestamp("2021-11-16T16:10:00"),
timestamp("2021-11-17T01:20:00"),
timestamp("2021-11-19T08:30:00"),
timestamp("2021-11-19T18:45:00"),
timestamp("2021-11-23T09:00:00"),
timestamp("2021-11-25T13:30:00"),
timestamp("2021-11-26T08:00:00"),
timestamp("2021-11-29T08:00:00"),
timestamp("2021-11-30T10:00:00"),
timestamp("2021-11-30T10:00:00"),
timestamp("2021-12-03T08:30:00"),
timestamp("2021-12-03T10:00:00"),
timestamp("2021-12-07T10:00:00"),
timestamp("2021-12-07T10:00:00"),
timestamp("2021-12-10T09:05:00"),
timestamp("2021-12-16T00:00:00"),
timestamp("2021-12-16T09:00:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T12:45:00"),
timestamp("2021-12-16T13:30:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-07T10:00:00"),
timestamp("2022-01-11T10:20:00"),
timestamp("2022-01-14T13:15:00"),
timestamp("2022-01-21T12:30:00"),
timestamp("2022-01-24T09:00:00"),
timestamp("2022-01-31T10:00:00"),
timestamp("2022-01-31T10:00:00"),
timestamp("2022-02-01T09:00:00"),
timestamp("2022-02-02T10:00:00"),
timestamp("2022-02-02T10:00:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T12:45:00"),
timestamp("2022-02-03T13:30:00"),
timestamp("2022-02-04T10:00:00"),
timestamp("2022-02-07T15:45:00"),
timestamp("2022-02-14T16:15:00"),
timestamp("2022-02-15T10:00:00"),
timestamp("2022-02-15T10:00:00"),
timestamp("2022-02-21T09:00:00"),
timestamp("2022-02-25T14:00:00"),
timestamp("2022-02-28T15:50:00"),
timestamp("2022-03-01T13:00:00"),
timestamp("2022-03-02T10:00:00"),
timestamp("2022-03-02T10:00:00"),
timestamp("2022-03-02T14:30:00"),
timestamp("2022-03-04T10:00:00"),
timestamp("2022-03-08T10:00:00"),
timestamp("2022-03-08T10:00:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T12:45:00"),
timestamp("2022-03-10T13:30:00"),
timestamp("2022-03-15T15:15:00"),
timestamp("2022-03-17T09:30:00"),
timestamp("2022-03-21T07:30:00"),
timestamp("2022-03-22T13:15:00"),
timestamp("2022-03-24T09:00:00"),
timestamp("2022-03-30T08:00:00"),
timestamp("2022-04-01T09:00:00"),
timestamp("2022-04-01T09:00:00"),
timestamp("2022-04-07T09:00:00"),
timestamp("2022-04-12T08:00:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T11:45:00"),
timestamp("2022-04-14T12:30:00"),
timestamp("2022-04-21T17:00:00"),
timestamp("2022-04-22T08:00:00"),
timestamp("2022-04-22T13:00:00"),
timestamp("2022-04-27T16:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-04-29T09:00:00"),
timestamp("2022-05-03T13:00:00"),
timestamp("2022-05-04T09:00:00"),
timestamp("2022-05-11T08:00:00"),
timestamp("2022-05-17T09:00:00"),
timestamp("2022-05-17T09:00:00"),
timestamp("2022-05-17T17:00:00"),
timestamp("2022-05-24T08:00:00"),
timestamp("2022-05-24T18:00:00"),
timestamp("2022-05-25T08:00:00"),
timestamp("2022-05-31T09:00:00"),
timestamp("2022-05-31T09:00:00"),
timestamp("2022-06-01T11:00:00"),
timestamp("2022-06-03T09:00:00"),
timestamp("2022-06-08T09:00:00"),
timestamp("2022-06-08T09:00:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T11:45:00"),
timestamp("2022-06-09T12:30:00"),
timestamp("2022-06-15T09:00:00"),
timestamp("2022-06-15T16:20:00"),
timestamp("2022-06-20T13:00:00"),
timestamp("2022-06-23T08:00:00"),
timestamp("2022-06-27T18:30:00"),
timestamp("2022-06-28T08:00:00"),
timestamp("2022-06-29T13:00:00"),
timestamp("2022-06-29T15:00:00"),
timestamp("2022-07-01T09:00:00"),
timestamp("2022-07-01T09:00:00"),
timestamp("2022-07-06T09:00:00"),
timestamp("2022-07-08T11:55:00"),
timestamp("2022-07-19T08:00:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:15:00"),
timestamp("2022-07-21T12:45:00"),
timestamp("2022-07-21T14:15:00"),
timestamp("2022-07-22T08:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-07-29T09:00:00"),
timestamp("2022-08-03T09:00:00"),
timestamp("2022-08-17T09:00:00"),
timestamp("2022-08-17T09:00:00"),
timestamp("2022-08-23T08:00:00"),
timestamp("2022-08-31T09:00:00"),
timestamp("2022-08-31T09:00:00"),
timestamp("2022-09-05T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-07T09:00:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:15:00"),
timestamp("2022-09-08T12:45:00"),
timestamp("2022-09-08T14:15:00"),
timestamp("2022-09-09T09:30:00"),
timestamp("2022-09-14T10:00:00"),
timestamp("2022-09-16T08:30:00"),
timestamp("2022-09-20T17:00:00"),
timestamp("2022-09-23T08:00:00"),
timestamp("2022-09-26T13:00:00"),
timestamp("2022-09-27T11:30:00"),
timestamp("2022-09-28T07:15:00"),
timestamp("2022-09-30T09:00:00"),
timestamp("2022-09-30T09:00:00"),
timestamp("2022-10-04T15:00:00"),
timestamp("2022-10-06T09:00:00"),
timestamp("2022-10-12T13:30:00"),
timestamp("2022-10-22T09:00:00"),
timestamp("2022-10-24T08:00:00"),
timestamp("2022-10-25T08:00:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:15:00"),
timestamp("2022-10-27T12:45:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-10-31T10:00:00"),
timestamp("2022-11-03T08:05:00"),
timestamp("2022-11-04T09:30:00"),
timestamp("2022-11-07T08:40:00"),
timestamp("2022-11-08T10:00:00"),
timestamp("2022-11-15T10:00:00"),
timestamp("2022-11-15T10:00:00"),
timestamp("2022-11-16T17:00:00"),
timestamp("2022-11-18T08:30:00"),
timestamp("2022-11-23T09:00:00"),
timestamp("2022-11-28T14:00:00"),
timestamp("2022-11-30T10:00:00"),
timestamp("2022-11-30T10:00:00"),
timestamp("2022-12-02T02:40:00"),
timestamp("2022-12-03T02:30:00"),
timestamp("2022-12-05T10:00:00"),
timestamp("2022-12-07T10:00:00"),
timestamp("2022-12-07T10:00:00"),
timestamp("2022-12-08T12:00:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:15:00"),
timestamp("2022-12-15T13:45:00"),
timestamp("2022-12-16T09:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-06T10:00:00"),
timestamp("2023-01-19T10:30:00"),
timestamp("2023-01-20T10:00:00"),
timestamp("2023-01-23T17:45:00"),
timestamp("2023-01-24T09:00:00"),
timestamp("2023-01-24T09:45:00"),
timestamp("2023-01-31T09:00:00"),
timestamp("2023-01-31T10:00:00"),
timestamp("2023-01-31T10:00:00"),
timestamp("2023-02-01T10:00:00"),
timestamp("2023-02-01T10:00:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:15:00"),
timestamp("2023-02-02T13:45:00"),
timestamp("2023-02-02T18:30:00"),
timestamp("2023-02-06T10:00:00"),
timestamp("2023-02-06T18:00:00"),
timestamp("2023-02-14T10:00:00"),
timestamp("2023-02-14T10:00:00"),
timestamp("2023-02-15T14:00:00"),
timestamp("2023-02-21T09:00:00"),
timestamp("2023-02-21T15:00:00"),
timestamp("2023-03-02T07:55:00"),
timestamp("2023-03-02T10:00:00"),
timestamp("2023-03-02T10:00:00"),
timestamp("2023-03-06T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-08T10:00:00"),
timestamp("2023-03-10T15:00:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:15:00"),
timestamp("2023-03-16T13:45:00"),
timestamp("2023-03-20T14:00:00"),
timestamp("2023-03-20T16:00:00"),
timestamp("2023-03-21T12:30:00"),
timestamp("2023-03-22T08:45:00"),
timestamp("2023-03-24T09:00:00"),
timestamp("2023-03-28T13:15:00"),
timestamp("2023-03-31T09:00:00"),
timestamp("2023-03-31T09:00:00"),
timestamp("2023-04-11T09:00:00"),
timestamp("2023-04-17T17:00:00"),
timestamp("2023-04-20T12:00:00"),
timestamp("2023-04-21T08:00:00"),
timestamp("2023-04-28T09:00:00"),
timestamp("2023-04-28T09:00:00"),
timestamp("2023-05-02T08:00:00"),
timestamp("2023-05-02T09:00:00"),
timestamp("2023-05-02T09:00:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:15:00"),
timestamp("2023-05-04T12:45:00"),
timestamp("2023-05-05T09:00:00"),
timestamp("2023-05-11T12:00:00"),
timestamp("2023-05-16T09:00:00"),
timestamp("2023-05-16T09:00:00"),
timestamp("2023-05-16T14:00:00"),
timestamp("2023-05-18T09:00:00"),
timestamp("2023-05-23T08:00:00"),
timestamp("2023-05-24T17:45:00"),
timestamp("2023-05-31T12:30:00"),
timestamp("2023-06-01T09:00:00"),
timestamp("2023-06-01T09:00:00"),
timestamp("2023-06-01T09:30:00"),
timestamp("2023-06-05T13:00:00"),
timestamp("2023-06-06T09:00:00"),
timestamp("2023-06-08T09:00:00"),
timestamp("2023-06-08T09:00:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:15:00"),
timestamp("2023-06-15T12:45:00"),
timestamp("2023-06-23T07:00:00"),
timestamp("2023-06-23T08:00:00"),
timestamp("2023-06-26T19:00:00"),
timestamp("2023-06-27T08:00:00"),
timestamp("2023-06-28T13:30:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-06-30T09:00:00"),
timestamp("2023-07-06T09:00:00"),
timestamp("2023-07-18T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-24T08:00:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:15:00"),
timestamp("2023-07-27T12:45:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-07-31T09:00:00"),
timestamp("2023-08-04T09:00:00"),
timestamp("2023-08-16T09:00:00"),
timestamp("2023-08-16T09:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-23T08:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-08-31T09:00:00"),
timestamp("2023-09-06T09:00:00"),
timestamp("2023-09-07T09:00:00"),
timestamp("2023-09-07T09:00:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:15:00"),
timestamp("2023-09-14T12:45:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-22T08:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-09-29T09:00:00"),
timestamp("2023-10-04T09:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-24T08:00:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:15:00"),
timestamp("2023-10-26T12:45:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-10-31T10:00:00"),
timestamp("2023-11-08T10:00:00"),
timestamp("2023-11-14T10:00:00"),
timestamp("2023-11-14T10:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-21T09:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-11-30T10:00:00"),
timestamp("2023-12-06T10:00:00"),
timestamp("2023-12-07T10:00:00"),
timestamp("2023-12-07T10:00:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:15:00"),
timestamp("2023-12-14T13:45:00"),
timestamp("2023-12-20T09:00:00"),
timestamp("2023-12-20T09:00:00"),
timestamp("2023-12-20T09:00:00")
) |
lib_drawing_composites | https://www.tradingview.com/script/yW7VH3dm-lib-drawing-composites/ | robbatt | https://www.tradingview.com/u/robbatt/ | 2 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © robbatt, extending Trendoscope's https://www.tradingview.com/script/eNM7BFaR-DrawingMethods/
//@version=5
//@description methods to draw and manage composite obejects. Based on Trendoscope's https://www.tradingview.com/script/eNM7BFaR-DrawingMethods/, added Triangle and Polygon composite objects, fixed tostring method output to be actual json
library("lib_drawing_composites", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as D
import HeWhoMustNotBeNamed/DrawingMethods/2
import robbatt/lib_drawing_composite_types/1 as DC
//******************************************************************* json *******************************************************/
// @function Converts lib_drawing_types/Point object to a json string representation
// @param this lib_drawing_types/Point object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Point
export method tostring(D.Point this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
(format_date ?
str.format('{0}{1}"bar": {2},{0}{1}"bartime": "{3}",{0}{1}"price": {4}{0}', separator, tab, this.bar, str.format_time(this.bartime, format, tz), this.price) :
str.format('{0}{1}"bar": {2},{0}{1}"bartime": {3},{0}{1}"price": {4}{0}', separator, tab, this.bar, this.bartime, this.price)
) + '}'
// @function Converts lib_drawing_types/LineProperties object to a json string representation
// @param this lib_drawing_types/LineProperties object
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/LineProperties
export method tostring(D.LineProperties this, simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' + str.format('{0}{1}"xloc": "{2}",{0}{1}"extend": "{3}",{0}{1}"style": "{4}",{0}{1}"width": {5}{0}', separator, tab, this.xloc, this.extend, this.style, this.width) + '}'
// @function Converts lib_drawing_types/Line object to a json string representation
// @param this lib_drawing_types/Line object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @returns string representation of lib_drawing_types/Line
export method tostring(D.Line this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"start": {2},{0}{1}"end": {3},{0}{1}"properties": {4}{0}', separator, tab,
this.start.tostring(format_date, format, tz, pretty),
this.end.tostring(format_date, format, tz, pretty),
this.properties.tostring(pretty)
) + '}'
// @function Converts lib_drawing_types/LabelProperties object to a json string representation
// @param this lib_drawing_types/LabelProperties object
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/LabelProperties
export method tostring(D.LabelProperties this, simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"xloc": "{2}",{0}{1}"yloc": "{3}",{0}{1}"style": "{4}",{0}{1}"size": "{5}",{0}{1}"textalign": "{6}",{0}{1}"text_font_family": "{7}"{0}', separator, tab, this.xloc, this.yloc, this.style, this.size, this.textalign, this.text_font_family )
+ '}'
// @function Converts lib_drawing_types/Label object to a json string representation
// @param this lib_drawing_types/Label object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Label
export method tostring(D.Label this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"point": {2},{0}{1}"labeltext": "{3}",{0}{1}"tooltip": "{4}",{0}{1}"properties": {5}{0}', separator, tab,
this.point.tostring(format_date, format, tz, pretty),
this.lblText,
this.tooltip,
this.properties.tostring(pretty)
) + '}'
// @function Converts lib_drawing_types/Linefill object to a json string representation
// @param this lib_drawing_types/Linefill object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Linefill
export method tostring(D.Linefill this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'':'{' +
str.format('{0}{1}"line1": {2},{0}{1}"line2": {3},{0}{1}"transparency": {4}{0}', separator, tab,
this.line1.tostring(format_date, format, tz, pretty),
this.line2.tostring(format_date, format, tz, pretty),
this.transparency
) + '}'
// @function Converts lib_drawing_types/BoxProperties object to a json string representation
// @param this lib_drawing_types/BoxProperties object
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/BoxProperties
export method tostring(D.BoxProperties this, simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"border_width": {2},{0}{1}"border_style": "{3}",{0}{1}"extend": "{4}",{0}{1}"xloc": "{5}"{0}', separator, tab,
this.border_width,
this.border_style,
this.extend,
this.xloc
) + '}'
// @function Converts lib_drawing_types/BoxText object to a json string representation
// @param this lib_drawing_types/BoxText object
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/BoxText
export method tostring(D.BoxText this, simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"boxText": "{2}",{0}{1}"text_size": "{3}",{0}{1}"text_halign": "{4}",{0}{1}"text_valign": "{5}",{0}{1}"text_wrap": "{6}",{0}{1}"text_font_family": "{7}"{0}', separator, tab,
this.boxText,
this.text_size,
this.text_valign,
this.text_wrap,
this.text_font_family
) + '}'
// @function Converts lib_drawing_types/Box object to a json string representation
// @param this lib_drawing_types/Box object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Box
export method tostring(D.Box this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"p1": {2},{0}{1}"p2": {3},{0}{1}"properties": {4},{0}{1}"text_properties": {5}{0}', separator, tab,
this.p1.tostring(format_date, format, tz, pretty),
this.p2.tostring(format_date, format, tz, pretty),
this.properties.tostring(pretty),
this.textProperties.tostring(pretty)
) + '}'
// @function Converts lib_drawing_types/TriangleProperties object to a json string representation
// @param this lib_drawing_types/TriangleProperties object
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/TriangleProperties
export method tostring(DC.TriangleProperties this, simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"fill_transparency": {2},{0}{1}"border_width": {3},{0}{1}"border_style": "{4}",{0}{1}"xloc": "{5}"{0}', separator, tab,
this.fill_transparency,
this.border_width,
this.border_style,
this.xloc
) + '}'
// @function Converts lib_drawing_types/Triangle object to a json string representation
// @param this lib_drawing_types/Triangle object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Triangle
export method tostring(DC.Triangle this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"p1": {2},{0}{1}"p2": {3},{0}{1}"p3": {4},{0}{1}"properties": {5},{0}', separator, tab,
this.p1.tostring(format_date, format, tz, pretty),
this.p2.tostring(format_date, format, tz, pretty),
this.p3.tostring(format_date, format, tz, pretty),
this.properties.tostring(pretty)
) + '}'
// @function Converts lib_drawing_types/Trianglefill object to a json string representation
// @param this lib_drawing_types/Trianglefill object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/TriangleProperties
export method tostring(DC.Trianglefill this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
var separator = pretty?'\n':' '
var tab = pretty?' ':''
na(this)?'null':'{' +
str.format('{0}{1}"triangle": {2},{0}{1}"transparency": {3}{0}', separator, tab,
this.triangle.tostring(format_date, format, tz, pretty),
this.transparency
) + '}'
// @function Converts a Polygon object to a json string representation
// @param this Polygon object array
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of Pivot object array
export method tostring(DC.Polygon this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
if na(this)
'null'
else if na(this.triangles)
'null'
else
array<string> combinedStr = array.new<string>()
for triangle in this.triangles
combinedStr.push(triangle.tostring(format_date, format, tz, pretty))
'['+array.join(combinedStr, ",")+']'
// @function Converts lib_drawing_types/Polygonfill object to a json string representation
// @param this lib_drawing_types/Polygonfill object
// @param format_date whether to format the bartime integer (unix timestamp) into a human readable format
// @param format the format for bartime (default: "yyyy-MM-dd HH:mm")
// @param tz the timezone for bartime, e.g. 'UTC+1' (default: exchange time zone)
// @param pretty if true adds a line feed after every property and a space before properties (default: true)
// @returns string representation of lib_drawing_types/Polygonfill
export method tostring(DC.Polygonfill this, simple bool format_date = true, simple string format = "yyyy-MM-dd HH:mm", simple string tz = 'UTC', simple bool pretty = false)=>
if na(this)
'null'
else if na(this._fills)
'null'
else
array<string> combinedStr = array.new<string>()
for fill in this._fills
combinedStr.push(fill.tostring(format_date, format, tz, pretty))
'['+array.join(combinedStr, ",")+']'
//******************************************************************* delete and clear *******************************************************/
deleteObj(this)=>
this.object.delete()
this
// @function Deletes Trianglefill from lib_drawing_types/Trianglefill object
// @param this lib_drawing_types/Trianglefill object
// @returns Trianglefill object deleted
export method delete(DC.Trianglefill this)=>deleteObj(this)
// @function Deletes Triangle from lib_drawing_types/Triangle object
// @param this lib_drawing_types/Triangle object
// @returns Triangle object deleted
export method delete(DC.Triangle this)=>
this.l12.delete()
this.l23.delete()
this.l31.delete()
this
deleteAll(this)=>
if(not na(this))
for obj in this
obj.delete()
this
// @function Deletes Triangle from array of lib_drawing_types/Triangle objects
// @param this Array of lib_drawing_types/Triangle objects
// @returns Array of lib_drawing_types/Triangle objects
export method delete(array<DC.Triangle> this)=>deleteAll(this)
// @function Deletes Trianglefill from array of lib_drawing_types/Trianglefill objects
// @param this Array of lib_drawing_types/Trianglefill objects
// @returns Array of lib_drawing_types/Trianglefill objects
export method delete(array<DC.Trianglefill> this)=>deleteAll(this)
// @function Deletes Triangle from lib_drawing_types/Triangle object
// @param this lib_drawing_types/Triangle object
// @returns Triangle object deleted
export method delete(DC.Polygon this)=>deleteAll(this.triangles)
// @function Deletes Polygonfill from lib_drawing_types/Polygonfill object
// @param this lib_drawing_types/Polygonfill object
// @returns Polygonfill object deleted
export method delete(DC.Polygonfill this)=>deleteAll(this._fills)
// @function Deletes Polygon from array of lib_drawing_types/Polygon objects
// @param this Array of lib_drawing_types/Polygon objects
// @returns Array of lib_drawing_types/Polygon objects
export method delete(array<DC.Polygon> this)=>
if not na(this)
for p in this
p.delete()
// @function Deletes Polygonfill from array of lib_drawing_types/Polygonfill objects
// @param this Array of lib_drawing_types/Polygonfill objects
// @returns Array of lib_drawing_types/Polygonfill objects
export method delete(array<DC.Polygonfill> this)=>
if not na(this)
for p in this
p.delete()
// @function clear items from array of lib_drawing_types/Triangle while deleting underlying objects
// @param this array<lib_drawing_types/Triangle>
// @returns void
export method clear(array<DC.Triangle> this)=>this.delete().clear()
// @function clear items from array of lib_drawing_types/Trianglefill while deleting underlying objects
// @param this array<lib_drawing_types/Trianglefill>
// @returns void
export method clear(array<DC.Trianglefill> this)=>this.delete().clear()
// @function clear items from array of lib_drawing_types/Polygon while deleting underlying objects
// @param this array<lib_drawing_types/Polygon>
// @returns void
export method clear(array<DC.Polygon> this)=>this.delete().clear()
// @function clear items from array of lib_drawing_types/Polygonfill while deleting underlying objects
// @param this array<lib_drawing_types/Polygonfill>
// @returns void
export method clear(array<DC.Polygonfill> this)=>this.delete().clear()
//******************************************************************* draw *******************************************************/
// @function Creates Triangle object from lib_drawing_types/Triangle
// @param this lib_drawing_types/Triangle objects
// @returns Triangle object created
export method draw(DC.Triangle this, bool is_polygon_section = false)=>
this.l12.delete()
this.l23.delete()
this.l31.delete()
this.properties := na(this.properties)? DC.TriangleProperties.new() : this.properties
if(not na(this.p1) and not na(this.p2) and not na(this.p3))
x1 = this.properties.xloc == xloc.bar_index ? this.p1.bar : this.p1.bartime
x2 = this.properties.xloc == xloc.bar_index ? this.p2.bar : this.p2.bartime
x3 = this.properties.xloc == xloc.bar_index ? this.p3.bar : this.p3.bartime
this.l23 := line.new(x2, this.p2.price, x3, this.p3.price, this.properties.xloc, style = this.properties.border_style, width = this.properties.border_width, color = this.properties.border_color)
this.l12 := line.new(x1, this.p1.price, x2, this.p2.price, this.properties.xloc, style = this.properties.border_style, width = this.properties.border_width, color = is_polygon_section ? #00000000 :this.properties.border_color)
this.l31 := line.new(x1, this.p1.price, x3, this.p3.price, this.properties.xloc, style = this.properties.border_style, width = this.properties.border_width, color = is_polygon_section ? #00000000 :this.properties.border_color)
this
// @function Creates Trianglefill object from lib_drawing_types/Trianglefill
// @param this lib_drawing_types/Trianglefill objects
// @returns Trianglefill object created
export method draw(DC.Trianglefill this)=>
this.object.delete()
if not na(this.triangle)
this.object := linefill.new(this.triangle.l12, this.triangle.l31, color.new(this.fill_color, this.transparency))
this
// @function Creates Triangles from array of lib_drawing_types/Triangle objects
// @param this Array of lib_drawing_types/Triangle objects
// @returns Array of lib_drawing_types/Triangle objects
export method draw(array<DC.Triangle> this, bool is_polygon = false)=>
if not na(this)
for t in this
t.draw(is_polygon)
this
// @function Creates Polygon object from lib_drawing_types/Polygon
// @param this lib_drawing_types/Polygon objects
// @returns Polygon object
export method draw(DC.Polygon this)=>
draw(this.triangles, is_polygon = true)
this
drawAll(this)=>
if(not na(this))
for obj in this
obj.draw()
this
// @function Creates Trianglefill from array of lib_drawing_types/Trianglefill objects
// @param this Array of lib_drawing_types/Trianglefill objects
// @returns Array of lib_drawing_types/Trianglefill objects
export method draw(array<DC.Trianglefill> this)=>
if not na(this)
for f in this
f.draw()
// @function Creates Polygonfill object from lib_drawing_types/Polygonfill
// @param this lib_drawing_types/Polygonfill objects
// @returns Polygonfill object
export method draw(DC.Polygonfill this)=>
draw(this._fills)
this
// @function Creates Polygons from array of lib_drawing_types/Polygon objects
// @param this Array of lib_drawing_types/Polygon objects
// @returns Array of lib_drawing_types/Polygon objects
export method draw(array<DC.Polygon> this)=>
if not na(this)
for p in this
p.draw()
this
// @function Creates Polygonfills from array of lib_drawing_types/Polygonfill objects
// @param this Array of lib_drawing_types/Polygonfill objects
// @returns Array of lib_drawing_types/Polygonfill objects
export method draw(array<DC.Polygonfill> this)=>
if not na(this)
for pf in this
pf._fills.draw()
this
//******************************************************************* createXXX *******************************************************/
// @function Creates centered lib_drawing_types/Point object between two lib_drawing_types/Points
// @param this lib_drawing_types/Point object
// @param other lib_drawing_types/Point object
// @returns lib_drawing_types/Label object
export method createCenter(D.Point this, D.Point other)=>
t_center = int(math.avg(this.bartime, other.bartime))
b_center = int(math.avg(this.bar, other.bar))
p_center = other.price + (this.price - other.price) * (b_center - other.bar) / (this.bar - other.bar)
D.Point.new(p_center, b_center, t_center)
// @function Creates centered lib_drawing_types/Point object between an array of given Points
// @param this lib_drawing_types/Point objects
// @param other1 lib_drawing_types/Point object
// @param other2 lib_drawing_types/Point object
// @returns lib_drawing_types/Point object
export method createCenter(array<D.Point> this)=>
t_center = 0.0
b_center = 0.0
p_center = 0.0
for point in this
t_center += point.bartime
b_center += point.bar
p_center += point.price
count = this.size()
t_center /= count
b_center /= count
p_center /= count
D.Point.new(p_center, int(b_center), int(t_center))
// @function Creates centered lib_drawing_types/Point object between three lib_drawing_types/Points
// @param this lib_drawing_types/Point object
// @param other1 lib_drawing_types/Point object
// @param other2 lib_drawing_types/Point object
// @returns lib_drawing_types/Point object
export method createCenter(D.Point this, D.Point other1, D.Point other2)=>
array.from(this, other1, other2).createCenter()
// @function Creates lib_drawing_types/Label centered between lib_drawing_types/Line endpoints, using bar_index for calculation
// @param this lib_drawing_types/Line object
// @param labeltext Label text
// @param tooltip Tooltip text. Default is na
// @param properties lib_drawing_types/LabelProperties object. Default is na - meaning default values are used.
// @returns lib_drawing_types/Label object
export method createLabel(D.Line this, string labeltext, string tooltip=na, D.LabelProperties properties=na)=>
D.Label.new(this.start.createCenter(this.end), labeltext, tooltip, na(properties)?D.LabelProperties.new():properties)
// @function Creates lib_drawing_types/Label centered between lib_drawing_types/Line endpoints, using bar_index for calculation
// @param this lib_drawing_types/Line object
// @param labeltext Label text
// @param tooltip Tooltip text. Default is na
// @param properties lib_drawing_types/LabelProperties object. Default is na - meaning default values are used.
// @returns lib_drawing_types/Label object
export method createLabel(DC.Triangle this, string labeltext, string tooltip=na, D.LabelProperties properties=na)=>
D.Label.new(this.p1.createCenter(this.p2, this.p3), labeltext, tooltip, na(properties)?D.LabelProperties.new():properties)
// @function Creates lib_drawing_types/Line object from one lib_drawing_types/Point to other
// @param this First lib_drawing_types/Point object
// @param other Second lib_drawing_types/Point object
// @param properties lib_drawing_types/LineProperties object. Default set to na - meaning default values are used.
// @returns lib_drawing_types/Line object
export method createTriangle(D.Point this, D.Point p2, D.Point p3, DC.TriangleProperties properties = na)=>
DC.Triangle.new(this, p2, p3, na(properties)? DC.TriangleProperties.new():properties)
// @function Creates lib_drawing_types/Trianglefill object from lib_drawing_types/Triangle object
// @param this lib_drawing_types/Trianglefill object
// @param fill_color fill color of linefill. Default is color.blue
// @param transparency fill transparency for linefill. Default is 80
// @returns Array of lib_drawing_types/Linefill object
export method createTrianglefill(DC.Triangle this, color fill_color=chart.fg_color, int transparency=93)=>
DC.Trianglefill.new(this, fill_color, transparency)
// @function Creates lib_drawing_types/Polygonfill object from lib_drawing_types/Polygon object
// @param this lib_drawing_types/Polygon object
// @param fill_color fill color of linefill. Default is chart.fg_color
// @param transparency fill transparency for Polygonfill. Default is 93
// @returns a lib_drawing_types/Polygonfill object
export method createPolygonfill(DC.Polygon this, color fill_color=chart.fg_color, int transparency=93)=>
if na(this.triangles)
na
else
fills = array.new<DC.Trianglefill>(this.triangles.size())
for [i, triangle] in this.triangles
fills.set(i, DC.Trianglefill.new(triangle, fill_color, transparency))
DC.Polygonfill.new(this, fills)
// @function Creates lib_drawing_types/Line object from one lib_drawing_types/Point to other
// @param this First lib_drawing_types/Point object
// @param other Second lib_drawing_types/Point object
// @param properties lib_drawing_types/LineProperties object. Default set to na - meaning default values are used.
// @returns lib_drawing_types/Line object
export method createPolygon(array<D.Point> points, DC.TriangleProperties properties)=>
if na(points)
DC.Polygon.new(na, array.new<DC.Triangle>())
else if points.size() < 3
DC.Polygon.new(na, array.new<DC.Triangle>())
else
count = points.size()
maxIdx = count-1
center = points.createCenter()
triangles = array.new<DC.Triangle>(count, center.createTriangle(points.get(0), points.get(maxIdx), properties))
for i = 1 to maxIdx
triangles.set(i, center.createTriangle(points.get(i-1), points.get(i), properties))
DC.Polygon.new(center, triangles)
// ###################################################################### Tests #############################################################
import robbatt/lib_log/6
var l = lib_log.Logger.new(min_level = 1, color_logs = true)
hh = ta.highest(high, 15)
hh_bars = ta.highestbars(high, 15)
hh_bar = bar_index[-hh_bars]
hh_time = time[-hh_bars]
l.debug(str.format('hh - bar: {0}, price: {1}', hh_bar, hh))
ll = ta.lowest(low, 15)
ll_bars = ta.lowestbars(low, 15)
ll_bar = bar_index[-ll_bars]
ll_time = time[-ll_bars]
l.debug(str.format('ll - bar: {0}, price: {1}', ll_bar, ll))
if barstate.islast
D.Point p1 = D.Point.new (high, bar_index, time)
D.Point p2 = D.Point.new (high[10], bar_index[10], time[10])
D.Point p3 = D.Point.new (high[15], bar_index[15], time[15])
D.Point p4 = D.Point.new (high[21], bar_index[21], time[21])
D.Point phh = D.Point.new(hh, hh_bar, hh_time)
D.Point pll = D.Point.new(ll, ll_bar, ll_time)
l.debug(p1.tostring())
D.LabelProperties l_props_up = D.LabelProperties.new(xloc = xloc.bar_index, color = chart.bg_color, textcolor = chart.fg_color, style = label.style_label_up)
D.LabelProperties l_props_down = D.LabelProperties.new(xloc = xloc.bar_index, color = chart.bg_color, textcolor = chart.fg_color, style = label.style_label_down)
D.LabelProperties l_props_center = D.LabelProperties.new(xloc = xloc.bar_index, color = chart.bg_color, textcolor = chart.fg_color, style = label.style_label_center)
D.Label lp1 = p1.createLabel('p1', properties = l_props_down)
lp1.draw()
D.Label lp2 = p2.createLabel('p2', properties = l_props_down)
lp2.draw()
D.Label lp3 = p3.createLabel('p3', properties = l_props_down)
lp3.draw()
D.Label lp4 = p4.createLabel('p4', properties = l_props_down)
lp4.draw()
D.Label lphh = phh.createLabel('HH', properties = l_props_down)
lphh.draw()
D.Label lpll = pll.createLabel('LL', properties = l_props_up)
lpll.draw()
l.debug(lp1.tostring())
D.Line ln = p1.createLine(p2)
ln.draw()
l.debug(ln.tostring())
D.Line ln2 = D.Line.new(D.Point.new(low, bar_index, time), D.Point.new(low, bar_index[10], time[10]))
ln2.draw()
D.Linefill lf = ln.createLinefill(ln2)
lf.draw()
l.debug(lf.tostring())
D.BoxText textProps = D.BoxText.new('This is my box')
D.Box bx = p2.createBox(p3, textProperties = textProps)
bx.draw()
D.Point c = p4.createCenter(p3)
D.Line lc = p4.createLine(p3)
lc.draw()
D.Label cl = c.createLabel('center point', properties = l_props_down)
cl.draw()
D.Line lc1 = c.createLine(p3)
lc1.draw()
D.Line lc2 = c.createLine(p4)
lc2.draw()
D.Label cl2 = lc.createLabel('line center', properties = l_props_center)
cl2.draw()
DC.Triangle t = p4.createTriangle(p3, phh)
t.draw()
D.Label tl = t.createLabel('triangle center', properties = l_props_center)
tl.draw()
DC.Trianglefill tf = t.createTrianglefill()
tf.draw()
l.debug(str.format('x1 {0} y1 {1} x2 {2} y2 {3} | x1 {4} y1 {5} x2 {6} y2 {7}', tf.object.get_line1().get_x1(), tf.object.get_line1().get_y1(), tf.object.get_line1().get_x2(), tf.object.get_line1().get_y2(), tf.object.get_line2().get_x1(), tf.object.get_line2().get_y1(), tf.object.get_line2().get_x2(), tf.object.get_line2().get_y2()))
DC.TriangleProperties polygon_props = DC.TriangleProperties.new(color.red, color.red)
D.Point[] polygonPoints = array.from(p1, phh, p3, pll)
DC.Polygon p = polygonPoints.createPolygon(polygon_props)
p.draw()
D.Point pcenter = polygonPoints.createCenter()
D.Label lpc = pcenter.createLabel('poly center', properties = l_props_center)
lpc.draw()
DC.Polygonfill pf = p.createPolygonfill(fill_color = color.blue, transparency = 93)
pf.draw()
// if barstate.isfirst
// label.new(bar_index, close, 'mandatory showcase')
|
Session Fibonacci Levels [QuantVue] | https://www.tradingview.com/script/nTMlTmw9-Session-Fibonacci-Levels-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © QuantVue
//@version=5
indicator('Session Fibonacci Levels [QuantVue]', overlay = true)
//----------settings----------/
var g0 = 'Sessions Settings'
tz = input.string("GMT-4", "Time Zone", tooltip = "GMT and UTC is the same thing \nMatch this setting to bottom right time", options = ["GMT-10", "GMT-9", "GMT-8", "GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT+0", "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5", "GMT+6", "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+10:30", "GMT+11", "GMT+12", "GMT+13", "GMT+13:45"], group = g0)
sessionTime = input.session('0600-0900', 'Session', group = g0)
showBox = input.bool(true, 'Session Box', group = g0, inline = '1')
boxCol = input.color(color.new(color.blue,80), 'Box Color', group = g0, inline = '1')
removeOld = input.bool(false, 'Remove Fibs When New Session Starts', group = g0)
var g1 = 'Fibs'
showFibs = input.bool(true, 'Show Fibs', inline = '0', group = g1)
fibStyle = input.string('Solid', ' ', options = ['Dashed', 'Dotted', 'Solid'], inline = '0', group = g1)
showTl = input.bool(true,'Range High to Low Line', inline = '1', group = g1)
tlColor = input.color(color.gray, ' ', inline = '1', group = g1)
tlStyle = input.string('Dashed', '', options = ['Dashed', 'Dotted', 'Solid'], inline = '1', group = g1)
labelLoc = input.string('Left', ' Fib Price Location ', options = ['Left', 'Right'], inline = '2', group = g1)
textColor = input.color(color.white, ' Text Color ', inline = '2', group = g1)
show_0 = input.bool(true, '', inline = 'Level0', group = g1)
value_0 = input.float(0, '', inline = 'Level0', group = g1)
color_0 = input.color(#787b86, '', inline = 'Level0', group = g1)
show_236 = input.bool(true, '', inline = 'Level0', group = g1)
value_236 = input.float(0.236, '', inline = 'Level0', group = g1)
color_236 = input.color(#c2c5ce, '', inline = 'Level0', group = g1)
show_382 = input.bool(true, '', inline = 'Level1', group = g1)
value_382 = input.float(0.382, '', inline = 'Level1', group = g1)
color_382 = input.color(#c2c5ce, '', inline = 'Level1', group = g1)
show_50 = input.bool(true, '', inline = 'Level1', group = g1)
value_50 = input.float(0.5, '', inline = 'Level1', group = g1)
color_50 = input.color(#c2c5ce, '', inline = 'Level1', group = g1)
show_618 = input.bool(true, '', inline = 'Level2', group = g1)
value_618 = input.float(0.618, '', inline = 'Level2', group = g1)
color_618 = input.color(#00ccff, '', inline = 'Level2', group = g1)
show_786 = input.bool(true, '', inline = 'Level2', group = g1)
value_786 = input.float(0.786, '', inline = 'Level2', group = g1)
color_786 = input.color(#c2c5ce, '', inline = 'Level2', group = g1)
show_1 = input.bool(true, '', inline = 'Level3', group = g1)
value_1 = input.float(1, '', inline = 'Level3', group = g1)
color_1 = input.color(#787b86, '', inline = 'Level3', group = g1)
show_E236 = input.bool(true, '', inline = 'Level3', group = g1)
value_E236 = input.float(-0.236, '', inline = 'Level3', group = g1)
color_E236 = input(#00e64d, '', inline = 'Level3', group = g1)
show_E382 = input.bool(true, '', inline = 'Level4', group = g1)
value_E382 = input.float(-0.382, '', inline = 'Level4', group = g1)
color_E382 = input(#00e64d, '', inline = 'Level4', group = g1)
show_E50 = input.bool(true, '', inline = 'Level4', group = g1)
value_E50 = input.float(-0.50, '', inline = 'Level4', group = g1)
color_E50 = input(#00e64d, '', inline = 'Level4', group = g1)
//----------methods----------//
method switcher(string this) =>
switch this
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
method switcherLabel(string this) =>
switch this
'Above Bar' => label.style_label_down
'Below Bar' => label.style_label_up
'Left' => label.style_label_right
'Right' => label.style_none
//----------variables----------//
var rangeLow = 0.0
var rangeHigh = 0.0
var firstBar = 0
var highIndex = 0
var lowIndex = 0
var box rangeBox = na
var line fibHL = na
var line fib0 = na, var float level0 = na, var label text0 = na
var line fib100 = na, var float level100 = na, var label text100 = na
var line fib236 = na, var float level236 = na, var label text236 = na
var line fib382 = na, var float level382 = na, var label text382 = na
var line fib50 = na, var float level50 = na, var label text50 = na
var line fib618 = na, var float level618 = na, var label text618 = na
var line fib786 = na, var float level786 = na, var label text786 = na
var line fibE236 = na, var float levelE236 = na, var label textE236 = na
var line fibE382 = na, var float levelE382 = na, var label textE382 = na
var line fibE50 = na, var float levelE50 = na, var label textE50 = na
lines = line.all
labels = label.all
//----------sessions----------//
session = time(timeframe.period, sessionTime, tz)
startSession = not na(session) and na(session[1])
endSession = na(session) and not na(session[1])
if startSession
rangeHigh := high
rangeLow := low
firstBar := bar_index
highIndex := bar_index
lowIndex := bar_index
if showBox
(rangeBox[1]).delete()
rangeBox := box.new(bar_index, rangeHigh, bar_index + 2, rangeLow, boxCol, bgcolor = boxCol)
if removeOld
for l in lines
l.delete()
if time == session
if showBox
rangeBox.set_right(bar_index)
if high > rangeHigh
rangeHigh := high
highIndex := bar_index
rangeBox.set_top(rangeHigh)
if low < rangeLow
rangeLow := low
lowIndex := bar_index
rangeBox.set_bottom(rangeLow)
//----------create fibs----------//
if endSession
for l in lines
l.delete()
for l in labels
l.delete()
if highIndex < lowIndex
fibTotal = rangeHigh - rangeLow
level0 := rangeLow + (fibTotal * value_0)
level100 := rangeLow + (fibTotal * value_1)
level236 := rangeLow + (fibTotal * value_236)
level382 := rangeLow + (fibTotal * value_382)
level50 := rangeLow + (fibTotal * value_50)
level618 := rangeLow + (fibTotal * value_618)
level786 := rangeLow + (fibTotal * value_786)
levelE236 := rangeLow + (fibTotal * value_E236)
levelE382 := rangeLow + (fibTotal * value_E382)
levelE50 := rangeLow + (fibTotal * value_E50)
if lowIndex < highIndex
fibTotal = rangeHigh - rangeLow
level0 := rangeHigh - (fibTotal * value_0)
level100 := rangeHigh - (fibTotal * value_1)
level236 := rangeHigh - (fibTotal * value_236)
level382 := rangeHigh - (fibTotal * value_382)
level50 := rangeHigh - (fibTotal * value_50)
level618 := rangeHigh - (fibTotal * value_618)
level786 := rangeHigh - (fibTotal * value_786)
levelE236 := rangeHigh - (fibTotal * value_E236)
levelE382 := rangeHigh - (fibTotal * value_E382)
levelE50 := rangeHigh - (fibTotal * value_E50)
if showFibs
if showTl
fibHL := line.new(lowIndex, rangeLow, highIndex, rangeHigh, style = tlStyle.switcher(), color = tlColor)
if show_0
fib0 := line.new(firstBar, level0, bar_index, level0, extend = extend.right, style = fibStyle.switcher(), color = color_0)
if show_1
fib100 := line.new(firstBar, level100, bar_index, level100, extend = extend.right, style = fibStyle.switcher(), color = color_1)
if show_236
fib236 :=line.new(firstBar, level236, bar_index, level236, extend = extend.right, style = fibStyle.switcher(), color = color_236)
if show_382
fib382 :=line.new(firstBar, level382, bar_index, level382, extend = extend.right, style = fibStyle.switcher(), color = color_382)
if show_50
fib50 := line.new(firstBar, level50, bar_index, level50, extend = extend.right, style = fibStyle.switcher(), color = color_50)
if show_618
fib618 :=line.new(firstBar, level618, bar_index, level618, extend = extend.right, style = fibStyle.switcher(), color = color_618)
if show_786
fib786 := line.new(firstBar, level786, bar_index, level786, extend = extend.right, style = fibStyle.switcher(), color = color_786)
if show_E236
fibE236 := line.new(firstBar, levelE236, bar_index, levelE236, extend = extend.right, style = fibStyle.switcher(), color = color_E236)
if show_E382
fibE382 := line.new(firstBar, levelE382, bar_index, levelE382, extend = extend.right, style = fibStyle.switcher(), color = color_E382)
if show_E50
fibE50 := line.new(firstBar, levelE50, bar_index, levelE50, extend = extend.right, style = fibStyle.switcher(), color = color_E50)
if show_0
text0 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level0, str.tostring(value_0) + ' (' + str.tostring(level0, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_1
text100 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level100, str.tostring(value_1) + ' (' + str.tostring(level100, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_236
text236 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level236, str.tostring(value_236) + ' (' + str.tostring(level236, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_382
text382 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level382, str.tostring(value_382) + ' (' + str.tostring(level382, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_50
text50 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level50, str.tostring(value_50) + ' (' + str.tostring(level50, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_618
text618 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level618, str.tostring(value_618) + ' (' + str.tostring(level618, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_786
text786 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, level786, str.tostring(value_786) +' (' + str.tostring(level786, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_E236
textE236 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, levelE236, str.tostring(value_E236) + ' (' + str.tostring(levelE236, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_E382
textE382 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, levelE382, str.tostring(value_E382) + ' (' + str.tostring(levelE382, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if show_E50
textE50 := label.new(labelLoc == 'Left' ? firstBar - 1 : bar_index + 2, levelE50, str.tostring(value_E50) + ' (' + str.tostring(levelE50, format.mintick) + ')',
style = labelLoc.switcherLabel(), color = color.new(color.white,100), textcolor = textColor)
if barstate.islast and labelLoc == 'Right'
for l in labels
l.set_x(bar_index + 3)
if na(session)
if lowIndex < highIndex and low <= level618
alert(str.tostring(value_618) + ' Fib Hit')
if highIndex < lowIndex and high >= level618
alert(str.tostring(value_618) + ' Fib Hit')
if lowIndex < highIndex and high >= levelE236
alert(str.tostring(value_E236) + ' Fib Extension Hit')
if highIndex < lowIndex and low <= levelE236
alert(str.tostring(value_E236) + ' Fib Extension Hit')
|
ICT HTF MSS & Liquidity (fadi) | https://www.tradingview.com/script/vzT0XcBD-ICT-HTF-MSS-Liquidity-fadi/ | fadizeidan | https://www.tradingview.com/u/fadizeidan/ | 84 | 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/
// © fadizeidan
//
//@version=5
indicator("ICT HTF MSS & Liquidity (fadi)", overlay=true, max_bars_back = 5000, max_lines_count = 500)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Types ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Settings
string level
string liquidity_open_style
string liquidity_claimed_style
color liquidity_open_color
color liquidity_claimed_color
int liquidity_open_size
int liquidity_claimed_size
int max_lines
int extend
type Pivot
int time = 0
float price = 0
int time_last = 0
bool claimed = false
bool isHigh = na
string lbl_text = ""
line ln = na
type MarketStructure
string name
Pivot[] ST
Pivot[] IT
Pivot[] LT
Pivot[] STH
Pivot[] ITH
Pivot[] STL
Pivot[] ITL
Settings settings
type Helper
string name = "Helper"
//+------------------------------------------------------------------------------------------------------------+//
//+--- Settings ---+//
//+------------------------------------------------------------------------------------------------------------+//
int MAX_BUFFER = 500 // internal maximum node count limit for performance
settings_liquidity = "Liquidity"
settings_liquidity_style = "Liquidity Style"
Settings Trend_Settings = Settings.new()
HTF = input.timeframe("15", "Higher Timeframe", group=settings_liquidity)
Trend_Settings.level := input.string("Short Term", "Use", options = ["Short Term", "Intermediate Term", "Long Term"], group=settings_liquidity)
Trend_Settings.liquidity_open_style := input.string('⎯⎯⎯', 'Open ', options = ['⎯⎯⎯', '----', '····'], group=settings_liquidity_style, inline="open")
Trend_Settings.liquidity_open_size := input.int(1, "", options = [1,2,3,4], group=settings_liquidity_style, inline="open")
Trend_Settings.liquidity_open_color := input.color(color.new(color.purple, 50), '', group=settings_liquidity_style, inline="open")
Trend_Settings.liquidity_claimed_style := input.string('····', 'Claimed ', options = ['⎯⎯⎯', '----', '····'], group=settings_liquidity_style, inline="claimed")
Trend_Settings.liquidity_claimed_size := input.int(1, "", options = [1,2,3,4], group=settings_liquidity_style, inline="claimed")
Trend_Settings.liquidity_claimed_color := input.color(color.new(color.black, 50), '', group=settings_liquidity_style, inline="claimed")
Trend_Settings.extend := input.int(10, title="Extend", minval = 1, group=settings_liquidity_style)
Trend_Settings.max_lines := input.int(50, "Number of lines", minval=1, maxval=250, group=settings_liquidity_style)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Variables ---+//
//+------------------------------------------------------------------------------------------------------------+//
color color_transparent = #ffffff00
Helper helper = Helper.new()
var MarketStructure Term = MarketStructure.new("Term")
var Pivot[] ST_array = array.new<Pivot>()
var Pivot[] IT_array = array.new<Pivot>()
var Pivot[] LT_array = array.new<Pivot>()
var Pivot[] STH_array = array.new<Pivot>()
var Pivot[] ITH_array = array.new<Pivot>()
var Pivot[] STL_array = array.new<Pivot>()
var Pivot[] ITL_array = array.new<Pivot>()
Term.ST := ST_array
Term.IT := IT_array
Term.LT := LT_array
Term.STH := STH_array
Term.ITH := ITH_array
Term.STL := STL_array
Term.ITL := ITL_array
Term.settings := Trend_Settings
var float[] highs = array.new_float()
var float[] lows = array.new_float()
var int[] times = array.new_int()
var line[] lines = array.new_line()
//+------------------------------------------------------------------------------------------------------------+//
//+--- Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
method Validtimeframe(Helper helper, tf) =>
helper.name := tf
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(tf)
n1 < n2
method LineStyle(Helper helper, string style) =>
helper.name := style
out = switch style
'----' => line.style_dashed
'····' => line.style_dotted
=> line.style_solid
out
// SkipEQHigh returns the first bar_index of before the equal highs
// This is used to compare pivot points, if two at equal levels
// then we need to compare it to previous high, otherwise it will
// not identify the right STH/STL
method SkipEQHigh(Helper helper, int idx) =>
helper.name := "Skip EQ Highs"
i = idx
while highs.get(i) == highs.get(i-1) and i < 5
i := i+1
i
// SkipEQLows returns the first bar_index of before the equal lows
method SkipEQLow(Helper helper, int idx) =>
helper.name := "Skip EQ Lows"
i = idx
while lows.get(i) == lows.get(i-1) and i < 5
i := i+1
i
// Same as above, but works on pivot points. it also doesn't care for
// high or low since Pivot is a single price point
method SkipEQPivot(Pivot[] p, int idx) =>
i = idx
while p.get(i).price == p.get(i-1).price and p.get(i).lbl_text == p.get(i-1).lbl_text and p.size() < i
i := i+1
i
// isHigh returns true if the Pivot point is a high Pivot (STH, ITH, LTH)
method isHigh(Helper helper, string lbl) =>
helper.name := "isHigh"
str.endswith(lbl, "H")
//isLow returns true if the Pivot is a low Pivot
method isLow(Helper helper, string lbl) =>
helper.name := "isLow"
str.endswith(lbl, "L")
//+------------------------------------------------------------------------------------------------------------+//
//+--- ICT Market Structure Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
// AddLiquidity adds the liquidity lines
method AddLiquidity(MarketStructure MS, Pivot pivot) =>
if (MS.settings.level == "Short Term" and str.startswith(pivot.lbl_text, "ST")) or (MS.settings.level == "Intermediate Term" and str.startswith(pivot.lbl_text, "IT")) or (MS.settings.level == "Long Term" and str.startswith(pivot.lbl_text, "LT"))
if na(pivot.ln)
pivot.ln := line.new(pivot.time, pivot.price, time+((time-time[1])*MS.settings.extend), pivot.price, xloc=xloc.bar_time, style=helper.LineStyle(MS.settings.liquidity_open_style), color=MS.settings.liquidity_open_color, width=MS.settings.liquidity_open_size)
lines.unshift(pivot.ln)
if lines.size() > MS.settings.max_lines
line l = lines.pop()
line.delete(l)
else
line.set_color(pivot.ln, pivot.claimed ? MS.settings.liquidity_claimed_color : MS.settings.liquidity_open_color)
line.set_width(pivot.ln, pivot.claimed ? MS.settings.liquidity_claimed_size : MS.settings.liquidity_open_size)
line.set_x2(pivot.ln, pivot.claimed ? pivot.time_last : time+((time-time[1])*MS.settings.extend))
line.set_style(pivot.ln, helper.LineStyle(pivot.claimed ? MS.settings.liquidity_claimed_style : MS.settings.liquidity_open_style))
MS
// FindIT rechecks the Pivot points and renames the Pivot point from ST to IT
method FindIT(MarketStructure MS) =>
if MS.STH.size() > 2
h1 = MS.STH.first()
h2 = MS.STH.get(1)
h3 = MS.STH.get(MS.STH.SkipEQPivot(2))
if h2.price > h3.price and h2.price > h1.price and h2.lbl_text == "STH"
h2.lbl_text := "ITH"
MS.ITH.unshift(h2)
MS.AddLiquidity(h2)
if MS.STL.size() > 2
l1 = MS.STL.first()
l2 = MS.STL.get(1)
l3 = MS.STL.get(MS.STL.SkipEQPivot(2))
if l2.price < l3.price and l2.price < l1.price and l2.lbl_text == "STL"
l2.lbl_text := "ITL"
MS.ITL.unshift(l2)
MS.AddLiquidity(l2)
MS
// FindLT rechecks the IT Pivot points and renames the Pivot point from IT to LT
method FindLT(MarketStructure MS) =>
if MS.ITH.size() > 2
h1 = MS.ITH.first()
h2 = MS.ITH.get(1)
h3 = MS.ITH.get(MS.ITH.SkipEQPivot(2))
if h2.price > h3.price and h2.price > h1.price and h2.lbl_text == "ITH"
h2.lbl_text := "LTH"
MS.LT.unshift(h2)
MS.AddLiquidity(h2)
if MS.ITL.size() > 2
l1 = MS.ITL.first()
l2 = MS.ITL.get(1)
l3 = MS.ITL.get(MS.ITL.SkipEQPivot(2))
if l2.price < l3.price and l2.price < l1.price and l2.lbl_text == "ITL"
l2.lbl_text := "LTL"
MS.LT.unshift(l2)
MS.AddLiquidity(l2)
MS
// Add method handles the addition of newly discovered ST[H/L] Pivot Point
method Add(MarketStructure MS, float p_price, int p_time, lbl) =>
bool isNew = true
if MS.ST.size() > 0
Pivot previous = MS.ST.first()
isNew := previous.time < p_time
if isNew
Pivot pivot = Pivot.new()
pivot.price := p_price
pivot.time := p_time
pivot.lbl_text := lbl
MS.ST.unshift(pivot)
if lbl == "STH"
MS.STH.unshift(pivot)
else
MS.STL.unshift(pivot)
MS.AddLiquidity(pivot).FindIT().FindLT()
if MS.ST.size() > MAX_BUFFER
Pivot temp = MS.ST.pop()
line.delete(temp.ln)
MS
method findST(MarketStructure MS, float[] h, float[] l, int[] t) =>
_h = h.get(1) > h.get(helper.SkipEQHigh(2)) and h.get(1) > h.first()
_l = l.get(1) < l.get(helper.SkipEQLow(2)) and l.get(1) < l.first()
if _h
MS.Add(h.get(1), t.get(1), "STH")
if _l
MS.Add(l.get(1), t.get(1), "STL")
MS
// CheckClaimed checks if liquidity has been swept
method CheckClaimed(MarketStructure MS) =>
if MS.ST.size() > 0
for i = 0 to MS.ST.size() - 1
pivot = MS.ST.get(i)
if not na(pivot.ln)
if not pivot.claimed
if helper.isHigh(pivot.lbl_text)
pivot.claimed := high > pivot.price
if helper.isLow(pivot.lbl_text)
pivot.claimed := low < pivot.price
if pivot.claimed
pivot.time_last := time
pivot.claimed := true
line.set_color(pivot.ln, pivot.claimed ? MS.settings.liquidity_claimed_color : MS.settings.liquidity_open_color)
line.set_width(pivot.ln, pivot.claimed ? MS.settings.liquidity_claimed_size : MS.settings.liquidity_open_size)
line.set_x2(pivot.ln, pivot.claimed ? pivot.time_last : time+((time-time[1])*MS.settings.extend))
line.set_style(pivot.ln, helper.LineStyle(pivot.claimed ? MS.settings.liquidity_claimed_style : MS.settings.liquidity_open_style))
else
line.set_x2(pivot.ln, time+((time-time[1])*MS.settings.extend))
MS
//+------------------------------------------------------------------------------------------------------------+//
//+--- Main call to start the process ---+//
//+------------------------------------------------------------------------------------------------------------+//
[h, h1, h2, h3, h4, h5, l, l1, l2, l3, l4, l5, t, t1]= request.security(syminfo.tickerid, HTF, [high, high[1], high[2], high[3], high[4], high[5], low, low[1], low[2], low[3], low[4], low[5], time, time[1]])
if helper.Validtimeframe(HTF)
if barstate.isconfirmed
array.clear(highs)
array.clear(lows)
array.unshift(highs, h5)
array.unshift(highs, h4)
array.unshift(highs, h3)
array.unshift(highs, h2)
array.unshift(highs, h1)
array.unshift(highs, h)
array.unshift(lows, l5)
array.unshift(lows, l4)
array.unshift(lows, l3)
array.unshift(lows, l2)
array.unshift(lows, l1)
array.unshift(lows, l)
array.unshift(times, t1)
array.unshift(times, t)
Term.findST(highs, lows, times)//.FindIT().FindLT()
//if barstate.isconfirmed or barstate.islastconfirmedhistory
Term.CheckClaimed() |
RSNPSD | https://www.tradingview.com/script/6lIWLH3E-rsnpsd/ | Vlad42motion | https://www.tradingview.com/u/Vlad42motion/ | 0 | 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/
// © Slava_Ukraini
//@version=5
library("RSNPSD")
export EMA5(float source, simple int EMAlength, simple int Smoothlength ) =>
if EMAlength > 0
ema1 = ta.ema(source, EMAlength)
ema2 = ta.ema(ema1, EMAlength)
ema3 = ta.ema(ema2, EMAlength)
ema4 = ta.ema(ema3, EMAlength)
ema5 = ta.ema(ema4, EMAlength)
ema6 = ta.ema(ema5, EMAlength)
ema7 = ta.ema(ema6, EMAlength)
ema8 = ta.ema(ema7, EMAlength)
out = 8 * ema1 - 28 * ema2 + 56 * ema3 - 70 * ema4 + 56 * ema5 - 28 * ema6 + 8 * ema7 - ema8
ta.ema(out,Smoothlength)
else
na
export SLOPE(float source, simple int slopeDistance) =>
math.atan( ta.change(source) / slopeDistance ) * (180 / math.pi)
export print(string txt) =>
var table t = table.new(position.middle_right, 1, 1)
table.cell(t, 0, 0, txt, bgcolor = color.yellow)
|
libHTF[without request.security()] | https://www.tradingview.com/script/8w1kNNjZ/ | nazomobile | https://www.tradingview.com/u/nazomobile/ | 4 | 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/
// © nazomobile
//@version=5
//@description this is libHTF under development.
//@description libHTF: use HTF values without request.security()
// This library enables to use HTF candles without request.security().
//
//@description Basic data structure
// Using <array> to access values in the same manner as series variable.
//The last member of HTF array is always latest current TF's data.
//If new bar in HTF(same as last bar closes), new member is pushed to HTF array.
//2nd from the last member of HTF array is latest fixed(closed) bar.
//
//@description HTF: How to use
//1. set TF
// tf_higher() function selects higher TF. TF steps are ()"1","5","15","60","240","D","W","M","3M","6M","Y").
// example:
// tfChart = timeframe.period
// htf1 = tf_higher(tfChart)
//
//2. set HTF matrix
// htf_candle() function returns 1 bool and 1 matrix.
//bool is a flag for start of new candle in HTF context.
//matrix is HTF candle data(0:open,1:time_open,2:close,3:time_close,4:high,5:time:high,6:low,7:time_low).
// example:
// [b_new_bar1,m1]=htf_candle(htf1)
//
//3. how to access HTF candle data
// you can get values using <matrix>.lastx() method.
// please be careful, return value is always float evenif it is "time". you need to cast to int time value when using for xloc.bartime.
// example:
// htf1open=m1.lastx("open")
// htf1close=m1.lastx("close")
// //if you need to use histrical value.
// lastopen=open[1]
// lasthtf1open=m1.lastx("open",1)
//
//4. how to store Data of HTF context
// you have to use array to store data of HTF context.
// array.htf_push() method handles the last member of array. if new_bar in HTF, it push new member. otherwise it set value to the last member.
// example:
// array a_close=array.new<float>(1,na)
// a_close.htf_push(b_new_bar1,m1.lastx("close"))
//
//@description HTFsrc: How to use
//1. how to setup src.
//set_src() function is set current tf's src from string(open/high/low/close/hl2/hlc3/ohlc4/hlcc4).
//set_htfsrc() function returns src array of HTF candle.
//
// example:
// _src="ohlc4"
// src=set_src(_src)
// htf1src=set_htfsrc(_src,b_new_bar1,m1)
// (if you need to use HTF src in series float)
// s_htf1src=htf1src.lastx()
//
//@description HighLow: How to use
//1. set HTF arrays
// highlow() and htfhighlow() function calculates high/low and return high/low prices and time.
//the functions return 1 int and 8arrays.
//int is a flag for new high(1) or new low(-1).
//arrays are high/low and return high/low data. float for price, int for time.
// example
// [i_renew,a_high,a_time_high,a_return_high,a_time_return_high,a_low,a_time_low,a_return_low,a_time_return_low] =
// highlow()
// [i_renew1,a_high1,a_time_high1,a_return_high1,a_time_return_high1,a_low1,a_time_low1,a_return_low1,a_time_return_low1] =
// htfhighlow(m1)
//
//2. how to access HighLow data
// you can get values using <array>.lastx() method.
// example:
// if i_renew==1
// myhigh=a_high.lastx()
// //if you need to use histrical value.
// myhigh=a_high.lastx(1)
//
//@description other functions
// functions for HTF candle matrix or HTF src array in this script are
// htf_sma()/htf_ema()/htf_rma()
// htf_rsi()/htf_rci()/htf_dmi()
//
library("libHTFwoRS",overlay=true)
var group_libHTF='libHTF'
// @function method like array.last. it returns lastindex from the last member, if parameter is set.
// @param lastindex (int) default value is "0"(the last member). if you need to access historical value, increment it(same manner as series vars).
// @returns float value of lastindex from the last member of the array. returns na, if fail.
export method lastx(array<float> arrayid,int lastindex=0)=> arrayid.size()>=lastindex+1?arrayid.get(arrayid.size()-lastindex-1):na
// @function method like array.last. it returns lastindex from the last member, if parameter is set.
// @param lastindex (int) default value is "0"(the last member). if you need to access historical value, increment it(same manner as series vars).
// @returns int value of lastindex from the last member of the array. returns na, if fail.
export method lastx(array<int> arrayid,int lastindex=0)=> arrayid.size()>=lastindex+1?arrayid.get(arrayid.size()-lastindex-1):na
// @function method to set a value of the last member of the array. it sets value to the last member.
// @param val (float) value to set.
// @returns nothing
export method set_last(array<float> arrayid,float val)=>
if arrayid.size()>0
arrayid.set(arrayid.size()-1,val)
// @function method to push new member to htf context. if new bar in htf, it works as push. else it works as set_last.
// @param b (bool) true:push,false:set_last
// @param val (float) _f the value to set.
// @returns nothing
export method htf_push(array<float> arrayid,bool b,float val)=>
if b
arrayid.push(val)
else if arrayid.size()>0
arrayid.set(arrayid.size()-1,val)
method tftype(string tf) =>
if na(tf)
na
else
_last = str.substring(tf,str.length(tf)-1)
_x = switch _last
"Y"=>"Y"
"M"=>"M"
"W"=>"W"
"D"=>"D"
"H"=>"H"
"S"=>"S"
=>"min"
method multiplier(string tf)=>
_x = switch tf.tftype()
"Y" => str.length(tf)==1?"1":str.replace(tf,"Y","")
"M" => str.length(tf)==1?"1":str.replace(tf,"M","")
"W" => str.length(tf)==1?"1":str.replace(tf,"W","")
"D" => str.length(tf)==1?"1":str.replace(tf,"D","")
"H" => str.length(tf)==1?"1":str.replace(tf,"H","")
"S" => str.length(tf)==1?"1":str.replace(tf,"S","")
=>tf
int(str.tonumber(_x))
// @function method to set higher tf from tf string. TF steps are ["1","5","15","60","240","D","W","M","3M","6M","Y"].
// @param tf (string) tf string
// @returns (string) string of higher tf.
export method tf_higher(string tf)=>
_m = tf.multiplier()
_x = switch tf.tftype()
"Y" => na
"M" => _m<3?"3M": _m<6?"6M": _m<12?"12M":na
"W" => "M"
"D" => "W"
"H" => "D"
"S" => "1"
"min" => _m<5?"5": _m<15?"15": _m<60?"60": _m<240?"240": "D"
=> na
method tfseq(string _tf,int _time,string _TZ="GMT+3")=>
_mul = _tf.multiplier()
_year=year(_time,_TZ),_month=month(_time,_TZ),_week=weekofyear(_time,_TZ),_day=dayofmonth(_time,_TZ)
_hour=hour(_time,_TZ),_minute=minute(_time,_TZ),_second=second(_time,_TZ)
switch _tf.tftype()
"Y"=>int(_year/_mul)
"M"=>int(_month/_mul)
"W"=>int(_week/_mul)
"D"=>int(_day/_mul)
"H"=>int(_hour/_mul)
"S"=>int(_second/_mul)
"min"=>str.tonumber(_tf)>=60?int(_hour/(_mul/60)): int(_minute/_mul)
=>na
method time_close (string _tf,int _time_open,string _TZ="GMT+3") =>
_mul = _tf.multiplier()
_year=year(_time_open,_TZ),_month=month(_time_open,_TZ),_week=weekofyear(_time_open,_TZ),_day=dayofmonth(_time_open,_TZ)
_hour=hour(_time_open,_TZ),_minute=minute(_time_open,_TZ)
_time_close = switch _tf.tftype()
"Y"=>timestamp(_TZ,_year+_mul,1,1)-1
"M"=>timestamp(_TZ,_month+_mul>=12?_year+1:_year,_month+_mul>=12?_month+_mul-12:_month+_mul,1)-1
"W"=>_time_open+timeframe.in_seconds(_tf)*1000*_mul-1
"D"=>_time_open+timeframe.in_seconds(_tf)*1000*_mul-1
"H"=>_time_open+timeframe.in_seconds(_tf)*1000*_mul-1
"S"=>_time_open+(timeframe.in_seconds(_tf)*1000)-1
"min"=> _time_open+(timeframe.in_seconds(_tf)*1000)-1
=>na
int(_time_close)
//*****
//HTF setup
//*****
//htf matrix rows; 0:open,1:time_open,2:close,3:time_close,4:high,5:time:high,6:low,7:time_low
method to_htfrow(string type) =>
switch type
"open" =>0
"time_open"=>1
"close" =>2
"time_close"=>3
"high" =>4
"time_high"=>5
"low" =>6
"time_low"=>7
// @function method for handling htf matrix.
// @param m (matrix<float>) matrix for htf candle.
// @param _type (string) value type of htf candle:["open","time_open","close","time_close","high","time_high","low","time_low"]
// @param lastindex (int) default value is "0"(the last member).
// @returns (float) value of htf candle. (caution: need to cast float to int to use time values!)
export method lastx(matrix<float> m,string _type,int lastindex=0)=>
if m.columns()>=lastindex+1
m.get(_type.to_htfrow(),m.columns()-lastindex-1)
else
na
method set_last(matrix<float> _m,string _type,float _x)=>
if _m.columns()>0
_m.set(_type.to_htfrow(),_m.columns()-1,_x)
// @function build htf candles
// @param _m (matrix<float>) matrix for htf candle. rows must be >=8.
// @param _tf (string) tf string.
// @param _TZ [optional string] of timezone. default value is "GMT+3".
// @returns [bool,(matrix<float>)] bool for new bar@htf and matrix for snapshot of htf candle
export htf_candle(string _tf,string _TZ="GMT+3")=>
var _m=matrix.new<float>(8,1,na)
var i_htf=0
i_htf:=_tf.tfseq(time,_TZ)
b_new_bar=ta.change(i_htf)
if b_new_bar
//closing
if high[1]>_m.lastx("high")
_m.set_last("high",high[1])
if low[1]<_m.lastx("low")
_m.set_last("low",low[1])
_m.set_last("close",close[1])
_m.set_last("time_close",time_close[1])
//push new bar
_m.add_col()
_m.set_last("open",open)
_m.set_last("time_open",time)
_m.set_last("close",close)
_m.set_last("time_close",_tf.time_close(time,_TZ))
_m.set_last("high",high)
_m.set_last("time_high",timenow)
_m.set_last("low",low)
_m.set_last("time_low",timenow)
else//update values
if high>=_m.lastx("high")
_m.set_last("high",high)
_m.set_last("time_high",timenow)
if low<=_m.lastx("low")
_m.set_last("low",low)
_m.set_last("time_low",timenow)
_m.set_last("close",close)
[b_new_bar,_m]
//src
//open/high/low/close/hl2/hlc3/ohlc4/hlcc4
sr0="open",sr1="high",sr2="low",sr3="close",sr4="hl2",sr5="hlc3",sr6="ohlc4",sr7="hlcc4"
// @function set src.
// @param _src_type (string) type of source:["open","high","low","close","hl2","hlc3","ohlc4","hlcc4"]
// @returns (series float) src value
export set_src(string _src_type) =>
switch _src_type
sr0 => open
sr1 => high
sr2 => low
sr3 => close
sr4 => hl2
sr5 => hlc3
sr6 => ohlc4
sr7 => hlcc4
f_htf_open (_m) =>
_m.lastx("open")
f_htf_high (_m) =>
_m.lastx("high")
f_htf_low (_m) =>
_m.lastx("low")
f_htf_hl2 (_m) =>
math.avg(_m.lastx("high"),_m.lastx("low"))
f_htf_hlc3 (_m) =>
math.avg(_m.lastx("high"),_m.lastx("low"),_m.lastx("close"))
f_htf_ohlc4 (_m) =>
math.avg(_m.lastx("open"),_m.lastx("high"),_m.lastx("low"),_m.lastx("close"))
f_htf_hlcc4 (_m) =>
math.avg(_m.lastx("high"),_m.lastx("low"),_m.lastx("close"),_m.lastx("close"))
// @function set htf src.
// @param _src_type (string) type of source:["open","high","low","close","hl2","hlc3","ohlc4","hlcc4"]
// @param _nb (bool) flag of new bar
// @param _m (matrix<float>) matrix for htf candle.
// @returns (array<float>) array of src value
export set_htfsrc (string _src_type,bool _nb, matrix<float> _m) =>
var _a_htfsrc=array.new<float>(0,na)
_s = switch _src_type
sr0 => f_htf_open(_m)
sr1 => f_htf_high(_m)
sr2 => f_htf_low(_m)
sr3 => close
sr4 => f_htf_hl2(_m)
sr5 => f_htf_hlc3(_m)
sr6 => f_htf_ohlc4(_m)
sr7 => f_htf_hlcc4(_m)
if not(_a_htfsrc.size()>0)
_a_htfsrc.push(_s)
else if _nb
_a_htfsrc.push(_s)
else
_a_htfsrc.set_last(_s)
_a_htfsrc
//highlow
f_renew_high_low(_peak_bottom,_last_renew,
_high,_time_high,_low,_time_low,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low)
=>
_i_renew=0
if _peak_bottom ==1
if _a_return_high.size()>0
if na(_a_return_high.last())
_a_return_high.set_last(_high)
_a_time_return_high.set_last(_time_high)
else
while(_a_return_high.size()>0)
if _a_return_high.lastx()<=_high
_a_return_high.pop()
_a_time_return_high.pop()
else
break
_a_return_high.push(_high)
_a_time_return_high.push(_time_high)
else
_a_return_high.push(_high)
_a_time_return_high.push(_time_high)
if _a_high.size()>0
if na(_a_high.last())
_i_renew:=1
_a_high.set_last(_a_return_high.lastx())
_a_time_high.set_last(_a_time_return_high.lastx())
else if _a_high.lastx()<_a_return_high.lastx()
_i_renew:=1
if _i_renew==_last_renew
_a_high.set_last(_a_return_high.lastx())
_a_time_high.set_last(_a_time_return_high.lastx())
else
_a_high.push(_a_return_high.lastx())
_a_time_high.push(_a_time_return_high.lastx())
else
_i_renew:=1
_a_high.push(_a_return_high.lastx())
_a_time_high.push(_a_time_return_high.lastx())
if _i_renew==1 and array.size(_a_return_low)>0
array.push(_a_low,array.last(_a_return_low))
array.push(_a_time_low,array.last(_a_time_return_low))
else if _peak_bottom==-1
if _a_return_low.size()>0
if na(_a_return_low.last())
_a_return_low.set_last(_low)
_a_time_return_low.set_last(_time_low)
else
while(_a_return_low.size()>0)
if _a_return_low.lastx()>=_low
_a_return_low.pop()
_a_time_return_low.pop()
else
break
_a_return_low.push(_low)
_a_time_return_low.push(_time_low)
else
_a_return_low.push(_low)
_a_time_return_low.push(_time_low)
if _a_low.size()>0
if na(_a_low.last())
_i_renew:=-1
_a_low.set_last(_a_return_low.lastx())
_a_time_low.set_last(_a_time_return_low.lastx())
else if _a_low.lastx()>_a_return_low.lastx()
_i_renew:=-1
if _i_renew==_last_renew
_a_low.set_last(_a_return_low.lastx())
_a_time_low.set_last(_a_time_return_low.lastx())
else
_a_low.push(_a_return_low.lastx())
_a_time_low.push(_a_time_return_low.lastx())
else
_i_renew:=-1
_a_low.push(_a_return_low.lastx())
_a_time_low.push(_a_time_return_low.lastx())
if _i_renew==-1 and array.size(_a_return_high)>0
array.push(_a_high,array.last(_a_return_high))
array.push(_a_time_high,array.last(_a_time_return_high))
[_i_renew,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low
]
// @function bool for latest bar is up.
// @returns (bool) latest bar is up.
export is_up()=>open<close
// @function bool for last bar is up.
// @returns (bool) last bar is up.
export last_is_up()=>open[1]<close[1]
// @function int for peak:1 or bottom:-1
// @param _latest (bool) latest bar is up.
// @param _last (bool) last bar is up.
// @returns (int) peak:1 or bottom:-1 or 0
export peak_bottom(bool _latest,bool _last)=> _last and not _latest?1: not _last and _latest?-1: 0
// @function bool for latest bar is up in htf.
// @param _m (matrix<float>) matrix for htf candle.
// @returns (bool) latest bar is up in htf.
export htf_is_up(matrix<float> _m)=>_m.lastx("open",1)<_m.lastx("close",1)
// @function bool for last bar is up in htf.
// @param _m (matrix<float>) matrix for htf candle.
// @returns (bool) last bar is up in htf.
export htf_last_is_up(matrix<float> _m)=>_m.lastx("open",2)<_m.lastx("close",2)
// @function highlow for current tf
// @param _b_bar_time_price (bool) default is "true":The price of peak/bottom is set by price of latest bar. "false": The price of peak/bottom is set by comparison of "last close" and "current open".
// @returns [int,array<float>,array<int>,array<float>,array<int>,array<float>,array<int>,array<float>,array<int>)] int for renew price(1:renew high,0:no renew,-1:renew low) and snapshot of highlow&return-highlow price&time.
export highlow(bool _b_bartime_price=true) =>
i_renew=0
var i_last_renew=i_renew
var _a_high=array.new<float>(1,na)
var _a_time_high=array.new<int>(1,na)
var _a_return_high=array.new<float>(1,na)
var _a_time_return_high=array.new<int>(1,na)
var _a_low=array.new<float>(1,na)
var _a_time_low=array.new<int>(1,na)
var _a_return_low=array.new<float>(1,na)
var _a_time_return_low=array.new<int>(1,na)
pb =peak_bottom(is_up(),last_is_up())
if pb!=0
_high=_b_bartime_price?open: close[1]>=open?close[1]:open
_time_high=_b_bartime_price?time: close[1]>=open?time_close[1]:time
_low=_b_bartime_price?open: close[1]<=open?close[1]:open
_time_low=_b_bartime_price?time: close[1]<=open?time_close[1]:time
[tmp_i_renew,
tmp_a_high,tmp_a_time_high,tmp_a_return_high,tmp_a_time_return_high,
tmp_a_low,tmp_a_time_low,tmp_a_return_low,tmp_a_time_return_low
] =
f_renew_high_low(pb,i_last_renew,_high,_time_high,_low,_time_low,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low)
i_renew:=tmp_i_renew
_a_high:=tmp_a_high
_a_time_high:=tmp_a_time_high
_a_return_high:=tmp_a_return_high
_a_time_return_high:=tmp_a_time_return_high
_a_low:=tmp_a_low
_a_time_low:=tmp_a_time_low
_a_return_low:=tmp_a_return_low
_a_time_return_low:=tmp_a_time_return_low
i_last_renew:=i_renew!=0?i_renew:i_last_renew
[i_renew,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low]
// @function highlow for htf
// @param _m (matrix<float>) htf candle matrix.
// @param _b_bar_time_price (bool) default is "true":The price of peak/bottom is set by price of latest bar. "false": The price of peak/bottom is set by comparison of "last close" and "current open".
// @returns [int,array<float>,array<int>,array<float>,array<int>,array<float>,array<int>,array<float>,array<int>)] int for renew price(1:renew high,0:no renew,-1:renew low) and snapshot of highlow&return-highlow price&time.
export htfhighlow(matrix<float> _m,bool _b_bartime_price=true) =>
i_renew=0
var i_last_renew=i_renew
var _a_high=array.new<float>(1,na)
var _a_time_high=array.new<int>(1,na)
var _a_return_high=array.new<float>(1,na)
var _a_time_return_high=array.new<int>(1,na)
var _a_low=array.new<float>(1,na)
var _a_time_low=array.new<int>(1,na)
var _a_return_low=array.new<float>(1,na)
var _a_time_return_low=array.new<int>(1,na)
pb =peak_bottom(htf_is_up(_m),htf_last_is_up(_m))
if pb!=0
float _high=_b_bartime_price?_m.lastx("open",1): _m.lastx("close",2)>_m.lastx("open",1)?_m.lastx("close",2):_m.lastx("open",1)
int _time_high=_b_bartime_price?int(_m.lastx("time_open",1)): _m.lastx("close",2)>_m.lastx("open",1)?int(_m.lastx("time_close",2)):int(_m.lastx("time_open",1))
float _low=_b_bartime_price?_m.lastx("open",1): _m.lastx("close",2)<_m.lastx("open",1)?_m.lastx("close",2):_m.lastx("open",1)
int _time_low=_b_bartime_price?int(_m.lastx("time_open",1)): _m.lastx("close",2)<_m.lastx("open",1)?int(_m.lastx("time_close",2)):int(_m.lastx("time_open",1))
[tmp_i_renew,
tmp_a_high,tmp_a_time_high,tmp_a_return_high,tmp_a_time_return_high,
tmp_a_low,tmp_a_time_low,tmp_a_return_low,tmp_a_time_return_low
] = f_renew_high_low(pb,i_last_renew,_high,_time_high,_low,_time_low,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low)
i_renew:=tmp_i_renew
_a_high:=tmp_a_high
_a_time_high:=tmp_a_time_high
_a_return_high:=tmp_a_return_high
_a_time_return_high:=tmp_a_time_return_high
_a_low:=tmp_a_low
_a_time_low:=tmp_a_time_low
_a_return_low:=tmp_a_return_low
_a_time_return_low:=tmp_a_time_return_low
i_last_renew:=i_renew!=0?i_renew:i_last_renew
[i_renew,
_a_high,_a_time_high,_a_return_high,_a_time_return_high,
_a_low,_a_time_low,_a_return_low,_a_time_return_low]
//MA
// @function sma for htf
// @param _a_src (array<float>) htf src array
// @param _len (int) lengh
// @returns (series float) sma value
export htf_sma(array<float> _a_src,int _len) =>
_a_slice =array.new_float(0,na)
if array.size(_a_src)>_len
_last=array.size(_a_src)-1
_a_slice:=array.slice(_a_src,_last-_len+1,_last)
array.avg(_a_slice)
// @function rma for htf
// @param _a_src (array<float>) htf src array
// @param _new_bar (bool) bool for htf new bar
// @param _len (int) lengh
// @returns (series float) rma value
export htf_rma(array<float> _a_src,bool _new_bar, int _len) =>
_alpha = 1/_len
var _a_rma=array.new_float(0,na)
_rma=_a_src.size()>_len? na(_a_rma.lastx(1))? htf_sma(_a_src, _len) : _alpha * _a_src.lastx() + (1 - _alpha) * _a_rma.lastx(1) :na
if _new_bar
_a_rma.push(_rma)
else
_a_rma.set_last(_rma)
_rma
// @function ema for htf
// @param _a_src (array<float>) htf src array
// @param _new_bar (bool) bool for htf new bar
// @param _len (int) lengh
// @returns (series float) ema value
export htf_ema(array<float> _a_src,bool _new_bar,int _len) =>
_alpha = 2/(_len+1)
var _a_ema =array.new_float(0,na)
_ema = _a_src.size()>_len? na(_a_ema.lastx(1))? htf_sma(_a_src, _len) : _alpha * _a_src.lastx() + (1 - _alpha) * _a_ema.lastx(1) :na
if _new_bar
_a_ema.push(_ema)
else
_a_ema.set_last(_ema)
_ema
// @function rsi for htf
// @param _a_src (array<float>) htf src array.
// @param _new_bar (bool) bool for htf new bar.
// @param _len (int) lengh.
// @returns (series float) rsi value.
export htf_rsi(array<float> _a_src,bool _new_bar,int _len) =>
var _a_rsi_a=array.new<float>(0,na)
var _a_rsi_b=array.new<float>(0,na)
_alpha=_a_rsi_a.lastx(1)
_beta=_a_rsi_b.lastx(1)
if na(_alpha)
if array.size(_a_src)>_len
_alpha:=0.0,_beta:=0.0
for i = 0 to _len-1
_diff=_a_src.lastx(i)-_a_src.lastx(i+1)
_alpha+=_diff>0?_diff:0
_beta+=_diff<0?_diff:0
_alpha/=_len
_beta/=_len
else
_alpha*=_len-1
_beta*=_len-1
_diff=_a_src.lastx()-_a_src.lastx(1)
_alpha+=_diff>0?_diff:0
_beta+=_diff<0?_diff:0
_alpha/=_len
_beta/=_len
if _new_bar
_a_rsi_a.push(_alpha)
_a_rsi_b.push(_beta)
else
_a_rsi_a.set_last(_alpha)
_a_rsi_b.set_last(_beta)
_alpha/(_alpha+math.abs(_beta)) * 100
// @function rci for htf
// @param _a_src (float) src array
// @param _len (int) lengh
// @returns (series float) rci value
export rci(float _src,int _len) =>
d = 0.0
for i = 0 to _len -1
v = _src[i]
s = -1
o = 1
for j = 0 to _len -1
s+= v==_src[j]?1:0
o+= v<_src[j]?1:0
o:= (2*o+s)/2
d+= math.pow((i+1-o),2)
(1.0 - 6.0 * d / (math.pow(_len,3) - _len - 1.0)) * 100.0
// @function rci for htf
// @param _a_src (array<float>) htf src array
// @param _len (int) lengh
// @returns (series float) rci value
export htf_rci(array<float> _a_src,int _len) =>
d = 0.0
if array.size(_a_src)>=_len
for i = 0 to _len-1
v = _a_src.lastx(i)
s = -1
o = 1
for j = 0 to _len-1
s+= v==_a_src.lastx(j)?1:0
o+= v<_a_src.lastx(j)?1:0
o:= (2*o+s)/2
d+= math.pow((i+1-o),2)
(1.0 - 6.0 * d / (math.pow(_len,3) - _len - 1.0)) * 100.0
else
na
// @function dmi for htf
// @param _m (matrix<float>) htf candle matrix.
// @param _new_bar (bool) bool for htf new bar.
// @param _len (int) lengh.
// @param _ma_type (string) type of ma for adx.(default:"rma",["sma","ema","rma"])
// @returns [(float) adx,(float) +DI,(float) -DI]
export htf_dmi(matrix<float> _m,bool _new_bar,int _len,string _ma_type="rma") =>
var _a_plus_dm = array.new_float(0,na)
var _a_minus_dm = array.new_float(0,na)
var _a_tr =array.new_float(0,na)
var _a_plus_di = array.new_float(0,na)
var _a_minus_di = array.new_float(0,na)
var _a_dx = array.new_float(0,na)
_dm1 =_m.lastx("high")-_m.lastx("high",1)
_dm1:=_dm1<0?0:_dm1
_dm2 =_m.lastx("low",1)-_m.lastx("low")
_dm2:=_dm2<0?0:_dm2
_tr =math.max(_m.lastx("high")-_m.lastx("low"),_m.lastx("high")-_m.lastx("close",1),_m.lastx("close")-_m.lastx("low"))
if na(_a_tr.lastx()) or _new_bar
_a_plus_dm.push(_dm1)
_a_minus_dm.push(_dm2)
_a_tr.push(_tr)
else
_a_plus_dm.set_last(_dm1)
_a_minus_dm.set_last(_dm2)
_a_tr.set_last(_tr)
if _a_tr.size()>_len
_a_plus_dm_sum = array.sum(_a_plus_dm.slice(_a_plus_dm.size()-_len,_a_plus_dm.size()-1))
_a_minus_dm_sum = array.sum(_a_minus_dm.slice(_a_minus_dm.size()-_len,_a_minus_dm.size()-1))
_a_tr_sum = array.sum(_a_tr.slice(_a_tr.size()-_len,_a_tr.size()-1))
_di1= _a_plus_dm_sum/_a_tr_sum *100
_di2= _a_minus_dm_sum/_a_tr_sum *100
_dx=math.abs(_di1-_di2)/(_di1+_di2) *100
if na(_a_dx.lastx()) or _new_bar
_a_plus_di.push(_di1)
_a_minus_di.push(_di2)
_a_dx.push(_dx)
else
_a_plus_di.set_last(_di1)
_a_minus_di.set_last(_di2)
_a_dx.set_last(_dx)
switch _ma_type
"sma" => [_a_plus_di.lastx(),_a_minus_di.lastx(),htf_sma(_a_dx,_len)]
"ema" => [_a_plus_di.lastx(),_a_minus_di.lastx(),htf_ema(_a_dx,_new_bar,_len)]
"rma" => [_a_plus_di.lastx(),_a_minus_di.lastx(),htf_rma(_a_dx,_new_bar,_len)]
=>na
//
//tf_higher() sample
var tfChart=timeframe.period
var htf1=tf_higher(tfChart)
var htf2=tf_higher(htf1)
var htf3=tf_higher(htf2)
var htf4=tf_higher(htf3)
//htf_candle() sample
[b_new_bar1,m1]=htf_candle(htf1)
[b_new_bar2,m2]=htf_candle(htf2)
[b_new_bar3,m3]=htf_candle(htf3)
[b_new_bar4,m4]=htf_candle(htf4)
//highlow() and htfhighlow() sample
[i_renew,a_high,a_time_high,a_return_high,a_time_return_high,a_low,a_time_low,a_return_low,a_time_return_low] =
highlow()
[i_renew1,a_high1,a_time_high1,a_return_high1,a_time_return_high1,a_low1,a_time_low1,a_return_low1,a_time_return_low1] =
htfhighlow(m1)
[i_renew2,a_high2,a_time_high2,a_return_high2,a_time_return_high2,a_low2,a_time_low2,a_return_low2,a_time_return_low2] =
htfhighlow(m2)
[i_renew3,a_high3,a_time_high3,a_return_high3,a_time_return_high3,a_low3,a_time_low3,a_return_low3,a_time_return_low3] =
htfhighlow(m3)
[i_renew4,a_high4,a_time_high4,a_return_high4,a_time_return_high4,a_low4,a_time_low4,a_return_low4,a_time_return_low4] =
htfhighlow(m4)
//
//draw HighLowBox
//
colorBoxT=color.new(color.white,5)
colorBoxU=color.new(#aaffaa,5)
colorBoxD=color.new(#ffaaaa,5)
var mybox=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
if i_renew!=0
top= a_high.lastx()
top_time= a_time_high.lastx()
bottom= a_low.lastx()
bottom_time= a_time_low.lastx()
c_box=bottom_time<top_time?colorBoxU:colorBoxD
_h = array.from(int(top_time),int(bottom_time))
_v = array.from(top,bottom)
_t = array.max(_v)
_b = array.min(_v)
_l = array.min(_h)
mybox:=box.new(_l,na,na,na,xloc=xloc.bar_time,border_width=1,text_halign=text.align_center,text_size=size.normal,
border_color=c_box,text_color=colorBoxT,bgcolor=na,border_style=line.style_dashed)
box.set_bottom(mybox,_b)
box.set_top(mybox,_t)
box.set_text(mybox,tfChart)
box.set_right(mybox,time_close)
var mybox1=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
if i_renew1!=0
top1= a_high1.lastx()
top_time1= a_time_high1.lastx()
bottom1= a_low1.lastx()
bottom_time1= a_time_low1.lastx()
c_box=bottom_time1<top_time1?colorBoxU:colorBoxD
va1=bottom_time1<top_time1?text.align_top:text.align_bottom
_h1 = array.from(int(top_time1),int(bottom_time1))
_v1 = array.from(top1,bottom1)
_t1 = array.max(_v1)
_b1 = array.min(_v1)
_l1 = array.min(_h1)
mybox1:=box.new(_l1,na,na,na,xloc=xloc.bar_time,border_width=2,text_halign=text.align_right,text_size=size.normal,
text_valign=va1,border_color=c_box,text_color=colorBoxT,bgcolor=na,border_style=line.style_solid)
box.set_bottom(mybox1,_b1)
box.set_top(mybox1,_t1)
box.set_text(mybox1,htf1)
box.set_right(mybox1,int(m1.lastx("time_close")))
var mybox2=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
if i_renew2!=0
top2= a_high2.lastx()
top_time2= a_time_high2.lastx()
bottom2= a_low2.lastx()
bottom_time2= a_time_low2.lastx()
c_box=bottom_time2<top_time2?colorBoxU:colorBoxD
va2=bottom_time2<top_time2?text.align_top:text.align_bottom
_h2 = array.from(int(top_time2),int(bottom_time2))
_v2 = array.from(top2,bottom2)
_t2 = array.max(_v2)
_b2 = array.min(_v2)
_l2 = array.min(_h2)
mybox2:=box.new(_l2,na,na,na,xloc=xloc.bar_time,border_width=4,text_halign=text.align_right,text_size=size.normal,
text_valign=va2,border_color=c_box,text_color=colorBoxT,bgcolor=na,border_style=line.style_dashed)
box.set_bottom(mybox2,_b2)
box.set_top(mybox2,_t2)
box.set_text(mybox2,htf2)
box.set_right(mybox2,int(m2.lastx("time_close")))
//set_src() and set_htfsrc sample
mysrc="hlcc4"
src=set_src(mysrc)
sma20=ta.sma(src,20)
plot(sma20,color=color.aqua)
l20=label.new(bar_index+4,sma20,text=tfChart+":sma20",style=label.style_none,textcolor=color.aqua)
label.delete(l20[1])
a_htfsrc1=set_htfsrc(mysrc,b_new_bar1,m1)
//htf_sma(), htf_rma(), htf_ema() sample
sma20htf1=htf_sma(a_htfsrc1,20)
rma20htf1=htf_rma(a_htfsrc1,b_new_bar1,20)
ema20htf1=htf_ema(a_htfsrc1,b_new_bar1,20)
plot(sma20htf1,color=color.aqua,linewidth=2)
l20_1=label.new(bar_index+4,sma20htf1,text=htf1+":sma20",style=label.style_none,textcolor=color.aqua)
label.delete(l20_1[1])
plot(rma20htf1,color=color.orange,linewidth=2)
l20r_1=label.new(bar_index+4,rma20htf1,text=htf1+":rma20",style=label.style_none,textcolor=color.orange)
label.delete(l20r_1[1])
plot(ema20htf1,color=color.yellow,linewidth=2)
l20e_1=label.new(bar_index+4,ema20htf1,text=htf1+":ema20",style=label.style_none,textcolor=color.yellow)
label.delete(l20e_1[1])
a_htfsrc2=set_htfsrc(mysrc,b_new_bar2,m2)
sma20htf2=htf_sma(a_htfsrc2,20)
plot(sma20htf2,color=color.aqua,linewidth=3)
l20_2=label.new(bar_index+4,sma20htf2,text=htf2+":sma20",style=label.style_none,textcolor=color.aqua)
label.delete(l20_2[1])
|
OKX Signal BOT - Strategy Scanner & Orderer | https://www.tradingview.com/script/o3i7HB05/ | only_fibonacci | https://www.tradingview.com/u/only_fibonacci/ | 78 | study | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © only_fibonacci
//@version=5
indicator("OKX Signal BOT - Scanner & Orderer", overlay = true)
// FUNCTIONS
operatorReturn(i1,selected,i2)=>
switch selected
">" => i1 > i2
"<" => i1 < i2
">=" => i1 >= i2
"<=" => i1 <= i2
"=" => i1 == i2
"!=" => i1 != i2
"CROSS ABOVE" => ta.crossover(i1, i2)
"CROSS BELOW" => ta.crossunder(i1,i2)
maTypeToMa(maType,maPeriod,src)=>
switch maType
"EMA" => ta.ema(src, maPeriod)
"SMA" => ta.sma(src, maPeriod)
"RMA" => ta.rma(src, maPeriod)
=> ta.wma(src, maPeriod)
// Indicators
// ATR
atrLen = input.int(defval = 14,minval = 1, title = "ATR Length", group = "ATR")
atr = ta.atr(atrLen) // ATR
// BB
bbMiddle = input.source(defval = close, title = "BB Middle", group = "BB")
bbLen = input.int(defval = 5, title = "BB Length",minval = 1, group = "BB")
bbMult = input.int(defval = 4, title = "BB Mult",minval = 1, group = "BB" )
[middle, upper, lower] = ta.bb(bbMiddle, bbLen, bbMult) // BB
bbw = ta.bbw(middle, bbLen, bbMult) // BB Genişlik
// CCI
cciSrc = input.source(defval = close, title = "CCI Source", group = "CCI")
cciLen = input.int(defval = 10, title = "CCI Len", minval = 1, group = "CCI")
cci = ta.cci(cciSrc,cciLen) // CCI
// MA1
ma1Type = input.string("EMA", "", options = ["EMA", "SMA", "RMA", "WMA"], group = "MA 1", inline = "2ma1")
ma1Period = input.int(defval = 20, title = "Period", minval = 1, group = "MA 1", inline = "2ma1")
ma1Src = input.source(defval = close, title = "Source", group = "MA 1", inline = "2ma1")
ma1 = maTypeToMa(ma1Type,ma1Period,ma1Src)
// MA2
ma2Type = input.string("EMA", "", options = ["EMA", "SMA", "RMA", "WMA"], group = "MA 2", inline = "2ma2")
ma2Period = input.int(defval = 50, title = "Period", minval = 1, group = "MA 2", inline = "2ma2")
ma2Src = input.source(defval = close, title = "Source", group = "MA 2", inline = "2ma2")
ma2 = maTypeToMa(ma2Type,ma2Period,ma1Src)
// RSI
rsiSrc = input.source(defval = close, title = "RSI Source", group = "RSI")
rsiLen = input.int(defval = 14, title = "RSI Length", minval = 1, group = "RSI")
rsi = ta.rsi(rsiSrc,rsiLen)
// ADX
lenAdx = input.int(17, minval=1, title="DI Length", group = "ADX")
lensigAdx = input.int(14, title="ADX Smoothing", minval=1, maxval=50, group = "ADX")
[diplus, diminus, adx] = ta.dmi(lenAdx, lensigAdx)
// MFI
mfiSrc = input.source(defval = close, title = "MFI Source", group = "MFI")
mfiLen = input.int(defval = 14, title = "MFI Length", minval = 1, group = "MFI")
mfi = ta.mfi(mfiSrc,mfiLen)
// MOM
momSrc = input.source(defval = close, title = "MOM Source", group = "MOM")
momLen = input.int(defval = 14, title = "MOM Length", minval = 1, group = "MOM")
mom = ta.mom(momSrc,momLen)
indicators(selected)=>
switch selected
"MA 1" => ma1
"MA 2" => ma2
"ATR" => atr
"CCI" => cci
"RSI" => rsi
"BBW" => bbw
"ADX" => adx
"MFI" => mfi
"MOM" => mom
andORLong = input.string(defval = "AND", title = "BUY/LONG CONNECT", options = ["AND","OR"], group = "SETTINGS")
andORShort = input.string(defval = "AND", title = "SELL/SHORT CONNECT", options = ["AND","OR"], group = "SETTINGS")
futureOrSpot = "FUTURE"
// futureOrSpot = input.string(defval = "SPOT", title = "FUTURE OR SPOT ?", options = ["SPOT","FUTURE"], group = "SETTINGS")
buyList = array.new_bool()
sellList = array.new_bool()
detect(status,series,di)=>
if status
if di == "BUY/LONG"
array.push(buyList,series)
else
array.push(sellList,series)
s1Group = "❗️❗️❗️❗️ CONDITION #1 ❗️❗️❗️❗️"
s1Inline = "s1i"
s1Status = input.bool(defval = false, title = "CONDITION Active", group = s1Group )
s1Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s1Group)
s1Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s1Group, inline = s1Inline)
s1Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s1Group, inline = s1Inline)
s1Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s1Group, inline = s1Inline)
s1ValueBool = input.bool(defval = false, title = "VALUE ", group = s1Group, inline = "v1")
s1EndRight = input.float(defval = 0. , title = "2️⃣", group = s1Group, inline = "v1")
s1Series = operatorReturn(indicators(s1Left),s1Mid,s1ValueBool ? s1EndRight : indicators(s1Right))
detect(s1Status,s1Series,s1Direction)
// CONDITION 2
s2Group = "❗️❗️❗️❗️ CONDITION #2 ❗️❗️❗️❗️"
s2Inline = "s2i"
s2Status = input.bool(defval = false, title = "CONDITION Active", group = s2Group )
s2Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s2Group)
s2Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s2Group, inline = s2Inline)
s2Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s2Group, inline = s2Inline)
s2Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s2Group, inline = s2Inline)
s2ValueBool = input.bool(defval = false, title = "VALUE ", group = s2Group, inline = "v2")
s2EndRight = input.float(defval = 0. , title = "2️⃣", group = s2Group, inline = "v2")
s2Series = operatorReturn(indicators(s2Left),s2Mid,s2ValueBool ? s2EndRight : indicators(s2Right))
detect(s2Status,s2Series,s2Direction)
s3Group = "❗️❗️❗️❗️ CONDITION #3 ❗️❗️❗️❗️"
s3Inline = "s3i"
s3Status = input.bool(defval = false, title = "CONDITION Active", group = s3Group )
s3Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s3Group)
s3Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s3Group, inline = s3Inline)
s3Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s3Group, inline = s3Inline)
s3Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s3Group, inline = s3Inline)
s3ValueBool = input.bool(defval = false, title = "VALUE ", group = s3Group, inline = "v3")
s3EndRight = input.float(defval = 0. , title = "2️⃣", group = s3Group, inline = "v3")
s3Series = operatorReturn(indicators(s3Left),s3Mid,s3ValueBool ? s3EndRight : indicators(s3Right))
detect(s3Status,s3Series,s3Direction)
s4Group = "❗️❗️❗️❗️ CONDITION #4 ❗️❗️❗️❗️"
s4Inline = "s4i"
s4Status = input.bool(defval = false, title = "CONDITION Active", group = s4Group )
s4Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s4Group)
s4Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s4Group, inline = s4Inline)
s4Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s4Group, inline = s4Inline)
s4Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s4Group, inline = s4Inline)
s4ValueBool = input.bool(defval = false, title = "VALUE ", group = s4Group, inline = "v4")
s4EndRight = input.float(defval = 0. , title = "2️⃣", group = s4Group, inline = "v4")
s4Series = operatorReturn(indicators(s4Left),s4Mid,s4ValueBool ? s4EndRight : indicators(s4Right))
detect(s4Status,s4Series,s4Direction)
s5Group = "❗️❗️❗️❗️ CONDITION #5 ❗️❗️❗️❗️"
s5Inline = "s5i"
s5Status = input.bool(defval = false, title = "CONDITION Active", group = s5Group )
s5Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s5Group)
s5Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s5Group, inline = s5Inline)
s5Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s5Group, inline = s5Inline)
s5Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s5Group, inline = s5Inline)
s5ValueBool = input.bool(defval = false, title = "VALUE ", group = s5Group, inline = "v5")
s5EndRight = input.float(defval = 0. , title = "2️⃣", group = s5Group, inline = "v5")
s5Series = operatorReturn(indicators(s5Left),s5Mid,s5ValueBool ? s5EndRight : indicators(s5Right))
detect(s5Status,s5Series,s5Direction)
s6Group = "❗️❗️❗️❗️ CONDITION #6 ❗️❗️❗️❗️"
s6Inline = "s6i"
s6Status = input.bool(defval = false, title = "CONDITION Active", group = s6Group )
s6Direction = input.string(defval = "BUY/LONG", title = "Direction",options = ["BUY/LONG","SELL/SHORT"], group = s6Group)
s6Left = input.string(defval = "CCI", title = "1️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s6Group, inline = s6Inline)
s6Mid = input.string(defval = ">=", title = "", options = [">","<",">=","<=","=","!=","CROSS ABOVE","CROSS BELOW"], group = s6Group, inline = s6Inline)
s6Right = input.string(defval = "CCI", title = "2️⃣", options = ["ATR","MA 1","MA 2","RSI","CCI","BBW", "ADX","MFI","MOM"], group = s6Group, inline = s6Inline)
s6ValueBool = input.bool(defval = false, title = "VALUE ", group = s6Group, inline = "v6")
s6EndRight = input.float(defval = 0. , title = "2️⃣", group = s6Group, inline = "v6")
s6Series = operatorReturn(indicators(s6Left),s6Mid,s6ValueBool ? s6EndRight : indicators(s6Right))
detect(s6Status,s6Series,s6Direction)
okxSignalId = input.string(defval = "", title = "OKX Signal ID")
// SCANNER
sembol1 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S1")
sembol2 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S2")
sembol3 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S3")
sembol4 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S4")
sembol5 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S5")
sembol6 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S6")
sembol7 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S7")
sembol8 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S8")
sembol9 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S9")
sembol10 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S10")
sembol11 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S11")
sembol12 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S12")
sembol13 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S13")
sembol14 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S14")
sembol15 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S15")
sembol16 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S16")
sembol17 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S17")
sembol18 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S18")
sembol19 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S19")
sembol20 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S20")
sembol21 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S21")
sembol22 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S22")
sembol23 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S23")
sembol24 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S24")
sembol25 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S25")
sembol26 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S26")
sembol27 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S27")
sembol28 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S28")
sembol29 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S29")
sembol30 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S30")
sembol31 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S31")
sembol32 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S32")
sembol33 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S33")
sembol34 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S34")
sembol35 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S35")
sembol36 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S36")
sembol37 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S37")
sembol38 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S38")
sembol39 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S39")
sembol40 = input.symbol(defval = "", title = "Symbol", group = "SCANNER",inline = "S40")
alarmTetikle(sembol_adi)=>
long_entry_text = "ENTER_LONG"
long_exit_text = "EXIT_LONG"
short_entry_text = "ENTER_SHORT"
short_exit_text = "EXIT_SHORT"
durum_long_entry = request.security(sembol_adi,timeframe.period,andORLong == "AND" ? array.every(buyList) : array.includes(buyList,true))
durum_short_entry = request.security(sembol_adi,timeframe.period,andORShort == "AND" ? array.every(sellList) : array.includes(sellList,true))
long_enter_json = '{"action": "'+long_entry_text+'", "instrument": "'+syminfo.ticker(sembol_adi)+'", "signalToken": "'+okxSignalId+'", "timestamp": "'+str.tostring(time)+'", "maxLag": "60"}'
long_exit_json = '{"action": "'+long_exit_text+'", "instrument": "'+syminfo.ticker(sembol_adi)+'", "signalToken": "'+okxSignalId+'", "timestamp": "'+str.tostring(time)+'", "maxLag": "60"}'
short_enter_json = '{"action": "'+short_entry_text+'", "instrument": "'+syminfo.ticker(sembol_adi)+'", "signalToken": "'+okxSignalId+'", "timestamp": "'+str.tostring(time)+'", "maxLag": "60"}'
short_exit_json = '{"action": "'+short_exit_text+'", "instrument": "'+syminfo.ticker(sembol_adi)+'", "signalToken": "'+okxSignalId+'", "timestamp": "'+str.tostring(time)+'", "maxLag": "60"}'
if durum_long_entry and str.length(sembol_adi) > 1
alert(short_exit_json,freq = alert.freq_once_per_bar)
alert(long_enter_json,freq = alert.freq_once_per_bar)
if durum_short_entry and str.length(sembol_adi) > 1
alert(long_exit_json,freq = alert.freq_once_per_bar)
alert(short_enter_json,freq = alert.freq_once_per_bar)
alarmTetikle(sembol1)
alarmTetikle(sembol2)
alarmTetikle(sembol3)
alarmTetikle(sembol4)
alarmTetikle(sembol5)
alarmTetikle(sembol6)
alarmTetikle(sembol7)
alarmTetikle(sembol8)
alarmTetikle(sembol9)
alarmTetikle(sembol10)
alarmTetikle(sembol11)
alarmTetikle(sembol12)
alarmTetikle(sembol13)
alarmTetikle(sembol14)
alarmTetikle(sembol15)
alarmTetikle(sembol16)
alarmTetikle(sembol17)
alarmTetikle(sembol18)
alarmTetikle(sembol19)
alarmTetikle(sembol20)
|
K`s Extreme Duration | https://www.tradingview.com/script/LXYSLGAn-K-s-Extreme-Duration/ | Sofien-Kaabar | https://www.tradingview.com/u/Sofien-Kaabar/ | 96 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sofien-Kaabar
//@version=5
indicator('K`s Extreme Duration', overlay = true)
upper_barrier = input(defval = 65, title = 'Upper Barrier')
lower_barrier = input(defval = 35, title = 'Lower Barrier')
length = input(defval = 8, title = 'Lookback')
rsi = ta.rsi(close, length)
buy = low < open[1] and rsi[1] < 50 and rsi[1] > lower_barrier and rsi[2] < lower_barrier[2] and rsi[3] < lower_barrier[3] and rsi[4] < lower_barrier[4] and rsi[5] < lower_barrier[5] and rsi[6] < lower_barrier[6]
sell = high > open[1] and rsi[1] > 50 and rsi[1] < upper_barrier and rsi[2] > upper_barrier[2] and rsi[3] > upper_barrier[3] and rsi[4] > upper_barrier[4] and rsi[5] > upper_barrier[5] and rsi[6] > upper_barrier[6]
plotshape(buy, style = shape.triangleup, color = color.green, location = location.belowbar, size = size.small)
plotshape(sell, style = shape.triangledown, color = color.red, location = location.abovebar, size = size.small)
|
CalendarCad | https://www.tradingview.com/script/2DluLp72-CalendarCad/ | wppqqppq | https://www.tradingview.com/u/wppqqppq/ | 0 | 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/
// © wppqqppq
//@version=5
// @description This library provides date and time data of the important events on CAD. Data source is csv exported from https://www.fxstreet.com/economic-calendar and transformed into perfered format by C# script.
library("CalendarCad")
// @function CAD high impact news date and time from 2015 to 2023
export HighImpactNews2015To2023() =>
array.from(
timestamp("2015-01-09T13:30:00"),
timestamp("2015-01-09T13:30:00"),
timestamp("2015-01-21T15:00:00"),
timestamp("2015-01-21T15:00:00"),
timestamp("2015-01-21T15:00:00"),
timestamp("2015-01-21T16:15:00"),
timestamp("2015-01-23T13:30:00"),
timestamp("2015-01-23T13:30:00"),
timestamp("2015-02-06T13:30:00"),
timestamp("2015-02-06T13:30:00"),
timestamp("2015-02-24T19:00:00"),
timestamp("2015-02-26T13:30:00"),
timestamp("2015-02-26T13:30:00"),
timestamp("2015-03-03T13:30:00"),
timestamp("2015-03-04T15:00:00"),
timestamp("2015-03-04T15:00:00"),
timestamp("2015-03-13T12:30:00"),
timestamp("2015-03-13T12:30:00"),
timestamp("2015-03-20T12:30:00"),
timestamp("2015-03-20T12:30:00"),
timestamp("2015-03-26T13:30:00"),
timestamp("2015-04-10T12:30:00"),
timestamp("2015-04-10T12:30:00"),
timestamp("2015-04-15T14:00:00"),
timestamp("2015-04-15T14:00:00"),
timestamp("2015-04-15T14:00:00"),
timestamp("2015-04-15T15:15:00"),
timestamp("2015-04-17T12:30:00"),
timestamp("2015-04-17T12:30:00"),
timestamp("2015-04-20T14:05:00"),
timestamp("2015-04-24T14:30:00"),
timestamp("2015-04-28T12:45:52"),
timestamp("2015-05-08T12:30:00"),
timestamp("2015-05-08T12:30:00"),
timestamp("2015-05-19T15:45:00"),
timestamp("2015-05-22T12:30:00"),
timestamp("2015-05-27T14:00:00"),
timestamp("2015-05-27T14:00:00"),
timestamp("2015-06-05T12:30:00"),
timestamp("2015-06-05T12:30:00"),
timestamp("2015-06-19T12:30:00"),
timestamp("2015-06-19T12:30:00"),
timestamp("2015-06-19T12:30:00"),
timestamp("2015-06-19T12:30:00"),
timestamp("2015-07-10T12:30:00"),
timestamp("2015-07-10T12:30:00"),
timestamp("2015-07-15T14:00:00"),
timestamp("2015-07-15T14:00:00"),
timestamp("2015-07-15T15:15:00"),
timestamp("2015-07-17T12:30:00"),
timestamp("2015-07-17T12:30:00"),
timestamp("2015-07-23T12:30:00"),
timestamp("2015-08-07T12:30:00"),
timestamp("2015-08-07T12:30:00"),
timestamp("2015-08-21T12:30:00"),
timestamp("2015-08-21T12:30:00"),
timestamp("2015-09-04T12:30:00"),
timestamp("2015-09-04T12:30:00"),
timestamp("2015-09-09T14:00:00"),
timestamp("2015-09-09T14:00:00"),
timestamp("2015-09-18T12:30:00"),
timestamp("2015-09-18T12:30:00"),
timestamp("2015-09-21T18:45:00"),
timestamp("2015-10-09T12:30:00"),
timestamp("2015-10-09T12:30:00"),
timestamp("2015-10-10T18:45:00"),
timestamp("2015-10-12T17:20:00"),
timestamp("2015-10-21T14:00:00"),
timestamp("2015-10-21T14:00:00"),
timestamp("2015-10-21T14:00:00"),
timestamp("2015-10-21T15:15:00"),
timestamp("2015-10-23T12:30:00"),
timestamp("2015-10-23T12:30:00"),
timestamp("2015-11-06T13:30:00"),
timestamp("2015-11-06T13:30:00"),
timestamp("2015-11-20T13:30:00"),
timestamp("2015-11-20T13:30:00"),
timestamp("2015-12-01T13:30:00"),
timestamp("2015-12-02T15:00:00"),
timestamp("2015-12-02T15:00:00"),
timestamp("2015-12-04T13:30:00"),
timestamp("2015-12-04T13:30:00"),
timestamp("2015-12-08T17:50:00"),
timestamp("2015-12-15T16:45:00"),
timestamp("2015-12-18T13:30:00"),
timestamp("2015-12-18T13:30:00"),
timestamp("2016-01-07T13:25:00"),
timestamp("2016-01-08T13:30:00"),
timestamp("2016-01-08T13:30:00"),
timestamp("2016-01-08T13:30:00"),
timestamp("2016-01-20T15:00:00"),
timestamp("2016-01-20T15:00:00"),
timestamp("2016-01-20T15:00:00"),
timestamp("2016-01-20T16:15:00"),
timestamp("2016-02-05T13:30:00"),
timestamp("2016-02-05T13:30:00"),
timestamp("2016-02-19T13:30:00"),
timestamp("2016-02-19T13:30:00"),
timestamp("2016-03-09T15:00:00"),
timestamp("2016-03-11T13:30:00"),
timestamp("2016-03-11T13:30:00"),
timestamp("2016-03-18T12:30:00"),
timestamp("2016-03-18T12:30:00"),
timestamp("2016-04-04T14:00:00"),
timestamp("2016-04-13T14:00:00"),
timestamp("2016-04-13T14:00:00"),
timestamp("2016-04-13T14:00:00"),
timestamp("2016-04-13T15:15:00"),
timestamp("2016-04-19T15:00:00"),
timestamp("2016-04-20T20:15:00"),
timestamp("2016-04-22T12:30:00"),
timestamp("2016-04-22T12:30:00"),
timestamp("2016-04-22T12:30:00"),
timestamp("2016-04-22T12:30:00"),
timestamp("2016-04-22T12:30:00"),
timestamp("2016-04-26T12:40:00"),
timestamp("2016-05-03T16:30:00"),
timestamp("2016-05-20T12:30:00"),
timestamp("2016-05-20T12:30:00"),
timestamp("2016-05-25T14:00:00"),
timestamp("2016-05-25T14:00:00"),
timestamp("2016-06-09T15:15:00"),
timestamp("2016-06-15T23:40:00"),
timestamp("2016-06-17T12:30:00"),
timestamp("2016-06-17T12:30:00"),
timestamp("2016-07-13T14:00:00"),
timestamp("2016-07-13T14:00:00"),
timestamp("2016-07-13T14:00:00"),
timestamp("2016-07-13T15:15:00"),
timestamp("2016-07-22T12:30:00"),
timestamp("2016-07-22T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-08-19T12:30:00"),
timestamp("2016-09-07T14:00:00"),
timestamp("2016-09-07T14:00:00"),
timestamp("2016-09-23T12:30:00"),
timestamp("2016-10-19T14:00:00"),
timestamp("2016-10-19T14:00:00"),
timestamp("2016-10-19T14:00:00"),
timestamp("2016-10-19T15:15:00"),
timestamp("2016-10-19T20:15:00"),
timestamp("2016-10-24T18:30:00"),
timestamp("2016-11-01T16:00:00"),
timestamp("2016-11-04T12:30:00"),
timestamp("2016-11-04T12:30:00"),
timestamp("2016-11-11T15:50:00"),
timestamp("2016-12-07T15:00:00"),
timestamp("2016-12-07T15:00:00"),
timestamp("2016-12-15T16:15:00"),
timestamp("2017-01-18T15:00:00"),
timestamp("2017-01-18T15:00:00"),
timestamp("2017-01-18T15:00:00"),
timestamp("2017-01-18T16:15:00"),
timestamp("2017-01-31T22:35:00"),
timestamp("2017-02-10T13:30:00"),
timestamp("2017-02-10T13:30:00"),
timestamp("2017-02-22T13:30:00"),
timestamp("2017-03-01T15:00:00"),
timestamp("2017-03-01T15:00:00"),
timestamp("2017-03-10T13:30:00"),
timestamp("2017-03-10T13:30:00"),
timestamp("2017-04-07T12:30:00"),
timestamp("2017-04-07T12:30:00"),
timestamp("2017-04-12T14:00:00"),
timestamp("2017-04-12T14:00:00"),
timestamp("2017-04-12T14:00:00"),
timestamp("2017-04-12T15:15:00"),
timestamp("2017-04-12T20:15:00"),
timestamp("2017-04-13T14:30:00"),
timestamp("2017-05-04T20:25:00"),
timestamp("2017-05-05T12:30:00"),
timestamp("2017-05-05T12:30:00"),
timestamp("2017-05-24T14:00:00"),
timestamp("2017-05-24T14:00:00"),
timestamp("2017-06-08T15:15:00"),
timestamp("2017-06-09T12:30:00"),
timestamp("2017-06-09T12:30:00"),
timestamp("2017-06-28T13:30:00"),
timestamp("2017-07-07T12:30:00"),
timestamp("2017-07-07T12:30:00"),
timestamp("2017-07-12T14:00:00"),
timestamp("2017-07-12T14:00:00"),
timestamp("2017-07-12T14:00:00"),
timestamp("2017-07-12T15:15:00"),
timestamp("2017-07-21T12:30:00"),
timestamp("2017-08-04T12:30:00"),
timestamp("2017-08-04T12:30:00"),
timestamp("2017-09-06T14:00:00"),
timestamp("2017-09-06T14:00:00"),
timestamp("2017-09-08T12:30:00"),
timestamp("2017-09-08T12:30:00"),
timestamp("2017-09-27T15:45:00"),
timestamp("2017-10-06T12:30:00"),
timestamp("2017-10-06T12:30:00"),
timestamp("2017-10-25T14:00:00"),
timestamp("2017-10-25T14:00:00"),
timestamp("2017-10-25T14:00:00"),
timestamp("2017-10-25T15:15:00"),
timestamp("2017-10-31T19:30:00"),
timestamp("2017-11-01T20:15:00"),
timestamp("2017-11-03T12:30:00"),
timestamp("2017-11-03T12:30:00"),
timestamp("2017-11-07T17:55:00"),
timestamp("2017-11-28T16:30:00"),
timestamp("2017-12-01T13:30:00"),
timestamp("2017-12-01T13:30:00"),
timestamp("2017-12-01T13:30:00"),
timestamp("2017-12-06T15:00:00"),
timestamp("2017-12-06T15:00:00"),
timestamp("2017-12-14T17:25:00"),
timestamp("2018-01-05T13:30:00"),
timestamp("2018-01-05T13:30:00"),
timestamp("2018-01-17T15:00:00"),
timestamp("2018-01-17T15:00:00"),
timestamp("2018-01-17T15:00:00"),
timestamp("2018-01-17T16:15:00"),
timestamp("2018-01-25T13:30:00"),
timestamp("2018-02-09T13:30:00"),
timestamp("2018-02-09T13:30:00"),
timestamp("2018-02-22T13:30:00"),
timestamp("2018-02-23T13:30:00"),
timestamp("2018-02-23T13:30:00"),
timestamp("2018-03-02T13:30:00"),
timestamp("2018-03-07T15:00:00"),
timestamp("2018-03-07T15:00:00"),
timestamp("2018-03-08T16:00:00"),
timestamp("2018-03-09T13:30:00"),
timestamp("2018-03-09T13:30:00"),
timestamp("2018-03-13T14:30:00"),
timestamp("2018-03-23T12:30:00"),
timestamp("2018-03-23T12:30:00"),
timestamp("2018-04-06T12:30:00"),
timestamp("2018-04-06T12:30:00"),
timestamp("2018-04-18T14:00:00"),
timestamp("2018-04-18T14:00:00"),
timestamp("2018-04-18T14:00:00"),
timestamp("2018-04-18T15:15:00"),
timestamp("2018-04-20T12:30:00"),
timestamp("2018-04-20T12:30:00"),
timestamp("2018-04-23T19:30:00"),
timestamp("2018-04-25T20:15:00"),
timestamp("2018-05-01T18:30:00"),
timestamp("2018-05-11T12:30:00"),
timestamp("2018-05-11T12:30:00"),
timestamp("2018-05-18T12:30:00"),
timestamp("2018-05-18T12:30:00"),
timestamp("2018-05-30T14:00:00"),
timestamp("2018-05-30T14:00:00"),
timestamp("2018-05-31T12:30:00"),
timestamp("2018-06-07T15:15:00"),
timestamp("2018-06-08T12:30:00"),
timestamp("2018-06-08T12:30:00"),
timestamp("2018-06-22T12:30:00"),
timestamp("2018-06-22T12:30:00"),
timestamp("2018-06-27T19:00:00"),
timestamp("2018-07-06T12:30:00"),
timestamp("2018-07-06T12:30:00"),
timestamp("2018-07-11T14:00:00"),
timestamp("2018-07-11T14:00:00"),
timestamp("2018-07-11T14:00:00"),
timestamp("2018-07-11T15:15:00"),
timestamp("2018-07-20T12:30:00"),
timestamp("2018-07-20T12:30:00"),
timestamp("2018-08-10T12:30:00"),
timestamp("2018-08-10T12:30:00"),
timestamp("2018-08-17T12:30:00"),
timestamp("2018-08-22T12:30:00"),
timestamp("2018-08-25T16:25:00"),
timestamp("2018-08-30T12:30:00"),
timestamp("2018-09-05T14:00:00"),
timestamp("2018-09-05T14:00:00"),
timestamp("2018-09-07T12:30:00"),
timestamp("2018-09-07T12:30:00"),
timestamp("2018-09-21T12:30:00"),
timestamp("2018-09-21T12:30:00"),
timestamp("2018-09-27T21:45:00"),
timestamp("2018-10-05T12:30:00"),
timestamp("2018-10-05T12:30:00"),
timestamp("2018-10-19T12:30:00"),
timestamp("2018-10-19T12:30:00"),
timestamp("2018-10-24T14:00:00"),
timestamp("2018-10-24T14:00:00"),
timestamp("2018-10-24T14:00:00"),
timestamp("2018-10-24T15:15:00"),
timestamp("2018-10-30T19:30:00"),
timestamp("2018-10-31T20:15:00"),
timestamp("2018-11-02T12:30:00"),
timestamp("2018-11-02T12:30:00"),
timestamp("2018-11-05T13:10:00"),
timestamp("2018-11-23T13:30:00"),
timestamp("2018-11-23T13:30:00"),
timestamp("2018-11-30T13:30:00"),
timestamp("2018-12-05T15:00:00"),
timestamp("2018-12-05T15:00:00"),
timestamp("2018-12-06T13:50:00"),
timestamp("2018-12-07T13:30:00"),
timestamp("2018-12-07T13:30:00"),
timestamp("2018-12-19T13:30:00"),
timestamp("2018-12-21T13:30:00"),
timestamp("2019-01-04T13:30:00"),
timestamp("2019-01-04T13:30:00"),
timestamp("2019-01-09T15:00:00"),
timestamp("2019-01-09T15:00:00"),
timestamp("2019-01-09T15:00:00"),
timestamp("2019-01-09T16:15:00"),
timestamp("2019-01-18T13:30:00"),
timestamp("2019-01-23T13:30:00"),
timestamp("2019-02-08T13:30:00"),
timestamp("2019-02-08T13:30:00"),
timestamp("2019-02-21T17:35:00"),
timestamp("2019-02-22T13:30:00"),
timestamp("2019-02-27T13:30:00"),
timestamp("2019-03-01T13:30:00"),
timestamp("2019-03-06T15:00:00"),
timestamp("2019-03-06T15:00:00"),
timestamp("2019-03-08T13:30:00"),
timestamp("2019-03-08T13:30:00"),
timestamp("2019-03-22T12:30:00"),
timestamp("2019-03-22T12:30:00"),
timestamp("2019-04-01T18:55:00"),
timestamp("2019-04-05T12:30:00"),
timestamp("2019-04-05T12:30:00"),
timestamp("2019-04-17T12:30:00"),
timestamp("2019-04-18T12:30:00"),
timestamp("2019-04-24T14:00:00"),
timestamp("2019-04-24T14:00:00"),
timestamp("2019-04-24T14:00:00"),
timestamp("2019-04-24T15:15:00"),
timestamp("2019-04-30T15:00:00"),
timestamp("2019-05-01T20:15:00"),
timestamp("2019-05-06T17:45:00"),
timestamp("2019-05-10T12:30:00"),
timestamp("2019-05-10T12:30:00"),
timestamp("2019-05-15T12:30:00"),
timestamp("2019-05-16T15:15:00"),
timestamp("2019-05-22T12:30:00"),
timestamp("2019-05-29T14:00:00"),
timestamp("2019-05-29T14:00:00"),
timestamp("2019-05-31T12:30:00"),
timestamp("2019-06-07T12:30:00"),
timestamp("2019-06-07T12:30:00"),
timestamp("2019-06-19T12:30:00"),
timestamp("2019-06-21T12:30:00"),
timestamp("2019-07-05T12:30:00"),
timestamp("2019-07-05T12:30:00"),
timestamp("2019-07-10T14:00:00"),
timestamp("2019-07-10T14:00:00"),
timestamp("2019-07-10T14:00:00"),
timestamp("2019-07-10T15:15:00"),
timestamp("2019-07-17T12:30:00"),
timestamp("2019-07-19T12:30:00"),
timestamp("2019-08-09T12:30:00"),
timestamp("2019-08-09T12:30:00"),
timestamp("2019-08-21T12:30:00"),
timestamp("2019-08-23T12:30:00"),
timestamp("2019-08-30T12:30:00"),
timestamp("2019-09-04T14:00:00"),
timestamp("2019-09-04T14:00:00"),
timestamp("2019-09-06T12:30:00"),
timestamp("2019-09-06T12:30:00"),
timestamp("2019-09-18T12:30:00"),
timestamp("2019-09-20T12:30:00"),
timestamp("2019-10-11T12:30:00"),
timestamp("2019-10-11T12:30:00"),
timestamp("2019-10-16T12:30:00"),
timestamp("2019-10-22T12:30:00"),
timestamp("2019-10-30T14:00:00"),
timestamp("2019-10-30T14:00:00"),
timestamp("2019-10-30T14:00:00"),
timestamp("2019-10-30T15:15:00"),
timestamp("2019-11-08T13:30:00"),
timestamp("2019-11-08T13:30:00"),
timestamp("2019-11-15T02:45:00"),
timestamp("2019-11-20T13:30:00"),
timestamp("2019-11-21T13:40:00"),
timestamp("2019-11-22T13:30:00"),
timestamp("2019-11-29T13:30:00"),
timestamp("2019-12-04T15:00:00"),
timestamp("2019-12-04T15:00:00"),
timestamp("2019-12-04T16:15:00"),
timestamp("2019-12-06T13:30:00"),
timestamp("2019-12-06T13:30:00"),
timestamp("2019-12-12T17:45:00"),
timestamp("2019-12-18T13:30:00"),
timestamp("2019-12-20T13:30:00"),
timestamp("2020-01-09T19:00:00"),
timestamp("2020-01-10T13:30:00"),
timestamp("2020-01-10T13:30:00"),
timestamp("2020-01-22T13:30:00"),
timestamp("2020-01-22T15:00:00"),
timestamp("2020-01-22T15:00:00"),
timestamp("2020-01-22T15:00:00"),
timestamp("2020-01-22T16:15:00"),
timestamp("2020-01-24T13:30:00"),
timestamp("2020-02-07T13:30:00"),
timestamp("2020-02-07T13:30:00"),
timestamp("2020-02-13T00:15:00"),
timestamp("2020-02-19T13:30:00"),
timestamp("2020-02-21T13:30:00"),
timestamp("2020-02-28T13:30:00"),
timestamp("2020-03-04T15:00:00"),
timestamp("2020-03-04T15:00:00"),
timestamp("2020-03-05T17:45:00"),
timestamp("2020-03-06T13:30:00"),
timestamp("2020-03-06T13:30:00"),
timestamp("2020-03-13T18:00:00"),
timestamp("2020-03-13T18:00:00"),
timestamp("2020-03-18T12:30:00"),
timestamp("2020-03-18T15:15:00"),
timestamp("2020-03-20T12:30:00"),
timestamp("2020-03-27T13:00:00"),
timestamp("2020-03-27T13:00:00"),
timestamp("2020-03-27T13:15:00"),
timestamp("2020-04-09T12:30:00"),
timestamp("2020-04-09T12:30:00"),
timestamp("2020-04-15T14:00:00"),
timestamp("2020-04-15T14:00:00"),
timestamp("2020-04-15T14:00:00"),
timestamp("2020-04-15T14:30:00"),
timestamp("2020-04-16T20:00:00"),
timestamp("2020-04-21T12:30:00"),
timestamp("2020-04-22T12:30:00"),
timestamp("2020-05-08T12:30:00"),
timestamp("2020-05-08T12:30:00"),
timestamp("2020-05-20T12:30:00"),
timestamp("2020-05-22T12:30:00"),
timestamp("2020-05-25T17:30:00"),
timestamp("2020-05-26T21:00:00"),
timestamp("2020-05-29T12:30:00"),
timestamp("2020-06-03T14:00:00"),
timestamp("2020-06-03T14:00:00"),
timestamp("2020-06-05T12:30:00"),
timestamp("2020-06-05T12:30:00"),
timestamp("2020-06-17T12:30:00"),
timestamp("2020-06-19T12:30:00"),
timestamp("2020-06-19T12:30:30"),
timestamp("2020-06-22T15:00:00"),
timestamp("2020-07-10T12:30:00"),
timestamp("2020-07-10T12:30:00"),
timestamp("2020-07-15T14:00:00"),
timestamp("2020-07-15T14:00:00"),
timestamp("2020-07-15T14:00:00"),
timestamp("2020-07-15T15:15:00"),
timestamp("2020-07-21T12:30:00"),
timestamp("2020-07-21T12:30:05"),
timestamp("2020-07-22T12:30:00"),
timestamp("2020-08-07T12:30:00"),
timestamp("2020-08-07T12:30:00"),
timestamp("2020-08-19T12:30:00"),
timestamp("2020-08-21T12:30:00"),
timestamp("2020-08-21T12:30:10"),
timestamp("2020-08-27T15:15:00"),
timestamp("2020-08-28T12:30:00"),
timestamp("2020-09-04T12:30:00"),
timestamp("2020-09-04T12:30:00"),
timestamp("2020-09-09T14:00:00"),
timestamp("2020-09-09T14:00:00"),
timestamp("2020-09-10T16:30:00"),
timestamp("2020-09-16T12:30:00"),
timestamp("2020-09-18T12:30:00"),
timestamp("2020-09-18T12:30:10"),
timestamp("2020-10-08T12:30:00"),
timestamp("2020-10-09T12:30:00"),
timestamp("2020-10-09T12:30:00"),
timestamp("2020-10-21T12:30:00"),
timestamp("2020-10-21T12:30:00"),
timestamp("2020-10-21T12:30:10"),
timestamp("2020-10-28T14:00:00"),
timestamp("2020-10-28T14:00:00"),
timestamp("2020-10-28T14:00:00"),
timestamp("2020-10-28T15:15:00"),
timestamp("2020-11-06T13:30:00"),
timestamp("2020-11-06T13:30:00"),
timestamp("2020-11-06T14:00:00"),
timestamp("2020-11-17T19:00:00"),
timestamp("2020-11-18T13:30:00"),
timestamp("2020-11-20T13:30:00"),
timestamp("2020-11-20T13:30:10"),
timestamp("2020-12-01T13:30:00"),
timestamp("2020-12-04T13:30:00"),
timestamp("2020-12-04T13:30:00"),
timestamp("2020-12-09T15:00:00"),
timestamp("2020-12-09T15:00:00"),
timestamp("2020-12-15T19:30:00"),
timestamp("2020-12-16T13:30:00"),
timestamp("2020-12-18T13:30:00"),
timestamp("2021-01-08T13:30:00"),
timestamp("2021-01-08T13:30:00"),
timestamp("2021-01-20T13:30:00"),
timestamp("2021-01-20T15:00:00"),
timestamp("2021-01-20T15:00:00"),
timestamp("2021-01-20T15:00:00"),
timestamp("2021-01-20T16:15:00"),
timestamp("2021-01-22T13:30:00"),
timestamp("2021-02-05T13:30:00"),
timestamp("2021-02-05T13:30:00"),
timestamp("2021-02-17T13:30:00"),
timestamp("2021-02-19T13:30:00"),
timestamp("2021-02-23T17:30:00"),
timestamp("2021-03-02T13:30:00"),
timestamp("2021-03-10T15:00:00"),
timestamp("2021-03-10T15:00:00"),
timestamp("2021-03-12T13:30:00"),
timestamp("2021-03-12T13:30:00"),
timestamp("2021-03-17T12:30:00"),
timestamp("2021-03-19T12:30:00"),
timestamp("2021-03-25T09:30:00"),
timestamp("2021-04-09T12:30:00"),
timestamp("2021-04-09T12:30:00"),
timestamp("2021-04-21T12:30:00"),
timestamp("2021-04-21T14:00:00"),
timestamp("2021-04-21T14:00:00"),
timestamp("2021-04-21T14:00:00"),
timestamp("2021-04-21T15:00:00"),
timestamp("2021-04-27T20:00:00"),
timestamp("2021-04-28T12:30:00"),
timestamp("2021-05-05T22:30:00"),
timestamp("2021-05-07T12:30:00"),
timestamp("2021-05-07T12:30:00"),
timestamp("2021-05-13T15:00:00"),
timestamp("2021-05-19T12:30:00"),
timestamp("2021-05-21T12:30:00"),
timestamp("2021-06-01T12:30:00"),
timestamp("2021-06-04T12:30:00"),
timestamp("2021-06-04T12:30:00"),
timestamp("2021-06-09T14:00:00"),
timestamp("2021-06-09T14:00:00"),
timestamp("2021-06-16T12:30:00"),
timestamp("2021-06-16T22:30:00"),
timestamp("2021-06-23T12:30:00"),
timestamp("2021-07-09T12:30:00"),
timestamp("2021-07-09T12:30:00"),
timestamp("2021-07-14T14:00:00"),
timestamp("2021-07-14T14:00:00"),
timestamp("2021-07-14T14:00:00"),
timestamp("2021-07-14T15:15:00"),
timestamp("2021-07-23T12:30:00"),
timestamp("2021-07-28T12:30:00"),
timestamp("2021-08-06T12:30:00"),
timestamp("2021-08-06T12:30:00"),
timestamp("2021-08-18T12:30:00"),
timestamp("2021-08-20T12:30:00"),
timestamp("2021-08-31T12:30:00"),
timestamp("2021-09-08T14:00:00"),
timestamp("2021-09-08T14:00:00"),
timestamp("2021-09-09T16:00:00"),
timestamp("2021-09-10T12:30:00"),
timestamp("2021-09-10T12:30:00"),
timestamp("2021-09-15T12:30:00"),
timestamp("2021-09-23T12:30:00"),
timestamp("2021-10-07T16:00:00"),
timestamp("2021-10-08T12:30:00"),
timestamp("2021-10-08T12:30:00"),
timestamp("2021-10-20T12:30:00"),
timestamp("2021-10-22T12:30:00"),
timestamp("2021-10-27T14:00:00"),
timestamp("2021-10-27T14:00:00"),
timestamp("2021-10-27T14:00:00"),
timestamp("2021-10-27T15:00:00"),
timestamp("2021-11-05T12:30:00"),
timestamp("2021-11-05T12:30:00"),
timestamp("2021-11-09T22:45:00"),
timestamp("2021-11-17T13:30:00"),
timestamp("2021-11-19T13:30:00"),
timestamp("2021-11-29T19:00:00"),
timestamp("2021-11-30T13:30:00"),
timestamp("2021-12-03T13:30:00"),
timestamp("2021-12-03T13:30:00"),
timestamp("2021-12-08T15:00:00"),
timestamp("2021-12-08T15:00:00"),
timestamp("2021-12-13T15:00:00"),
timestamp("2021-12-13T15:30:00"),
timestamp("2021-12-15T13:30:00"),
timestamp("2021-12-15T17:00:00"),
timestamp("2021-12-21T13:30:00"),
timestamp("2022-01-07T13:30:00"),
timestamp("2022-01-07T13:30:00"),
timestamp("2022-01-19T13:30:00"),
timestamp("2022-01-21T13:30:00"),
timestamp("2022-01-26T15:00:00"),
timestamp("2022-01-26T15:00:00"),
timestamp("2022-01-26T15:00:00"),
timestamp("2022-01-26T16:00:00"),
timestamp("2022-02-02T20:00:00"),
timestamp("2022-02-04T13:30:00"),
timestamp("2022-02-04T13:30:00"),
timestamp("2022-02-09T17:00:00"),
timestamp("2022-02-16T13:30:00"),
timestamp("2022-02-18T13:30:00"),
timestamp("2022-03-01T13:30:00"),
timestamp("2022-03-02T15:00:00"),
timestamp("2022-03-02T15:00:00"),
timestamp("2022-03-03T16:30:00"),
timestamp("2022-03-03T20:30:00"),
timestamp("2022-03-11T13:30:00"),
timestamp("2022-03-11T13:30:00"),
timestamp("2022-03-16T12:30:00"),
timestamp("2022-03-18T12:30:00"),
timestamp("2022-04-08T12:30:00"),
timestamp("2022-04-08T12:30:00"),
timestamp("2022-04-13T14:00:00"),
timestamp("2022-04-13T14:00:00"),
timestamp("2022-04-13T14:00:00"),
timestamp("2022-04-13T15:00:00"),
timestamp("2022-04-20T12:30:00"),
timestamp("2022-04-22T12:30:00"),
timestamp("2022-04-25T15:00:00"),
timestamp("2022-04-27T22:30:00"),
timestamp("2022-05-06T12:30:00"),
timestamp("2022-05-06T12:30:00"),
timestamp("2022-05-18T12:30:00"),
timestamp("2022-05-26T12:30:00"),
timestamp("2022-05-31T12:30:00"),
timestamp("2022-06-01T14:00:00"),
timestamp("2022-06-01T14:00:00"),
timestamp("2022-06-10T12:30:00"),
timestamp("2022-06-10T12:30:00"),
timestamp("2022-06-21T12:30:00"),
timestamp("2022-06-22T12:30:00"),
timestamp("2022-07-08T12:30:00"),
timestamp("2022-07-08T12:30:00"),
timestamp("2022-07-13T14:00:00"),
timestamp("2022-07-13T14:00:00"),
timestamp("2022-07-13T14:00:00"),
timestamp("2022-07-13T15:00:00"),
timestamp("2022-07-20T12:30:00"),
timestamp("2022-07-22T12:30:00"),
timestamp("2022-08-05T12:30:00"),
timestamp("2022-08-05T12:30:00"),
timestamp("2022-08-16T12:30:00"),
timestamp("2022-08-19T12:30:00"),
timestamp("2022-08-31T12:30:00"),
timestamp("2022-09-07T14:00:00"),
timestamp("2022-09-07T14:00:00"),
timestamp("2022-09-09T12:30:00"),
timestamp("2022-09-09T12:30:00"),
timestamp("2022-09-20T12:30:00"),
timestamp("2022-09-23T12:30:00"),
timestamp("2022-10-06T15:35:00"),
timestamp("2022-10-07T12:30:00"),
timestamp("2022-10-07T12:30:00"),
timestamp("2022-10-19T12:30:00"),
timestamp("2022-10-21T12:30:00"),
timestamp("2022-10-26T14:00:00"),
timestamp("2022-10-26T14:00:00"),
timestamp("2022-10-26T14:00:00"),
timestamp("2022-10-26T15:00:00"),
timestamp("2022-11-01T22:30:00"),
timestamp("2022-11-04T12:30:00"),
timestamp("2022-11-04T12:30:00"),
timestamp("2022-11-10T16:50:00"),
timestamp("2022-11-16T13:30:00"),
timestamp("2022-11-22T13:30:00"),
timestamp("2022-11-23T21:30:00"),
timestamp("2022-11-29T13:30:00"),
timestamp("2022-12-02T13:30:00"),
timestamp("2022-12-02T13:30:00"),
timestamp("2022-12-07T15:00:00"),
timestamp("2022-12-07T15:00:00"),
timestamp("2022-12-12T20:25:00"),
timestamp("2022-12-20T13:30:00"),
timestamp("2022-12-21T13:30:00"),
timestamp("2023-01-06T13:30:00"),
timestamp("2023-01-06T13:30:00"),
timestamp("2023-01-10T10:10:00"),
timestamp("2023-01-17T13:30:00"),
timestamp("2023-01-20T13:30:00"),
timestamp("2023-01-25T15:00:00"),
timestamp("2023-01-25T15:00:00"),
timestamp("2023-01-25T15:00:00"),
timestamp("2023-01-25T16:00:00"),
timestamp("2023-02-07T17:30:00"),
timestamp("2023-02-10T13:30:00"),
timestamp("2023-02-10T13:30:00"),
timestamp("2023-02-16T16:00:00"),
timestamp("2023-02-21T13:30:00"),
timestamp("2023-02-21T13:30:00"),
timestamp("2023-02-28T13:30:00"),
timestamp("2023-03-08T15:00:00"),
timestamp("2023-03-08T15:00:00"),
timestamp("2023-03-10T13:30:00"),
timestamp("2023-03-10T13:30:00"),
timestamp("2023-03-21T12:30:00"),
timestamp("2023-03-24T12:30:00"),
timestamp("2023-04-06T12:30:00"),
timestamp("2023-04-06T12:30:00"),
timestamp("2023-04-12T14:00:00"),
timestamp("2023-04-12T14:00:00"),
timestamp("2023-04-12T14:00:00"),
timestamp("2023-04-12T15:00:00"),
timestamp("2023-04-13T13:00:00"),
timestamp("2023-04-18T12:30:00"),
timestamp("2023-04-18T15:30:00"),
timestamp("2023-04-20T15:30:00"),
timestamp("2023-04-21T12:30:00"),
timestamp("2023-05-04T16:50:00"),
timestamp("2023-05-05T12:30:00"),
timestamp("2023-05-05T12:30:00"),
timestamp("2023-05-16T12:30:00"),
timestamp("2023-05-19T12:30:00"),
timestamp("2023-05-31T12:30:00"),
timestamp("2023-06-07T14:00:00"),
timestamp("2023-06-07T14:00:00"),
timestamp("2023-06-09T12:30:00"),
timestamp("2023-06-09T12:30:00"),
timestamp("2023-06-21T12:30:00"),
timestamp("2023-06-27T12:30:00"),
timestamp("2023-06-27T12:30:00"),
timestamp("2023-07-07T12:30:00"),
timestamp("2023-07-07T12:30:00"),
timestamp("2023-07-12T14:00:00"),
timestamp("2023-07-12T14:00:00"),
timestamp("2023-07-12T14:00:00"),
timestamp("2023-07-12T15:00:00"),
timestamp("2023-07-19T12:30:00"),
timestamp("2023-07-19T12:30:00"),
timestamp("2023-08-04T12:30:00"),
timestamp("2023-08-04T12:30:00"),
timestamp("2023-08-16T12:30:00"),
timestamp("2023-08-16T12:30:00"),
timestamp("2023-08-31T12:30:00"),
timestamp("2023-09-06T14:00:00"),
timestamp("2023-09-06T14:00:00"),
timestamp("2023-09-08T12:30:00"),
timestamp("2023-09-08T12:30:00"),
timestamp("2023-09-20T12:30:00"),
timestamp("2023-09-20T12:30:00"),
timestamp("2023-10-06T12:30:00"),
timestamp("2023-10-06T12:30:00"),
timestamp("2023-10-18T12:30:00"),
timestamp("2023-10-18T12:30:00"),
timestamp("2023-10-25T14:00:00"),
timestamp("2023-10-25T14:00:00"),
timestamp("2023-10-25T14:00:00"),
timestamp("2023-10-25T15:00:00"),
timestamp("2023-11-03T12:30:00"),
timestamp("2023-11-03T12:30:00"),
timestamp("2023-11-15T13:30:00"),
timestamp("2023-11-15T13:30:00"),
timestamp("2023-11-30T13:30:00"),
timestamp("2023-12-01T13:30:00"),
timestamp("2023-12-01T13:30:00"),
timestamp("2023-12-06T15:00:00"),
timestamp("2023-12-06T15:00:00"),
timestamp("2023-12-13T13:30:00"),
timestamp("2023-12-13T13:30:00")
)
|
Anchored Relative Strength | https://www.tradingview.com/script/8tovLkXm-Anchored-Relative-Strength/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 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/
// © Amphibiantrading
//@version=5
indicator("Anchored RS", overlay = true)
//----------settings----------//
date = input.time(timestamp('Jan 01 23'), 'Anchor Date', confirm = true)
sym = input.symbol('SPX', 'Symbol to Compare')
rsCol = input.color(color.blue, 'RS Line Color')
showComp = input.bool(true, 'Show Comparative Symbol Line', inline = '1')
spxCol = input.color(color.red, '', inline = '1')
showMa = input.bool(true, 'Show RS Moving Average', inline = '2')
maCol = input.color(color.fuchsia, '', inline = '2')
maLen = input.int(10, 'Length', inline = '2', tooltip = 'Simple moving average of the RS line.')
offSet = input.int(20, 'Vertical Offset', minval = 1, tooltip = 'Adjusts the vertical offset of the lines. \nThis has no effect on calculations, adjust as needed for optimal viewing.')
//----------functions----------//
getComp(x)=>
comp = request.security(sym, timeframe.period, close[x], gaps = barmerge.gaps_off)
//----------variables----------//
var closeArr = array.new<float>()
var spxArr = array.new<float>()
rsArr = array.new<float>()
float avg = na
float sum = 0.0
float rs = 0.0
float comp = 0.0
//----------get data----------//
if time >= date
closeArr.unshift(close)
barsBack = closeArr.size()
if barstate.isfirst
spxArr.unshift(getComp(0))
else if not barstate.isfirst
spxArr.unshift(getComp(0))
//----------calculate RS----------//
if barsBack > 0
for i = barsBack-1 to 0
rsArr.unshift(close[i] / spxArr.get(i) * 100)
if rsArr.size() > maLen-1
for i = 0 to maLen-1
sum := sum + rsArr.get(i)
avg := rsArr.size() > maLen-1 ?(sum / maLen) * offSet : na
rs := rsArr.size() > 0 ? rsArr.get(0) : na
comp := spxArr.size() > 0 ? spxArr.get(0) : na
mult = rsArr.size() > 0 ? comp[barsBack-1] / (rs[barsBack-1] * offSet) : na
//----------draw RS line----------//
plot(rsArr.size() > maLen-1 and showMa ? avg : na, 'MA', maCol, 2, plot.style_linebr)
plot(time >= date ? rs*offSet : na, 'rs', rsCol, 2, plot.style_linebr)
plot(time >= date and showComp ? comp/mult : na, 'Comp', spxCol, 2, plot.style_linebr)
|
Multi-Trend | https://www.tradingview.com/script/GT5zHOcP-Multi-Trend/ | faiyaz7283 | https://www.tradingview.com/u/faiyaz7283/ | 86 | 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/
// © faiyaz7283
//@version=5
indicator(title="Multi-Trend", overlay=true)
// ::Imports:: {
import faiyaz7283/tools/10 as tools
import faiyaz7283/printer/6 as prnt
import faiyaz7283/multidata/7 as mltd
// }
// ::Inputs:: {
var section00 = 'HEADER'
//---------------------:
var header = input.string(defval='Multi Trend', title='Header', inline='hdr', group=section00)
var headerShow = input.bool(defval = false, title = 'Show', inline = 'hdr', group = section00)
var section01 = 'POSITION, SIZE & COLORS'
//---------------------:
var displayLoc = input.string(defval = position.top_right, title = 'Display Location', options = [position.top_left,
position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right,
position.bottom_left, position.bottom_center, position.bottom_right], group = section01)
var cellPad = input.int(defval=2, title='Cell Spacing', minval=0, maxval=5, group=section01)
var orientation = input.string(defval = 'vertical', title = 'Orientation', options = ['horizontal', 'vertical'],
group = section01) == 'vertical' ? false : true
var headerBgColor = input.color(defval=#1E283273, title = 'Header:\tBG', inline = 'hdrCl', group = section01)
var headerColor = input.color(defval=#E1E1E1 , title = 'Text', inline = 'hdrCl', group = section01)
var headerSize = input.string(defval=size.auto, title = 'Size', options = [size.auto, size.tiny, size.small,
size.normal, size.large, size.huge], inline = 'hdrCl', group = section01)
var headerAlign = input.string(defval=text.align_center, title = 'Align',
options = [text.align_left, text.align_center, text.align_right], inline = 'hdrCl', group = section01)
var titleBgColor = input.color(defval=#00000000, title = 'Title:\tBG', inline = 'ttlCl', group = section01)
var titleColor = input.color(defval=#80deea , title = 'Text', inline = 'ttlCl', group = section01)
var titleSize = input.string(defval=size.auto, title = 'Size', options = ['hide', size.auto, size.tiny, size.small,
size.normal, size.large, size.huge], inline = 'ttlCl', group = section01)
var titleAlign = input.string(defval=text.align_left, title = 'Align',
options = [text.align_left, text.align_center, text.align_right], inline = 'ttlCl', group = section01)
var keyColor = input.color(defval=#000000, title = 'Key:\tText', inline = 'keyCl', group = section01)
var keySize = input.string(defval=size.normal, title = 'Size', options = [size.auto, size.tiny, size.small,
size.normal, size.large, size.huge], inline = 'keyCl', group = section01)
var keyAlign = input.string(defval=text.align_center, title = 'Align',
options = [text.align_left, text.align_center, text.align_right], inline = 'keyCl', group = section01)
var textBgColor = input.color(defval=#00000033, title = 'Value:\tBG', inline = 'txtCl', group = section01)
var textSize = input.string(defval=size.large, title = 'Size', options = [size.auto, size.tiny, size.small,
size.normal, size.large, size.huge], inline = 'txtCl', group = section01)
var textAlign = input.string(defval=text.align_center, title = 'Align',
options = [text.align_left, text.align_center, text.align_right], inline = 'txtCl', group = section01)
var up = input.string(defval='↑', title='Up', inline = 'U', group=section01)
var upColor = input.color(defval = #00FF00, title = '', inline = 'U', group = section01)
var neutral = input.string(defval='→', title='Unchanged', inline = 'N', group=section01)
var neutralColor = input.color(defval = #fff9c4, title = '', inline = 'N', group = section01)
var down = input.string(defval='↓', title='Down', inline = 'D', group=section01)
var downColor = input.color(defval = #FF0000, title = '', inline = 'D', group = section01)
var section02 = 'TREND'
//----------------------------:
var calcTip1 = 'Close: Determine the trend direction by comparing the current close price with the close price of the '
var calcTip2 = calcTip1 + 'previous candle within the chosen timeframe.\n\nOpen: Establish the trend direction by '
var calcTip3 = calcTip2 + 'contrasting the current close price with the open price of the current candle within the '
var calcTip = calcTip3 + 'selected timeframe.\n\nNote: "Candle" refers to each of the chosen timeframes below.'
var source = input.string(defval='close', title = 'Source', tooltip=calcTip, options = ['close', 'open'],
inline='dd', group = section02)
var showVol = input.bool(defval=false, title='Show Volume Trend', group=section02)
var section03 = 'TIMEFRAMES'
//--------------------------------:
var tfNote0 = "M: Multiplier | U: Unit\n\nValid Multipliers per Unit:\n- Seconds, ONLY use 1, 5, 10, 15 or 30."
var tfNote1 = tfNote0 + '\n- Minutes, 1 to 1439.\n- Days, 1 to 365.\n- Weeks, 1 to 52.\n- Months, 1 to 12.\n\n'
var tfNote2 = tfNote1 + 'N: nth candle\n\n- Nth 0 is current candle.\n- Nth 1 is previous candle.\n- Nth 2 is previous '
var tfNote = tfNote2 + '2nd candle in past.\n- Nth 3 is previous 3rd candle in past.\n ...\n\nCheck box to display.'
// Timeframe 1
var tfM1 = input.int(defval = 5, title = 'M', minval = 1, maxval = 1439, inline = 'tf1',
group = section03)
var tfU1 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf1', group = section03)
var tfN1 = input.int(defval=0, title = 'N', minval=0, inline = 'tf1', group = section03)
var useTf1 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf1', group = section03)
// Timeframe 2
var tfM2 = input.int(defval = 15, title = 'M', minval = 1, maxval = 1439, inline = 'tf2',
group = section03)
var tfU2 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf2', group = section03)
var tfN2 = input.int(defval=0, title = 'N', minval=0, inline = 'tf2', group = section03)
var useTf2 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf2', group = section03)
// Timeframe 3
var tfM3 = input.int(defval = 30, title = 'M', minval = 1, maxval = 1439, inline = 'tf3',
group = section03)
var tfU3 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf3', group = section03)
var tfN3 = input.int(defval=0, title = 'N', minval=0, inline = 'tf3', group = section03)
var useTf3 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf3', group = section03)
// Timeframe 4
var tfM4 = input.int(defval = 60, title = 'M', minval = 1, maxval = 1439, inline = 'tf4',
group = section03)
var tfU4 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf4', group = section03)
var tfN4 = input.int(defval=0, title = 'N', minval=0, inline = 'tf4', group = section03)
var useTf4 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf4', group = section03)
// Timeframe 5
var tfM5 = input.int(defval = 240, title = 'M', minval = 1, maxval = 1439, inline = 'tf5',
group = section03)
var tfU5 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf5', group = section03)
var tfN5 = input.int(defval=0, title = 'N', minval=0, inline = 'tf5', group = section03)
var useTf5 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf5', group = section03)
// Timeframe 6
var tfM6 = input.int(defval = 480, title = 'M', minval = 1, maxval = 1439, inline = 'tf6',
group = section03)
var tfU6 = input.string(defval = 'Minutes', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf6', group = section03)
var tfN6 = input.int(defval=0, title = 'N', minval=0, inline = 'tf6', group = section03)
var useTf6 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf6', group = section03)
// Timeframe 7
var tfM7 = input.int(defval = 1, title = 'M', minval = 1, maxval = 1439, inline = 'tf7',
group = section03)
var tfU7 = input.string(defval = 'Days', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf7', group = section03)
var tfN7 = input.int(defval=0, title = 'N', minval=0, inline = 'tf7', group = section03)
var useTf7 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf7', group = section03)
// Timeframe 8
var tfM8 = input.int(defval = 1, title = 'M', minval = 1, maxval = 1439, inline = 'tf8',
group = section03)
var tfU8 = input.string(defval = 'Weeks', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf8', group = section03)
var tfN8 = input.int(defval=0, title = 'N', minval=0, inline = 'tf8', group = section03)
var useTf8 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf8', group = section03)
// Timeframe 9
var tfM9 = input.int(defval = 1, title = 'M', minval = 1, maxval = 1439, inline = 'tf9',
group = section03)
var tfU9 = input.string(defval = 'Months', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf9', group = section03)
var tfN9 = input.int(defval=0, title = 'N', minval=0, inline = 'tf9', group = section03)
var useTf9 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf9', group = section03)
// Timeframe 10
var tfM10 = input.int(defval = 12, title = 'M', minval = 1, maxval = 1439, inline = 'tf10',
group = section03)
var tfU10 = input.string(defval = 'Months', title = 'U',
options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf10', group = section03)
var tfN10 = input.int(defval=0, title = 'N', minval=0, inline = 'tf10', group = section03)
var useTf10 = input.bool(defval = true, title = 'Show', tooltip = tfNote, inline = 'tf10', group = section03)
// }
// Functions: {
displayTf(m, u) =>
_m = m
_u = switch
str.endswith(u, "S") =>
m == 1 ? 'Second' : 'Seconds'
str.endswith(u, "D") =>
m == 1 ? 'Day' : 'Days'
str.endswith(u, "W") =>
m == 1 ? 'Week' : 'Weeks'
str.endswith(u, "M") =>
if m == 1
'Month'
else if m == 12
_m := 1
'Year'
else
'Months'
=>
if m == 1
'Minute'
else if m % 60 == 0
_m := m / 60
_m == 1 ? 'Hour' : 'Hours'
else
'Minutes'
_m == 1 ? _u : str.format('{0} {1}', _m, _u)
getKv(multiplier, unit, nth) =>
u = switch unit
'Seconds' => 'S'
'Minutes' => ''
'Days' => 'D'
'Weeks' => 'W'
'Months' => 'M'
tf = str.tostring(multiplier) + u
srce = source == 'close' ? close[nth + 1] : open[nth]
tckr = ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session)
[c, c1, v, v1] = request.security(tckr, tf, [close[nth], srce, volume[nth], volume[nth + 1]], ignore_invalid_symbol = true)
dsplyPrice = c > c1 ? up : (c < c1 ? down : neutral)
dsplyVol = v > v1 ? up : (v < v1 ? down : neutral)
nthKey = nth > 0 ? (nth == 1 ? 'Previous ' : str.format('(Past {0}) ', tools.ordinal(nth))) : na
key = nthKey + displayTf(multiplier, u)
[mltd.kv(key, val=dsplyPrice), mltd.kv(key, val=dsplyVol)]
// }
if barstate.islast
tbs = prnt.tableStyle.new(bgColor=na, frameColor=na, borderWidth=cellPad)
hs = prnt.headerStyle.new(textHalign=headerAlign, textColor=headerColor, textSize=headerSize, bgColor=headerBgColor)
ts = prnt.titleStyle.new(textHalign=titleAlign, textColor=titleColor, textSize=titleSize, bgColor=titleBgColor)
kcs = prnt.cellStyle.new(textHalign=keyAlign, textSize=keySize)
cs = prnt.cellStyle.new(horizontal=orientation, textHalign=textAlign, textSize=textSize)
// Initialize the printer
printer = prnt.printer(header=(headerShow ? header : na), stack=orientation, tableStyle=tbs, headerStyle=hs,
titleStyle=ts, keyCellStyle=kcs, cellStyle=cs, loc=displayLoc)
// Data {
price = array.new<mltd.kv>()
vol = array.new<mltd.kv>()
if useTf1
[p, v] = getKv(tfM1, tfU1, tfN1)
price.push(p)
if showVol
vol.push(v)
if useTf2
[p, v] = getKv(tfM2, tfU2, tfN2)
price.push(p)
if showVol
vol.push(v)
if useTf3
[p, v] = getKv(tfM3, tfU3, tfN3)
price.push(p)
if showVol
vol.push(v)
if useTf4
[p, v] = getKv(tfM4, tfU4, tfN4)
price.push(p)
if showVol
vol.push(v)
if useTf5
[p, v] = getKv(tfM5, tfU5, tfN5)
price.push(p)
if showVol
vol.push(v)
if useTf6
[p, v] = getKv(tfM6, tfU6, tfN6)
price.push(p)
if showVol
vol.push(v)
if useTf7
[p, v] = getKv(tfM7, tfU7, tfN7)
price.push(p)
if showVol
vol.push(v)
if useTf8
[p, v] = getKv(tfM8, tfU8, tfN8)
price.push(p)
if showVol
vol.push(v)
if useTf9
[p, v] = getKv(tfM9, tfU9, tfN9)
price.push(p)
if showVol
vol.push(v)
if useTf10
[p, v] = getKv(tfM10, tfU10, tfN10)
price.push(p)
if showVol
vol.push(v)
if price.size() > 0
// Store multidata
d2dPrice = mltd.data2d(price)
d2dVol = showVol ? mltd.data2d(vol) : na
// Setup dynamic styles
d2dStyles = map.new<string, prnt.cellStyle>()
keyStyle = prnt.cellStyle.copy(printer.keyCellStyle)
dc = prnt.dynamicColor.new(stringUp=up, stringNeutral=neutral, stringDown=down, up=upColor,
neutral=neutralColor, down=downColor)
keyStyle.dynamicColor := prnt.dynamicColor.copy(dc)
keyStyle.dynamicColor.offsetItem :='text'
keyStyle.dynamicColor.offsetColor := keyColor
valStyle = prnt.cellStyle.copy(printer.cellStyle)
valStyle.dynamicColor := prnt.dynamicColor.copy(dc)
valStyle.dynamicColor.offsetItem := 'bg'
valStyle.dynamicColor.offsetColor := textBgColor
d2dStyles.put('key', keyStyle)
d2dStyles.put('val', valStyle)
// Output
pTitle = titleSize != 'hide' ? 'Price' : na
printer.print(d2dPrice, title=pTitle, styles=d2dStyles, dynamicKey=true)
if showVol
vTitle = titleSize != 'hide' ? 'Volume' : na
printer.print(d2dVol, title=vTitle, styles=d2dStyles, dynamicKey=true)
// } |
gFancyMA | https://www.tradingview.com/script/eJF5SbBr-gFancyMA/ | GalacticS2021 | https://www.tradingview.com/u/GalacticS2021/ | 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/
// © GalacticS2021
//@version=5
// @description: Contains reusable functions/ labeled moving average
library("gFancyMA", true)
// @function : Connects label to ma
// @param y : add parameter y coordinate
// @param x : add paramete length
// @param c : add parameter c add the label color
// @param m : add parameter mode of the moving averagee
// @param a : add parameter a bool to toggle the ma visibility
// @param b : add parameter b bool to toggle the label visibility
// @param o : add parameter o bool lablel offset
// @returns : function returns the label
bool a = true
bool b = true
color c = na
var src = close
string s = na
string m = na
float y = na
loffset = 5
Xoffset = time_close + loffset * timeframe.multiplier * 60 * 1000
export printLbl(float y,int x,color c,string m,bool b,string s) =>
var label labelX = na
int o = Xoffset
if a and b and barstate.isrealtime
labelX := label.new(x=o, y=y, xloc=xloc.bar_time,style = label.style_none, textalign=text.align_right,size = s)
//labelX.set_x(labelX, arg2)
label.set_text(labelX, str.tostring(x)+' '+ m)
label.set_textcolor(labelX, c)
label.delete(labelX[1])
labelX
|
JapaneseCandlestickPatterns | https://www.tradingview.com/script/Gz71b7Qk-JapaneseCandlestickPatterns/ | Marceeelll | https://www.tradingview.com/u/Marceeelll/ | 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/
// © Marceeelll
//@version=5
// @description Japanese Candlestick Patterns is a library of functions that enables the detection of popular Japanese candlestick patterns such as Doji, Hammer, and Engulfing, among others. The library provides a simple yet powerful way to analyze financial markets and make informed trading decisions. Japanese Candlestick Patterns library can help you identify potential trading opportunities.
library("JapaneseCandlestickPatterns", overlay = true)
///////////////////////
// --- CONSTANTS --- //
///////////////////////
C_BodyHigh = math.max(close, open)
C_BodyLow = math.min(close, open)
C_Body = C_BodyHigh - C_BodyLow
C_BodyAvg = ta.ema(C_Body, 14)
C_CandleAvg = ta.ema(high - low, 14)
C_IsSmallBody = C_Body < C_BodyAvg
C_IsLongBody = C_Body > C_BodyAvg
C_IsWhiteBody = open < close
C_IsBlackBody = open > close
C_Range = high - low
C_IsInsideBar = C_BodyHigh[1] > C_BodyHigh and C_BodyLow[1] < C_BodyLow
C_BodyMiddle = C_Body / 2 + C_BodyLow
C_UpShadow = high - C_BodyHigh
C_DnShadow = C_BodyLow - low
// Returns in percent (1-100) how much the upper shadow takes of the high and lows
C_UpShadowPercentageOfBody = (C_UpShadow / C_Range) * 100
// Returns in percent (1-100) how much the down shadow takes of the high and lows
C_DnShadowPercentageOfBody = (C_DnShadow / C_Range) * 100
////////////////////////////
// --- HELPER METHODS --- //
////////////////////////////
str_array_to_string(array, separator) =>
result = ""
lastIndex = array.size(array) - 1
for i = 0 to lastIndex
result := result + array.get(array, lastIndex - i) + (i == lastIndex ? "" : "\n")
result
isInDeviationRange(float price1, price2, float deviation) =>
price1 - price1 * deviation < price2 and price1 + price1 * deviation > price2
///////////////////////////
// --- DOJI PATTERNS --- //
///////////////////////////
//
// --- DOJI PATTERN ---
//
export isDojiCandle() =>
// 1. Has Doji Body
C_DojiBodyPercent = 5.0
if C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
true
//
// --- GRAVESTONE DOJI PATTERN ---
//
export isGravestoneDojiCandle() =>
// 1. Is a doji candle
if isDojiCandle()
// 2. When the opening and closing prices are at 15% of the low of the day
if C_DnShadowPercentageOfBody < 15
true
//
// --- DRAGONFLY DOJI PATTERN ---
//
export isDragonflyDojiCandle() =>
// 1. Is a doji candle
if isDojiCandle()
// 2. When the opening and closing prices are at 15% of the high of the day
if C_UpShadowPercentageOfBody < 15
true
//
// --- EVENING DOJI STAR PATTERN ---
//
export isEveningDojiStarCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
// 2. Long, doji, long body
if C_IsLongBody[2] and isDojiCandle()[1] and C_IsLongBody
// 3. First is a white
if C_IsWhiteBody[2]
// 4. Followed by a small body which gaps higher
if C_BodyHigh[2] < C_BodyLow[1]
// 5. Second gap
if C_BodyHigh < C_BodyLow[1]
// 6. Black body that moves well within the first period white body
if C_IsBlackBody and C_BodyLow <= C_BodyMiddle[2]
true
//
// --- LONG LEGGED DOJI PATTERN ---
//
export isLongLeggedDojiCandle() =>
// 1. Is doji candle with long upper and down wicks
if C_DnShadowPercentageOfBody > 45 and C_UpShadowPercentageOfBody > 45
// 2. Candle range is higher thatn the previous candle range
if C_Range > C_CandleAvg
true
//
// --- MORNING DOJI STAR PATTERN ---
//
export isMorningDojiStarCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
// 1. Long, doji, long body
if C_IsLongBody[2] and isDojiCandle()[1] and C_IsLongBody
// 2. First is a black body
if C_IsBlackBody[2]
// 3. Followed by a small body which gaps lower
if C_BodyHigh[1] < C_BodyLow[2]
// 4. Second gap
if C_BodyHigh[1] < C_BodyLow
// 5. White body that moves well within the first period black body
if C_IsWhiteBody and C_BodyHigh >= C_BodyMiddle[2]
true
///////////////////////////////
// --- REVERSAL PATTERNS --- //
///////////////////////////////
//
// --- COUNTERATTACK LINES PATTERN ---
//
export isBullishCounterattackLinesCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. The first candle is black (down) with a long real body.
if C_IsBlackBody[1] and C_IsLongBody[1]
// 3. The second candle gaps down on the open, is white with a real body that's similar in size to the first candle (min 80%)
if open < close[1] and C_IsWhiteBody and C_Body > C_Body[1] * 0.8
// 4. The second candle closes near the first candle's close.
if isInDeviationRange(C_BodyLow[1], C_BodyHigh, 0.003)
true
export isBearishCounterattackLinesCandle(bool isUpTrend) =>
// 1. The market is in a uptrend.
if isUpTrend
// 2. The first candle is white (updown) with a long real body.
if C_IsWhiteBody[1] and C_IsLongBody[1]
// 3. The second candle gaps up on the open, is black with a real body that's similar in size to the first candle (min 80%)
if open > close[1] and C_IsBlackBody and C_Body > C_Body[1] * 0.8
// 4. The second candle closes near the first candle's close.
if isInDeviationRange(C_BodyHigh[1], C_BodyLow, 0.003)
true
//
// --- DARK-CLOUD COVER PATTERN ---
//
export isDarkCloudCoverCandle(bool isUpTrend) =>
// 1. The market is in a uptrend.
if isUpTrend
// 1. The second day's price opens above the prior session's high (that is, above the top of the upper shadow)
if open > high[1]
// 2. By the end of the second day's session, the market closes near the low of the day and well within the priors day's white body
darkCloudCoverPatternPenetrationInPercentage = (close[1] - close) / (close[1] - open[1]) * 100
// 3. The greater the degree of penetration into the white real body the more likely a top will occur (more than 50%)
if darkCloudCoverPatternPenetrationInPercentage > 50 and darkCloudCoverPatternPenetrationInPercentage < 100
[C_IsWhiteBody[1], darkCloudCoverPatternPenetrationInPercentage]
//
// --- ENGULFING PATTERN ---
//
export isBullishEngulfingCandle() =>
// Two candlesticks comprise the engulfing pattern.
// 1.1 The second real body must engluf the prior real body (it need not engluf the shadows)
// Check for a bullish engulfing pattern
if C_BodyHigh > C_BodyHigh[1] and C_BodyLow < C_BodyLow[1]
// 2. The second real body should be the opposite color of the first real body.
// The exception to this rule is if the first real body of the engulfing pattern is so small it is almost a doji
if isDojiCandle()[1] ? true : C_IsWhiteBody != C_IsWhiteBody[1]
// 3. Is bullish
if close > open
true
export isBearishEngulfingCandle() =>
// Two candlesticks comprise the engulfing pattern.
// 1.1 The second real body must engluf the prior real body (it need not engluf the shadows)
// Check for a bullish engulfing pattern
if C_BodyHigh > C_BodyHigh[1] and C_BodyLow < C_BodyLow[1]
// 2. The second real body should be the opposite color of the first real body.
// The exception to this rule is if the first real body of the engulfing pattern is so small it is almost a doji
if isDojiCandle()[1] ? true : C_IsWhiteBody != C_IsWhiteBody[1]
// 3. Is bearish
if close < open
true
//
// --- HAMMER & HANGING MAN PATTERN ---
//
export isHammerCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. Small body
if C_IsSmallBody
// 3. The real body is at the upper end of the trading range.
if C_UpShadowPercentageOfBody < 10
// 4. A long lower shadow should be twice the height of the real body.
if C_DnShadow >= 2 * C_Body
// 5. It should have no, or a very short, upper shadow (max 10% of body).
if C_UpShadow <= 0.1 * C_Body
true
//
// --- HAMMER & HANGING MAN PATTERN ---
//
export isHangingManCandle(bool isUpTrend) =>
// 1. The market is in a downtrend.
if isUpTrend
// 2. Small body
if C_IsSmallBody
// 3. The real body is at the upper end of the trading range.
if C_UpShadowPercentageOfBody < 10
// 4. A long lower shadow should be twice the height of the real body.
if C_DnShadow >= 2 * C_Body
// 5. It should have no, or a very short, upper shadow (max 10% of body).
if C_UpShadow <= 0.1 * C_Body
true
//
// --- HARAMI PATTERN ---
//
export isHaramiBearishCandle(bool isUpTrend) =>
// 1. There is an uptrend. The first candle must continue with the trend’s direction (white body). The color of the second candle doesn't matter.
if isUpTrend[1] and C_IsWhiteBody[1]
// 2. The first candle will have a long body.
if C_IsLongBody[1] and C_IsSmallBody
// 3. The second candle must be contained within the first candle’s body (so it opens and closes within the body of the first candle). The wicks are irrelevant.
if C_BodyHigh <= C_BodyHigh[1] and C_BodyLow >= C_BodyLow[1]
true
export isHaramiBullishCandle(bool isDownTrend) =>
// 1. There is a downtrend. The first candle must continue with the trend’s direction (black body). The color of the second candle doesn't matter.
if isDownTrend[1] and C_IsBlackBody[1]
// 2. The first candle will have a long body.
if C_IsLongBody[1] and C_IsSmallBody
// 3. The second candle must be contained within the first candle’s body (so it opens and closes within the body of the first candle). The wicks are irrelevant.
if C_BodyHigh <= C_BodyHigh[1] and C_BodyLow >= C_BodyLow[1]
true
//
// --- IN-NECK PATTERN ---
//
export isInNeckCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. First candlestick is a black real body day and the second is a long, white real body day
if C_IsBlackBody[1] and C_IsWhiteBody
// 3. This white day opens sharply lower, under the low of the prior black day
if open < low[1]
// 4. white candlestick closes slightly into the prior real body (it should also be a small white candlestick)
if close < close[1] * 1.002 and close > close[1]
// 5. a long real bodied down candle is followed by a smaller real bodied up candle
if C_Body[1] > C_Body
true
//
// --- ON-NECK PATTERN ---
//
export isOnNeckCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. First candlestick is a black real body day and the second is a long, white real body day
if C_IsBlackBody[1] and C_IsWhiteBody
// 3. This white day opens sharply lower, under the low of the prior black day
if open < low[1]
// 4. white candlestick (usually a small one) closes near the low of the previous session
if close < low[1] * 1.001 and close > low[1] * 0.999
// 5. a long real body down candle is followed by a smaller real bodied up candle
if C_Body[1] > C_Body
true
//
// --- PIERCING PATTERN ---
//
export isPiercingCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. First candlestick is a black real body day and the second is a long, white real body day
if C_IsBlackBody[1] and C_IsWhiteBody
// 3. This white day opens sharply lower, under the low of the prior black day
if open < low[1]
// 4. Closes above the mid-point of the prior day's black real body
if close > C_BodyMiddle[1] and close < open[1]
true
//
// --- THREE BLACK CROWS PATTERN ---
//
export threeBlackCrowsCandle(bool isUpTrend) =>
// 1. The market is in an uptrend.
if isUpTrend
// 2. The first candlestick is a long bullish candlestick
if C_IsWhiteBody[3] and C_IsLongBody[3]
// 3. The second candlestick is a long bearish candlestick that opens above the close of the first candlestick and closes below the midpoint of the first candlestick.
if C_IsBlackBody[2] and C_IsLongBody[2] and open[2] > close[3] and close[2] < C_BodyMiddle[3]
// 4. The third candlestick is a long bearish candlestick that opens below the midpoint of the second candlestick and closes below the close of the second candlestick.
if C_IsBlackBody[1] and C_IsLongBody[1] and open[1] < C_BodyMiddle[2]
// 5. The fourth candlestick is a long bearish candlestick that opens below the midpoint of the third candlestick and closes below the close of the third candlestick.
if C_IsBlackBody and C_IsLongBody and open < C_BodyMiddle[1] and close < close[1]
true
//
// --- THRUSTING-NECK PATTERN ---
//
export isThrustingNeckCandle(bool isDownTrend) =>
// 1. The market is in a downtrend.
if isDownTrend
// 2. First candlestick is a black real body day and the second is a long, white real body day
if C_IsBlackBody[1] and C_IsWhiteBody
// 3. This white day opens sharply lower, under the low of the prior black day
if open < low[1]
// 4. should be a longer white candlestick that is stronger than the in-neck pattern but still does not close above the middle of the prior black real body
if close < C_BodyMiddle[1] and close > close[1] * 1.002
// 5. a long real bodied down candle is followed by a smaller real bodied up candle
if C_Body[1] > C_Body
true
//
// --- UPSIDE-GAP TWO CROWS PATTERN ---
//
export isUpsideGapTwoCrowsCandle(bool isUpTrend) =>
// 1. The upside gap two crows must occur during an uptrend.
if isUpTrend
// 2. The first candle is bullish.
if C_IsWhiteBody[2]
// 3. The second candle must be bearish with a small real body and closes higher than the first, creating a gap.
if C_IsBlackBody[1] and C_IsSmallBody[1] and close[1] > close[2]
// 4. The third candle must be bearish while closing above the first candle’s close.
if C_IsBlackBody and close > close[2]
// 5. The third candle must engulf the second candle's real body
if C_Body > C_Body[1] and C_BodyHigh > C_BodyHigh[1] and C_BodyLow < C_BodyLow[1]
true
///////////////////////////
// --- STAR PATTERNS --- //
///////////////////////////
//
// --- ABANDONED BABY TOP (BEARISH) PATTERN ---
//
export isAbandonedBabyTopCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
// 2. First is a white long body
if C_IsWhiteBody[2] and C_IsLongBody[2]
// 3. Followed by a second small body which gaps higher
if C_IsSmallBody[1] and high[2] < low[1]
// 4. Followed by a third body which gaps lower
if high < low[1]
// 5. Black third body that moves well within the first period white body
if C_IsBlackBody and C_BodyLow <= C_BodyMiddle[2]
true
//
// --- ABANDONED BABY BOTTOM (BULLISH) PATTERN ---
//
export isAbandonedBabyBottomCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
// 2. First is a black long body
if C_IsBlackBody[2] and C_IsLongBody[2]
// 3. Followed by a second small body which gaps lower
if C_IsSmallBody[1] and high[1] < low[2]
// 4. Followed by a third body which gaps higher
if low > high[1]
// 5. White third body that moves well within the first period black body
if C_IsWhiteBody and C_BodyHigh >= C_BodyMiddle[2]
true
//
// --- EVENING STAR PATTERN ---
//
export isEveningStarCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
C_EveningStarPatternIdeal = false
// 2. Long, small, long body
if C_IsLongBody[2] and C_IsSmallBody[1] and C_IsLongBody
// 3. First is a white body
if C_IsWhiteBody[2]
// 4.1 Followed by a small body which gaps higher
if C_BodyHigh[2] < C_BodyLow[1]
// 4.2 [Optional] The second gap is rare, but lack of it does not seem to vitiate the power of this formation
C_EveningStarPatternIdeal := C_BodyHigh < C_BodyLow[1]
// 5. Black body that moves well within the first period white body
if C_IsBlackBody and C_BodyLow <= C_BodyMiddle[2]
[true, C_EveningStarPatternIdeal]
//
// --- INVERTED HAMMER PATTERN ---
//
export isInvertedHammerCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
// 2. Small body
if C_IsSmallBody
// 3. The real body is at the upper end of the trading range.
if C_DnShadowPercentageOfBody < 10
// 4. A long upper shadow should be twice the height of the real body.
if C_UpShadow >= 2 * C_Body
true
//
// --- MORNING STAR PATTERN ---
//
export isMorningStarCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
C_MorningStarPatternIdeal = false
// 1. Long, small, long body
if C_IsLongBody[2] and C_IsSmallBody[1] and C_IsLongBody
// 2. First is a black body
if C_IsBlackBody[2]
// 3.1 Followed by a small body which gaps lower
if C_BodyHigh[1] < C_BodyLow[2]
// 3.2 [Optional] The second gap is rare, but lack of it does not seem to vitiate the power of this formation
C_MorningStarPatternIdeal := C_BodyHigh[1] < C_BodyLow
// 4. White body that moves well within the first period black body
if C_IsWhiteBody and C_BodyHigh >= C_BodyMiddle[2]
[true, C_MorningStarPatternIdeal]
//
// --- SHOOTING STAR ---
//
export isShootingStarCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
// 2. Small body
if C_IsSmallBody
// 3. The real body is at the upper end of the trading range.
if C_DnShadowPercentageOfBody < 10
// 4. A long upper shadow should be twice the height of the real body.
if C_UpShadow >= 2 * C_Body
true
///////////////////////////////////
// --- CONTINUATION PATTERNS --- //
///////////////////////////////////
//
// --- RISING THREE METHODS PATTERN ---
//
export isRisingThreeMethodsCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
// 2. The first candlestick is a long white candlestick
if C_IsLongBody[4] and C_IsWhiteBody[4]
// 3. Follow by three consecutive smaller black candles
if C_IsBlackBody[3] and C_IsBlackBody[2] and C_IsBlackBody[1] and C_IsSmallBody[3] and C_IsSmallBody[2] and C_IsSmallBody[1]
// 4. Those three bearish candles trade above the low and below the high of the first candlestick
if open[3] < high[4] and close[3] > low[4] and close[2] > low[4]
// 5. The fifth candlestick is a white long candlestick that closes above the high of the fourth candlestick and confirms the continuation of the uptrend.
if close > close[4] and C_IsLongBody
true
//
// --- FALLING THREE METHODS PATTERN ---
//
export isFallingThreeMethodsCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
// 2. The first candlestick is a long black candlestick
if C_IsLongBody[4] and C_IsBlackBody[4]
// 3. Follow by three consecutive smaller white candles
if C_IsWhiteBody[3] and C_IsWhiteBody[2] and C_IsWhiteBody[1] and C_IsSmallBody[3] and C_IsSmallBody[2] and C_IsSmallBody[1]
// 4. Those three bullish candles trade above the low and below the high of the first candlestick
// if open[3] < high[4] and open[2] > open[3] and open[1] > open[2] and close[3] > low[4] and close[2] > low[4]
if open[3] > low[4] and close < high[4] and close[2] < high[4] and close[1] < high[4]
// 5. The fifth candlestick is a black long candlestick that closes below the low of the fourth candlestick and confirms the continuation of the downtrend.
if close < close[4] and C_IsLongBody
true
//
// --- UPSIDE TASUKI GAP PATTERN ---
//
export isUpsideTasukiGapCandle(bool isUpTrend) =>
// 1. The market is in a uptrend
if isUpTrend
// 2. First white long body followed by a smal white body
if C_IsLongBody[2] and C_IsSmallBody[1] and C_IsWhiteBody[2] and C_IsWhiteBody[1]
// 3. First two candles create a gap
if C_BodyHigh[2] < C_BodyLow[1]
// 4. The third candle is black and closes inside the gap created by the first two candles
if C_IsBlackBody and C_BodyLow > C_BodyHigh[2] and C_BodyLow < C_BodyLow[1]
true
//
// --- DOWNSIDE TASUKI GAP PATTERN ---
//
export isDownsideGapTasukiCandle(bool isDownTrend) =>
// 1. The market is in a downtrend
if isDownTrend
// 2. First black long body followed by a smal black body
if C_IsLongBody[2] and C_IsSmallBody[1] and C_IsBlackBody[2] and C_IsBlackBody[1]
// 3. First two candles create a gap
if C_BodyLow[2] > C_BodyHigh[1]
// if C_BodyHigh[1] < C_BodyLow[2]
// 4. The third candle is white and closes inside the gap created by the first two candles
if C_IsWhiteBody and C_BodyHigh < C_BodyLow[2] and C_BodyHigh > C_BodyHigh[1]
true
///////////////////////
// --- UTILITIES --- //
///////////////////////
//
// --- LONG LOWER SHADDOW ---
//
export isLongLowerShadowCandle() =>
if C_DnShadowPercentageOfBody > 75
true
//
// --- LONG UPPER SHADDOW ---
//
export isLongUpperShadowCandle() =>
if C_UpShadowPercentageOfBody > 75
true
///////////////////
// --- DEBUG --- //
///////////////////
// plotchar(C_IsUpTrend, "C_IsUpTrend", " ", display = display.all - display.status_line)
// plotchar(C_IsDownTrend, "C_IsDownTrend", " ", display = display.all - display.status_line)
// plotchar(C_BodyHigh, "C_BodyHigh", " ", display = display.all - display.status_line)
// plotchar(C_BodyLow, "C_BodyLow", " ", display = display.all - display.status_line)
// plotchar(C_Body, "C_Body", " ", display = display.all - display.status_line)
// plotchar(C_BodyAvg, "C_BodyAvg", " ", display = display.all - display.status_line)
// plotchar(C_CandleAvg, "C_CandleAvg", " ", display = display.all - display.status_line)
// plotchar(C_IsSmallBody, "C_IsSmallBody", " ", display = display.all - display.status_line)
// plotchar(C_IsLongBody, "C_IsLongBody", " ", display = display.all - display.status_line)
// plotchar(C_IsWhiteBody, "C_IsWhiteBody", " ", display = display.all - display.status_line)
// plotchar(C_IsBlackBody, "C_IsBlackBody", " ", display = display.all - display.status_line)
// plotchar(C_Range, "C_Range", " ", display = display.all - display.status_line)
// plotchar(C_IsInsideBar, "C_IsInsideBar", " ", display = display.all - display.status_line)
// plotchar(C_BodyMiddle, "C_BodyMiddle", " ", display = display.all - display.status_line)
// plotchar(C_UpShadow, "C_UpShadow", " ", display = display.all - display.status_line)
// plotchar(C_DnShadow, "C_DnShadow", " ", display = display.all - display.status_line)
// plotchar(C_UpShadowPercentageOfBody, "C_UpShadowPercentageOfBody", " ", display = display.all - display.status_line)
// plotchar(C_DnShadowPercentageOfBody, "C_DnShadowPercentageOfBody", " ", display = display.all - display.status_line) |
ZigZag++ Fibonacci | https://www.tradingview.com/script/SDSUbcya-ZigZag-Fibonacci/ | DevLucem | https://www.tradingview.com/u/DevLucem/ | 327 | 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/
// © DevLucem
// ( (
// )\ ) )\ )
// (()/( ( ) (()/( ( ( )
// /(_)) ))\ /(( /(_)) ))\ ( ))\ (
// (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ '
// | \ (_)) _)((_) | | (_))( ((_)(_)) _((_))
// | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \()
// |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_|
import DevLucem/ZigLib/1 as ZigZag
//@version=5
indicator("ZigZag++ Fibonacci", "ZigFib", true)
resolution = input.timeframe("")
_high = input.source(high, "High", inline="source")
_low = input.source(low, "Low", inline="source")
depth = input.int(12)
deviation = input.int(5)
backstep = input.int(2)
[direction, z1, z2] = request.security(syminfo.tickerid, resolution, ZigZag.zigzag(_low, _high, depth, deviation, backstep))
mode = input.string('Retracements','Fibonacci',options=['Retracements', 'Timezone'])
fib = array.new_float(0)
fib_col = array.new_color(0)
fib_0_lvl = input(0,'',inline='inline0',group='Fibonacci')
fib_0_col = input(#21f321,'',inline='inline0',group='Fibonacci')
if input(false,'Fib 0',inline='inline0',group='Fibonacci')
array.push(fib, fib_0_lvl)
array.push(fib_col, fib_0_col)
fib_a_lvl = input(0.236,'',inline='inline1',group='Fibonacci')
fib_a_col = input(#21c6f3,'',inline='inline1',group='Fibonacci')
if input(false,'Fib A',inline='inline1',group='Fibonacci')
array.push(fib, fib_a_lvl)
array.push(fib_col, fib_a_col)
fib_b_lvl = input(0.382,'',inline='inline2',group='Fibonacci')
fib_b_col = input(#0cb51a,'',inline='inline2',group='Fibonacci')
if input(false,'Fib B',inline='inline2',group='Fibonacci')
array.push(fib,fib_b_lvl)
array.push(fib_col,fib_b_col)
fib_c_lvl = input(0.5,'',inline='inline3',group='Fibonacci')
fib_c_col = input(#ff5d00,'',inline='inline3',group='Fibonacci')
if input(true,'Fib C',inline='inline3',group='Fibonacci')
array.push(fib,fib_c_lvl)
array.push(fib_col,fib_c_col)
fib_d_lvl = input(0.618,'',inline='inline4',group='Fibonacci')
fib_d_col = input(#64b5f6,'',inline='inline4',group='Fibonacci')
if input(false,'Fib D',inline='inline4',group='Fibonacci')
array.push(fib,fib_d_lvl)
array.push(fib_col,fib_d_col)
fib_e_lvl = input(0.786,'',inline='inline5',group='Fibonacci')
fib_e_col = input(#673ab7,'',inline='inline5',group='Fibonacci')
if input(false,'Fib E',inline='inline5',group='Fibonacci')
array.push(fib,fib_e_lvl)
array.push(fib_col,fib_e_col)
fib_f_lvl = input(1.,'',inline='inline6',group='Fibonacci')
fib_f_col = input(#e91e63,'',inline='inline6',group='Fibonacci')
if input(true,'Fib F',inline='inline6',group='Fibonacci')
array.push(fib,fib_f_lvl)
array.push(fib_col,fib_f_col)
drawFib(x1, y1, x2, y2) =>
lines = array.new_line(na)
labels = array.new_label(na)
sum = 0, a = 0, b = 0
for i = 0 to array.size(fib)-1
if mode == 'Retracements'
lvl = y2 + array.get(fib, i)*(y1-y2)
array.push(lines, line.new(x1, lvl, x2, lvl, xloc.bar_time, color=array.get(fib_col, i)))
array.push(labels, label.new(x1, lvl, str.tostring(array.get(fib,i)), xloc.bar_time, yloc.price, #00000000, label.style_label_right, array.get(fib_col,i), size.small, text.align_center))
if mode == 'Timezone'
array.push(lines, line.new(x1 + (x2-x1)*sum, high, x1 + (x2-x1)*sum, low, xloc.bar_time, extend=extend.both, color=array.get(fib_col,i)))
sum := a + b
a := b, b := sum
[lines, labels]
bgcolor(color.new(direction<0? fib_f_col: fib_a_col, 80))
line zigzag = line.new(z1.time, z1.price, z2.time, z2.price, xloc.bar_time, width=3)
[fibs, labels] = drawFib(z1.time, z1.price, z2.time, z2.price)
if direction==direction[1]
line.delete(zigzag[1])
for i = 0 to array.size(fibs[1])-1
line.delete(array.get(fibs[1], i))
if array.size(labels[1])>i
label.delete(array.get(labels[1], i))
// ( (
// )\ ) )\ )
// (()/( ( ) (()/( ( ( )
// /(_)) ))\ /(( /(_)) ))\ ( ))\ (
// (_))_ /((_)(_))\ (_)) /((_) )\ /((_) )\ '
// | \ (_)) _)((_) | | (_))( ((_)(_)) _((_))
// | |) |/ -_) \ V / | |__| || |/ _| / -_)| ' \()
// |___/ \___| \_/ |____|\_,_|\__| \___||_|_|_| |
CandlestickPatterns | https://www.tradingview.com/script/kP7u3HKD-CandlestickPatterns/ | MUQWISHI | https://www.tradingview.com/u/MUQWISHI/ | 18 | 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/
// © MUQWISHI
//@version=5
// @description This library provides a wide range of candlestick patterns, and available for user to call each pattern individually. It's a comprehensive and common tool designed for traders seeking to raise their technical analysis, and it may help users identify key turning of price action in financial instruments. Credit to public technical “*All Candlestick Patterns*” indicator.
library("CandlestickPatterns")
// Candle Structure
cUpBody = open < close // Green Candle
cDnBody = open > close // Red Candle
cRange = high-low // Candle Range
// Candle's Body Structure
cBodyHi = math.max(close, open) // Body high (Open/Close)
cBodyLw = math.min(close, open) // Body low (Open/Close)
cBody = cBodyHi - cBodyLw // Tall body
cUpWick = high - cBodyHi // Tall upper Wick
cDnWick = cBodyLw - low // Tall lower Wick
cBodyMd = cBody / 2 + cBodyLw // Midpoint body
// Candle Calculation
cBodyAvg(len) => ta.ema(cBody, len) // Compare candle's body to the average of previous candles' body.
cLwBodyAvg(x, n) => x ? cBody < cBodyAvg(n) : true // Candle's Body lower than average
cHiBodyAvg(x, n) => x ? cBody > cBodyAvg(n) : true // Candle's Body higher than average
cHasUpWick = cUpWick > 5.0 / 100 * cBody // Compare candle's body to its upper wick.
cHasDnWick = cDnWick > 5.0 / 100 * cBody // Compare candle's body to its lower wick.
// Doji Calculation
dojiBody(x) => cRange > 0 and cBody <= cRange * x / 100
dojiCandle(x) => dojiBody(x) and (cUpWick == cDnWick or
(math.abs(cUpWick - cDnWick) / cDnWick * 100) < 100 and
(math.abs(cDnWick - cUpWick) / cUpWick * 100) < 100)
// ++++ Abandoned Baby
// Bull/Bear, 3 Candles
// @function The "Abandoned Baby" candlestick pattern is a bullish/bearish pattern consists of three candles.
// @param order (simple string) Pattern order type "bull" or "bear".
// @param d1 (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
export abandonedBaby(simple string order, simple float d1 = 5.0) =>
if order == "bull"
cDnBody[2] and dojiBody(d1)[1] and low[2] > high[1] and cUpBody and high[1] < low // C_DownTrend[2]
else if order == "bear"
cUpBody[2] and dojiBody(d1)[1] and high[2] < low[1] and cDnBody and low[1] > high // C_UpTrend[2]
else
false
// ++++ Dark Cloud Cover
// Bear, 2 Candles
// @function The "Dark Cloud Cover" is a bearish pattern consists of two candles.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export darkCloudCover(simple bool c1 = true, simple int n = 14) =>
cUpBody[1] and cHiBodyAvg(c1, n)[1] and cDnBody and open >= high[1] and close < cBodyMd[1] and close > open[1] // C_UpTrend[1]
// ++++ Doji
// Neither, 1 Candle
// @function The "Doji" is neither bullish or bearish consists of one candles.
// @param d0 (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
export doji(simple float d0 = 5.0) =>
dojiCandle(d0) and not(dojiBody(d0) and cUpWick <= cBody) and not(dojiBody(d0) and cDnWick <= cBody)
// ++++ Doji Star
// Bull/Bear, 2 Candles
// @function The "Doji Star" is a bullish/bearish pattern consists of two candles.
// @param order (simple string) Pattern order type "bull" or "bear" .
// @param d0 (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export dojiStar(simple string order, simple bool c1 = true, simple int n = 14, simple float d0 = 5.0) =>
cHiBodyAvg = cHiBodyAvg(c1, n)
if order == "bull"
cDnBody[1] and cHiBodyAvg[1] and dojiBody(d0) and cBodyHi < cBodyLw[1] // C_DownTrend
else if order == "bear"
cUpBody[1] and cHiBodyAvg[1] and dojiBody(d0) and cBodyLw > cBodyHi[1] // C_UpTrend
else
false
// ++++ Downside Tasuki Gap
// Bear, 3 Candles
// @function The "Downside Tasuki Gap" is a bearish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export downsideTasukiGap(simple bool c2 = true, simple bool c1 = true, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and cLwBodyAvg(c1, n)[1] and cDnBody[2] and cBodyHi[1] < cBodyLw[2] and
cDnBody[1] and cUpBody and cBodyHi <= cBodyLw[2] and cBodyHi >= cBodyHi[1] // C_DownTrend
// ++++ Dragon Fly Doji
// Bull, 1 Candle
// @function The "Dragon Fly Doji" is a bullish pattern consists of one candle.
// @param d0 (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
export dragonflyDoji(simple float d0 = 5.0) =>
dojiBody(d0) and cUpWick <= cBody
// ++++ Engulfing
// Bull/Bear, 2 Candles
// @function The "Engulfing" is a bullish/bearish pattern consists of two candles.
// @param order (simple string) Pattern order type "bull" or "bear".
// @param c1 (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export engulfing(simple string order, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
cHiBodyAvg = cHiBodyAvg(c0, n)
cLwBodyAvg = cLwBodyAvg(c1, n)
if order == "bull"
cUpBody and cHiBodyAvg and cDnBody[1] and cLwBodyAvg[1] and close >= open[1] and
open <= close[1] and (close > open[1] or open < close[1]) // C_DownTrend
else if order == "bear"
cDnBody and cHiBodyAvg and cUpBody[1] and cLwBodyAvg[1] and close <= open[1] and
open >= close[1] and ( close < open[1] or open > close[1]) // C_UpTrend
else
false
// ++++ Evening Doji Star
// Bear, 3 Candles
// @function The "Evening Doji Star" is a bearish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param d1 (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export eveningDojiStar(simple bool c2 = true, simple bool c0 = true, simple float d1 = 5.0, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and dojiBody(d1)[1] and cHiBodyAvg(c0, n) and cUpBody[2] and cBodyLw[1] > cBodyHi[2] and
cDnBody and cBodyLw <= cBodyMd[2] and cBodyLw > cBodyLw[2] and cBodyLw[1] > cBodyHi // C_UpTrend
// ++++ Evening Star
// Bear, 3 Candles
// @function The "Evening Star" is a bearish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export eveningStar(simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and cLwBodyAvg(c1, n)[1] and cHiBodyAvg(c0, n) and cUpBody[2] and
cBodyLw[1] > cBodyHi[2] and cDnBody and cBodyLw <= cBodyMd[2] and cBodyLw > cBodyLw[2] and cBodyLw[1] > cBodyHi // C_UpTrend
// ++++ Falling Three Methods
// Bear, 5 Candles
// @function The "Falling Three Methods" is a bearish pattern consists of five candles.
// @param c4 (simple bool) 5th candle ago body must be higher than average. Optional argument, default is true.
// @param c3 (simple bool) 4th candle ago body must be lower than average. Optional argument, default is true.
// @param c2 (simple bool) 3rd candle ago body must be lower than average. Optional argument, default is true.
// @param c1 (simple bool) 2nd candle ago body must be lower than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
// @returns (bool)
export fallingThreeMethods(simple bool c4 = true, simple bool c3 = true, simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
( cHiBodyAvg(c4, n)[4] and cDnBody[4]) and
(cLwBodyAvg(c3, n)[3] and cUpBody[3] and open[3]>low[4] and close[3]<high[4]) and
(cLwBodyAvg(c2, n)[2] and cUpBody[2] and open[2]>low[4] and close[2]<high[4]) and
(cLwBodyAvg(c1, n)[1] and cUpBody[1] and open[1]>low[4] and close[1]<high[4]) and
(cHiBodyAvg(c0, n) and cDnBody and close<close[4]) // C_DownTrend[4]
// ++++ Falling Window
// Bear, 2 Candles
// @function The "Falling Window" is a bearish pattern consists of two candles.
export fallingWindow() =>
(cRange != 0 and cRange[1] != 0) and high < low[1] // C_DownTrend[1] and
// ++++ Gravestone Doji
// Bear, 1 Candle
// @function The "Gravestone Doji" is a bearish pattern consists of one candle.
// @param d0 (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
export gravestoneDoji(simple float d0 = 5.0) =>
dojiBody(d0) and cDnWick <= cBody
// ++++ Hammer
// Bull, 1 Candle
// @function The "Hammer" is a bullish pattern consists of one candle.
// @param c0 (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export hammer(simple bool c0 = true, simple int n = 14) =>
cLwBodyAvg(c0, n) and cBody > 0 and cBodyLw > hl2 and cDnWick >= 2.0 * cBody and not cHasUpWick // C_DownTrend
// ++++ Hanging Man
// Bear, 1 Candle
// @function The "Hanging Man" is a bearish pattern consists of one candle.
// @param c0 (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export hangingMan(simple bool c0 = true, simple int n = 14) =>
cLwBodyAvg(c0, n) and cBody > 0 and cBodyLw > hl2 and cDnWick >= 2.0 * cBody and not cHasUpWick // C_UpTrend
// ++++ Harami Cross
// Bull/Bear, 2 Candles
// @function The "Harami Cross" candlestick pattern is a bullish/bearish pattern consists of two candles.
// @param order (simple string) Pattern order type "bull" or "bear".
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export haramiCross(string order, simple bool c1 = true, simple int n = 14) =>
cHiBodyAvg = cHiBodyAvg(c1, n)
if order == "bull"
cHiBodyAvg[1] and cDnBody[1] and dojiBody(5.0) and high <= cBodyHi[1] and low >= cBodyLw[1] // C_DownTrend[1]
else if order == "bear"
cHiBodyAvg[1] and cUpBody[1] and dojiBody(5.0) and high <= cBodyHi[1] and low >= cBodyLw[1] // C_UpTrend[1]
else
false
// ++++ Harami
// Bull/Bear, 2 Candles
// @function The "Harami" candlestick pattern is a bullish/bearish pattern consists of two candles.
// @param order (simple string) Pattern order type "bull" or "bear"
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export harami(string order, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
cHiBodyAvg = cHiBodyAvg(c1, n)
cLwBodyAvg = cLwBodyAvg(c0, n)
if order == "bull"
cHiBodyAvg[1] and cDnBody[1] and cUpBody and cLwBodyAvg and high <= cBodyHi[1] and low >= cBodyLw[1] // C_DownTrend[1]
else if order == "bear"
cHiBodyAvg[1] and cUpBody[1] and cDnBody and cLwBodyAvg and high <= cBodyHi[1] and low >= cBodyLw[1] // C_UpTrend[1]
else
false
// ++++ Inverted Hammer
// Bull, 1 Candle
// @function The "Inverted Hammer" is a bullish pattern consists of one candle.
// @param c0 (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export invertedHammer(simple bool c0 = true, simple int n = 14) =>
cLwBodyAvg(c0, n) and cBody > 0 and cBodyHi < hl2 and cUpWick >= 2.0 * cBody and not cHasDnWick // C_DownTrend
// +++ Kicking
// Bull/Bear, 2 Candles
// @function The "Kicking" candlestick pattern is a bullish/bearish pattern consists of two candles.
// @param order (simple string) Pattern order type "bull" or "bear"
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export kicking(string order, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
marubozu = cHiBodyAvg(c0, n) and cUpWick <= 5.0/100*cBody and cDnWick <= 5.0/100*cBody
marubozu1 = cHiBodyAvg(c1, n) and cUpWick <= 5.0/100*cBody and cDnWick <= 5.0/100*cBody
if order == "bull"
marubozu1[1] and cDnBody[1] and marubozu and cUpBody and high[1] < low
else if order == "bear"
marubozu1[1] and cUpBody[1] and marubozu and cDnBody and low[1] > high
else
false
// +++ Long Lower Shadow
// Bull, 1 Candle
// @function The "Long Lower Shadow" candlestick pattern is a bullish pattern consists of one candles.
// @param l0 (simple float) Current candle's lower wick min percentage out of candle range. Optional argument, default is 75.
export longLowerShadow(simple float l0 = 75.0) =>
cDnWick > cRange/100*l0
// +++ Long Upper Shadow
// Bear, 1 Candle
// @function The "Long Upper Shadow" candlestick pattern is a bearish pattern consists of one candles.
// @param u0 (simple float) Current candle's upper wick min percentage out of candle range. Optional argument, default is 75.
export longUpperShadow(simple float u0 = 75.0) =>
cUpWick > cRange/100*u0
// +++ Marubozu Black
// Bear, 1 Candle
// @function The "Marubozu Black" candlestick pattern is a bearish pattern consists of one candles.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export marubozuBlack(simple bool c0 = true, simple int n = 14) =>
cDnBody and cHiBodyAvg(c0, n) and cUpWick <= 5.0/100*cBody and cDnWick <= 5.0/100*cBody and cDnBody
// +++ Marubozu White
// Bull, 1 Candle
// @function The "Marubozu White" candlestick pattern is a bullish pattern consists of one candles.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export marubozuWhite(simple bool c0 = true, simple int n = 14) =>
cUpBody and cHiBodyAvg(c0, n) and cUpWick <= 5.0/100*cBody and cDnWick <= 5.0/100*cBody and cUpBody
// ++++ Morning Doji Star
// Bull, 3 Candles
// @function The "Morning Doji Star" candlestick pattern is a bullish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param d1 (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export morningDojiStar(simple bool c2 = true, simple float d1 = 5.0, simple bool c0 = true, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and cDnBody[2] and dojiBody(d1)[1] and cHiBodyAvg(c0, n) and cUpBody and
cBodyHi[1] < cBodyLw[2] and cBodyHi >= cBodyMd[2] and cBodyHi < cBodyHi[2] and cBodyHi[1] < cBodyLw // C_DownTrend
// ++++ Morning Star
// Bull, 3 Candles
// @function The "Morning Star" candlestick pattern is a bullish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
// @param c0 (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export morningStar(simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and cLwBodyAvg(c1, n)[1] and cHiBodyAvg(c0, n) and cDnBody[2] and cBodyHi[1] < cBodyLw[2] and
cUpBody and cBodyHi >= cBodyMd[2] and cBodyHi < cBodyHi[2] and cBodyHi[1] < cBodyLw // C_DownTrend
// ++++ On Neck
// Bear, 2 Candles
// @function The "On Neck" candlestick pattern is a bearish pattern consists of two candles.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param c0 (simple bool) Cuurent candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export onNeck(simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
cDnBody[1] and cHiBodyAvg(c1, n)[1] and cUpBody and open < close[1] and cLwBodyAvg(c0, n) and cRange!=0
and math.abs(close-low[1])<=cBodyAvg(14)*0.05 // C_DownTrend
// ++++ Piercing
// Bull, 2 Candles
// @function The "Piercing" candlestick pattern is a bullish pattern consists of two candles.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export piercing(simple bool c1 = true, simple int n = 14) =>
cDnBody[1] and cHiBodyAvg(c1, n)[1] and cUpBody and open <= low[1] and close > cBodyMd[1] and close < open[1] // C_DownTrend[1]
// ++++ Rising Three Methods
// Bull, 5 Candles
// @function The "Rising Three Methods" candlestick pattern is a bullish pattern consists of five candles.
// @param c4 (simple bool) 5th candle ago body must be higher than average. Optional argument, default is true.
// @param c3 (simple bool) 4th candle ago body must be Lower than average. Optional argument, default is true.
// @param c2 (simple bool) 3rd candle ago body must be Lower than average. Optional argument, default is true.
// @param c1 (simple bool) 2nd candle ago body must be Lower than average. Optional argument, default is true.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export risingThreeMethods(simple bool c4 = true, simple bool c3 = true, simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
(cHiBodyAvg (c4, n)[4] and cUpBody[4]) and
(cLwBodyAvg(c3, n)[3] and cDnBody[3] and open[3]<high[4] and close[3]>low[4]) and
(cLwBodyAvg(c2, n)[2] and cDnBody[2] and open[2]<high[4] and close[2]>low[4]) and
(cLwBodyAvg(c1, n)[1] and cDnBody[1] and open[1]<high[4] and close[1]>low[4]) and
(cHiBodyAvg(c0, 14) and cUpBody and close>close[4]) // C_UpTrend[4] and
// ++++ Rising Window
// Bull, 2 Candles
// @function The "Rising Window" candlestick pattern is a bullish pattern consists of two candle.
export risingWindow() =>
cRange!=0 and cRange[1]!=0 and low > high[1] // C_UpTrend[1] and
// ++++ Shooting Star
// Bear, 1 Candle
// @function The "Shooting Star" candlestick pattern is a bearish pattern consists of one candle.
// @param c0 (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export shootingStar(simple bool c0 = true, simple int n = 14) =>
cLwBodyAvg(c0, n) and cBody > 0 and cBodyHi < hl2 and cUpWick >= 2.0 * cBody and not cHasDnWick // C_UpTrend
// ++++ Spinning Top Black
// Neither, 1 Candle
// @function The "Spinning Top Black" is neither bullish or bearish.
// @param l0 (simple float) Current candle's lower wick min percentage out of candle range. Optional argument, default is 34.
// @param u0 (simple float) Current candle's upper wick min percentage out of candle range. Optional argument, default is 34.
export spinningTopBlack(simple float l0 = 34.0, simple float u0 = 34) =>
cDnWick >= cRange / 100 * l0 and cUpWick >= cRange / 100 * u0 and not dojiBody(5.0) and cDnBody
// ++++ Spinning Top White
// Neither, 1 Candle
// @function The "Spinning Top White" is neither bullish or bearish.
// @param l0 (simple float) Current candle's lower wick min percentage out of candle range. Optional argument, default is 34.
// @param u0 (simple float) Current candle's upper wick min percentage out of candle range. Optional argument, default is 34.
export spinningTopWhite(simple float l0 = 34.0, simple float u0 = 34) =>
cDnWick >= cRange / 100 * l0 and cUpWick >= cRange / 100 * u0 and not dojiBody(5.0) and cUpBody
// ++++ Three Black Crows
// Bear, 3 Candles
// @function The "Three Black Crows" candlestick pattern is a bearish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param c0 (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export threeBlackCrows(simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
noDnWick = cRange * 5.0 / 100 > cDnWick
cHiBodyAvg(c0, n) and cHiBodyAvg(c1, n)[1] and cHiBodyAvg(c2, n)[2] and cDnBody and cDnBody[1] and cDnBody[2] and
close < close[1] and close[1] < close[2] and open > close[1] and open < open[1] and open[1] > close[2] and
open[1] < open[2] and noDnWick and noDnWick[1] and noDnWick[2]
// ++++ Three White Soldiers
// Bull, 3 Candles
// @function The "Three White Soldiers" candlestick pattern is a bullish pattern consists of three candles.
// @param c2 (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param c0 (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export threeWhiteSoldiers(simple bool c2 = true, simple bool c1 = true, simple bool c0 = true, simple int n = 14) =>
noUpWick = cRange * 5.0 / 100 > cUpWick
cHiBodyAvg(c0, n) and cHiBodyAvg(c1, n)[1] and cHiBodyAvg(c2, n)[2] and cUpBody and cUpBody[1] and cUpBody[2] and
close > close[1] and close[1] > close[2] and open < close[1] and open > open[1] and open[1] < close[2] and
open[1] > open[2] and noUpWick and noUpWick[1] and noUpWick[2]
// ++++ Tri Star
// Bull/Bear, 3 Candles
// @function The "Tri Star" candlestick pattern is a bullish/bearish pattern consists of three candles.
// @param order (simple string) Pattern order type "bull" or "bear".
// @param d2 (simple float) Before previous candle's body percentage out of candle range. Optional argument, default is 5.
// @param d1 (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
// @param d0 (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
export triStar(simple string order, simple float d2 = 5.0, simple float d1 = 5.0, simple float d0 = 5.0) =>
if order == "bull"
dojiCandle(d2)[2] and dojiCandle(d1)[1] and dojiCandle(d0) and
cBodyLw[2] > cBodyHi[1] and cBodyHi[1] < cBodyLw // C_DownTrend[2]
else if order == "bear"
dojiCandle(d2)[2] and dojiCandle(d1)[1] and dojiCandle(d0) and
cBodyHi[2] < cBodyLw[1] and cBodyLw[1] > cBodyHi // C_UpTrend[2]
else
false
// ++++ Tweezer Bottom
// Bull, 2 Candles
// @function The "Tweezer Bottom" candlestick pattern is a bullish pattern consists of two candles.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export tweezerBottom(simple bool c1 = true, simple int n = 14) =>
(not dojiBody(5.0) or (cHasUpWick and cHasDnWick)) and math.abs(low-low[1]) <= cBodyAvg(n)*0.05
and cDnBody[1] and cUpBody and cHiBodyAvg(c1, n)[1] // C_DownTrend[1] and
// ++++ Tweezer Top
// Bear, 2 Candles
// @function The "Tweezer Top" candlestick pattern is a bearish pattern consists of two candles.
// @param c1 (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export tweezerTop(simple bool c1 = true, simple int n = 14) =>
(not dojiBody(5.0) or (cHasUpWick and cHasDnWick)) and math.abs(high-high[1]) <= cBodyAvg(n)*0.05
and cUpBody[1] and cDnBody and cHiBodyAvg(c1, n)[1] // C_UpTrend[1]
// ++++ Upside Tasuki Gap
// Bull, 3 Candles
// @function The "Tri Star" candlestick pattern is a bullish pattern consists of three candles.
// @param c2 (simple bool) Before Previous candle's body must be higher than average. Optional argument, default is true.
// @param c1 (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
// @param n (simple int) Length of average candle's body. Optional argument, default is 14.
export upsideTasukiGap(simple bool c2 = true, simple bool c1 = true, simple int n = 14) =>
cHiBodyAvg(c2, n)[2] and cLwBodyAvg(c1, n)[1] and cUpBody[2] and cBodyLw[1] > cBodyHi[2]
and cUpBody[1] and cDnBody and cBodyLw >= cBodyHi[2] and cBodyLw <= cBodyLw[1] // C_UpTrend
|
LibrarySupertrend | https://www.tradingview.com/script/DcwulV7o-LibrarySupertrend/ | Yungbluh | https://www.tradingview.com/u/Yungbluh/ | 1 | 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/
// © Yungbluh
//@version=5
library("LibrarySupertrend")
//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) =>
// Trend 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]
// Strength 4 Zone _______________________________________________________________________________________________________
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 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 _______________________________________________________________________________________________
//// © wbburgin
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] |
debug | https://www.tradingview.com/script/3Mxa5WVh-debug/ | kurtsmock | https://www.tradingview.com/u/kurtsmock/ | 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/
// © kurtsmock
//@version=5
// @description Show Array or Matrix Elements In Table
library("debug")
// @function Debug Variables in Matrix
// @param _col (int) Assign Column
// @param _row (int) Assign Row
// @param _name (simple matrix) Matrix Name
// @param _value (string) Assign variable as a string (str.tostring())
// @param _lb (string) Constant label (optional)
// @param _ip (int) (default 1) 1 for continuous updates. 2 for barstate.isnew updates. 3 for barstate.isconfirmed updates. -1 to only add once
// @returns Returns Variable _value output and _msg formatted as '_msg: variableOutput' in designated column and row
export debug(int _col, int _row, simple matrix<string> _name, string _value, string _msg='', int _ip=1) =>
ipOn = _ip == 1 ? true : false
bsnOn = _ip == 2 ? true : false
bscOn = _ip == 3 ? true : false
if matrix.get(_name, _row, _col) == ''
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if ipOn
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bsnOn
if barstate.isnew
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bscOn
if barstate.isconfirmed
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
export debug(int _col, int _row, simple matrix<string> _name, float _value, string _msg='', int _ip=1) =>
ipOn = _ip == 1 ? true : false
bsnOn = _ip == 2 ? true : false
bscOn = _ip == 3 ? true : false
if matrix.get(_name, _row, _col) == ''
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if ipOn
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bsnOn
if barstate.isnew
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bscOn
if barstate.isconfirmed
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
export debug(int _col, int _row, simple matrix<string> _name, int _value, string _msg='', int _ip=1) =>
ipOn = _ip == 1 ? true : false
bsnOn = _ip == 2 ? true : false
bscOn = _ip == 3 ? true : false
if matrix.get(_name, _row, _col) == ''
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if ipOn
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bsnOn
if barstate.isnew
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bscOn
if barstate.isconfirmed
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
export debug(int _col, int _row, simple matrix<string> _name, bool _value, string _msg='', int _ip=1) =>
ipOn = _ip == 1 ? true : false
bsnOn = _ip == 2 ? true : false
bscOn = _ip == 3 ? true : false
if matrix.get(_name, _row, _col) == ''
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if ipOn
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bsnOn
if barstate.isnew
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
if bscOn
if barstate.isconfirmed
matrix.set(_name, _row, _col, _msg + ": " + str.tostring(_value))
// @function Debug Scope in Matrix - Identify When Scope Is Accessed
// @param _col (int) Column Number
// @param _row (int) Row Number
// @param _name (simple matrix) Matrix Name
// @param _msg (string) Message
// @returns Message appears in debug panel using _col/_row as the identifier
export debugs(int _col, int _row, simple matrix<string> _name, string _msg='') =>
matrix.set(_name, _row, _col, "debugs(" + str.tostring(_col) + "," + str.tostring(_row) + "): " + _msg)
// Example:
// Define Matrix at beginning of script so functions work throughout the script
// You must add a matrix into the host script as it cannot be imported.
rows = 2
cols = 1
console = matrix.new<string>(rows,cols,'')
// debug: Show variable value in table
varip ticks = 0.0
ticks := close != close[1] ? ticks + 1 : ticks
if barstate.isconfirmed
ticks := 0.0
debug(0,0,console,ticks, "debug() This will show up price in table on every bar\nBecause the variable is varip it is counting ticks on every\ncalculation and updating that value on the table.\n(It will update the variable as the value changes on the live bar.)")
// debugs: detect access scopes. Must be placed in scope.
sampleBool = timenow > time and timenow < time + 60000
if sampleBool
debugs(0,1,console,"debugs() This will show up in the table for the first 60 seconds\nof a bar sampleBool will have fired this scope.\nIt will not show up in the table thereafter")
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DEBUG NOTES:
// Anywhere you want to test the value of a variable, add a debug() function. Debug functions can be stacked together at the end of the script
// However, if you want to clearly see how variables are updated during intrabar calculations, you will need to place the debug function immediately
// below the variable you want to display and see real time updates
// If variable updates are disgused by the execution model, you can place debug() above and below code blocks that modify the variable of interest.
// This will allow you to see the variable state before and after the processing. If it is in a local scope, you can use debugs() to detect that.
// Historical bars will just use barstate.isconfirmed variables since it will only output the final calculation.
// Historical states can be viewed using replay mode
// console matrix must be a string matrix. All values in the table will be converted to strings to prevent type errors
// You can use with float, int, and bool types and it will automatically convert the variable to a string
// debug(0,0,rows,"Total Rows")
// Debug-Scope [debugs()] is used to show when a scope is accessed. Thus debugs() must be placed inside the scope being analyzed.
// if close>open
// debugs(0,1,"Close>Open")
// debugs:
// CAUTION: Value's will be overwritten if two debug/debugs functions share the same column and row. This can be a desired effect or undesired.
// It will generally show the debug() or debugs() function on the lowest line that is assigned to that matrix position.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// showArray Functions {
// @function Array Element Display (Supports float[], int[], string[], and bool[])
// @param _arrayName ID of Array to be Displayed
// @param _pos Position for Table
// @param _txtSize Size of Table Cell Text
// @param s_index (Optional. Default True.) Show/Hide Index Numbers
// @param s_border (Optional. Default False.) Show/Hide Border
// @param bCol = (Optional. Default Black.) Frame/Border Color.
// @param _fillCond (Optional) Conditional statement. Function displays array only when true. For instances where size is not immediately known or indices are na. Default = true, indicating array size is set at bar_index 0.
// @param _offset (Optional) Use to view historical array states. Default = 0, displaying realtime bar.
// @param _tRows Number of Rows to Display Data In (columns will be calculated accordingly)
// @returns A Display of Array Values in a Table
export viewArray(float[] _arrayName, string _pos, string _txtSize, int _tRows, bool s_index = true, bool s_border = false, string _rowCol = "col", color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getSize = array.size(_arrayName[_offset])
getCols = math.ceil(getSize / _tRows)
viewArray = table.new(_pos, getCols, _tRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = _tRows - 1
if _rowCol == "col"
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endRow
row += 1
row := 0
if _i < endCol
column += 1
else if _rowCol == "row"
for _i = 0 to endRow
for _j = 0 to endCol
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endCol
column += 1
column := 0
if _i < endRow
row += 1
export viewArray(int[] _arrayName, string _pos, string _txtSize, int _tRows, bool s_index = true, bool s_border = false, string _rowCol = "col", color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getSize = array.size(_arrayName[_offset])
getCols = math.ceil(getSize / _tRows)
viewArray = table.new(_pos, getCols, _tRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = _tRows - 1
if _rowCol == "col"
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endRow
row += 1
row := 0
if _i < endCol
column += 1
else if _rowCol == "row"
for _i = 0 to endRow
for _j = 0 to endCol
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endCol
column += 1
column := 0
if _i < endRow
row += 1
export viewArray(string[] _arrayName, string _pos, string _txtSize, int _tRows, bool s_index = true, bool s_border = false, string _rowCol = "col", color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getSize = array.size(_arrayName[_offset])
getCols = math.ceil(getSize / _tRows)
viewArray = table.new(_pos, getCols, _tRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = _tRows - 1
if _rowCol == "col"
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endRow
row += 1
row := 0
if _i < endCol
column += 1
else if _rowCol == "row"
for _i = 0 to endRow
for _j = 0 to endCol
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endCol
column += 1
column := 0
if _i < endRow
row += 1
export viewArray(bool[] _arrayName, string _pos, string _txtSize, int _tRows, bool s_index = true, bool s_border = false, string _rowCol = "col", color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getSize = array.size(_arrayName[_offset])
getCols = math.ceil(getSize / _tRows)
viewArray = table.new(_pos, getCols, _tRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = _tRows - 1
if _rowCol == "col"
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endRow
row += 1
row := 0
if _i < endCol
column += 1
else if _rowCol == "row"
for _i = 0 to endRow
for _j = 0 to endCol
table.cell(viewArray, column, row,
text = array.size(_arrayName[_offset]) > index ?
s_index ? str.tostring(index) + ' - ' + str.tostring(array.get(_arrayName[_offset], index)) : str.tostring(array.get(_arrayName[_offset], index)) :
"-",
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if index <= array.size(_arrayName[_offset]) - 1
index += 1
if _j < endCol
column += 1
column := 0
if _i < endRow
row += 1
//}
// Examples {
arraySize = 15
a = array.new_float(arraySize, math.round(hlc3,2))
for l = 0 to arraySize - 1
array.set(a, l, math.round(hlc3[l],2))
viewArray(a, position.top_left, size.normal, 5, true, true, 'col', color.orange, color.purple)
b = array.new_int(arraySize, 0)
inc = 0
for l = 0 to arraySize - 1
array.set(b, l, inc)
inc += 1
viewArray(b, position.top_right, size.normal, 5, true, false, 'row')
c = array.new_string(arraySize, "")
str = 'a'
for l = 0 to arraySize - 1
array.set(c, l, str)
str := str + 'a'
viewArray(c, position.bottom_left, size.normal, 5, true, false, 'row')
//}
// showMatrix Functions {
// @function Matrix Element Display (Supports <float>, <int>, <string>, and <bool>)
// @param _matrixName ID of Matrix to be Displayed
// @param _pos Position for Table
// @param _txtSize Size of Table Cell Text
// @param s_index (Optional. Default True.) Show/Hide Index Numbers
// @param s_border (Optional. Default False.) Show/Hide Border
// @param bCol = (Optional. Default Black.) Frame/Border Color.
// @param _fillCond (Optional) Conditional statement. Function displays matrix only when true. For instances where size is not immediately known or indices are na. Default = true, indicating matrix size is set at bar_index 0.
// @param _offset (Optional) Use to view historical matrix states. Default = 0, displaying realtime bar.
// @returns A Display of Matrix Values in a Table
export viewMatrix(simple matrix<float> _matrixName, string _pos, string _txtSize, bool s_index = true, bool _resetIdx = true, bool s_border = false, color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getRows = matrix.rows(_matrixName[_offset])
getCols = matrix.columns(_matrixName[_offset])
viewMatrix = table.new(_pos, getCols, getRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = getRows - 1
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewMatrix, column, row,
text = s_index ? str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row,column)) : str.tostring(matrix.get(_matrixName[_offset],row,column)),
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if _j < endRow
row += 1
index += 1
row := 0
if _i < endCol
column += 1
if _resetIdx
index := 0
export viewMatrix(simple matrix<int> _matrixName, string _pos, string _txtSize, bool s_index = true, bool _resetIdx = true, bool s_border = false, color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getRows = matrix.rows(_matrixName[_offset])
getCols = matrix.columns(_matrixName[_offset])
viewMatrix = table.new(_pos, getCols, getRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = getRows - 1
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewMatrix, column, row,
text = s_index ? str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row,column)) : str.tostring(matrix.get(_matrixName[_offset],row,column)),
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if _j < endRow
row += 1
index += 1
row := 0
if _i < endCol
column += 1
if _resetIdx
index := 0
export viewMatrix(simple matrix<string> _matrixName, string _pos, string _txtSize, bool s_index = true, bool _resetIdx = true, bool s_border = false, color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getRows = matrix.rows(_matrixName[_offset])
getCols = matrix.columns(_matrixName[_offset])
viewMatrix = table.new(_pos, getCols, getRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = getRows - 1
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewMatrix, column, row,
text = s_index ? str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row,column)) : str.tostring(matrix.get(_matrixName[_offset],row,column)),
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if _j < endRow
row += 1
index += 1
row := 0
if _i < endCol
column += 1
if _resetIdx
index := 0
export viewMatrix(simple matrix<bool> _matrixName, string _pos, string _txtSize, bool s_index = true, bool _resetIdx = true, bool s_border = false, color bCol = color.black, color txtCol = color.black, bool _fillCond = true, int _offset = 0) =>
if _fillCond
getRows = matrix.rows(_matrixName[_offset])
getCols = matrix.columns(_matrixName[_offset])
viewMatrix = table.new(_pos, getCols, getRows, frame_color=bCol, frame_width=s_border ? 1 : 0, border_color=bCol, border_width=s_border ? 1 : 0)
row = 0, column = 0, index = 0
endCol = getCols - 1
endRow = getRows - 1
for _i = 0 to endCol
for _j = 0 to endRow
table.cell(viewMatrix, column, row,
text = s_index ? str.tostring(index) + " - " + str.tostring(matrix.get(_matrixName[_offset],row,column)) : str.tostring(matrix.get(_matrixName[_offset],row,column)),
text_halign=text.align_left,
text_valign=text.align_top,
text_color=txtCol,
text_size=_txtSize)
if _j < endRow
row += 1
index += 1
row := 0
if _i < endCol
column += 1
if _resetIdx
index := 0
//}
// -- Examples {
d = matrix.new<float>(5, 5, close[1])
viewMatrix(d, position.top_center, size.small, true, true, true)
viewMatrix(console, position.bottom_right, size.normal, false, false, true)
//} |
TradingToolsLibrary | https://www.tradingview.com/script/KYOAAz0P-TradingToolsLibrary/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 60 | 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/
// © Gentleman-Goat
// Version 1.0.1
// ▄██████▄ ▄████████ ███▄▄▄▄ ███ ▄█ ▄████████ ▄▄▄▄███▄▄▄▄ ▄████████ ███▄▄▄▄ ▄██████▄ ▄██████▄ ▄████████ ███
// ███ ███ ███ ███ ███▀▀▀██▄ ▀█████████▄ ███ ███ ███ ▄██▀▀▀███▀▀▀██▄ ███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ███ ▀█████████▄
// ███ █▀ ███ █▀ ███ ███ ▀███▀▀██ ███ ███ █▀ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ▀███▀▀██
// ▄███ ▄███▄▄▄ ███ ███ ███ ▀ ███ ▄███▄▄▄ ███ ███ ███ ███ ███ ███ ███ ▄███ ███ ███ ███ ███ ███ ▀
// ▀▀███ ████▄ ▀▀███▀▀▀ ███ ███ ███ ███ ▀▀███▀▀▀ ███ ███ ███ ▀███████████ ███ ███ ▀▀███ ████▄ ███ ███ ▀███████████ ███
// ███ ███ ███ █▄ ███ ███ ███ ███ ███ █▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███
// ███ ███ ███ ███ ███ ███ ███ ███▌ ▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███
// ████████▀ ██████████ ▀█ █▀ ▄████▀ █████▄▄██ ██████████ ▀█ ███ █▀ ███ █▀ ▀█ █▀ ████████▀ ▀██████▀ ███ █▀ ▄████▀
//
//@version=5
// @description Easily create advanced entries, exits, filters and qualifiers to simulate strategies. Supports DCA (Dollar Cost Averaging) Lines, Stop Losses, Take Profits (with trailing or without) & ATR.
library("TradingToolsLibrary",overlay=true)
//TYPES
export type filter
bool disabled = true
string filter_for_entries_or_exits = na //This is the entries or exits the filter applies to. Comma separated to add more.
string filter_for_groups = na //Which groups should this filter apply to? Comma separated to add more.
bool condition = true //This is the custom condition to determine the filter use. If this is set to true it will not allow the entry or exit associated with the filter to occur.
bool dynamic_condition = false //INTERNAL USE ONLY -> This is the optional dynamic condition value itself for if the filter should be activated or not
bool use_dynamic_condition = false //Should the dynamic condition be used?
bool use_override_default_condition = false //Should the dynamic condition (if being used) override the hardcoded default condition that might be present?
string dynamic_condition_operator = "=" //What operator is being used for testing the dynamic_condition_value to see if it's true or not? Supports '=','>','<','≤','≥' and more...
float dynamic_condition_source = na //This is the actual value from the dynamic source. This should be set when the entry is created and updated every bar.
float dynamic_compare_source = na //This is the actual value from the dynamic source. This is the variable used for comparing against the condition source, for cross over and cross under.
float dynamic_condition_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
float dynamic_compare_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
bool use_dynamic_compare_source = false //This controls if the dynamic compare source will be used for comparison purposes
string dynamic_condition_activate_value = "0" //This is what the condition value should be that will ultimatly create the 'true' or 'false' condition for allowing the entry to pass.
//INTERNAL USE ONLY ALL BELOW -> This type does NOT use these variables, but it needed to be here to make a dynamic function work with entries,exits, filters and qualifiers
string expire_condition_activate_value = "0"
float expire_condition_source = na
float expire_condition_source_prior = na
float expire_compare_source = na
float expire_compare_source_prior = na
bool use_expire_compare_source = false
string expire_condition_operator = "="
//**
export type qualifier
bool disabled = true
string qualify_for_entries_or_exits = na //This is the entries or exits the filter applies to. Comma separated to add more.
string qualify_for_groups = na //Which groups should this filter apply to? Comma separated to add more.
bool disqualify = false //Should this disqualify entries instead of qualify them?
bool condition = true //This is the custom condition to determine the qualifier use. If this is set to true it will not allow the entry or exit associated with the qualifier to occur.
bool dynamic_condition = false //INTERNAL USE ONLY -> This is the optional dynamic condition value itself for if the filter should be activated or not
bool use_dynamic_condition = false //Should the dynamic condition be used?
bool use_override_default_condition = false //Should the dynamic condition (if being used) override the hardcoded default condition that might be present?
string dynamic_condition_operator = "=" //What operator is being used for testing the dynamic_condition_value to see if it's true or not? Supports '=','>','<','≤','≥' and more...
float dynamic_condition_source = na //This is the actual value from the dynamic source. This should be set when the entry is created and updated every bar.
float dynamic_compare_source = na //This is the actual value from the dynamic source. This is the variable used for comparing against the condition source, for cross over and cross under.
float dynamic_condition_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
float dynamic_compare_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
bool use_dynamic_compare_source = false //This controls if the dynamic compare source will be used for comparison purposes
string dynamic_condition_activate_value = "0" //This is what the condition value should be that will ultimatly create the 'true' or 'false' condition for allowing the entry to pass.
int expire_after_x_bars = 10 //This is how many bars until the qualifier expires from allowing the specified entries or exit to trigger.
bool use_expire_after_x_bars = false //Should this be allowed to use expire after x bars?
bool use_expire_condition = false //Should the expire condition be used?
bool use_override_expire_condition = false //Should the expire condition (if being used) override the hardcoded default expire condition that might be present?
string expire_condition_operator = "=" //What operator is being used for testing the expire_condition_value to see if it's true or not? Supports '=','>','<','≤','≥' and more...
float expire_condition_source = na //This is the actual value from the expire source. This should be set when the entry is created and updated every bar.
float expire_compare_source = na //This is the actual value from the expire source. This is the variable used for comparing against the condition source, for cross over and cross under.
float expire_condition_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
float expire_compare_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
bool use_expire_compare_source = false //This controls if the expire compare source will be used for comparison purposes
string expire_condition_activate_value = "0" //This is what the condition value should be that will ultimatly create the 'true' or 'false' condition for allowing the qualifier to pass.
bool active = false //While the qualifier is active, entries or exits are allowed to happen that are tied to it.
int expire_after_bars_bar_index = 0 //This keeps track of what bar index it currently is.
int expire_after_bars_bar_index_prior = 0 //This is related to above, but needed so we can calculate when there was a change. Since when the timeframe changes this will be different from the non prior version.
int expire_bar_count = 0 //INTERNAL USE ONLY -> This keeps track of how many bars have actually passed for the timeframe selected
bool expire_bar_changed = false //INTERNAL USE ONLY -> Returns true if there was a calculated change that turn.
//**
export type entry_position
bool disabled = true //Use this to manually disable this entry from being possible to activate.
bool activate = false //INTERNAL USE ONLY -> Should this entry be activated
bool active = false //INTERNAL USE ONLY -> Is the entry currently active
bool override_occured = false //INTERNAL USE ONLY -> Keeps track if this entry caused an override
bool[] passDebug = na //INTERNAL USE ONLY -> This is used to test the pass engine to see what passed and didn't for debug purposes.
float initial_activation_price = 0.0 //INTERNAL USE ONLY -> This tracks what the price was when this entry activated. Used by exits when the adjust to average position is turned off.
bool dca_done = false //INTERNAL USE ONLY -> This is used if the entry is 'considered done' for DCA use. This can happen if an exit flags the entry this way. For example a close exit can flag an entry as no_more_dca_allowed after exiting 50%. This will prevent future DCA from triggering (if the entry enabled that option) and only other exits can close the position.
bool condition = false //This is condition that will activate this entry, REQUIRED to be user supplied or the entry will never happen UNLESS you are using dynamic_condition
bool dynamic_condition = false //INTERNAL USE ONLY -> This is the optional dynamic condition value that will be determined based on the other settings.
bool use_dynamic_condition = false //Should the dynamic condition be used?
bool use_override_default_condition = false //Should the dynamic condition (if being used) override the hardcoded default condition that might be present?
string dynamic_condition_operator = "=" //What operator is being used for testing the dynamic_condition_value to see if it's true or not? Supports '=','>','<','≤','≥'
float dynamic_condition_source = na //This is the actual value from the dynamic source. This should be set when the entry is created and updated every bar.
float dynamic_compare_source = na //This is the actual value that we want to compare against the dynamic source. It could be dynamic itself or simply be the close. Used for cross over and cross under.
float dynamic_condition_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
float dynamic_compare_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
bool use_dynamic_compare_source = false //This controls if the dynamic compare source will be used for comparison purposes
string dynamic_condition_activate_value = "0" //This is what the condition value should be that will ultimatly create the 'true' or 'false' condition for allowing the entry to pass.
bool use_cash = false
bool use_percent_equity = true
float percent_equity_amount = 100.0 //Note, this can be overwritten if use_dynamic percent equity is active
float cash_amount = 1000.0
float position_size = 0 //INTERNAL USE ONLY -> Running total of what the position_size for the entry is. Useful for calculating if active should be false or not during closures. This does NOT take into account pyramiding, just what the position_size would be at time of activation.
float total_position_size = 0 //INTERNAL USE ONLY -> This is a running total of the position size for the entry, which can increase with pyramiding.
float prior_total_position_size = 0 //INTERNAL USE ONLY -> Keeps track of the prior total position size in case we need to reset it later in the bar.
float equity_remaining = 0.0 //INTERNAL USE ONLY -> This calculates a running total of the equity you have remaining to work with for DCA purposes. Useful for MARKET ORDER DCA to calculate position sizes correctly.
float prior_equity_remaining = 0.0 //INTERNAL USE ONLY -> There are circumstances like flip position that may have occured when a DCA activated. In this situation we need to undo any changes to the entry before they make it to becoming an actual order.
float initial_equity = 0.0 //INTERNAL USE ONLY -> This is how much equity it started with before DCA on the initial qualified entry into the market.
//float activation_price = 0.0 //INTERNAL USE ONLY -> This calculates what the price was upon activation. Used by exits when NOT using average position for calculating stops & profits.
bool use_martingale = false
float martingale_win_ratio = 1.0
float martingale_lose_ratio = 2.0
int martingale_win_limit = 5
int martingale_lose_limit = 5
string martingale_limit_reset_mode = "Original"
bool use_dynamic_percent_equity = false //This allows the percent equity to used on every entry to be dynamic based on other conditions & calculations (I.E, think RSI, MacD etc...)
float dynamic_percent_equity_amount = 100.0 //This variable should be set by the user if the above is set to TRUE. It will prioritize use of this over kelly or percent equity amounts.
float initial_dynamic_percent_equity_amount = 100.0 //INTERNAL USE ONLY -> This is used to keep track of the initial dynamic percent equity in case you are not using Dynamic DCA equity.
float dynamic_percent_equity_source = close //Set this to what the source should be for determining dynamic percent equity
float dynamic_percent_equity_min = 0.25 //This is the minimum percentage it should use for dynamic percent equity
float dynamic_percent_equity_max = 1.00 //This is the maximum percentage it should use for dynamic percent equity
float dynamic_percent_equity_source_sell_range = 80 //This is the range from the source that would trigger minimum equity usage
float dynamic_percent_equity_source_buy_range = 30 //This is the range from the source that would trigger maximum equity usage
string dynamic_equity_interpolation_method = "Linear" //This controls what method is used to determine the interpolation. There is only 2 choices. 'Linear' and 'Linear From Mid'.
int total_bars = 0 //INTERNAL USE ONLY -> This is a running total of all bars since the simulation began
int bar_index_at_activate = 0 //INTERNAL USE ONLY -> What was the bar_index when it activated. This is used to find the most recent entry which in turn is used for cooldown logic.
int bars_since_active = 0 //INTERNAL USE ONLY -> This is how many bars have gone by since it's been active.
int time_at_activate = 0 //INTERNAL USE ONLY -> Returns the unix time stamp at activation. Useful for drawing lines and time based math.
int time_since_active = 0 //INTERNAL USE ONLY -> Unix time difference in terms of how much time has gone by since it was activated.
int bar_index_at_activated = 0 //INTERNAL USE ONLY -> bar_index it activated on, needed for drawing the DCA lines.
int bar_index_at_pyramid_change = na //INTERNAL USE ONLY -> This is the bar_index that will be set when a new pyramid occurs so that DCA lines will draw correctly.
//int start_after_bars = 100 //This is the minimum number of bars that should pass before this order is allowed to occur.
string name //The name of this entry position. Can be whatever you want and will be used in strategy comments accordingly.
string id //The ID to refer to this for Exit conditions
string group //The group ID to refer to this for exit conditions
int pyramiding_limit = 1 //This is the limit for how many simultaneous entries can occur in the same direction at the same time if equity allows. DCA does NOT count toward this limit (which is a good thing, but please be aware of this)!
int self_pyramiding_limit = 1 //This is the limit for how many simultaneous entries of this particular entry can occur in the same direction at the same time if equity allows. As with other entries, DCA does NOT count toward the limit.
array<entry_position> self_pyramiding_positions = na //INTERNAL USE ONLY -> This keeps track of a copy of it's own entry but with new DCA_Positions that it may have. Everytime a new self position occurs, it will be pushed here, and closed accordingly. If this is NA it will be automatically filled by default to always have at least one entry.
bool new_pyramid_cancels_dca = true // This controls if a new pyramid should cancel previous DCA (Including self pyramid entries DCA)
int num_active_long_positions = 0 //INTERNAL USE ONLY -> Keeps track of how many active long positions there are currently across all entries
int num_active_short_positions = 0 //INTERNAL USE ONLY -> Keeps track of how many active short positions there are currently across all entries
int num_active_positions = 0 //INTERNAL USE ONLY -> Tracks how many known active positions each entry thinks there is.
float position_remaining = 0.0 //INTERNAL USE ONLY -> Keeps track of how much the position has remains to be used.
float prior_position_remaining = 0.0 //INTERANL USE ONLY -> Keeps track of how much the prior position was before it was adjusted.
string direction //This should be either "LONG" or "SHORT"
bool allow_flip_position = true //This is if this posiiton is allowed to FLIP from long to short and short to long etc... If set to false, it must wait for the market to be FLAT before allowing an entry.
bool flip_occurred = false //This keeps track if a flip occurred. If this is the case, then it will NOT close, since the flip in the opposite direction will take care of this.
bool ignore_flip = true //This will ignore entries that have the allow flip option to override them.
bool use_dca = false //Controls if DCA should be used or not for this entry.
bool dca_use_limit = false //This order should be LIMIT based. By defualt it assumes market order entry.
int dca_num_positions = 5 //This keeps track of how many DCA positions are needed.
array<float> dca_positions = na //INTERAL USE ONLY -> This should be an array holding the number of DCA_Positions you want to calculate for. If this array is empty it assumes NO DCA for the order. Calculated from percentages string
float dca_deviation_percentage = 1.0 //This is how much each position should deviate from each other. Note that with dca_scale of 1.0 this will always be this number exactly everytime.
float dca_scale = 1.0 //This controls how the DCA will split from each other by this scale factor.
string dca_percentages = "" //This controls how much percentage of equity will be used at each DCA level.
bool dca_close_cancels = true //This will assume DCA orders cancel once a close occurs (even if it's 50%)
int dca_active_positions = 0 //INTERNAL USE ONLY -> Keeps track of how many active DCA positions there are for the entry. This applies ONLY to market mode DCA.
bool use_atr_deviation = false //Calculates if the DCA deviations should be calculated using ATR instead
int dca_atr_length = 14 //The length of the ATR to use for DCA ATR Deviations
float dca_atr_mult = 1.0 //The multiplier factor to use for DCA ATR Deviations
bool dca_atr_updates_dca_positions = false //This controls if the DCA positions should be constantly updated via the ATR
float close_price_at_order = 0.0 //INTERNAL USE ONLY -> This is used to calculate what the 'close' was at the initial order. This helps for updating ATR DCA in realtime
bool dca_use_deviation_atr_min = false //This will set a minimum deviatio percentage for use with the ATR for DCA
float[] dca_position_quantities = na //INTERNAL USE ONLY -> This keeps track of the quantities that would be purchased at each DCA Level. Useful only for LIMIT ORDERS NOT MARKET ORDERS!
bool use_dca_dynamic_percent_equity = false //Should this use dynamic percent equity for the DCA instead of the defined percent levels? This only works for MARKET MODE!
bool[] dca_in_use = na //INTERNAL USE ONLY -> This keeps track of which dca is currently in use. This works ideally for LIMIT ORDERS, (But for market orders it will store to this once it HAS been used)
bool[] dca_activated = na //INTERNAL USE ONLY -> This will track which DCA line has been activated. Used by the create function to actually create the limit or market order.
float[] dca_money_used = na //INTERNAL USE ONLY -> Used for debug purposes to track how much 'money' was used for that particular DCA from the budget available.
line[] dca_lines = na //INTERNAL USE ONLY -> This defines the line objects that hold the DCA representations.
color dca_color = color.white //The color of the DCA Lines. Useful to tell the difference between multiple DCA that may be active at the same time.
bool show_dca_lines = true //Should we draw DCA Lines?
float atr_value = na //This sets the ATR value used for ATR related features like DCA Entry positions
float atr_value_at_activation = na //INTERNAL USE ONLY -> This is the value of the ATR at activation ONLY. Only gets reset when a new order is placed for the entry.
bool use_cooldown_bars = false //Should this use the bar cooldown feature?
int cooldown_bars = 0 //This is how many bars must go by before it's allowd to trade again.
bool cooldown_bar_changed = false //INTERAL USE ONLY -> Keeps track of if the entries cooldown timeframe bar has changed.
int cooldown_bar_index = na //Keeps track of the bar_index in relation to the cooldown_bars_timeframe. MUST be set correctly in order to work.
int cooldown_bar_index_prior = na //Helps calculate the cooldown_bar_changed correctly based on cooldown_bars_timeframe. MUST be set correctly if you want to use this feature.
int cooldown_bar_change_count = 0 //INTERNAL USE ONLY -> This keeps track of how many cooldown bars have occured for cooldown bar checking.
//INTERNAL USE ONLY ALL BELOW -> This type does NOT use these variables, but it needed to be here to make a dynamic function work with entries,exits, filters and qualifiers
string expire_condition_activate_value = "0"
float expire_condition_source = na
float expire_condition_source_prior = na
float expire_compare_source = na
float expire_compare_source_prior = na
bool use_expire_compare_source = false
string expire_condition_operator = "="
//**
export type exit_position
bool disabled = true //Use this to manually disable this exit from being possible to activate.
string id //The ID to refer to this for exit condition
string group //The group to refer to this exit condition
string exit_for_entries = na //This is the entries this is an EXIT for. If "" or na is given this will assume ALL entries.
string exit_for_groups = na //This is the entry groups this is an EXIT for. If "" or na is given this will assume ALL groups.
int total_bars = 0//INTERNAL USE ONLY -> Tracks how mayn bars the exit has been running for.
string name = na //Overide the default name for the comments on exit
bool condition = true //This is the custom condition to determine the exit. If this is set to true it will (try to if other rules are good) immediately close the position according to the rules of the exit defined in this object.
bool dynamic_condition = false //INTERNAL USE ONLY -> This is the optional dynamic condition value that will be determined the exit based on the other settings.
bool use_dynamic_condition = false //Should the dynamic condition be used?
bool use_override_default_condition = false //Should the dynamic condition (if being used) override the hardcoded default condition that might be present?
string dynamic_condition_operator = "=" //What operator is being used for testing the dynamic_condition_value to see if it's true or not? Supports '=','>','<','≤','≥'
float dynamic_condition_source = na //This is the actual value from the dynamic source. This should be set when the entry is created and updated every bar.
float dynamic_compare_source = na //This is the actual value from the dynamic source. This is the variable used for comparing against the condition source, for cross over and cross under.
float dynamic_condition_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
float dynamic_compare_source_prior = na //INTERNAL USE ONLY -> Used for testing cross overs and unders
bool use_dynamic_compare_source = false //This controls if the dynamic compare source will be used for comparison purposes
string dynamic_condition_activate_value = "0" //This is what the condition value should be that will ultimatly create the 'true' or 'false' condition for allowing the entry to pass.
bool activate = false //INTERAL USE ONLY -> This signifies that it will be activated during the creation phase.
bool active = false //INTERNAL USE ONLY -> Is this truly active for the rest of the bar it's on.
bool reset_equity = false //INTERNAL USE ONLY -> This is a flag that if set will reset the equity because an exit occured. The price of the exit is not known until the OPEN of the next bar which can be different from the CLOSE, so we use this variable to tell the equity_remaining the proper amount of funds it has to work with.
bool use_limit = true //Assumes market if false (Note: close orders would set this to false)
bool use_alerts = true //Should this create alerts for creating/completing
bool reset_entry_cooldowns = true //Should this reset entry cooldowns when it closes completely?
bool prevent_new_entries_on_partial_close = true //This will consider a partial close an 'end to any new DCA or Pyramiding Entries'. This is useful if the exit settings do not close 100% of the equity.
// bool is_stop_loss = false
// bool is_take_profit = false
// bool is_trailing_stop_loss = false
// bool is_trailing_take_profit = false
// bool is_atr_stop_loss = false
// bool is_atr_take_profit = false
// bool is_close = false
//bool show_wait_time = true //Should this show visually on your charts to verify/understand the delay functionality.
//bool show_stop_zone = true //Should this show visually the STOP ZONE for TRAILING STOP LOSS & TRAILING TAKE PROFIT (once activated) on your charts to show where its located.
bool show_activation_zone = true //Shold this show the ACTIVATION_ZONE for TRAILING TAKE PROFIT visually on the chart.
bool use_average_position = true //This will use the strategy average price for determining stop loss and take profit locations & atr deviations.
float source_value = close //TODO: -> Add support for this, This should be some kind of source value, like CLOSE, HIGH, LOW, OPEN etc...
// float activation_percent_value //This should be the value the TRAILING TAKE PROFIT activates at.
// float percent_value //The percentage value the STOP LOSS or TAKE PROFIT should be.
int trigger_x_times = 1 //How many times should the close be allowed to trigger? If the close does not close 100% then it can hypothetically trigger over and over again. This will limit how many times it's allowed to do that.
int amount_of_times_triggered = 0 //INTERNAL USE -> Keeps track of how many times it has been triggered for reasons listed above on trigger_x_times.
float quantity_percent = 100 //The amount to exit with (should be a value between 0 and 100). Useful for positions where you want to close only half the position under certain circumstances.
float trade_qty = 0.0 //INTERNAL USE -> This is how much is calcualted to be the trade_qty at any given time for the exit.
float exit_amount = 0.0 //INTERNAL USE -> This is how much it will be exiting for equity tracking purposes.
entry_position[] entries_exiting_for = na
float atr_value = na //Keep track of the ATR Value for this exit if applicable.
bool update_atr = false //Should the ATR update with every bar?
bool use_activate_after_bars = false //This controls if the exit should be delayed before its created.
bool show_activate_after_bars = false //This controls whether a label will show to signify the countdown before the close activates. Used mostly to just verify it's working.
int activate_after_bars = na //This is how many bars should go by before the exit starts to activate (this includes creating the limit orders)
bool activate_after_bars_bar_changed = false //INTERAL USE ONLY -> Keeps track of if the exits timeframe bar has changed.
int activate_after_bars_bar_index = na //Keeps track of the bar_index in relation to the exits timeframe. MUST be set correctly in order to work.
int activate_after_bars_bar_index_prior = na //Helps calculate the exit bars correctly based on exit bars timeframe. MUST be set correctly if you want to use this feature.
int activate_after_bars_bar_change_count = 0 //INTERNAL USE ONLY -> This keeps track of how many exit activate_after_bars_bar_changed have occured for exit bar checking.
bool all_conditions_pass = false //INTERNAL USE ONLY -> This keeps track of the exit conditions have all passed with the EXCEPTION, of the primary exit_value meeting it's condition. This is so stop loss and take profit types exits will still be visible in plots.
bool use_close_if_profit_only = false
float profit_value = 0.0 //What profit should it be in to allow to close? Only applied if close_if_profit_only is true.
string exit_type = "Close" //This can be Close, Stop Loss or Take Profit
string exit_modifier = "None" //This can be None, Trailing or ATR
bool update_atr_with_new_pyramid = false //This will update the ATR to use for calculations based on the most_recent_entry instead of the original entry that started the pyramid chain.
float percentage = 5.0 //If trailing stop loss or take profit is set this will be the trailing percentage, otherwise this defaults to regular percentage like for a typical stop loss or take profit.
float activation_percentage = 5.0 //If trailing take profit is used this is the level that the stop loss would activate at. Thus ensuring at least 'that' much profit before trailing.
float atr_multiplier = 2.0 //If ATR take profit or stop loss is set this is the multiplier used for those positions.
bool use_cancel_if_percent = false //Should this cancel if a certain percentage for the exit would have been calculated?
float cancel_if_percent = 1.0 //The percent it should cancel the entry if the stop loss or take profit would be this value.
float activation_value = na //INTERNAL USE ONLY -> This keeps track of the activation level for trailing take profits.
bool activation_value_crossed = false //INTERNAL USE ONLY -> This keeps track of if the activation_value_crossed. This would allow a trailing take profit for example to start working.
float exit_value = na //INTERNAL USE ONLY -> This stores what the Stop Loss Value or Take Profit Value or ATR Stop Loss/Take Profit Value will be.
float hypo_long_exit_value = na //INTERNAL USE ONLY -> This calcualtes a hypothetical exit value long that is never meant to be displayed but used for deciding if an entry should be canceled or not.
float hypo_short_exit_value = na //INTERNAL USE ONLY -> Calcualtes short version of the above for same reason. We have to calcualte both since we don't know what type the exit is.
float close_exit_value = na //INTERNAL USE ONLY -> This is used by trailing stop loss to keep track of the close exit position. This is needed to account for the average position size effecting the true exit_value.
float debug = 0.0 //INTERNAL USE ONLY -> For checking debug values
//INTERNAL USE ONLY ALL BELOW -> This type does NOT use these variables, but it needed to be here to make a dynamic function work with entries,exits, filters and qualifiers
string expire_condition_activate_value = "0"
float expire_condition_source = na
float expire_condition_source_prior = na
float expire_compare_source = na
float expire_compare_source_prior = na
bool use_expire_compare_source = false
string expire_condition_operator = "="
//**
export type equity_management
float equity = 0 //This keeps track of how much equity is remaining for taking pyramiding positions (and how much to use for orders in general). Think of this like the 'big picture' equity management variable. Works better than the default strategy.equity since we need to know equity available to use as the orders are happening.
float prior_equity = 0 //INTERNAL USE ONLY -> Keeps track of what the equity was the prior bar in case we need to backtrack due to flip position & DCA
float position_used = 0 //INTERNAL USE ONLY -> This is how much of the position is currently being used. This is used to prevent exiting orders from duplicating more then it should (or exiting with position that was not there)
float prior_position_used = 0 //INTERNAL USE ONLY -> Keep track of the prior position used in case we need to backtrack due to situations like DCA on a flip position.
bool prevent_future_entries = false //INTERNAL USE ONLY -> This is used when an exit has a partial close and the prevent OFC option is checked. It will prevent any future entries from triggering including DCA.
float minimum_order_size = 5 //Set this to stop orders that are too small from occuring and messing up the backtests & visuals.
int decimal_rounding_precision = 0 // *IMPORTANT* This is critical to set correctly! Set this to adjust the decimal rounding precision for different tickers accordingly.
string direction = na //INTERNAL USE ONLY -> This keeps track of if the current position is SHORT or LONG direction. Useful for allowing entries to activate for pyramiding or not.
bool show_order_info_in_comments = true
bool show_order_info_in_labels = false
bool allow_longs = true //Master setting to turn off all long entries
bool allow_shorts = true //Master setting to turn off all shorts entries
bool override_occured = false //Will be true if an override occured.
bool flip_occured = false //Keep track if a flip has occured during this bar which will trigger an override on the next bar.
int num_concurrent_wins = 0 //This is for martingale tracking
int num_concurrent_losses = 0 //This is also for martingale tracking
entry_position first_entry = na //This will be the first recorded entry after a close, only gets set once, and reset on a close. Useful for getting information about the initial entry that started the possible pyramid chain.
int num_win_trades = 0 //How many trades so far are winners
int num_losing_trades = 0 //How many trades so far are losers.
//**
//FUNCTIONS
// @function This creates a deep copy instead of a shallow copy of an entry_position. This does NOT deep copy the self_pyramiding_positions array reference, since only the master entry_position needs this to track the rest of its copies for efficiency reasons. This is to prevent a feedback loop.
// @param entry_position position, IS REQUIRED.
// @returns entry_position
export method deepCopy(entry_position this) =>
array<line> dca_lines = array.new_line()
array<bool> dca_in_use = array.new_bool()
array<bool> dca_activated = array.new_bool()
array<float> dca_position_quantities = array.new_float()
array<float> dca_money_used = array.new_float()
array<float> dca_positions = array.new_float()
if(na(this.dca_lines)==false)
for[index,value] in this.dca_lines
temp_dca_line = array.get(this.dca_lines,index)
dca_lines.push(line.copy(temp_dca_line))
if(na(this.dca_in_use)==false)
for[index,value] in this.dca_in_use
temp_dca_in_use = array.get(this.dca_in_use,index)
dca_in_use.push(temp_dca_in_use)
if(na(this.dca_activated)==false)
for[index,value] in this.dca_activated
temp_dca_activated = array.get(this.dca_activated,index)
dca_activated.push(temp_dca_activated)
if(na(this.dca_position_quantities)==false)
for[index,value] in this.dca_position_quantities
temp_dca_position_quantities = array.get(this.dca_position_quantities,index)
dca_position_quantities.push(temp_dca_position_quantities)
if(na(this.dca_money_used)==false)
for[index,value] in this.dca_money_used
temp_dca_money_used = array.get(this.dca_money_used,index)
dca_money_used.push(temp_dca_money_used)
if(na(this.dca_positions)==false)
for[index,value] in this.dca_positions
temp_dca_positions = array.get(this.dca_positions,index)
dca_positions.push(temp_dca_positions)
//float[] dca_position_quantities = na
//bool[] dca_in_use = na
//bool[] dca_activated = na
//line[] dca_lines = na
entry_position.new(
disabled =this.disabled,
activate =this.activate,
active =this.active,
initial_activation_price =this.initial_activation_price,
dca_done =this.dca_done,
condition =this.condition,
dynamic_condition =this.dynamic_condition,
use_dynamic_condition =this.use_dynamic_condition,
use_override_default_condition =this.use_override_default_condition,
dynamic_condition_operator =this.dynamic_condition_operator,
dynamic_condition_source =this.dynamic_condition_source,
dynamic_condition_activate_value =this.dynamic_condition_activate_value,
use_cash =this.use_cash,
use_percent_equity =this.use_percent_equity,
percent_equity_amount =this.percent_equity_amount,
cash_amount =this.cash_amount,
position_size =this.position_size,
total_position_size =this.total_position_size,
prior_total_position_size =this.prior_total_position_size,
equity_remaining =this.equity_remaining,
prior_equity_remaining =this.prior_equity_remaining,
initial_equity =this.initial_equity,
//activation_price =this.activation_price,
use_dynamic_percent_equity =this.use_dynamic_percent_equity,
dynamic_percent_equity_amount =this.dynamic_percent_equity_amount,
initial_dynamic_percent_equity_amount =this.initial_dynamic_percent_equity_amount,
dynamic_percent_equity_source =this.dynamic_percent_equity_source,
dynamic_percent_equity_min =this.dynamic_percent_equity_min,
dynamic_percent_equity_max =this.dynamic_percent_equity_max,
dynamic_percent_equity_source_sell_range =this.dynamic_percent_equity_source_sell_range,
dynamic_percent_equity_source_buy_range =this.dynamic_percent_equity_source_buy_range,
total_bars =this.total_bars,
bar_index_at_activate =this.bar_index_at_activate,
bars_since_active =this.bars_since_active,
bar_index_at_activated =this.bar_index_at_activated,
name =this.name,
id =this.id,
group =this.group,
pyramiding_limit =this.pyramiding_limit,
self_pyramiding_limit =this.self_pyramiding_limit,
//self_pyramiding_positions IS NOT DEEP COPIED!
new_pyramid_cancels_dca =this.new_pyramid_cancels_dca,
num_active_long_positions =this.num_active_long_positions,
num_active_short_positions =this.num_active_short_positions,
num_active_positions =this.num_active_positions,
position_remaining =this.position_remaining,
prior_position_remaining =this.prior_position_remaining,
direction =this.direction,
allow_flip_position =this.allow_flip_position,
flip_occurred =this.flip_occurred,
ignore_flip =this.ignore_flip,
use_dca =this.use_dca,
dca_use_limit =this.dca_use_limit,
dca_num_positions =this.dca_num_positions,
dca_positions =dca_positions, //dca_positions we need to deep copy still to prevent NA errors when dca is off
dca_deviation_percentage =this.dca_deviation_percentage,
dca_scale =this.dca_scale,
dca_percentages =this.dca_percentages,
dca_close_cancels =this.dca_close_cancels,
dca_active_positions =this.dca_active_positions,
use_atr_deviation =this.use_atr_deviation,
dca_atr_length =this.dca_atr_length,
dca_atr_mult =this.dca_atr_mult,
dca_atr_updates_dca_positions =this.dca_atr_updates_dca_positions,
close_price_at_order =this.close_price_at_order,
dca_use_deviation_atr_min =this.dca_use_deviation_atr_min,
dca_position_quantities =dca_position_quantities, //dca_position_quantities deep copy required here since the array is an object.
use_dca_dynamic_percent_equity =this.use_dca_dynamic_percent_equity,
dca_in_use =dca_in_use, //dca_in_use deep copy required here since the array is an object
dca_activated =dca_activated, //deep copy required
dca_money_used =dca_money_used, //deep copy required
dca_lines =dca_lines, //dca_lines deep copy required here since object
dca_color =color.new(this.dca_color,color.t(this.dca_color)),
atr_value =this.atr_value,
use_cooldown_bars =this.use_cooldown_bars,
cooldown_bars =this.cooldown_bars,
cooldown_bar_changed =this.cooldown_bar_changed,
cooldown_bar_index =this.cooldown_bar_index,
cooldown_bar_index_prior =this.cooldown_bar_index_prior,
cooldown_bar_change_count =this.cooldown_bar_change_count,
atr_value_at_activation =this.atr_value_at_activation
)
//**
// @function Convert a floating point number to a precise floating point number with digit precision to avoid floating point errors in quantity calculations.
// @param float number, int precision value
// @returns float
export method precision_fix(float this,int precision)=>
formatString = "#."
for i = 1 to precision
formatString := formatString + "#"
str.tonumber(str.tostring(this,formatString))
//**
// @function Creates an interpolation for a sell range and buy range but with an emphasis on reaching the _low the closer to the middle of the _sell and _buy range you go.
// @param _x is the value you want to use to control interpolation bewteen the _high and _low value. This will return the lowest percentage at the mid between high and low and highest percentage at the _high and _low.
// @returns an interpolated float between the _high and _low supplied.
export xSellBuyMidInterpolation(float _x, float _high, float _low, float _sellRange, float _buyRange) =>
_midRange = (_sellRange + _buyRange) / 2
_x >= _sellRange ? _high : _x <= _buyRange ? _high : _low + (math.abs(_x - _midRange) * (_high - _low)) / (_midRange - _buyRange)
//**
// @function Creates an interpolation a sell range and buy range
// @param _x is the value you want to use to control interpolation bewteen the _high and _low value.
// @returns an interpolated float between the _high and _low supplied.
export xSellBuyInterpolation(float _x, float _high, float _low, float _sellRange, float _buyRange) =>
x = _x
x := _x > _sellRange ? _sellRange : x
// if(_x > _sellRange)
// x := _sellRange
x := _x < _buyRange ? _buyRange : x
// if(_x < _buyRange)
// x := _buyRange
_sellRatio = _sellRange / 100
_buyRatio = _buyRange / 100
_range = _high - _low
_interpolatedValue = _low + (x - _sellRange) / (_buyRange - _sellRange) * _range
_interpolatedValue
//**
//This function is used internally and does not need to be exported.
// @function Qualifies if the dynamic condition will pass or not
// @param _fqeoe MUST be an filter,qualifier, entry_position or exit_position.
// @returns true or false if the qualifying condition passed the checks required
qualifyCondition(_fqeoe,bool expire=false)=>
qualifyingConditionPassed = false
dynamic_condition_activation_values = expire ? str.split(_fqeoe.expire_condition_activate_value,",") : str.split(_fqeoe.dynamic_condition_activate_value,",")
condition_source = expire ? _fqeoe.expire_condition_source : _fqeoe.dynamic_condition_source
condition_source_prior = expire ? _fqeoe.expire_condition_source_prior : _fqeoe.dynamic_condition_source_prior
compare_source = expire ? _fqeoe.expire_compare_source : _fqeoe.dynamic_compare_source
compare_source_prior = expire ? _fqeoe.expire_compare_source_prior : _fqeoe.dynamic_compare_source_prior
use_compare_source = expire ? _fqeoe.use_expire_compare_source : _fqeoe.use_dynamic_compare_source
condition_operator = expire ? _fqeoe.expire_condition_operator : _fqeoe.dynamic_condition_operator
if(use_compare_source==false)
for[index,value] in dynamic_condition_activation_values
bool passed_filter_condition = switch condition_operator
"=" => condition_source == str.tonumber(value)
">" => condition_source > str.tonumber(value)
"<" => condition_source < str.tonumber(value)
"≤" => condition_source <= str.tonumber(value)
"≥" => condition_source >= str.tonumber(value)
'≠' => condition_source != str.tonumber(value)
'≠ NA' => na(condition_source)==false
'†>' => ((condition_source > str.tonumber(value)) and (condition_source <= str.tonumber(value))[1])
'†<' => ((condition_source < str.tonumber(value)) and (condition_source >= str.tonumber(value))[1])
// Default
=> false
qualifyingConditionPassed := passed_filter_condition //meaning it did match so this should not be allowed to pass.
if(qualifyingConditionPassed)
break
else
bool passed_filter_condition = switch condition_operator
"=" => condition_source == compare_source
">" => condition_source > compare_source
"<" => condition_source < compare_source
"≤" => condition_source <= compare_source
"≥" => condition_source >= compare_source
'≠' => condition_source != compare_source
'≠ NA' => na(condition_source)==false and na(compare_source)==false
'†>' => ((condition_source > compare_source) and (condition_source_prior <= compare_source_prior))
'†<' => ((condition_source < compare_source) and (condition_source_prior >= compare_source_prior))
// Default
=> false
qualifyingConditionPassed := passed_filter_condition //meaning it did match so this should not be allowed to pass.
qualifyingConditionPassed
//**
//This function is used internally for a list of qualifiers to see if it should be true/false for activation of the entry or exit in question. _eoe stands for 'entry or exit' since this all this function can take.
// @function Will check if the qualifier should activate or deactivate the entry or exit. It does a multitude of checks including making sure the ID's and Groups match.
// @param _eoe MUST be an entry_position or exit_position. _qualifiers should be the array of qualifiers that need to be checked against the _eoe
// @returns true or false if the qualifier should allow the entry or exit to proceed with activation. Should be used with array.set(... true) etc...
validateQualifier(_eoe,_qualifiers)=>
pass = false
if(array.size(_qualifiers)>0)
for [q_index, q_qualifier] in _qualifiers
qualifier_pass = false
was_id_group_match = false
//Does the ID Match?
qualified_eoe = str.split(q_qualifier.qualify_for_entries_or_exits,",") //Get list of what ids for entries or exits this is filtering for
if(na(qualified_eoe)==false)
if(array.size(qualified_eoe)>0)
if(array.includes(qualified_eoe,_eoe.id))
was_id_group_match := true
//Does the GROUP Match?
qualified_eoe_groups = str.split(q_qualifier.qualify_for_groups,",") //Get list of what ids for entries or exits this is filtering for
if(na(qualified_eoe_groups)==false)
if(array.size(qualified_eoe_groups)>0)
if(array.includes(qualified_eoe_groups,_eoe.group))
was_id_group_match := true
if(was_id_group_match) //If it was a match check if met the qualification condition.
qualifier_pass := qualifyCondition(q_qualifier)==true ? true : qualifier_pass
qualifier_pass := (q_qualifier.condition and q_qualifier.use_override_default_condition==false) ? true : qualifier_pass
if(qualifier_pass)
if(q_qualifier.disqualify==false)
pass := true //Might as well for this bar set this to true here.
else
pass := false//Then might as well false it right away for now since this is a disqualify condition
q_qualifier.active := true
q_qualifier.expire_bar_count := 0
else //This is the situation where we need to check if it's still in a viable expire time
//Determine if this is still active at this point
//Does this use an expire bar length?
if(q_qualifier.use_expire_after_x_bars)
if(q_qualifier.expire_bar_count >= q_qualifier.expire_after_x_bars)
q_qualifier.active := false
//Does this use an expire condition?
if(q_qualifier.use_expire_condition)
if(qualifyCondition(q_qualifier,true)==true) //Using expire mode check to see if we need to kill the qualifier.
q_qualifier.active := false
if(q_qualifier.active)
if(q_qualifier.disqualify==false)
pass := true
else
pass := false
else
if(q_qualifier.disqualify==false)
pass := false
else
pass := true
q_qualifier.expire_bar_count := 0
break //It only takes 1 to not be active to kill the need to check the rest.
else
pass := true //Just let it pass then since it can't be qualifying it anyways
else
pass := true //There was no qualifiers so it has to be TRUE
pass//Return the state of the pass variable. This will be used in setting the array position true/false for the entry or exit
//**
//This function is used internally for a list of filters to see if it should be true/false for activation of the entry or exit in question. _eoe stands for 'entry or exit' since this all this function can take.
// @function Will check if the filter should activate or deactivate the entry or exit. It does a multitude of checks including making sure the ID's and Groups match.
// @param _eoe MUST be an entry_position or exit_position. _filters should be the array of filters that need to be checked against the _eoe
// @returns true or false if the qualifier should allow the entry or exit to proceed with activation. Should be used with array.set(... true) etc...
validateFilter(_eoe,_filters)=>
pass = true
if(array.size(_filters)>0)
for [f_index, f_filter] in _filters
was_id_group_match = false
if(f_filter.disabled==false)
//Does the ID Match?
filter_entries = str.split(f_filter.filter_for_entries_or_exits,",") //Get list of what ids for entries or exits this is filtering for
if(na(filter_entries)==false)
if(array.size(filter_entries)>0)
if(array.includes(filter_entries,_eoe.id))
was_id_group_match := true
//Does the GROUP Match?
filter_entry_groups = str.split(f_filter.filter_for_groups,",") //Get list of what ids for entries or exits this is filtering for
if(na(filter_entry_groups)==false)
if(array.size(filter_entry_groups)>0)
if(array.includes(filter_entry_groups,_eoe.group))
was_id_group_match := true
if(was_id_group_match)
if(qualifyCondition(f_filter)==true)
pass := false //This will essentially not allow filter_pass to be true, therefore not allowing the entry.
break //End the loop early so it can't be true again. Something already failed.
pass
//**
// @function Determines activation for entries or exits. Does not place the actual orders.
// @param entry_position and exit_position and filter and qualifier array to use alng with equity_management
// @returns void
export activate_entries_and_exits(array<entry_position> _entries, array<exit_position> _exits,array<filter> _filters,array<qualifier> _qualifiers, equity_management _equity) =>
//Note: This can handle pyramiding if there is available equity. This will NOT work with the default pyramiding setting since DCA would interfere with this.
//Determine which entries are currently active and push them to an array of active entries and the others to an array of 'not active'
array<entry_position> active_entries = array.new<entry_position>()
array<exit_position> active_exits = array.new<exit_position>()
entry_position most_recent_entry = na //This will be the most recent pyramid entry
exit_position most_recent_exit = na
int num_long_active_entries = 0 //How many long entries are there (INCLUDING pyramiding!)
int num_short_active_entries = 0 //Same as ^ but short
//int total_active_entries = 0 //This is the total number of active entries (NOT counting pyramiding!)
bool overide_activate = false //This allows overiding activate. Useful for flipping position that has already been verified on a previous bar.
string[] cancel_ids_long = array.new_string() //Keep track of the ids that are supposed to be cancel.
string[] cancel_groups_long = array.new_string() //Keep track of the groups that are supposed to be canceled.
string[] cancel_ids_short = array.new_string() //Keep track of the ids that are supposed to be cancel.
string[] cancel_groups_short = array.new_string() //Keep track of the groups that are supposed to be canceled.
_equity.override_occured := false //Default this to false each bar.
_equity.flip_occured := false
_equity.prior_position_used := _equity.position_used //Store the past value before this gets manipulated in case we need the original to backtrack.
_equity.prior_equity := _equity.equity //Store the past equity value in case we need to backtrack to the original.
//Optimize the loops by removing anything that is disabled or empty ~ (NA) ~ so we don't bother looping through it on every bar.
if(bar_index==0)
entry_array_size = array.size(_entries)
for i = entry_array_size-1 to 0
entry = array.get(_entries,i)
if(na(entry))
array.remove(_entries,i)
else
if(entry.disabled)
array.remove(_entries,i)
exit_array_size = array.size(_exits)
for i = exit_array_size-1 to 0
exit = array.get(_exits,i)
if(na(exit))
array.remove(_exits,i)
else
if(exit.disabled)
array.remove(_exits,i)
//Causing nothing to happen
filter_array_size = array.size(_filters)
for i = filter_array_size-1 to 0
afilter = array.get(_filters,i)
if(na(afilter))
array.remove(_filters,i)
else
if(afilter.disabled)
array.remove(_filters,i)
qualifier_array_size = array.size(_qualifiers)
for i = qualifier_array_size-1 to 0
aqualifier = array.get(_qualifiers,i)
if(na(aqualifier))
array.remove(_qualifiers,i)
else
if(aqualifier.disabled)
array.remove(_qualifiers,i)
highest_total_bar_index = 0
//Determine which entries are already active and the most_recent_entry.
for [index, entry] in _entries
entry.total_bars := entry.total_bars + 1 //Running total of bars of the current time frame that has been running.
//If there is no position then there should be no self pyramiding positions either, therefore set this to NA
entry.self_pyramiding_positions := strategy.position_size==0 ? na : entry.self_pyramiding_positions
// if(strategy.position_size==0)
// //Reset all pyramiding arrays to na
// entry.self_pyramiding_positions := na
if(na(entry.self_pyramiding_positions)) //Initialize the self_pyramiding_positions if it has not been done already.
entry.self_pyramiding_positions := array.new<entry_position>() //Set the self pyramiding_positions initially to this particular entry in this situation.
//Cooldown tracking
entry.cooldown_bar_changed := entry.cooldown_bar_index != entry.cooldown_bar_index_prior //This signifies that the timeframe selected for cooldown has had a bar change. (for cooldown tracking)
entry.cooldown_bar_change_count := entry.cooldown_bar_changed ? entry.cooldown_bar_change_count + 1 : entry.cooldown_bar_change_count
// if(entry.cooldown_bar_changed)
// entry.cooldown_bar_change_count := entry.cooldown_bar_change_count + 1
//Active bars & entry tracking
if(entry.active)
entry.bars_since_active := entry.bars_since_active + 1 //Total bars that have gone by while the entry is considered active
//Cycle through the self pyramiding positions in case one of these is the most recent recent entry.
if(array.size(entry.self_pyramiding_positions)>0)//If this entry has known curreny pyramided positions, then we want to find the latest one.
for [p_index, p_entry] in entry.self_pyramiding_positions //Go through the pyramid positions 1 by 1, find the latest one.
if(p_entry.direction=="LONG")
num_long_active_entries := num_long_active_entries + 1
else
num_short_active_entries := num_short_active_entries + 1
if(p_entry.bar_index_at_activate > highest_total_bar_index) //The entry with the highest total bars so far is the most recent entry.
highest_total_bar_index := p_entry.bar_index_at_activate
most_recent_entry := p_entry
else
if(entry.bars_since_active > highest_total_bar_index) //The entry with the highest total bars so far is the most recent entry.
highest_total_bar_index := entry.bar_index_at_activate
most_recent_entry := entry
if(entry.direction=="LONG")
num_long_active_entries := num_long_active_entries + 1
else
num_short_active_entries := num_short_active_entries + 1
active_entries.push(entry) //Push the active entires into the array tracking them. Can use it to get running total of all active entries by using array length.
//**
//Determine which exits are currently *already* active and push them to an array of active exits. Also handles reseting equity based on exits that have fired previously
for [index, exit] in _exits
//Cooldown tracking
exit.activate_after_bars_bar_changed := exit.activate_after_bars_bar_index != exit.activate_after_bars_bar_index_prior //This signifies that the timeframe selected for cooldown has had a bar change. (for cooldown tracking)
if(exit.activate_after_bars_bar_changed)
exit.activate_after_bars_bar_change_count := exit.activate_after_bars_bar_change_count + 1
if(exit.show_activate_after_bars and array.size(active_entries)>0)
label_text = str.tostring(exit.activate_after_bars_bar_change_count,'#')
temp_label = label.new(bar_index,close,label_text,color=color.black,textcolor = color.white,yloc=yloc.abovebar)
//Cancel If Percent Check
if(exit.use_cancel_if_percent)
cancel_exit_long = false
cancel_exit_short = false
if(exit.exit_type=="Stop Loss")
exit.hypo_long_exit_value := (close - (exit.atr_value * exit.atr_multiplier))
exit.hypo_short_exit_value := (close + (exit.atr_value * exit.atr_multiplier))
if(exit.hypo_long_exit_value <= (close - (exit.cancel_if_percent * close)))
exit.debug := (close - (exit.cancel_if_percent * close))
cancel_exit_long := true
if(exit.hypo_short_exit_value >= (close + (exit.cancel_if_percent * close)))
cancel_exit_short := true
if(exit.exit_type=="Take Profit")
exit.hypo_long_exit_value := (close + (exit.atr_value * exit.atr_multiplier))
exit.hypo_short_exit_value := (close - (exit.atr_value * exit.atr_multiplier))
if(exit.hypo_long_exit_value >= (close + (exit.cancel_if_percent * close)))
cancel_exit_long := true
if(exit.hypo_short_exit_value <= (close - (exit.cancel_if_percent * close)))
cancel_exit_short := true
if(cancel_exit_long)
for [idx, id] in str.split(exit.exit_for_entries,",")
cancel_ids_long.push(id)
for [idx, group] in str.split(exit.exit_for_groups,",")
cancel_groups_long.push(group)
if(cancel_exit_short)
for [idx, id] in str.split(exit.exit_for_entries,",")
cancel_ids_short.push(id)
for [idx, group] in str.split(exit.exit_for_groups,",")
cancel_groups_short.push(group)
if(exit.reset_equity)
exit.reset_equity := false //This way it won't do this again on the next bar.
_equity.prevent_future_entries := (exit.prevent_new_entries_on_partial_close and strategy.position_size != 0) ? true : _equity.prevent_future_entries
// if(exit.prevent_new_entries_on_partial_close and strategy.position_size != 0) //If there is still position and we have a partial close this should prevent any future entries from occuring with this option enabled.
// _equity.prevent_future_entries := true
if(strategy.position_size==0)
_equity.position_used := 0 //Reset this to zero since the equity has been completely reset at this point
_equity.equity := strategy.initial_capital+strategy.netprofit //Only once we are sure everything is cleared out do we reset the equity to work with.
_equity.prevent_future_entries := false //So we can take trades again normally
_equity.direction := na //so that any entry can open again.
_equity.first_entry := na //after every close where there is no position left the first_entry needs to be cleared.
if(strategy.wintrades > _equity.num_win_trades)
_equity.num_concurrent_wins := _equity.num_concurrent_wins + 1
_equity.num_concurrent_losses := 0
else
_equity.num_concurrent_losses := _equity.num_concurrent_losses + 1
_equity.num_concurrent_wins := 0
_equity.num_win_trades := strategy.wintrades
_equity.num_losing_trades := strategy.losstrades
for [index2, exit2] in _exits //Loop through every exit to ensure NA values are reset
exit2.exit_amount := 0 //To reset this, but only if position size is 0 because this information about the exit amount so far is handy for calculation purposes.
exit2.close_exit_value := na //This is needed to reset trailing stop loss tracker
exit2.exit_value := na //this resets the known exit_value used for trialing stop loss tracker as well
exit2.activation_value := na //this resets the value used in case trailing take profit is used.
exit2.activation_value_crossed := false //reset this so we don't think it crossed anymore
exit2.amount_of_times_triggered := 0 //reset to 0 so it can actually exit this amount of times again.
//If the option to reset entry coodowns is ON, then we should reset cooldowns for every entry if the position_size is truly 0.
for [a_index, entry] in _entries
if(strategy.position_size==0) //If the entry is truly closed out then officially make it active := false
entry.active := false
entry.bars_since_active := 0
entry.total_position_size := 0
entry.position_size := 0
entry.bar_index_at_pyramid_change := na
entry.dca_positions := na
entry.cooldown_bar_change_count := exit.reset_entry_cooldowns ? 0 : entry.cooldown_bar_change_count
// if(exit.reset_entry_cooldowns)
// entry.cooldown_bar_change_count := 0 //Reset this again in this case also if option enabled.
//**
//Qualifiers Prerequisites
for [index, q_qualifier] in _qualifiers
q_qualifier.expire_bar_changed := q_qualifier.expire_after_bars_bar_index != q_qualifier.expire_after_bars_bar_index_prior //This signifies that the timeframe selected for cooldown has had a bar change. (for cooldown tracking)
q_qualifier.expire_bar_count := q_qualifier.expire_bar_changed ? q_qualifier.expire_bar_count + 1 : q_qualifier.expire_bar_count
// if(q_qualifier.expire_bar_changed)
// q_qualifier.expire_bar_count := q_qualifier.expire_bar_count + 1
//**
//Activate entries
for [index, entry] in _entries //TODO -> This should be the non-active entries array to see if we want to make it active this time around.
entry.override_occured := false //default to false for each entry
entry.num_active_long_positions := num_long_active_entries
entry.num_active_short_positions := num_short_active_entries
entry.num_active_positions := array.size(active_entries)
pass = array.new_bool(15,false) //This is how many pass requirements are needed for the entry to activate succesfully.
if(entry.condition)
array.set(pass,0,true)
else
if(entry.use_override_default_condition and entry.use_dynamic_condition) //In this situation we want to ignore what we have hardcoded and only use the dynamic source for entry control logic.
array.set(pass,0,true)
if(entry.use_cooldown_bars)
if(entry.cooldown_bar_change_count >= entry.cooldown_bars)
array.set(pass,1,true)
else
array.set(pass,1,false)
else
array.set(pass,1,true)
//Do we have any capital available to even do this entry?
if((strategy.initial_capital + strategy.netprofit) > 0)
array.set(pass,2,true)
else
array.set(pass,2,false)
//Does the internal tracker say we have enough money to do this trade?
//This is useful because if more than one entry would 'activate' at the same time (bar) this value will lower with whichever would have activated first not allowing the other to trigger if there would not be enough equity.
if(_equity.equity > 0)
array.set(pass,3,true)
else
if(strategy.position_size>0 and entry.direction=="LONG" or strategy.position_size<0 and entry.direction=="SHORT")
array.set(pass,3,false)
else
array.set(pass,3,true) //If there is no equity, BUT this was an entry for a different direction, this can still be true because FLIP Position will clear the position and give equity later.
//Check if we hit self pyramiding limit for this entry.
if(array.size(entry.self_pyramiding_positions) >= entry.self_pyramiding_limit)
array.set(pass,4,false)
else
array.set(pass,4,true)
//Check if we hit the regular pyramiding limit for all entries. Direction check is IMPORTANT
if((num_long_active_entries >= entry.pyramiding_limit and entry.direction=="LONG") or (num_short_active_entries >= entry.pyramiding_limit and entry.direction=="SHORT"))
array.set(pass,5,false)
else
array.set(pass,5,true)
if(_equity.prevent_future_entries)
array.set(pass,6,false)
else
array.set(pass,6,true)
if(_equity.equity < _equity.minimum_order_size)
if(strategy.position_size>0 and entry.direction=="LONG" or strategy.position_size<0 and entry.direction=="SHORT")
array.set(pass,7,false)
else
array.set(pass,7,true) //Allow this because equity doesn't matter when flipping position at this time.
else
array.set(pass,7,true)
//Pyramid Direction Check. For example, if it's going long already, it can't pyramid short and vice versa.
possible_flip_occured = false
if(entry.flip_occurred)
entry.flip_occurred := false //This is the bar after the flip activated then, lets turn this off.
_equity.position_used := 0 //Reset this to zero since the equity has been completely reset at this point
_equity.equity := strategy.initial_capital+strategy.netprofit //Only once we are sure everything is cleared out do we reset the equity to work with.
entry.bars_since_active := 0 //Reset so cooldowns come into affect.
entry.dca_positions := na //Clear out any DCA that may be present
most_recent_entry.active := false //Set the previous entries active to false since it's no longer 'active' and has been flipped (therefore all positions taken care of)
overide_activate := true //This will allow the order to go through even though it's a different entry and may not meet other conditions at this time.
_equity.override_occured := true //Default this to false each bar.
entry.override_occured := true
else
if(na(_equity.direction))
array.set(pass,8,true)
else
if(_equity.direction == entry.direction)
array.set(pass,8,true)
else
if(na(most_recent_entry)==false) //No else neccesary, because the default will be FALSE
if(most_recent_entry.ignore_flip) //The prior entry does not allow flips so DO NOT ALLOW activation!
array.set(pass,8,false)
else
if(entry.allow_flip_position)//Then, does this entry allow the flip?
array.set(pass,8,true)
possible_flip_occured := true //This signifies that it's possible given all the other conditions were true that a flip occured. This will be used to do offset calculations for position to close out existing longs later.
else
array.set(pass,8,false)
//**
//Dynamic Condition Check
if(entry.use_dynamic_condition)
//Check if the source meets the dynamic condition
if(qualifyCondition(entry)==true)
array.set(pass,9,true)
else
array.set(pass,9,true)
//Check if any filters apply to this entry.
array.set(pass,10,validateFilter(entry,_filters))
//Check if any qualifiers apply to this entry.
array.set(pass,11,validateQualifier(entry,_qualifiers))
//Check if allow long or allow short is present.
if(_equity.allow_longs and entry.direction=="LONG" or _equity.allow_shorts and entry.direction=="SHORT")
array.set(pass,12,true)
//Check if the entries ID is in the cancel list
cancel_entry = false
cancel_entry := entry.direction=="LONG" and array.includes(cancel_ids_long,entry.id) ? true : (array.includes(cancel_ids_short,entry.id)) ? true : cancel_entry
// if(entry.direction=="LONG")
// if(array.includes(cancel_ids_long,entry.id))
// cancel_entry := true
// else
// if(array.includes(cancel_ids_short,entry.id))
// cancel_entry := true
cancel_entry := entry.direction=="LONG" and array.includes(cancel_groups_long,entry.group) ? true : (array.includes(cancel_groups_short,entry.group)) ? true : cancel_entry
// if(entry.direction=="LONG")
// if(array.includes(cancel_groups_long,entry.group))
// cancel_entry := true
// else
// if(array.includes(cancel_groups_short,entry.group))
// cancel_entry := true
if(cancel_entry==false)
array.set(pass,13,true)
//Debug Condition (That forces the engine to wait for a ceratin bar so we don't have to scroll to the left everytime to check problems). Uncomment this if Debugging.
//if(bar_index >= 20942)
//array.set(pass,13,true)
array.set(pass,14,true) //<-- Comment this when done debugging so the pass is TRUE
//Debug Pass Variables (uncomment to print label with debug information. You can wrap an IF condition on bar_index to have it print for only certain bar ranges)
// if(bar_index >= 22100)
// entry.passDebug := pass
// string label_text = ""
// for [pass_index, pass_value] in entry.passDebug
// label_text := label_text + (pass_value ? "1\n" : "0\n")
// temp_label = label.new(bar_index,close,label_text,color=entry.direction=="LONG" ? color.rgb(21, 70, 31) : color.rgb(70, 23, 31),textcolor = color.white,yloc=entry.direction=="SHORT" ? yloc.abovebar : yloc.belowbar)
//DCA Check. Which DCA lines would activate if applicable? Take note of the minimum order size allowed when considering if it could activate or not.
if(_equity.equity >= _equity.minimum_order_size) //Only bother with further calculations if the equity is greater than or equal to the minimum order size
//Preserve the entry.total_position_size before we change it just in case of DCA Activations on a flip position. NOTE: This is on entry NOT p_entry, since entry needs to track the entire combined position for exiting later.
entry.prior_total_position_size := entry.total_position_size
//Loop through this entries pyramids, see if the close meets the conditions to activate and if the DCA has not already been activated then activate it.
for[a_index,p_entry] in entry.self_pyramiding_positions //Go through the entries pyramid positions
if(entry.use_dca)
if(_equity.flip_occured==false and _equity.override_occured==false) //A flip or override can not occur during activation of DCA
//This MUST happen here, because inside the dca_loop these values could change.
p_entry.prior_equity_remaining := p_entry.equity_remaining //Whatever this was prior, store this before we change it through the DCA loop.
p_entry.prior_position_remaining := p_entry.position_remaining //Whatever this was prior, store this before we change it through the DCA loop.
for i = 0 to entry.dca_num_positions - 1
if(na(p_entry.dca_positions)==false) //If there actually is a DCA position array for the pyramid (meaning it has not canceled itself yet from a new pyramid possibly)
if(array.size(p_entry.dca_positions) > 0) //Does the array actually have something in it?
if((entry.direction=="LONG" and close <= array.get(p_entry.dca_positions,i)) or (entry.direction=="SHORT" and close >= array.get(p_entry.dca_positions,i))) //Did the price cross a DCA Level?
if(array.size(p_entry.dca_in_use) > 0 ) //This can get destroyed upon new pyramids, therefore check to see if greater than 0
if(array.get(p_entry.dca_in_use,i)==false)
dca_percentage_levels_array = str.split(entry.dca_percentages,"\n") //Calculate the array of the DCA percentage levels desired.
float money_used = 0.0
if(entry.use_dca_dynamic_percent_equity==false)
money_used := _equity.equity * (str.tonumber(array.get(dca_percentage_levels_array,i))*0.01)
else
if(entry.dynamic_equity_interpolation_method=="Linear From Mid")
p_entry.initial_dynamic_percent_equity_amount := xSellBuyMidInterpolation(entry.dynamic_percent_equity_source,entry.dynamic_percent_equity_max,entry.dynamic_percent_equity_min,entry.dynamic_percent_equity_source_sell_range,entry.dynamic_percent_equity_source_buy_range)*0.01
if(entry.dynamic_equity_interpolation_method=="Linear")
p_entry.initial_dynamic_percent_equity_amount := xSellBuyInterpolation(entry.dynamic_percent_equity_source,entry.dynamic_percent_equity_max,entry.dynamic_percent_equity_min,entry.dynamic_percent_equity_source_sell_range,entry.dynamic_percent_equity_source_buy_range)*0.01
money_used := _equity.equity * (p_entry.initial_dynamic_percent_equity_amount)
if(money_used >= _equity.minimum_order_size)
float purchase_qty = money_used / close
purchase_qty := math.round(purchase_qty,_equity.decimal_rounding_precision)//round to be safe first to the precision
p_entry.equity_remaining := _equity.equity - money_used //** Accounted for Reversal
p_entry.position_remaining := p_entry.position_remaining + purchase_qty //** Accounted for Reversal
_equity.equity := _equity.equity - money_used //** Accounted for Reversal
entry.total_position_size := entry.total_position_size + purchase_qty //** Accounted for Reversal
_equity.position_used := _equity.position_used + purchase_qty //Adjust the internal tracker for position used ** Accounted for Reversal
array.set(p_entry.dca_position_quantities,i,purchase_qty) //Store what position is supposed to be purchased as this position. In case of reversal, this does not matter to store prior value.
array.set(p_entry.dca_in_use,i,true) //Set it to in_use then. For reversal this simply gets set to false since NO DCA should be allowed to be in use.
array.set(p_entry.dca_activated,i,true) //Set it to TRUE for activated. For reversal this simply gets set to false since NO DCA should be allowed to be activated.
array.set(p_entry.dca_money_used,i,money_used) //Set to the money used at this DCA level for reference later. In case of reversal, this does not matter to store prior value.
else
array.set(p_entry.dca_activated,i,false) //Set it to FALSE otherwise since the DCA is already in use and therefore not activated. Activation can only happen ONCE!
else
array.set(p_entry.dca_in_use,i,false) //If there is no DCA position, then this should be reset to false.
array.set(p_entry.dca_activated,i,false) //If there is no DCA position, this should be reset to false.
array.set(p_entry.dca_position_quantities,i,0.0) //Reset it since there is no quantity anymore.
array.set(p_entry.dca_money_used,i,0.0) //Reset it since there is no money_used potential anymore.
//**
if(array.includes(pass,false) and overide_activate == false) //If the array contains even 1 false then...
entry.activate := false
if(entry.use_dca and entry.flip_occurred == false) //If using DCA update existing lines to reflect activity so far. This does not create new lines, just updates it.
if(na(entry.dca_positions)==false)
if(entry.dca_atr_updates_dca_positions)//If we are using the option that updates the DCA positions every bar, then we do that here.
atr_dca_value = close + (1*entry.atr_value*entry.dca_atr_mult)*(entry.direction=="LONG" ? -1 : 1)
deviation_change = math.abs(1 - (atr_dca_value/close))//This will calculate the percentage change this would be.
if(entry.dca_use_deviation_atr_min)
if(deviation_change < entry.dca_deviation_percentage) //This will force it to always be the minimum percentage.
deviation_change := entry.dca_deviation_percentage
for i = 0 to (array.size(most_recent_entry.dca_positions) == 0 ? na : most_recent_entry.dca_num_positions - 1)
dca_value = close //just to set a default
if(i==0)
//dca_value := close + (1*entry.atr_value*entry.dca_atr_mult)*(entry.direction=="LONG" ? -1 : 1) //This calculates it for what it would be one position down.
dca_value := close + ((deviation_change * close)*(entry.direction=="LONG" ? -1 : 1))
if(i!=0)
deviation_change := deviation_change * entry.dca_scale
dca_value := array.get(most_recent_entry.dca_positions,i-1) + (((deviation_change)*array.get(most_recent_entry.dca_positions,i-1))*(entry.direction=="LONG" ? -1 : 1))
array.set(most_recent_entry.dca_positions,i,dca_value)//change the most recent entry (which will be a pyramid)
if(na(entry.dca_lines)==false and na(entry.dca_positions)==false and entry.show_dca_lines==true)
for i = 0 to entry.dca_num_positions - 1
for[a_index,p_entry] in entry.self_pyramiding_positions //Go through the entries pyramid positions
if(na(p_entry.bar_index_at_pyramid_change)==false)
true //TODO - Why did I need this if check originally?????
else
if(na(array.get(p_entry.dca_positions,i))==false)
line.set_x2(array.get(p_entry.dca_lines,i),time)//This works because when the dca_position gets removed this can't draw anymore, so therefore it draws to the correct location.
line.set_y2(array.get(p_entry.dca_lines,i),array.get(p_entry.dca_positions,i))
true
if(na(p_entry.dca_in_use)==false and na(p_entry.dca_activated)==false)
if(na(p_entry.dca_positions)==false)
if(array.size(p_entry.dca_in_use) > 0)
if(array.get(p_entry.dca_in_use,i)==true)
line.set_style(array.get(p_entry.dca_lines,i),line.style_solid)
entry.flip_occurred := false //Ensure this is always reset
else
//Adjust the _equity that is available for activations
position_size = 0.0 //What kind of position will the order have? 50% 100% or some fixed $Cash amount?
money_used = 0.0 //Keep track of what kind of money will be used to create the order.
//Below is the multiplier used for martingale calculations. To save on IF statements, I have it converted in ternary form, but kept the IF form for readability below.
multiplier = entry.use_martingale ? strategy.closedtrades.profit(strategy.closedtrades-1) > 0 ? entry.martingale_limit_reset_mode == "Original" ? _equity.num_concurrent_wins >= entry.martingale_win_limit ? 1.0 : math.pow(entry.martingale_win_ratio, _equity.num_concurrent_wins) : _equity.num_concurrent_wins >= entry.martingale_win_limit ? math.pow(entry.martingale_win_ratio, entry.martingale_win_limit-1) : math.pow(entry.martingale_win_ratio, _equity.num_concurrent_wins) : entry.martingale_limit_reset_mode == "Original" ? _equity.num_concurrent_losses >= entry.martingale_lose_limit ? 1.0 : math.pow(entry.martingale_lose_ratio, _equity.num_concurrent_losses) : _equity.num_concurrent_losses >= entry.martingale_lose_limit ? math.pow(entry.martingale_lose_ratio, entry.martingale_lose_limit-1) : math.pow(entry.martingale_lose_ratio, _equity.num_concurrent_losses) : 1.0
//BELOW IS TRANSLATION OF THE TERENARY CRAZYNESS ABOVE (HAD TO DO THIS TO SAVE ON LOCAL SCOPES)
// if(strategy.closedtrades.profit(strategy.closedtrades-1)>0)
// if(entry.martingale_limit_reset_mode=="Original")
// if(_equity.num_concurrent_wins >= entry.martingale_win_limit)
// multiplier := 1.0 //Reset to normal for original mode.
// else
// multiplier := math.pow(entry.martingale_win_ratio,_equity.num_concurrent_wins)
// else
// if(_equity.num_concurrent_wins >= entry.martingale_win_limit)
// multiplier := math.pow(entry.martingale_win_ratio,entry.martingale_win_limit-1)
// else
// multiplier := math.pow(entry.martingale_win_ratio,_equity.num_concurrent_wins)
// else //Broken even counts as loss
// if(entry.martingale_limit_reset_mode=="Original")
// if(_equity.num_concurrent_losses >= entry.martingale_lose_limit)
// multiplier := 1.0 //Reset to normal for original mode.
// else
// multiplier := math.pow(entry.martingale_lose_ratio,_equity.num_concurrent_losses)
// else
// if(_equity.num_concurrent_losses >= entry.martingale_lose_limit)
// multiplier := math.pow(entry.martingale_lose_ratio,entry.martingale_lose_limit-1)
// else
// multiplier := math.pow(entry.martingale_lose_ratio,_equity.num_concurrent_losses)
if(entry.use_percent_equity)
money_used := (_equity.equity * entry.percent_equity_amount) * multiplier
money_used := (money_used > _equity.equity) ? _equity.equity : money_used
money_used := (money_used < _equity.minimum_order_size) ? _equity.minimum_order_size : money_used
// if(money_used > _equity.equity) //If by chance this would try to use more money then you have, make it use the max amount
// money_used := _equity.equity
// if(money_used < _equity.minimum_order_size)
// money_used := _equity.minimum_order_size
position_size := money_used / close
if(entry.use_cash)
money_used := entry.cash_amount * multiplier
money_used := (money_used > _equity.equity) ? _equity.equity : money_used
money_used := (money_used < _equity.minimum_order_size) ? _equity.minimum_order_size : money_used
// if(money_used > _equity.equity) //If by chance this would try to use more money then you have, make it use the max amount
// money_used := _equity.equity
// if(money_used < _equity.minimum_order_size)
// money_used := _equity.minimum_order_size
position_size := money_used / close
if(entry.use_dynamic_percent_equity)//This will overide the other settings
//Sample Usage: xSellBuyInterpolation(g_rsi,100,25,70,30)
if(entry.dynamic_equity_interpolation_method=="Linear From Mid")
entry.initial_dynamic_percent_equity_amount := xSellBuyMidInterpolation(entry.dynamic_percent_equity_source,entry.dynamic_percent_equity_max,entry.dynamic_percent_equity_min,entry.dynamic_percent_equity_source_sell_range,entry.dynamic_percent_equity_source_buy_range)*0.01
if(entry.dynamic_equity_interpolation_method=="Linear")
entry.initial_dynamic_percent_equity_amount := xSellBuyInterpolation(entry.dynamic_percent_equity_source,entry.dynamic_percent_equity_max,entry.dynamic_percent_equity_min,entry.dynamic_percent_equity_source_sell_range,entry.dynamic_percent_equity_source_buy_range)*0.01
money_used := (_equity.equity * (entry.initial_dynamic_percent_equity_amount)) * multiplier
money_used := (money_used > _equity.equity) ? _equity.equity : money_used
money_used := (money_used < _equity.minimum_order_size) ? _equity.minimum_order_size : money_used
// if(money_used > _equity.equity) //If by chance this would try to use more money then you have, make it use the max amount
// money_used := _equity.equity
// if(money_used < _equity.minimum_order_size)
// money_used := _equity.minimum_order_size
position_size := money_used / close
//**
float total_position_to_adjust = 0
if(possible_flip_occured)
entry.flip_occurred := true //Its official a flip occured if it got to this point
_equity.flip_occured := true //This is needed to prevent exits from triggering on the same bar as a flip.
for[a_index, a_entry] in active_entries //Loop through all active entries
for[p_index, p_entry] in a_entry.self_pyramiding_positions //Loop through all known pyramids for each of these entries.
//Add the previous entries position_sizes to this to cancel them out accordingly for the flip.
total_position_to_adjust := total_position_to_adjust + p_entry.position_size
//Make sure to change _equity direction as well at this point and clear DCA's
entry.position_size := math.round(position_size + total_position_to_adjust,_equity.decimal_rounding_precision) //Set the position_size rounded to 6 decimal points. TODO -> Make this settable option for precision
entry.total_position_size := entry.total_position_size + entry.position_size //Set the total position_size
_equity.position_used := _equity.position_used + entry.position_size //Track the overall equity position_used for exit purposes.
entry.position_remaining := entry.position_size //Sets the initial tracker variable for how much position remains to be sold.
entry.initial_equity := money_used //Track what money was used to place this order, will display on order comment.
//TODO -> Maybe remove below? _equity.equity tracks this anyways?
entry.equity_remaining := _equity.equity - money_used //This will be used to keep track of what 'remains' for the entry. This can happen if a close only partially closes the equity.
//Adjust the master equity in equity management accordingly.
_equity.equity := _equity.equity - money_used
//Safe to activate and make active now
entry.activate := true
entry.active := true
entry.atr_value_at_activation := entry.atr_value //Store the initial value of the ATR, useful for stop loss and take profits that only want the initial value for future moves.
entry.initial_activation_price := close //Set the initial activation price for use by exits with adjust to average position turned off.
entry.time_at_activate := time_close //Set the current unix time of when the bar closed (which is happening right now when this calculates)
entry.bar_index_at_activate := bar_index
_equity.direction := entry.direction
//Loop through all entries and set their cooldown_bar_change_counts to 0 again.
for [index2, entry2] in _entries
entry2.cooldown_bar_change_count := 0 //If the entry has activated then reset this. This will ensure cooldown works correctly regardless of the entry that activated.
//Loop through all exits and change the activate bars to 0 again
for [index2, exit] in _exits
//TODO -> This should only be reset to 0 if the option to do this is selected. By default it will only do this if there is no active entries yet.
if(array.size(active_entries)==0)
exit.activate_after_bars_bar_change_count := 0
entry.bar_index_at_activated := bar_index //Needed for drawing the DCA correctly.
if(entry.use_dca and entry.flip_occurred != true) //Only create DCA on NON-FLIPS! (It will still do it for flips, but on the next bar right after this one instead. This will account for knowing what $ is available)
entry.dca_lines := array.new_line() //Create a new line set at activation (this overwrites any line array before it)
entry.dca_activated := array.new_bool(entry.dca_num_positions, false) //default to not activated on any DCA
entry.dca_in_use := array.new_bool(entry.dca_num_positions, false) //default to not in use for any DCA
entry.dca_position_quantities := array.new_float(entry.dca_num_positions, 0.0) //Copy over some blank dca position quantities to get it started. Quantity is determined at time of activation for DCA.
entry.dca_money_used := array.new_float(entry.dca_num_positions, 0.0) //Set the default money used to be assumed at 0.0
entry.dca_positions := array.new_float(entry.dca_num_positions)//Intialize it with empty slots equal to how many DCA we want.
if(entry.use_atr_deviation==false) //Create standard DCA Points
deviation_change = entry.dca_deviation_percentage
for i = 0 to (array.size(entry.dca_positions) == 0 ? na : entry.dca_num_positions - 1)
dca_value = close //just to set a default
if(i==0)
dca_value := close + ((1*entry.dca_deviation_percentage)*close)*(entry.direction=="LONG" ? -1 : 1)
if(i!=0) //and i!=1
deviation_change := deviation_change * entry.dca_scale
dca_value := array.get(entry.dca_positions,i-1) + (((deviation_change)*array.get(entry.dca_positions,i-1))*(entry.direction=="LONG" ? -1 : 1)) //Take the previous DCA value into consideration for calculation of the next DCA position
array.set(entry.dca_positions,i,dca_value)
else //Using ATR Deviation for DCA
atr_dca_value = close + (1*entry.atr_value*entry.dca_atr_mult)*(entry.direction=="LONG" ? -1 : 1)
deviation_change = math.abs(1 - (atr_dca_value/close))//This will calculate the percentage change this would be.
if(entry.dca_use_deviation_atr_min)
if(deviation_change < entry.dca_deviation_percentage) //This will force it to always be the minimum percentage.
deviation_change := entry.dca_deviation_percentage
for i = 0 to (array.size(entry.dca_positions) == 0 ? na : entry.dca_num_positions - 1)
dca_value = close //just to set a default
if(i==0)
//dca_value := close + (1*entry.atr_value*entry.dca_atr_mult)*(entry.direction=="LONG" ? -1 : 1) //This calculates it for what it would be one position down.
dca_value := close + ((deviation_change * close)*(entry.direction=="LONG" ? -1 : 1))
if(i!=0)
deviation_change := deviation_change * entry.dca_scale
dca_value := array.get(entry.dca_positions,i-1) + (((deviation_change)*array.get(entry.dca_positions,i-1))*(entry.direction=="LONG" ? -1 : 1))
array.set(entry.dca_positions,i,dca_value)
//Loop through the now set DCA Positions
if(entry.show_dca_lines)
for i = 0 to entry.dca_num_positions - 1
dca_line = line.new(
x1 = entry.time_at_activate,
y1 = array.get(entry.dca_positions,i),
x2 = entry.time_at_activate+(time-time[1]),//Extend out initially 1 bar ~ entry.bars_since_active,
y2 = array.get(entry.dca_positions,i),
xloc = xloc.bar_time,
extend = extend.none,
color = entry.dca_color,
width = 1,
style= line.style_dotted
)
entry.dca_lines.push(dca_line)
if(entry.new_pyramid_cancels_dca and _equity.override_occured==false)//This check can be ignored on an override because it thinks there is more entries than there is temporarily during this time. TODO: Do I need to fix this?
if(entry.num_active_positions >= 1)
if(na(most_recent_entry)==false)
most_recent_entry.bar_index_at_pyramid_change := bar_index
most_recent_entry.dca_positions := na //Clear these so it doesn't try to activate anything with these anymore for this pyramid
//Must happen at this point to ensure we don't get errors on the arrays for DCA use.
if(overide_activate==true) //This can happen as the result of a flip.
overide_activate := false //So the next entries in the loop don't think they had override on.
//Set active state to false for all other entries so it does not linger thinking it's still active.
for [ a_index,a_entry ] in _entries
if(a_entry.id != entry.id)
a_entry.active := false
for [ a_index, a_exit ] in _exits //Reset the exit cooldowns
a_exit.activate_after_bars_bar_change_count := 0
if(entry.flip_occurred != true) //A flip does not count as truly activated until the next bar, therefore don't add this to the known pyramids yet.
entry_copy = entry.deepCopy()
if(na(_equity.first_entry))
_equity.first_entry := entry_copy
entry.self_pyramiding_positions.push(entry_copy)//Always push to the self_pyramiding_positions array even if we are not using pyramiding. In the case of no pyramiding we just always use 0th index of this array.
active_entries.push(entry)//Add this to the list of active entries since it will be active now.
//**
//Activate exits
for [index, exit] in _exits
pass = array.new_bool(14,false) //This is how many pass requirements are needed for the exit to activate succesfully.
//This will keep track of what entry positions are affected by the exit for adjusting their values accordingly.
entry_position[] entries_exiting_for = array.new<entry_position>()
if(exit.condition)
array.set(pass,0,true)
else
if(exit.use_override_default_condition and exit.use_dynamic_condition) //In this situation we want to ignore what we have hardcoded and only use the dynamic source for entry control logic.
array.set(pass,0,true)
//Check if any of the active entries belong to this exits id
//Split exit_for_entries by ,
exit_entries = str.split(exit.exit_for_entries,",")
was_valid_id = false
if(array.size(exit_entries)>0)
//Loop through all the active entries to see if an ID matches
for[a_index,entry] in active_entries
if(array.includes(exit_entries,entry.id))
array.set(pass,1,true)
was_valid_id := true
else //If nothing is there assume this part passes.
array.set(pass,1,true)
was_valid_id := true
//Check if any of the active entries belong to this exits group
//Split exit_for_groups by ,
exit_groups = str.split(exit.exit_for_groups,",")
was_valid_group = false
if(array.size(exit_groups)>0)
//Loop through all the active entries to see if an GROUP matches
for[a_index,entry] in active_entries
if(array.includes(exit_groups,entry.group)) //Push only the 'set' known active entires into the qualifying for the exit.
array.set(pass,2,true)
was_valid_group := true
else //If nothing is there assume this part passes.
array.set(pass,2,true)
was_valid_group := true
//Push only the 'set' known active entires into the qualifying for the exit.
for[a_index,entry] in active_entries //Push all the known active entries into qualifying for the exit.
if(array.includes(exit_groups,entry.group) or array.includes(exit_entries,entry.id))
entries_exiting_for.push(entry)
exit.entries_exiting_for := entries_exiting_for //Update the entries it's exiting for if available
//If the exit is already active this should not be able to activate again.
if(exit.active)
array.set(pass,3,false)
else
array.set(pass,3,true)
//Did an exit bar timeframe requirement since a valid entry it tied to trigger? (valid is determined by simply the entry being active and belonging to the supported group or id and the custom condition being true)
if( was_valid_group and was_valid_id)
if(exit.use_activate_after_bars)
if(exit.activate_after_bars_bar_change_count >= exit.activate_after_bars)
array.set(pass,4,true)
else
array.set(pass,4,false)
else
array.set(pass,4,true) //Allowed to be activated by other means instead.
else
exit.activate_after_bars_bar_change_count := 0 //Reset what was added from a previous loop detecting bar changes, since it will be invalid.
array.set(pass,4,false)
if(strategy.position_size==0) //If there is no position to exit then there is nothing to exit
array.set(pass,5,false)
else
array.set(pass,5,true)
//Decide what price will be used for comparing if we are hitting price targets for stop loss or take profit
price_target = strategy.position_avg_price
entry_position first_entry = na //Record of what the earliest entry is for exit calculation purposes.
//Find the initial_activation_price and set the price_target to this.
//This can be done by finding the earliest activation_time for the 1st pyramid of the entries the exit can work with.
int earliest_activation_time = 99999999999999
for[a_index,a_entry] in entries_exiting_for
if(na(a_entry.self_pyramiding_positions)==false)
if(array.size(a_entry.self_pyramiding_positions)>0)
if(array.get(a_entry.self_pyramiding_positions,0).time_at_activate < earliest_activation_time)
earliest_activation_time := array.get(a_entry.self_pyramiding_positions,0).time_at_activate //grab the first pyramid of the entry
first_entry := array.get(a_entry.self_pyramiding_positions,0)
if(exit.use_average_position==false)
if(na(first_entry)==false)
price_target := first_entry.initial_activation_price //This will set it to the first known entry that was active, therefore setting the initial activation price correctly.
//Check if in profit if being used
if(exit.use_close_if_profit_only)
//Are we in profit by the profit_value?
//Calculate what the close has to be to be in the profit percentage for the average of all the positions at the time.
target = price_target + ((price_target * exit.profit_value) * (strategy.position_size > 0 ? 1 : -1))
if(strategy.position_size>0)
if(close>target)
array.set(pass,6,true)
else
array.set(pass,6,false)
if(strategy.position_size<0)
if(close<target)
array.set(pass,6,true)
else
array.set(pass,6,false)
else
array.set(pass,6,true)
//Dynamic Condition Check
if(exit.use_dynamic_condition)
//Check if the source meets the dynamic condition
if(qualifyCondition(exit)==true)
array.set(pass,7,true)
else
array.set(pass,7,true)
//Calculate if it's exited too many times
if(exit.amount_of_times_triggered < exit.trigger_x_times )
array.set(pass,8,true)
array.set(pass,9,validateFilter(exit,_filters))
//Check if _equity.override_occured happened, if so this exit can NOT be allowed to activate.
if(_equity.flip_occured == false)
array.set(pass,10,true)
//Check if any qualifiers apply to this exit.
array.set(pass,11,validateQualifier(exit,_qualifiers))
//!!! *IMPORTANT* !!! Up to this point all the conditions are non primary conditions, if these are all true then set all_conditions_pass to true for plot drawing purposes. IF ADDING NEW EXIT IDEAS, PUT ABOVE AND CHANGE ALL PASS #s
if(array.get(pass,0)==true
and array.get(pass,1)==true
and array.get(pass,2)==true
and array.get(pass,3)==true
and array.get(pass,4)==true
and array.get(pass,5)==true
and array.get(pass,6)==true
and array.get(pass,7)==true
and array.get(pass,8)==true
and array.get(pass,9)==true
and array.get(pass,10)==true
and array.get(pass,11)==true)
exit.all_conditions_pass := true
else
exit.all_conditions_pass := false
atr_value = exit.atr_value //By default set to the exits updated ATR value. This is the equivlent of update_atr = true
if(exit.update_atr_with_new_pyramid and exit.update_atr==false)
if(na(most_recent_entry)==false)
atr_value := most_recent_entry.atr_value_at_activation
if(exit.update_atr_with_new_pyramid==false and exit.update_atr==false)
if(na(_equity.first_entry)==false)
atr_value := _equity.first_entry.atr_value_at_activation
//TODO add condition for update_atr ONLY
//NOTE: - IMPORTANT - If future array.set commands are needed place them BEFORE this because of the all_conditions_pass check!
if(exit.exit_type=="Stop Loss")
//Check modifiers
//Is this trailing?
if(exit.exit_modifier=="Trailing")
if(strategy.position_size > 0)
if(na(exit.exit_value))
exit.exit_value := 0
if(na(exit.close_exit_value))
exit.close_exit_value := 0
close_exit_value = (close - (close*exit.percentage))
if(close_exit_value > exit.close_exit_value)
exit.close_exit_value := close_exit_value
price_target_difference_value = exit.use_average_position ? (first_entry.initial_activation_price - strategy.position_avg_price ) : 0
exit.exit_value := exit.close_exit_value - price_target_difference_value
if(close <= exit.exit_value)
array.set(pass,12,true)
if(strategy.position_size < 0)
if(na(exit.exit_value))
exit.exit_value := 99999999999999
if(na(exit.close_exit_value))
exit.close_exit_value := 99999999999999
close_exit_value = (close + (close*exit.percentage))
if(close_exit_value < exit.close_exit_value)
exit.close_exit_value := close_exit_value
price_target_difference_value = exit.use_average_position ? (first_entry.initial_activation_price - strategy.position_avg_price ) : 0
exit.exit_value := exit.close_exit_value - price_target_difference_value
if(close >= exit.exit_value)
array.set(pass,12,true)
//Is this ATR?
if(exit.exit_modifier=="ATR")
hypo_long_exit_value = (price_target - (atr_value * exit.atr_multiplier))
hypo_short_exit_value = (price_target + (atr_value * exit.atr_multiplier))
if(strategy.position_size > 0)
exit.exit_value := hypo_long_exit_value
if(close < exit.exit_value)
array.set(pass,12,true)
if(strategy.position_size < 0)
exit.exit_value := hypo_short_exit_value
if(close > exit.exit_value)
array.set(pass,12,true)
//No Modifier?
if(exit.exit_modifier=="None")
if(strategy.position_size > 0)
exit.exit_value := (price_target - (price_target*exit.percentage))
if(close < exit.exit_value)
array.set(pass,12,true)
if(strategy.position_size < 0)
exit.exit_value := (price_target + (price_target*exit.percentage))
if(close > exit.exit_value)
array.set(pass,12,true)
else
array.set(pass,12,true)
if(exit.exit_type=="Take Profit")
//Check modifiers
//Is this trailing?
if(exit.exit_modifier=="Trailing")
//activation_value
if(strategy.position_size > 0)
if(na(exit.exit_value))
exit.exit_value := 0
if(na(exit.close_exit_value))
exit.close_exit_value := 0
if(na(exit.activate))
exit.activation_value := 0
close_exit_value = (close - (close*exit.percentage))
if(close_exit_value > exit.close_exit_value)
exit.close_exit_value := close_exit_value
exit.activation_value := (price_target + (price_target*exit.activation_percentage))
if(close>=exit.activation_value)
exit.activation_value_crossed := true
price_target_difference_value = exit.use_average_position ? (first_entry.initial_activation_price - strategy.position_avg_price ) : 0
exit.exit_value := exit.close_exit_value - price_target_difference_value
if(close <= exit.exit_value and exit.activation_value_crossed)
array.set(pass,13,true)
if(strategy.position_size < 0)
if(na(exit.exit_value))
exit.exit_value := 99999999999999
if(na(exit.close_exit_value))
exit.close_exit_value := 99999999999999
if(na(exit.activate))
exit.activation_value := 99999999999999
close_exit_value = (close + (close*exit.percentage))
if(close_exit_value < exit.close_exit_value)
exit.close_exit_value := close_exit_value
exit.activation_value := (price_target - (price_target*exit.activation_percentage))
if(close<=exit.activation_value)
exit.activation_value_crossed := true
price_target_difference_value = exit.use_average_position ? (first_entry.initial_activation_price - strategy.position_avg_price ) : 0
exit.exit_value := exit.close_exit_value - price_target_difference_value
if(close >= exit.exit_value and exit.activation_value_crossed)
array.set(pass,13,true)
//Is this ATR?
if(exit.exit_modifier=="ATR")
hypo_long_exit_value = (price_target + (atr_value * exit.atr_multiplier))
hypo_short_exit_value = (price_target - (atr_value * exit.atr_multiplier))
if(strategy.position_size > 0)
exit.exit_value := hypo_long_exit_value
if(close > exit.exit_value)
array.set(pass,13,true)
if(strategy.position_size < 0)
exit.exit_value := hypo_short_exit_value
if(close < exit.exit_value)
array.set(pass,13,true)
//No Modifier?
if(exit.exit_modifier=="None")
if(strategy.position_size > 0)
exit.exit_value := (price_target + (price_target*exit.percentage))
if(close > exit.exit_value)
array.set(pass,13,true)
if(strategy.position_size < 0)
exit.exit_value := (price_target - (price_target*exit.percentage))
if(close < exit.exit_value)
array.set(pass,13,true)
else
array.set(pass,13,true)
if(array.includes(pass,false)) //If the array contains even 1 false then...
exit.activate := false
else
//Adjust all equity values for orders exit was qualified for (group name, id)
exit.exit_amount := 0 //Just to be sure it's 0
exit.entries_exiting_for := array.new<entry_position>()
for[a_index,entry] in entries_exiting_for
exit.entries_exiting_for.push(entry) //This will let the exit know what entries it's tied to at the moment.
//Loop through the pyramids (even if none) for each entry and add their exit amounts and detract from their position remaining to be sold off.
for[ap_index,p_entry] in entry.self_pyramiding_positions
position_size_to_exit = math.round(p_entry.position_remaining * exit.quantity_percent,_equity.decimal_rounding_precision) //Very important to round here!
exit.exit_amount := math.round(exit.exit_amount + position_size_to_exit,_equity.decimal_rounding_precision) //Very important to round here!
p_entry.position_remaining := p_entry.position_remaining - position_size_to_exit
if(p_entry.dca_close_cancels and p_entry.use_dca)
p_entry.dca_positions := array.new_float(p_entry.dca_num_positions,na)
//p_entry.dca_active_positions = na //Clear the active state of the positions
//Final check to see if the exit_amount is greater than the equity position_used. If not then we can't allow this since it's position is already in use (maybe by another exit that would trigger first)
if(exit.exit_amount > _equity.position_used)
exit.activate := false
exit.active := false
exit.entries_exiting_for := array.new<entry_position>()
exit.exit_amount := 0
else
//Safe to activate now
exit.activate := true
exit.active := true
_equity.position_used := _equity.position_used - exit.exit_amount
//**
//**
// @function Creates actual entry and exit orders if activated
// @param entry_position and exit_position array to use along with equity mangement
// @returns void
export create_entries_and_exits(array<entry_position> _entries, array<exit_position> _exits, equity_management _equity) =>
cancel_dca_orders = false
//Loop through entries to determine if DCA need to be canceled first.
for [index, entry] in _entries
if(entry.activate)
if(entry.flip_occurred)
cancel_dca_orders := true
break //Exit the loop early, all it takes is one entry to have a flip to need to exit this.
for [index, entry] in _entries //Loop through all entires and place orders.
if(entry.activate)
if(entry.flip_occurred)
//This will close all current positions, which is OK, because all the positions must be from the opposite direction at this point.
//Then for visual purposes, reset the lines to reflect this for each pyramid of every entry.
for [index2, entry2] in _entries //Loop through all the entries again
if(entry2.use_dca) //Does this entry use dca?
for [p_index, p_entry] in entry2.self_pyramiding_positions //Loop through the self pyramiding positions of this entry.
//Undo any DCA that may have activated on this same bar for ALL entries. This can be done by setting it back to it's previous known values.
// for i = 0 to entry2.dca_num_positions - 1
// array.set(p_entry.dca_in_use,i,false) //If a flip position occured, all DCA should NOT be in USE!
// array.set(p_entry.dca_activated,i,false) //If a flip position occured, all DCA should be DE-ACTIVATED!
p_entry.equity_remaining := p_entry.prior_equity_remaining //Restore correct reference to equity remaining.
p_entry.position_remaining := p_entry.prior_position_remaining //Restore the prior known position remaining as well.
entry2.total_position_size := entry2.prior_total_position_size //Restore the known prior total position size for proper exiting.
_equity.equity := _equity.prior_equity //Restore equity to known past value before any entry or DCA could have changed it.
_equity.position_used := _equity.prior_position_used //Restore the position_used to what it was before any entry or DCA could have changed it.
//array.set(p_entry.dca_position_quantities,i,purchase_qty) // DO NOT UN COMMENT <- This is here only for reference that this does NOT need to be changed to it's prior version.
//array.set(p_entry.dca_money_used,i,money_used) // DO NOT UN COMMENT <- This is here only for reference that this does NOT need to be changed to it's prior version.
//Change the style if dca_activated was false. This can happen if it was changed true during the loop, and we need to undo that now for this situation.
// if(na(p_entry.dca_in_use)==false and na(p_entry.dca_activated)==false)
// if(na(p_entry.dca_positions)==false)
// if(array.size(p_entry.dca_in_use) > 0)
// for i = 0 to entry2.dca_num_positions - 1
// if(array.get(p_entry.dca_in_use,i)==false)
// line.set_style(array.get(p_entry.dca_lines,i),line.style_dotted) //Set it back to dotted since it's not active
cancel_dca_orders := true
strategy.close_all(comment=entry.name+ " | Flipping Position Next Bar ")//+(dca_cleared ? "YES" : "NO")) //This does have a 1 bar delay, to compensate for this try running under a lower timeframe and using request.security commands can help to adjust to the higher time frame data but with the resolution of the lower timeframe. Then use deep back test for proper testing.
else
order_comment = entry.name + " ⟁"+str.tostring(array.size(entry.self_pyramiding_positions)) //by default this is the order comment
if(_equity.show_order_info_in_comments)
order_comment := order_comment+" | (P="+(entry.use_dynamic_percent_equity ? str.tostring(entry.initial_dynamic_percent_equity_amount*100,format.percent) : str.tostring(entry.percent_equity_amount*100,format.percent))+")"+(entry.use_dynamic_percent_equity ? " | (DV=" + str.tostring(entry.dynamic_percent_equity_source,'#.##')+")": "")+" | (EU="+str.tostring(entry.initial_equity,'$#.##')+") | (ER="+str.tostring(_equity.equity,'$#.##')+" / "+str.tostring(strategy.initial_capital+strategy.netprofit,'$#.##')+")"
if(_equity.show_order_info_in_labels)
label_text = "Percent Used: "+(entry.use_dynamic_percent_equity ? str.tostring(entry.initial_dynamic_percent_equity_amount*100,format.percent) : str.tostring(entry.percent_equity_amount*100,format.percent))+"\n"
label_text := label_text + (entry.use_dynamic_percent_equity ? "Dynamic Value: " + str.tostring(entry.dynamic_percent_equity_source,'#.##')+"\n": "")
label_text := label_text + "Equity Used: "+str.tostring(entry.initial_equity,'$#.##')+"\n"
label_text := label_text + "Equity Remaining: "+str.tostring(_equity.equity,'$#.##')+"\n"
label_text := label_text + "Starting Equity: "+str.tostring(strategy.initial_capital+strategy.netprofit,'$#.##')
temp_label = label.new(bar_index,close,label_text,color=entry.direction=="LONG" ? color.rgb(21, 70, 31) : color.rgb(70, 23, 31),textcolor = color.white,yloc=yloc.abovebar)
strategy.order(entry.name,entry.direction=="LONG" ? strategy.long : strategy.short,qty=entry.position_size.precision_fix(_equity.decimal_rounding_precision), oca_name=entry.direction=="LONG" ? "LONGS" : "SHORTS", oca_type = strategy.oca.none, comment=order_comment)
if(entry.use_dca and cancel_dca_orders==false) //Handle creating DCA orders if any activate, assuming it's not canceled by a flip position
for [p_index, p_entry] in entry.self_pyramiding_positions
for [pa_index, dca_activated] in p_entry.dca_activated //Go through the pyramid entries activation array
if(dca_activated==true) //Was one activated? For each one do the code below...
// if(bar_index==20218)
// runtime.error("DCA was activated somehow here")
dca_percentage_levels_array = str.split(entry.dca_percentages,"\n") //Calculate the array of the DCA percentage levels desired.
dca_percentage_used = array.get(dca_percentage_levels_array,pa_index)
dca_order_name = entry.name+str.tostring(pa_index+1)
dca_equity_used = array.get(p_entry.dca_money_used,pa_index) //_equity.equity * str.tonumber(dca_percentage_used)*0.01 //TODO -> Read custom array to determine equity used.
array.set(p_entry.dca_activated,pa_index,false)//Set this to false since we are placing the order now so it doesn't activate again!
dca_order_qty = array.get(p_entry.dca_position_quantities,pa_index) //The DCA_Activated index matches DCA_position_quantities, therefore we can use the same index to grab coresponding values.
order_comment = dca_order_name + " ⟁"+str.tostring(p_index+1) //by default this is the order comment. The pyramid activation could occur from a previous line so we use p_index instead of self_pyramiding_position array size
if(_equity.show_order_info_in_comments)
order_comment := order_comment+" | (P="+(entry.use_dca_dynamic_percent_equity ? str.tostring(p_entry.initial_dynamic_percent_equity_amount*100,format.percent) : dca_percentage_used)+"%)"+(entry.use_dynamic_percent_equity ? " | (DV=" + str.tostring(entry.dynamic_percent_equity_source,'#.##')+")": "")+" | (EU="+str.tostring(dca_equity_used,'$#.##')+") | (ER="+str.tostring(_equity.equity,'$#.##')+" / "+str.tostring(strategy.initial_capital+strategy.netprofit,'$#.##')+")"
if(_equity.show_order_info_in_labels)
label_text = "Percent Used: "+(entry.use_dca_dynamic_percent_equity ? str.tostring(p_entry.initial_dynamic_percent_equity_amount*100,format.percent) : dca_percentage_used+"%")+"\n"
label_text := label_text + (entry.use_dca_dynamic_percent_equity ? "Dynamic Value: " + str.tostring(entry.dynamic_percent_equity_source,'#.##')+"\n": "")
label_text := label_text + "Equity Used: "+str.tostring(dca_equity_used,'$#.##')+"\n"
label_text := label_text + "Equity Remaining: "+str.tostring(_equity.equity,'$#.##')+"\n"
label_text := label_text + "Starting Equity: "+str.tostring(strategy.initial_capital+strategy.netprofit,'$#.##')
temp_label = label.new(bar_index,close,label_text,color=entry.direction=="LONG" ? color.rgb(21, 70, 31) : color.rgb(70, 23, 31),textcolor = color.white,yloc=yloc.abovebar)
strategy.order(dca_order_name,entry.direction=="LONG" ? strategy.long : strategy.short,qty=dca_order_qty.precision_fix(_equity.decimal_rounding_precision), oca_name=entry.direction=="LONG" ? "LONGS" : "SHORTS", oca_type = strategy.oca.none, comment=order_comment)
//**
for [index, exit] in _exits
if(exit.activate)
if(exit.use_limit==false) //Market Orders
strategy.order(exit.name,strategy.position_size>0 ? strategy.short : strategy.long,qty=exit.exit_amount.precision_fix(_equity.decimal_rounding_precision), oca_name="EXITS", oca_type = strategy.oca.none, comment=exit.name + " | (P="+str.tostring(exit.quantity_percent*100,format.percent)+")")
//Since this is a market order, we know we can reset_equity right away and change the activate_after_bars_bar_change_count accordingly
exit.activate_after_bars_bar_change_count := 0
exit.reset_equity := true //This will also fix activation states for entries if applicable.
exit.amount_of_times_triggered := exit.amount_of_times_triggered + 1
exit.active := false //Because the order is actually closing it can't be active anymore.
//**
//**
|
lib_plot_objects | https://www.tradingview.com/script/6pfVVhaZ-lib-plot-objects/ | robbatt | https://www.tradingview.com/u/robbatt/ | 2 | 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/
// © robbatt
//@version=5
// @description library wrapping basic builtin object constructors, to be able to do calculations with points/lines/boxes/triangles/polygons via libraries and on securities. inspired by Trendoscope's (https://www.tradingview.com/script/63c8VXSa-DrawingTypes/ and https://www.tradingview.com/script/eNM7BFaR-DrawingMethods/) with added update mechanism to not have to recreate objects on every iteration for continously drawn items, automated xloc selection for coordinates, compatibility check for chart.points, added Triangle and Polygon types, object reflection via tostring to valid json (logging via webhook)
library("lib_plot_objects", overlay = true)
///////////////////////////////////////////////////////
//#region BUILTIN OBJECT WRAPPERS structures
///////////////////////////////////////////////////////
//@description candle data
//@field bar_time time based x coordinate
//@field bar_time_close time based x coordinate for closing time
//@field bar_idx bar index based x coordinate
//@field o candle open price
//@field h candle highest price
//@field l candle lowest price
//@field c candle close price
//@field v candle volume
export type Candle
int bar_time = time
int bar_time_close = time_close
int bar_idx = bar_index
float o = open
float h = high
float l = low
float c = close
float v = volume
//@description Reusable arguments for label.new()
//@field text_font_family The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
//@field xloc See description of x argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
//@field yloc Possible values are yloc.price, yloc.abovebar, yloc.belowbar. If yloc=yloc.price, y argument specifies the price of the label position. If yloc=yloc.abovebar, label is located above bar. If yloc=yloc.belowbar, label is located below bar. Default is yloc.price.
//@field bg_color Color of the label border and arrow.
//@field style Label style. Possible values: label.style_none, label.style_xcross, label.style_cross, label.style_triangleup, label.style_triangledown, label.style_flag, label.style_circle, label.style_arrowup, label.style_arrowdown, label.style_label_up, label.style_label_down, label.style_label_left, label.style_label_right, label.style_label_lower_left, label.style_label_lower_right, label.style_label_upper_left, label.style_label_upper_right, label.style_label_center, label.style_square, label.style_diamond, label.style_text_outline. Default is label.style_label_down.
//@field text_color Text color.
//@field size Label size. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default value is size.normal.
//@field text_align Label text alignment. Possible values: text.align_left, text.align_center, text.align_right. Default value is text.align_center.
export type LabelArgs
color text_color = chart.fg_color
color bg_color = #00000000
string text_font_family = font.family_default
string xloc = xloc.bar_index
string yloc = yloc.price
string style = label.style_label_down
string size = size.normal
string text_align = text.align_center
//@description Wrapper for builtin label
//@field point The Label coordinates
//@field txt Label text. Default is empty string.
//@field args Wrapper for reusable arguments for label.new()
//@field tooltip Hover to see tooltip label.
//@field plot The label object to be added and plotted via draw()
export type Label
chart.point point
string txt = ''
LabelArgs args = na
string tooltip = na
label plot = na
//@description Wrapper for Label centered between an array of chart.points
//@field points The coordinates around the center
//@field center_label The generated, centered Label
export type CenterLabel
chart.point[] points
Label center_label
//@description Reusable arguments for line.new()
//@field line_color Line color.
//@field style 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 Line width in pixels.
//@field xloc Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
//@field extend f 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.
export type LineArgs
color line_color = chart.fg_color
string style = line.style_solid
int width = 1
string xloc = xloc.bar_index
string extend = extend.none
//@description Wrapper for builtin line
//@field start starting point of the line
//@field start end point of the line
//@field args Wrapper for reusable arguments for line.new()
//@field plot The line object to be added and plotted via draw()
export type Line
chart.point start
chart.point end
LineArgs args
line plot = na
//@description Creates a new linefill object and displays it on the chart, filling the space between a and b with the color specified in fill_color.
//@field a The first Line object
//@field b The second Line object
//@field fill_color The color used to fill the space between the lines.
//@field plot The linefill object to be added and plotted via draw()
export type LineFill
Line a
Line b
color fill_color = #dededede
bool needs_support = false
Line support = na
linefill plot = na
//@description Reusable arguments for box.new()
//@field border_color Color of the four borders. Optional. The default is color.blue.
//@field border_width Width of the four borders, in pixels. Optional. The default is 1 pixel.
//@field border_style Style of the four borders. Possible values: line.style_solid, line.style_dotted, line.style_dashed. Optional. The default value is line.style_solid.
//@field bg_color Background color of the box. Optional. The default is color.blue.
//@field xloc Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc = xloc.bar_index, the arguments must be a bar index. If xloc = xloc.bar_time, the arguments must be a UNIX time. Possible values: xloc.bar_index and xloc.bar_time. Optional. The default is xloc.bar_index.
//@field extend When extend.none is used, the horizontal borders start at the left border and end at the right border. With extend.left or extend.right, the horizontal borders are extended indefinitely to the left or right of the box, respectively. With extend.both, the horizontal borders are extended on both sides. Optional. The default value is extend.none.
export type BoxArgs
color border_color = chart.fg_color
int border_width = 1
string border_style = line.style_solid
color bg_color = #dededede
string xloc = xloc.bar_index
string extend = extend.none
//@description Reusable text arguments for box.new()
//@field text_size The size of the text. An optional parameter, the default value is size.auto. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge.
//@field text_font_family The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
//@field text_color The color of the text. Optional. The default is color.black.
//@field text_halign The horizontal alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_left, text.align_center, text.align_right.
//@field text_valign The vertical alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_top, text.align_center, text.align_bottom.
//@field text_wrap Defines whether the text is presented in a single line, extending past the width of the box if necessary, or wrapped so every line is no wider than the box itself (and clipped by the bottom border of the box if the height of the resulting wrapped text is higher than the height of the box). Optional. The default value is text.wrap_none. Possible values: text.wrap_none, text.wrap_auto.
export type BoxTextArgs
color text_color = chart.fg_color
string text_size = size.normal
string text_halign = text.align_center
string text_valign = text.align_center
string text_wrap = text.wrap_none
string text_font_family = font.family_default
//@description Wrapper for builtin box
//@field left_top top-left corner of the box
//@field right_bottom bottom-right corner of the box
//@field txt The text to be displayed inside the box. Optional. The default is empty string.
//@field args Wrapper for reusable arguments for box.new()
//@field plot The box object to be added and plotted via draw()
export type Box
chart.point left_top
chart.point right_bottom
string txt = ''
BoxArgs args = na
BoxTextArgs text_args = na
box plot = na
///////////////////////////////////////////////////////
//#endregion BUILTIN OBJECT WRAPPERS
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region SETTERS
///////////////////////////////////////////////////////
export method set_line_color(LineArgs this, color value) =>
this.line_color := value
this
export method set_style(LineArgs this, string style) =>
this.style := style
this
export method set_width(LineArgs this, int width) =>
this.width := width
this
export method set_extend(LineArgs this, string extend) =>
this.extend := extend
this
export method set_txt_color(LabelArgs this, color value) =>
this.text_color := value
this
export method set_bg_color(LabelArgs this, color value) =>
this.bg_color := value
this
export method set_style(LabelArgs this, string value) =>
this.style := value
this
export method set_yloc(LabelArgs this, string yloc) =>
this.yloc := yloc
this
export method set_size(LabelArgs this, string value) =>
this.size := value
this
export method extend_to(Line this, int end_time, int end_idx, float end_price = na) =>
if not na(this)
this.end.time := end_time
this.end.index := end_idx
if not na(end_price)
this.end.price := end_price
this
///////////////////////////////////////////////////////
//#endregion SETTERS
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region HELPER METHODS
///////////////////////////////////////////////////////
//@function checks args oject for being na, if so, provide a default instead
export method or_default(LineArgs args) => na(args) ? LineArgs.new() : args
//@function checks args oject for being na, if so, provide a default instead
export method or_default(LabelArgs args) => na(args) ? LabelArgs.new() : args
//@function checks args oject for being na, if so, provide a default instead
export method or_default(BoxArgs args) => na(args) ? BoxArgs.new() : args
//@function checks args oject for being na, if so, provide a default instead
export method or_default(BoxTextArgs args) => na(args) ? BoxTextArgs.new() : args
export method direction(Candle this) =>
this.o <= this.c ? 1 : -1
export method is_green(Candle this) =>
this.direction() == 1
export method is_red(Candle this) =>
this.direction() == -1
export method is_bullish(Candle this) =>
this.direction() == 1
export method is_bearish(Candle this) =>
this.direction() == -1
export method total_size(Candle this) =>
this.h - this.l
export method body_size(Candle this) =>
math.abs(this.o - this.c)
export method body_top(Candle this) =>
math.max(this.o, this.c)
export method body_bottom(Candle this) =>
math.min(this.o, this.c)
export method wick_size_top(Candle this) =>
this.h - this.body_top()
export method wick_size_bottom(Candle this) =>
this.body_bottom() - this.l
export method body_total_ratio(Candle this) =>
this.body_size() / this.total_size()
export method duration(Candle this) =>
this.bar_time_close - this.bar_time
///////////////////////////////////////////////////////
//#endregion HELPER METHODS
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region OBJECT INSPECTION / CONVERSION TO JSON read
///////////////////////////////////////////////////////
//@function converts object to json representation
export method tostring(LineArgs this) =>
na(this)?'null':'{' + str.format('"style": {0}, "width": {1}, "extend": {2}', this.style, this.width, this.extend) + '}'
//@function converts object to json representation
export method tostring(LabelArgs this) =>
na(this)?'null':'{' + str.format('"text_font_family": "{0}", "yloc": "{1}", "style": "{2}", "size": "{3}", "text_align": "{4}"', this.text_font_family, this.yloc, this.style, this.size, this.text_align) + '}'
//@function converts object to json representation
export method tostring(BoxArgs this) =>
na(this)?'null':'{' + str.format('"border_style": {0}, "border_width": {1}, "extend": {2}', this.border_style, this.border_width, this.extend) + '}'
//@function converts object to json representation
export method tostring(BoxTextArgs this) =>
na(this)?'null':'{' + str.format('"text_font_family": "{0}", "text_valign": "{1}", "text_halign": "{2}", "text_size": "{3}", "text_wrap": "{4}"', this.text_font_family, this.text_valign, this.text_halign, this.text_size, this.text_wrap) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Candle this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"bar_idx": {0}, "bar_time": "{1,date,'+date_format+'}", "o": {2}, "h": {3}, "l": {4}, "c": {5}, "v": {6}, "bar_time_close": "{7,date,'+date_format+'}"', this.bar_idx, this.bar_time, this.o, this.h, this.l, this.c, this.v, this.bar_time_close) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(chart.point this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"bar_idx": {0}, "bar_time": "{1,date,'+date_format+'}", "price": {2}', this.index, this.time, this.price) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(chart.point[] this, simple string date_format = 'dd-MM-y HH:mm') =>
strings = array.new<string>(this.size())
for [i,item] in this
strings.set(i, item.tostring(date_format))
'[' + strings.join(', ') + ']'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Line this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"start": {0}, "end": {1}, "args": {2}', this.start.tostring(date_format), this.end.tostring(date_format), this.args.tostring()) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Label this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"point": {0}, "txt": "{1}", "args": {2}', this.point.tostring(date_format), this.txt, this.args.tostring()) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(LineFill this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"a": {0}, "b": {1}, "needs_support" : {2}, "support" : {3}', this.a.tostring(date_format), this.b.tostring(date_format), this.needs_support, this.support.tostring(date_format)) + '}'
//@function converts object to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Box this, simple string date_format = 'dd-MM-y HH:mm') =>
na(this)?'null':'{' + str.format('"left_top": {0}, "right_bottom": {1}, "text": "{2}", "args": {3}, "text_args": {4}', this.left_top.tostring(date_format), this.right_bottom.tostring(date_format), this.txt, this.args.tostring(), this.text_args.tostring()) + '}'
tostrings(this, simple string date_format = 'dd-MM-y HH:mm') =>
strings = array.new<string>(this.size())
for [i,item] in this
strings.set(i, item.tostring(date_format))
'[' + strings.join(', ') + ']'
tostrings_args(this) =>
strings = array.new<string>(this.size())
for [i,item] in this
strings.set(i, tostring(item))
'[' + strings.join(', ') + ']'
//@function converts array of objecta to json representation
export method tostring(LineArgs[] this) => tostrings_args(this)
//@function converts array of objecta to json representation
export method tostring(LabelArgs[] this) => tostrings_args(this)
//@function converts array of objecta to json representation
export method tostring(BoxArgs[] this) => tostrings_args(this)
//@function converts array of objecta to json representation
export method tostring(BoxTextArgs[] this) => tostrings_args(this)
//@function converts array of objecta to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Candle[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format)
//@function converts array of objecta to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Line[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format)
//@function converts array of objecta to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Label[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format)
//@function converts array of objecta to json representation
//@param date_format optional date format for str.format'ing point bar_time coordinates (default: 'dd-MM-y HH:mm')
export method tostring(Box[] this, simple string date_format = 'dd-MM-y HH:mm') => tostrings(this, date_format)
///////////////////////////////////////////////////////
//#endregion OBJECT INSPECTION / CONVERSION TO JSON
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region OBJECT CREATION / FACTORY METHODS create
///////////////////////////////////////////////////////
// Candle
// @function Creates Candle with ohlc and index data
// @param t bar time of this candle
// @param tc bar close time of this candle
// @param idx bar index of this candle
// @param o open price of this candle
// @param h highest price of this candle
// @param l lowest price of this candle
// @param c close price of this candle
// @returns new Candle
export create_candle(int t = time, int tc = time_close, int idx = bar_index, float o = open, float h = high, float l = low, float c = close, float v = volume) =>
Candle.new(t, tc, idx, o, h, l, c, v)
// chart.points
// @function Workaround for chart.point.new/now() returning the same instance when being fed equal parameters. This function only creates a new instance when id's match (as long as this behaviour exists)
// @param this chart.point
// @param other chart.point
// @returns center chart.point
export create_point_var(int id, int bar_time = time, int bar_idx = bar_index, float price = close) =>
point = chart.point.new(id, bar_idx, price)
point.time := bar_time
point
// @function Creates center chart.point between two chart.points
// @param this chart.point
// @param other chart.point
// @returns center chart.point
export method create_center(chart.point this, chart.point other) =>
if not na(this) and not na(other)
center_bar_idx = int(math.avg(this.index, other.index))
center_bar_time = time[bar_index - center_bar_idx]
center_price = other.price + (this.price - other.price) * (center_bar_idx - other.index) / (this.index - other.index)
chart.point.new(center_bar_time, center_bar_idx, center_price)
else
not na(this) ? this : not na(other) ? other : chart.point.now()
// @function Creates center chart.point between an array of given chart.points
// @param points array of chart.points for calculation of the center
// @returns center chart.point
export method create_center(chart.point[] points) =>
count = points.size()
bar_sum = 0
price_sum = 0.0
center_xloc = xloc.bar_index
chart.point center_point = na
if count == 2
center_point := create_center(points.get(0), points.get(1))
else
for point in points
if not na(point)
bar_sum += point.index
price_sum += point.price
center_bar_idx = int(bar_sum/count)
center_bar_time = time[bar_index - center_bar_idx]
center_price = price_sum / count
center_point := chart.point.new(center_bar_time, center_bar_idx, center_price)
center_point
export method create_center(Line this) =>
this.start.create_center(this.end)
// Labels
//@function Creates a new Label object.
export method create_label(chart.point this, string txt = na, LabelArgs args = na, string tooltip = na) =>
if not na(this)
Label.new(this, txt, args.or_default(), tooltip)
//@function Creates a new Label object.
export method create_label(Line this, string txt = na, LabelArgs args = na, string tooltip = na) =>
if not na(this)
Label.new(this.start.create_center(this.end), txt, args.or_default(), tooltip)
//@function Creates a new Label object.
export method create_label(Box this, string txt = na, LabelArgs args = na, string tooltip = na) =>
if not na(this)
Label.new(this.left_top.create_center(this.right_bottom), txt, args.or_default(), tooltip)
//@function Creates a new Label object.
export method create_center_label(Line this, string txt = na, LabelArgs args = na, string tooltip = na) =>
points = array.from(this.start, this.end)
center_label = this.create_center().create_label(txt, args.or_default(), tooltip)
CenterLabel.new(points, center_label)
_nz(this, default) =>
na(this) ? default : this
export method nz(chart.point this, chart.point default = na) => not na(default) ? _nz(this, default) : _nz(this, chart.point.now())
export method nz(Candle this, Candle default = na) => not na(default) ? _nz(this, default) : _nz(this, Candle.new())
export method nz(LabelArgs this, LabelArgs default = na) => not na(default) ? _nz(this, default) : _nz(this, LabelArgs.new())
export method nz(Label this, Label default = na) => not na(default) ? _nz(this, default) : _nz(this, Label.new(chart.point.now()))
export method nz(LineArgs this, LineArgs default = na) => not na(default) ? _nz(this, default) : _nz(this, LineArgs.new())
export method nz(Line this, Line default = na) => not na(default) ? _nz(this, default) : _nz(this, Line.new(chart.point.now(), chart.point.now(), LineArgs.new()))
export method nz(CenterLabel this, CenterLabel default = na) => not na(default) ? _nz(this, default) : _nz(this, Line.new(chart.point.now(), chart.point.now(), LineArgs.new()).create_center_label('', LabelArgs.new()))
export method nz(LineFill this, LineFill default = na) => not na(default) ? _nz(this, default) : _nz(this, LineFill.new(Line.new(chart.point.now(1), chart.point.now(2), LineArgs.new()),Line.new(chart.point.now(3), chart.point.now(4), LineArgs.new())))
export method nz(BoxArgs this, BoxArgs default = na) => not na(default) ? _nz(this, default) : _nz(this, BoxArgs.new())
export method nz(BoxTextArgs this, BoxTextArgs default = na) => not na(default) ? _nz(this, default) : _nz(this, BoxTextArgs.new())
export method nz(Box this, Box default = na) => not na(default) ? _nz(this, default) : _nz(this, Box.new(chart.point.now(3), chart.point.now(3), '', BoxArgs.new(), BoxTextArgs.new()))
// Lines
export method create_line(chart.point this, chart.point other, LineArgs args = na) =>
Line.new(this, other, na(args) ? LineArgs.new() : args)
// Boxes
export method create_box(chart.point this, chart.point other, string txt = na, BoxArgs args = na, BoxTextArgs text_args = na) =>
Box.new(this, other, txt, na(args) ? BoxArgs.new() : args, na(text_args) ? BoxTextArgs.new() : text_args)
export method create_box(Line this, string txt = na, BoxArgs args = na, BoxTextArgs text_args = na) =>
Box.new(this.start, this.end, txt, na(args) ? BoxArgs.new() : args, na(text_args) ? BoxTextArgs.new() : text_args)
// LineFill
//@function Creates a new LineFill object.
//@field this The first Line object
//@field other The second Line object
//@field fill_color The color used to fill the space between the lines.
//@field support Optional support line if this.end == other.start, if that's the case and line is not passed as parameter, a new one is created
export method create_fill(Line this, Line other, color fill_color = #dededede, Line support = na) =>
if na(this) or na(other) ? false : not na(this.start) and not na(this.end) and not na(other.start) and not na(other.end)
var LineArgs transp = LineArgs.new(#00000000)
needs_support = this.start.index == other.end.index or this.end.index == other.start.index
LineFill.new(this, other, fill_color, needs_support, needs_support ? nz(support, Line.new(other.end, other.start, transp)) : na)
export create_line(int start_time, int start_idx, float start_price, int end_time, int end_idx, float end_price, LineArgs args = na) =>
start = chart.point.new(start_time, start_idx, start_price)
end = chart.point.new(end_time, end_idx, end_price)
Line.new(start, end, args.nz())
export create_box(int left_time, int left_idx, float top, int right_time, int right_idx, float bottom, string txt = na, BoxArgs args = na, BoxTextArgs text_args = na) =>
left_top = chart.point.new(left_time, left_idx, top)
right_bottom = chart.point.new(right_time, right_idx, bottom)
Box.new(left_top, right_bottom, txt, args.nz(), text_args.nz())
///////////////////////////////////////////////////////
//#endregion OBJECT CREATION / FACTORY METHODS
///////////////////////////////////////////////////////
_enqueue(id, item, int max = 0) =>
if not na(id)
id.unshift(item)
if max > 0 and id.size() > max
id.pop()
id
export method enqueue(Candle[] id, Candle item, int max = 0) => _enqueue(id, item, max)
export method enqueue(chart.point[] id, chart.point item, int max = 0) => _enqueue(id, item, max)
export method enqueue(Label[] id, Label item, int max = 0) => _enqueue(id, item, max)
export method enqueue(CenterLabel[] id, CenterLabel item, int max = 0) => _enqueue(id, item, max)
export method enqueue(Line[] id, Line item, int max = 0) => _enqueue(id, item, max)
export method enqueue(LineFill[] id, LineFill item, int max = 0) => _enqueue(id, item, max)
///////////////////////////////////////////////////////
//#region OBJECT UPDATE update
///////////////////////////////////////////////////////
//@function Updates a Candle object with new data.
export method update(Candle this, int bar_time = time, int bar_time_close = time, int bar_idx = bar_index, float o = open, float h = high, float l = low, float c = close, float v = volume) =>
this.bar_time := bar_time
this.bar_time_close := bar_time_close
this.bar_idx := bar_idx
this.o := o
this.h := h
this.l := l
this.c := c
this.v := v
this
//@function Updates a chart.point object with new data.
export method update(chart.point this, int bar_time = time, int bar_idx = bar_index, float price = close) =>
if not na(this)
this.time := bar_time
this.index := bar_idx
this.price := price
this
//@function Updates a chart.point object with new data from another chart.point.
export method update(chart.point this, chart.point update) =>
if na(update)
runtime.error('chart.point.update parameter must not be na')
this.update(update.time, update.index, update.price)
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(Label this, chart.point point) =>
if na(this.point)
this.point := point
else
this.point.update(point)
this
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(Label this, chart.point point, string txt) =>
this.update(point)
this.txt := txt
this
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(CenterLabel this, chart.point[] points) =>
center = points.create_center()
this.points := points
this.center_label.update(center)
this
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(CenterLabel this, chart.point[] points, string txt) =>
this.update(points)
this.center_label.txt := txt
this
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(CenterLabel this, Line l) =>
center = l.create_center()
this.points := array.from(l.start, l.end)
this.center_label.update(center)
this
//@function Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
export method update(CenterLabel this, Line l, string txt) =>
this.update(l)
this.center_label.txt := txt
this
//@function Updates this Line's chart.point objects with new data from other chart.points.
export method update(Line this, chart.point start, chart.point end) =>
if na(this.start)
this.start := start
else
this.start.update(start)
if na(this.end)
this.end := end
else
this.end.update(end)
this
//@function Updates a Box's chart.point objects with new data from other chart.points.
export method update(Box this, chart.point left_top, chart.point right_bottom) =>
if na(this.left_top)
this.left_top := left_top
else
this.left_top.update(left_top)
if na(this.right_bottom)
this.right_bottom := right_bottom
else
this.right_bottom.update(right_bottom)
this
///////////////////////////////////////////////////////
//#endregion OBJECT UPDATE
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region OBJECT REMOVAL delete
///////////////////////////////////////////////////////
safe_delete(this) =>
if not na(this)
this.plot.delete()
this
//@function Removes an objects representation from the chart.
export method delete(Line this) => safe_delete(this)
//@function Removes an objects representation from the chart.
export method delete(Label this) => safe_delete(this)
//@function Removes an objects representation from the chart.
export method delete(CenterLabel this) => safe_delete(this.center_label)
//@function Removes an objects representation from the chart.
export method delete(Box this) => safe_delete(this)
//@function Removes an objects representation from the chart.
export method delete(LineFill this) =>
safe_delete(this)
this.support.delete()
safe_delete_all(this) =>
if not na(this)
for item in this
item.delete()
this
//@function Removes the representations of an array of objects from the chart.
export method delete (line[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete (label[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete (box[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete (linefill[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete(Line[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete(Label[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete(CenterLabel[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete(LineFill[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
export method delete(Box[] this) => safe_delete_all(this)
//@function Removes the representations of an array of objects from the chart.
///////////////////////////////////////////////////////
//#endregion OBJECT REMOVAL
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//#region OBJECT TO BUILTIN draw
///////////////////////////////////////////////////////
method x(chart.point this, string xloc = xloc.bar_index) =>
if na(this)
na
else if xloc == xloc.bar_time
this.time
else
this.index
init_args(this) =>
if not na(this)
this.args := this.args.or_default()
//@function Adds/Updates the representations of an object to the chart.
//@param extend_only this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
export method draw(line this, chart.point a, chart.point b, LineArgs args, bool extend_only = true) =>
l = na(this) and not na(a) and not na(b) ? line.new(a, b, args.xloc, args.extend, args.line_color, args.style, args.width) : this
if not na(this)
if extend_only
l.set_y1(a.price)
else
l.set_first_point(a)
l.set_second_point(b)
l
//@function Adds/Updates the representations of an object to the chart.
export method draw(Label this) =>
init_args(this)
if not na(this)
this.plot := na(this.plot) ? label.new(this.point, this.txt, this.args.xloc, this.args.yloc, this.args.bg_color, this.args.style, this.args.text_color, this.args.size, this.args.text_align, this.tooltip) : this.plot
this.plot.set_point(this.point)
this.plot.set_text(this.txt)
this.plot.set_tooltip(this.tooltip)
this
//@function Adds/Updates the representations of an object to the chart.
export method draw(CenterLabel this) =>
if not na(this)
this.center_label.update(this.points.create_center())
this.center_label.draw()
this
//@function Adds/Updates the representations of an object to the chart.
//@param extend_only this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
export method draw(Line this, bool extend_only = true) =>
init_args(this)
if not na(this)
this.plot := this.plot.draw(this.start, this.end, this.args, extend_only)
this
//@function Adds/Updates the representations of an object to the chart.
//@param extend_only this will omit redrawing the left side of the box, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
export method draw(Box this, bool extend_only = true) =>
this.plot := na(this.plot) ? box.new(this.left_top, this.right_bottom, this.args.border_color, this.args.border_width, this.args.border_style, this.args.extend, this.args.xloc, this.args.bg_color, this.txt, this.text_args.text_size, this.text_args.text_color, this.text_args.text_halign, this.text_args.text_valign, this.text_args.text_wrap, this.text_args.text_font_family) : this.plot
if extend_only
this.plot.set_top(this.left_top.price)
else
this.plot.set_top_left_point(this.left_top)
this.plot.set_bottom_right_point(this.right_bottom)
this
//@function Adds/Replaces the representations of the object on the chart.
export method draw(LineFill this)=>
// no init, doesn't have args
if not na(this)
this.plot := na(this.plot) ? linefill.new(this.a.plot, this.needs_support and not na(this.support) ? this.support.draw().plot : this.b.plot, this.fill_color) : this.plot
if this.needs_support and not na(this.support)
this.support.draw()
this
draw_all(id) =>
for item in id
item.draw()
id
draw_all(id, extend_only) =>
for item in id
item.draw(extend_only)
id
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
export method draw(Label[] this) => draw_all(this)
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
export method draw(CenterLabel[] this) => draw_all(this)
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
export method draw(Line[] this, bool extend_only = true) => draw_all(this, extend_only)
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
export method draw(LineFill[] this) => draw_all(this)
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
export method draw(Box[] this, bool extend_only = true) => draw_all(this, extend_only)
//@function converts this object into a builtin plot object, drawing it on the chart, plot objects will be recycled, if you want them to stay, make a copy
_hide(chart.point point, drawable) =>
point.update(na,na,na)
drawable.draw()
//@function hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
export method hide(Label this) => _hide(this.point, this)
//@function hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
export method hide(CenterLabel this) => _hide(this.center_label.point, this)
//@function hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
export method hide(Line this) => _hide(this.end, this)
//@function hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
export method hide(Box this) => _hide(this.right_bottom, this)
export method apply_style(line this, LineArgs args) =>
if not na(this) and not na(args)
this.set_color(args.line_color)
this.set_style(args.style)
export method apply_style(label this, LabelArgs args) =>
if not na(this) and not na(args)
this.set_textcolor(args.text_color)
this.set_color(args.bg_color)
this.set_style(args.style)
export method apply_style(box this, BoxArgs args, BoxTextArgs text_args) =>
if not na(this)
if not na(args)
this.set_border_color(args.border_color)
this.set_border_style(args.border_style)
this.set_bgcolor(args.bg_color)
if not na(text_args)
this.set_text_color(text_args.text_color)
_apply_style(this, args) =>
if not na(this)
this.args := args
this.plot.apply_style(args)
this
//@function updates styles on this objects plot
export method apply_style(Label this, LabelArgs args) => _apply_style(this, args)
export method apply_style(CenterLabel this, LabelArgs args) => _apply_style(this.center_label, args)
export method apply_style(Line this, LineArgs args) => _apply_style(this, args)
//@function updates styles on this objects plot
export method apply_style(Box this, BoxArgs args, BoxTextArgs text_args) =>
if not na(this)
this.args := args
this.text_args := text_args
this.plot.apply_style(args, text_args)
this
_apply_style_all(this, args) =>
if not na(this)
for i in this
i.apply_style(args)
this
//@function updates styles on these objects' plots
export method apply_style(label[] this, LabelArgs args) => _apply_style_all(this, args)
//@function updates styles on these objects' plots
export method apply_style(Label[] this, LabelArgs args) => _apply_style_all(this, args)
//@function updates styles on these objects' plots
export method apply_style(CenterLabel[] this, LabelArgs args) => _apply_style_all(this, args)
//@function updates styles on these objects' plots
export method apply_style(line[] this, LineArgs args) => _apply_style_all(this, args)
//@function updates styles on these objects' plots
export method apply_style(Line[] this, LineArgs args) => _apply_style_all(this, args)
//@function updates styles on these objects' plots
export method apply_style(Box[] this, BoxArgs args, BoxTextArgs text_args) =>
if not na(this)
for i in this
i.apply_style(args, text_args)
this
///////////////////////////////////////////////////////
//#endregion OBJECT TO BUILTIN
///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// DEMO
/////////////////////////////////////////////////////////
chart.point now = chart.point.now()
plot(now.time, 'point time', display = display.data_window)
plot(now.index, 'point bar index', display = display.data_window)
plot(now.price, 'point price', display = display.data_window)
float hhp = ta.highest(high, 30)
float llp = ta.lowest(low, 30)
int hhi = ta.highestbars(high, 30)
int lli = ta.lowestbars(low, 30)
// HACK via differing price, otherwise function returns same instance for all points
var chart.point p1 = chart.point.now(2)
var chart.point p2 = chart.point.now(3)
var chart.point p3 = chart.point.now(4)
var chart.point p4 = chart.point.now(5)
var chart.point hh = chart.point.now(6)
var chart.point hhe = chart.point.now(7)
var chart.point ll = chart.point.now(8)
var chart.point lle = chart.point.now(9)
var Label l_hh = hh.create_label('hh', LabelArgs.new())
var Label l_ll = ll.create_label('ll', LabelArgs.new(style = label.style_label_up))
var Label l_p1 = p1.create_label('p1')
var Label l_p2 = p2.create_label('p2')
var Label l_p3 = p3.create_label('p3')
var Label l_p4 = p4.create_label('p4')
var Line lhh = Line.new(hh, hhe, LineArgs.new(color.red))
var Line lll = Line.new(ll, lle, LineArgs.new(color.green))
var Line l2 = na // (p3, p2)
// // single point update
// var chart.point latest_point = now.copy()
// var Label latest = latest_point.create_label('latest').draw()
// latest_point.update()
// latest.draw()
if barstate.islast
p1.update(time[0], bar_index[0], high[0])
p2.update(time[20], bar_index[20], high[20])
p3.update(time[30], bar_index[30], high[30])
p4.update(time[40], bar_index[40], high[40])
hh.update(time[-hhi], bar_index[-hhi], hhp)
ll.update(time[-lli], bar_index[-lli], llp)
hhe.update(time, bar_index, hhp)
lle.update(time, bar_index, llp)
// label update indirect, still same point, but point was updated
l_hh.draw()
l_ll.draw()
l_p1.draw()
l_p2.draw()
// label update with new point
l_p3.update(p3).draw()
l_p4.update(p4).draw()
// line update indirect
lhh.draw(extend_only = false) // based on updated point instances hh and hhe
lll.draw(extend_only = false) // based on updated point instances ll and lle
// updating center label positions
var Label l_lhh = lhh.create_label('hh line\ncenter')
l_lhh.update(lhh.create_center()).draw() // line center label needs update, since center is a separate point
var CenterLabel l_lll = lll.create_center_label('ll line\ncenter', LabelArgs.new(style = label.style_label_up))
l_lll.draw() // line center updated in draw()
// test delayed init/plot
l2 := na(l2) ? Line.new(p3, p2, LineArgs.new(color.fuchsia, width = 3)) : l2
l2.draw(extend_only = false)
var CenterLabel l_l2 = l2.create_center_label('🏂\n', LabelArgs.new(size = size.large, style = label.style_label_center))
l_l2.draw()
// test nested scope
var chart.point fix3 = p3.copy()
var chart.point fix4 = p4.copy()
var Label l_fixp3 = fix3.create_label('fix 3').draw() // draw once
var Label l_fixp4 = fix4.create_label('fix 4').draw() // draw once
// extend only
var chart.point p_dyn = chart.point.now(1)
p_dyn.update()
var Line l_dyn = Line.new(fix4, p_dyn)
l_dyn.draw()
var CenterLabel cl_dyn = l_dyn.create_center_label('cl_dyn')
cl_dyn.draw()
// line fill test between dynamic lines
var LineFill lf12 = lll.create_fill(l2,color.new(color.gray, 70))
lf12.draw()
var Box b1 = p4.create_box(p3, 'box', BoxArgs.new(bg_color = #00000000)) // expanding box, with one fix point p3 and one updating point p1
b1.draw(extend_only = false)
var Box b2 = p4.create_box(p3, 'boxt', BoxArgs.new(bg_color = #00000000, xloc = xloc.bar_time)) // expanding box, with one fix point p3 and one updating point p1
if bar_index % 2 == 0
b2.hide()
b2.draw()
|
merge_pinbar_modified | https://www.tradingview.com/script/AKBK7E8V-merge-pinbar-modified/ | RpNm1337 | https://www.tradingview.com/u/RpNm1337/ | 1 | 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/
// © dandrideng
// modified by RpNm1337
//@version=5
// @description merge_pinbar: merge bars and check whether the bar is a pinbar
library("merge_pinbar", overlay=true)
// @function merge_pinbar: merge bars and check whether the bar is a pinbar
// @param simple int period: the statistic bar period
// @param simple int max_bars: the max bars to be merged
// @returns array: [bar_type, bar_num, pbar_strength]
export merge_pinbar(simple int period, simple int max_bars) =>
float upperwick = open > close ? high - open: high - close
float lowerwick = open > close ? close - low: open - low
float candlebody = open > close ? open - close: close - open
float totalbody = high - low
float upperwick_ma = ta.sma(upperwick, period)
float lowerwick_ma = ta.sma(lowerwick, period)
float candlebody_ma = ta.sma(candlebody, period)
float totalbody_ma = ta.sma(totalbody, period)
int pbar_type = 0
int pbar_num = 0
float pbar_strength = 0.0
for bars = 1 to max_bars
float _open = open[bars - 1]
float _high = ta.highest(high, bars)
float _low = ta.lowest(low, bars)
float _close = close
float _upperwick = _open > _close ? _high - _open: _high - _close
float _lowerwick = _open > _close ? _close - _low: _open - _low
float _candlebody = _open > _close ? _open - _close: _close - _open
float _totalbody = _high - _low
float _upperwick_ratio = _upperwick / upperwick_ma
float _lowerwick_ratio = _lowerwick / lowerwick_ma
float _candlebody_ratio = _candlebody / candlebody_ma
float _totalbody_ratio = _totalbody / totalbody_ma
if _candlebody_ratio < 3.0 and _upperwick_ratio < 2.0 and _lowerwick / _candlebody > 2.0
pbar_type := 1
pbar_num := bars
pbar_strength := math.log(_lowerwick / _candlebody - _upperwick / _candlebody * 2.0) * _totalbody_ratio
break
else if _candlebody_ratio < 3.0 and _lowerwick_ratio < 2.0 and _upperwick / _candlebody > 2.0
pbar_type := -1
pbar_num := bars
pbar_strength := math.log(_upperwick / _candlebody - _lowerwick / _candlebody * 2.0) * _totalbody_ratio
break
else
continue
[pbar_type, pbar_num, pbar_strength] |
Extended Moving Average (MA) Library | https://www.tradingview.com/script/bvNwsfA7-Extended-Moving-Average-MA-Library/ | gotbeatz26107 | https://www.tradingview.com/u/gotbeatz26107/ | 10 | 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/
// © gotbeatz26107
//@version=5
// @description This library is made to expand traders moving average arsenal.
library("ma_")
// Simple Moving Average
export sma(float src, simple int length) =>
// Input
sma = src
// Calculation
for i = 0 to length - 1
sma += src[i] / length
// Output
sma
//
export sma(float src, series int length) =>
// Input
sma = src
// Calculation
for i = 0 to length - 1
sma += src[i] / length
// Output
sma
//
// Ehlers Instantaneous Trendline
export eit(float src) =>
// Input
ma = src
eit_alpha = 0.07
// Calculation
ma := bar_index < 7 ? (src + (2 * nz(src[1])) + nz(src[2])) / 4 : ((0.07 - (math.pow(eit_alpha, 2) / 4)) * src)
+ (0.5 * math.pow(eit_alpha, 2) * nz(src[1])) - ((eit_alpha - (0.75 * math.pow(eit_alpha, 2))) * nz(src[2]))
+ (2 * (1 - eit_alpha) * nz(ma[1])) - (math.pow(1 - eit_alpha, 2) * nz(ma[2]))
// Output
ma
//
// Exponential moving Average
export ema(float src, simple int length) =>
// Input
ema = src
// Calculation
ema := na(ema[1]) ? src : (src - nz(ema[1])) * (2 / (length + 1)) + nz(ema[1])
// Output
ema
//
export ema(float src, series int length) =>
// Input
ema = src
// Calculation
ema := na(ema[1]) ? src : (src - nz(ema[1])) * (2 / (length + 1)) + nz(ema[1])
// Output
ema
//
// Ahrens Moving Average
export ahma(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := nz(ma[1]) + (src - (nz(ma[1]) + nz(ma[length])) / 2) / length
// Output
ma
//
export ahma(float src, series int length) =>
// Input
ma = src
// Calculation
ma := nz(ma[1]) + (src - (nz(ma[1]) + nz(ma[length])) / 2) / length
// Output
ma
//
// Blackman Filter
export bmf(float src, simple int length) =>
// Input
ma = src
bmf_sum = 0.0
bmf_sumw = 0.0
// Calculation
for i = 0 to length - 1
k = i / length
w = 0.42 - 0.5 * math.cos(2 * math.pi * k) + 0.08 * math.cos(4 * math.pi * k)
bmf_sumw := bmf_sumw + w
bmf_sum := bmf_sum + w*src[i]
ma := bmf_sum / bmf_sumw
// Output
ma
//
export bmf(float src, series int length) =>
// Input
ma = src
bmf_sum = 0.0
bmf_sumw = 0.0
// Calculation
for i = 0 to length - 1
k = i / length
w = 0.42 - 0.5 * math.cos(2 * math.pi * k) + 0.08 * math.cos(4 * math.pi * k)
bmf_sumw := bmf_sumw + w
bmf_sum := bmf_sum + w*src[i]
ma := bmf_sum / bmf_sumw
// Output
ma
//
// Corrective MA
export cma(float src, simple int length) =>
// Input
ma = sma(src, length)
// Calculation
v1 = ta.variance(src, length)
v2 = math.pow(nz(ma[1], ma) - ma, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
ma := nz(ma[1], src) + k * (ma - nz(ma[1], src))
// Output
ma
//
export cma(float src, series int length) =>
// Input
ma = sma(src, length)
// Calculation
v1 = ta.variance(src, length)
v2 = math.pow(nz(ma[1], ma) - ma, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
ma := nz(ma[1], src) + k * (ma - nz(ma[1], src))
// Output
ma
//
// Double Exponential Moving Average
export dema(float src, simple int length) =>
// Input
ma = src
// Calculation
e1 = ema(src, length)
e2 = ema(e1, length)
ma := 2 * e1 - e2
// Output
ma
//
export dema(float src, series int length) =>
// Input
ma = src
// Calculation
e1 = ema(src, length)
e2 = ema(e1, length)
ma := 2 * e1 - e2
// Output
ma
//
// Damped Sine Wave Weighted Filter
export dswf(float src, simple int length) =>
// Input
ma = src
dswf_sum = 0.0
dswf_sumw = 0.0
// Calculation
for i = 1 to length
w = math.sin(2.0*math.pi * i / length) / i
dswf_sumw := dswf_sumw + w
dswf_sum := dswf_sum + w*src[i-1]
ma := dswf_sum/dswf_sumw
// Output
ma
//
export dswf(float src, series int length) =>
// Input
ma = src
dswf_sum = 0.0
dswf_sumw = 0.0
// Calculation
for i = 1 to length
w = math.sin(2.0*math.pi * i / length) / i
dswf_sumw := dswf_sumw + w
dswf_sum := dswf_sum + w*src[i-1]
ma := dswf_sum/dswf_sumw
// Output
ma
//
// Elastic Volume Weighted MA
export evwma(float src, simple int length, float volume) =>
// Input
ma = src
volume_sum = math.sum(volume, length)
// Calculation
ma := ((volume_sum - volume) * nz(ma[1]) + volume * src ) / volume_sum
// Output
ma
//
export evwma(float src, series int length, float volume) =>
// Input
ma = src
volume_sum = math.sum(volume, length)
// Calculation
ma := ((volume_sum - volume) * nz(ma[1]) + volume * src ) / volume_sum
// Output
ma
//
// Ehlers Simple Decycler
export esd(float src, simple int length) =>
// Input
ma = src
eit_alpha = 0.07
// Calculation
alphaArg = 2 * math.pi / (length * math.sqrt(2))
alpha = 0.0
alpha := math.cos(alphaArg) != 0
? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg)
: nz(alpha[1])
hp = 0.0
hp := math.pow(1 - (alpha / 2), 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2])
ma := src - hp
// Output
ma
//
export esd(float src, series int length) =>
// Input
ma = src
eit_alpha = 0.07
// Calculation
alphaArg = 2 * math.pi / (length * math.sqrt(2))
alpha = 0.0
alpha := math.cos(alphaArg) != 0
? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg)
: nz(alpha[1])
hp = 0.0
hp := math.pow(1 - (alpha / 2), 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2])
ma := src - hp
// Output
ma
//
// Fractal Adaptive MA
export frama(float src, simple int length) =>
// Input
ma = src
// Calculation
length2 = math.floor(length / 2)
hh2 = ta.highest(length2)
ll2 = ta.lowest(length2)
N1 = (hh2 - ll2) / length2
N2 = (hh2[length2] - ll2[length2]) / length2
N3 = (ta.highest(length) - ta.lowest(length)) / length
D = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
factor = math.exp(-4.6 * (D - 1))
ma := factor * src + (1 - factor) * nz(ma[1])
// Output
ma
//
export frama(float src, series int length) =>
// Input
ma = src
// Calculation
length2 = math.floor(length / 2)
hh2 = ta.highest(length2)
ll2 = ta.lowest(length2)
N1 = (hh2 - ll2) / length2
N2 = (hh2[length2] - ll2[length2]) / length2
N3 = (ta.highest(length) - ta.lowest(length)) / length
D = (math.log(N1 + N2) - math.log(N3)) / math.log(2)
factor = math.exp(-4.6 * (D - 1))
ma := factor * src + (1 - factor) * nz(ma[1])
// Output
ma
//
// Fisher Least Squares MA
export flsma(float src, simple int len) =>
// Input
ma = src
// Calculation
e = ta.sma(math.abs(src - nz(ma[1])), len)
z = ta.sma(src - nz(ma[1], src), len) / e
r = (math.exp(2 * z) - 1) / (math.exp(2 * z) + 1)
a = (bar_index - ta.sma(bar_index, len)) / ta.stdev(bar_index, len) * r
ma := ta.sma(src, len) + a * ta.stdev(src, len)
// Output
ma
//
export flsma(float src, series int len) =>
// Input
ma = src
// Calculation
e = ta.sma(math.abs(src - nz(ma[1])), len)
z = ta.sma(src - nz(ma[1], src), len) / e
r = (math.exp(2 * z) - 1) / (math.exp(2 * z) + 1)
a = (bar_index - ta.sma(bar_index, len)) / ta.stdev(bar_index, len) * r
ma := ta.sma(src, len) + a * ta.stdev(src, len)
// Output
ma
//
// Geometric Mean MA
export gmma(float src, simple int length) =>
// Input
ma = src
// Calculation
lmean = math.log(src)
smean = math.sum(lmean, length)
ma := math.exp(smean / length)
// Output
ma
//
export gmma(float src, series int length) =>
// Input
ma = src
// Calculation
lmean = math.log(src)
smean = math.sum(lmean, length)
ma := math.exp(smean / length)
// Output
ma
//
// Hybrid Convolution Filter
export hcf(float src, simple int length) =>
// Input
ma = src
sum = 0.
// Calculation
for i = 1 to length
sgn = .5*(1 - math.cos((i/length)*math.pi))
sum := sum + (sgn*(nz(ma[1],src)) + (1 - sgn)*src[i-1]) * ( (.5*(1 - math.cos((i/length)*math.pi))) - (.5*(1 - math.cos(((i-1)/length)*math.pi))))
ma := sum
// Output
ma
//
export hcf(float src, series int length) =>
// Input
ma = src
sum = 0.
// Calculation
for i = 1 to length
sgn = .5*(1 - math.cos((i/length)*math.pi))
sum := sum + (sgn*(nz(ma[1],src)) + (1 - sgn)*src[i-1]) * ( (.5*(1 - math.cos((i/length)*math.pi))) - (.5*(1 - math.cos(((i-1)/length)*math.pi))))
ma := sum
// Output
ma
//
// Double Exponential Moving Average
export hma(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
// Output
ma
//
export hma(float src, series int length) =>
// Input
ma = src
// Calculation
ma := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
// Output
ma
//
// Jurik Moving Average
export jma(float src, simple int length) =>
// Input
ma = src
tmp0 = 0.0
tmp1 = 0.0
tmp2 = 0.0
tmp3 = 0.0
tmp4 = 0.0
// Calculation
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = beta
tmp0 := (1 - alpha) * src + alpha * nz(tmp0[1])
tmp1 := (src - tmp0[0]) * (1 - beta) + beta * nz(tmp1[1])
tmp2 := tmp0[0] + tmp1[0]
tmp3 := (tmp2[0] - nz(tmp4[1])) * (1 - alpha) * (1 - alpha) + alpha * alpha * nz(tmp3[1])
tmp4 := nz(tmp4[1]) + tmp3[0]
ma := tmp4
// Ouput
ma
//
export jma(float src, series int length) =>
// Input
ma = src
tmp0 = 0.0
tmp1 = 0.0
tmp2 = 0.0
tmp3 = 0.0
tmp4 = 0.0
// Calculation
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = beta
tmp0 := (1 - alpha) * src + alpha * nz(tmp0[1])
tmp1 := (src - tmp0[0]) * (1 - beta) + beta * nz(tmp1[1])
tmp2 := tmp0[0] + tmp1[0]
tmp3 := (tmp2[0] - nz(tmp4[1])) * (1 - alpha) * (1 - alpha) + alpha * alpha * nz(tmp3[1])
tmp4 := nz(tmp4[1]) + tmp3[0]
ma := tmp4
// Ouput
ma
//
// Kaufman's Adaptive Moving Average
export kama(float src, simple int length) =>
// Input
ma = src
fastAlpha = 3
fastAlpha_ = 2.0 / (fastAlpha + 1)
slowAlpha = 2.0 / 31
// Calculation
momentum = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
ratio = volatility != 0 ? momentum / volatility : 0
smoothing = math.pow(ratio * (fastAlpha_ - slowAlpha) + slowAlpha, 2)
ma := nz(ma[1], src) + smoothing * (src - nz(ma[1], src))
// Output
ma
//
export kama(float src, series int length) =>
// Input
ma = src
fastAlpha = 3
fastAlpha_ = 2.0 / (fastAlpha + 1)
slowAlpha = 2.0 / 31
// Calculation
momentum = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
ratio = volatility != 0 ? momentum / volatility : 0
smoothing = math.pow(ratio * (fastAlpha_ - slowAlpha) + slowAlpha, 2)
ma := nz(ma[1], src) + smoothing * (src - nz(ma[1], src))
// Output
ma
//
// Kijun-sen
export kijun(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := math.avg(ta.lowest(length), ta.highest(length))
// Output
ma
//
export kijun(float src, series int length) =>
// Input
ma = src
// Calculation
ma := math.avg(ta.lowest(length), ta.highest(length))
// Output
ma
//
// Least Squares MA
export lsma(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := ta.linreg(src, length, 0)
// Output
ma
//
export lsma(float src, series int length) =>
// Input
ma = src
// Calculation
ma := ta.linreg(src, length, 0)
// Output
ma
//
// Leo MA
export lma(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := 2 * ta.wma(src, length) - ta.sma(src, length)
// Output
ma
//
export lma(float src, series int length) =>
// Input
ma = src
// Calculation
ma := 2 * ta.wma(src, length) - ta.sma(src, length)
// Output
ma
//
// McGinley Dynamic
export md(float src, simple int length) =>
// Input
ma = 0.0
// Calculation
ma := na(ma[1]) ? ema(src, length) : ma[1] + (src - ma[1]) / (length * math.pow(src / ma[1], 4))
// Output
ma
//
export md(float src, series int length) =>
// Input
ma = 0.0
// Calculation
ma := na(ma[1]) ? ema(src, length) : ma[1] + (src - ma[1]) / (length * math.pow(src / ma[1], 4))
// Output
ma
//
// Modular Filter
export mf(float src, simple int length) =>
// Input
ma = 0.0
b = 0.0
c = 0.0
os = 0.0
ts = 0.0
// Calculation
alpha = 2 / (length + 1)
a = src
b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a)
c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a)
os := a == b ? 1 : a == c ? 0 : os[1]
upper = 0.8 * b + (1 - 0.8) * c
lower = 0.8 * c + (1 - 0.8) * b
ma := os*upper+(1-os)*lower
// Output
ma
//
export mf(float src, series int length) =>
// Input
ma = 0.0
b = 0.0
c = 0.0
os = 0.0
ts = 0.0
// Calculation
alpha = 2 / (length + 1)
a = src
b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a)
c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a)
os := a == b ? 1 : a == c ? 0 : os[1]
upper = 0.8 * b + (1 - 0.8) * c
lower = 0.8 * c + (1 - 0.8) * b
ma := os*upper+(1-os)*lower
// Output
ma
//
// Moving Median
export mm(float src, simple int length) =>
// Input
ma = 0.0
// Calculation
ma := ta.percentile_nearest_rank(src, length, 50)
// Output
ma
//
export mm(float src, series int length) =>
// Input
ma = 0.0
// Calculation
ma := ta.percentile_nearest_rank(src, length, 50)
// Output
ma
//
// The Smoothed Moving Average
export smma(float src, simple int length) =>
// Input
ma = src
// Calculation
smaval = sma(src, length)
ma := na(ma[1]) ? smaval : (ma[1] * (length - 1) + src) / length
// Output
ma
//
export smma(float src, series int length) =>
// Input
ma = src
// Calculation
smaval = sma(src, length)
ma := na(ma[1]) ? smaval : (ma[1] * (length - 1) + src) / length
// Output
ma
//
// Shapeshifting MA
export ssma(float src, simple int length) =>
// Input
ma = src
ssma_smooth = false
ssma_pow = 4.0
// Calculation
ssma_sum = 0.0
ssma_sumw = 0.0
alpha = ssma_smooth ? 2 : 1
power = ssma_smooth ? ssma_pow - ssma_pow % 2 : ssma_pow
for i = 0 to length - 1
x = i / (length - 1)
n = ssma_smooth ? -1 + x * 2 : x
w = 1 - 2 * math.pow(n,alpha)/(math.pow(n,power) + 1)
ssma_sumw := ssma_sumw + w
ssma_sum := ssma_sum + src[i] * w
ma := ssma_sum/ssma_sumw
// Output
ma
//
export ssma(float src, series int length) =>
// Input
ma = src
ssma_smooth = false
ssma_pow = 4.0
// Calculation
ssma_sum = 0.0
ssma_sumw = 0.0
alpha = ssma_smooth ? 2 : 1
power = ssma_smooth ? ssma_pow - ssma_pow % 2 : ssma_pow
for i = 0 to length - 1
x = i / (length - 1)
n = ssma_smooth ? -1 + x * 2 : x
w = 1 - 2 * math.pow(n,alpha)/(math.pow(n,power) + 1)
ssma_sumw := ssma_sumw + w
ssma_sum := ssma_sum + src[i] * w
ma := ssma_sum/ssma_sumw
// Output
ma
//
// Sine Weighted MA
export swma(float src, simple int length) =>
// Input
ma = src
sum = 0.0
sum_weight = 0.0
// Calculation
for i = 0 to length - 1
weight = math.sin(i * math.pi / (length + 1))
sum := sum + nz(src[i]) * weight
sum_weight := sum_weight + weight
ma := sum / sum_weight
// Output
ma
//
export swma(float src, series int length) =>
// Input
ma = src
sum = 0.0
sum_weight = 0.0
// Calculation
for i = 0 to length - 1
weight = math.sin(i * math.pi / (length + 1))
sum := sum + nz(src[i]) * weight
sum_weight := sum_weight + weight
ma := sum / sum_weight
// Output
ma
//
// Triangular Moving Average
export tma(float src, simple int length) =>
// Input
ma = src
// Calculation
ma := sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
// Output
ma
//
export tma(float src, series int length) =>
// Input
ma = src
// Calculation
ma := sma(sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
// Output
ma
//
// Triple Exponential MA
export tema(float src, simple int length) =>
// Input
e = ema(src, length)
ma = src
// Calculation
ma := 3 * (e - ema(e, length)) + ema(ema(e, length), length)
// Output
ma
//
export tema(float src, series int length) =>
// Input
e = ema(src, length)
ma = src
// Calculation
ma := 3 * (e - ema(e, length)) + ema(ema(e, length), length)
// Output
ma
//
// True Strength Force
export tsf(float src, simple int length) =>
// Input
ma = src
// Calculation
lrc = ta.linreg(src, length, 0)
lrc1 = ta.linreg(src, length, 1)
lrs = lrc - lrc1
ma := ta.linreg(src, length, 0) + lrs
// Output
ma
//
export tsf(float src, series int length) =>
// Input
ma = src
// Calculation
lrc = ta.linreg(src, length, 0)
lrc1 = ta.linreg(src, length, 1)
lrs = lrc - lrc1
ma := ta.linreg(src, length, 0) + lrs
// Output
ma
//
// Vector Autoregression MA
export varma(float src, simple int length) =>
// Input
ma = src
// Calculation
valpha = 2 / (length + 1)
vud1 = (src > src[1]) ? (src - src[1]) : 0
vdd1 = (src < src[1]) ? (src[1] - src) : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz( (vUD - vDD) / (vUD + vDD) )
ma := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(ma[1])
// Output
ma
//
export varma(float src, series int length) =>
// Input
ma = src
// Calculation
valpha = 2 / (length + 1)
vud1 = (src > src[1]) ? (src - src[1]) : 0
vdd1 = (src < src[1]) ? (src[1] - src) : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz( (vUD - vDD) / (vUD + vDD) )
ma := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(ma[1])
// Output
ma
//
// Volume Adjusted Moving Average
export vama(float src, simple int length) =>
// Input
ma = src
lookback = 12
// Calculation
mid = ema(src, length)
dev = src - mid
volUp = ta.highest(dev, lookback)
volDown = ta.lowest(dev, lookback)
ma := mid + math.avg(volUp, volDown)
// Output
ma
//
export vama(float src, series int length) =>
// Input
ma = src
lookback = 12
// Calculation
mid = ema(src, length)
dev = src - mid
volUp = ta.highest(dev, lookback)
volDown = ta.lowest(dev, lookback)
ma := mid + math.avg(volUp, volDown)
// Output
ma
//
// Volume Moving Average (Not applicable for price data)
export vma(float src, simple int length) =>
// Input
ma = src
// Calculation
valpha = 2 / (length + 1)
vud1 = src > src[1] ? src - src[1] : 0
vdd1 = src < src[1] ? src[1] - src : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz((vUD - vDD) / (vUD + vDD))
ma := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(ma[1])
// Output
ma
//
export vma(float src, series int length) =>
// Input
ma = src
// Calculation
valpha = 2 / (length + 1)
vud1 = src > src[1] ? src - src[1] : 0
vdd1 = src < src[1] ? src[1] - src : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz((vUD - vDD) / (vUD + vDD))
ma := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(ma[1])
// Output
ma
//
// Variable MA
export vbma(float src, simple int length) =>
// Input
ma = src
// Calculation
k = 1.0 / length
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = float(0.0)
mdmS = float(0.0)
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = float(0.0)
mdiS = float(0.0)
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = float(0.0)
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = ta.highest(iS, length)
llv = ta.lowest(iS, length)
d1 = hhv - llv
vI = (iS - llv)/d1
ma := (1 - k * vI) *nz(ma[1]) + k * vI * src
// Output
ma
//
export vbma(float src, series int length) =>
// Input
ma = src
// Calculation
k = 1.0 / length
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = float(0.0)
mdmS = float(0.0)
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = float(0.0)
mdiS = float(0.0)
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = float(0.0)
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = ta.highest(iS, length)
llv = ta.lowest(iS, length)
d1 = hhv - llv
vI = (iS - llv)/d1
ma := (1 - k * vI) *nz(ma[1]) + k * vI * src
// Output
ma
//
// Variable Index Dynamic Average
export vida(float src, simple int length) =>
// Input
ma = src
// Calculation
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), length)
downSum = math.sum(-math.min(mom, 0), length)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (length + 1)
ma := src * alpha * cmo + nz(ma[1]) * (1 - alpha * cmo)
// Output
ma
//
export vida(float src, series int length) =>
// Input
ma = src
// Calculation
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), length)
downSum = math.sum(-math.min(mom, 0), length)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (length + 1)
ma := src * alpha * cmo + nz(ma[1]) * (1 - alpha * cmo)
// Output
ma
//
// Quick MA
export qma(float src, simple int length) =>
// Input
ma = src
peak = length / 3
num = 0.0
denom = 0.0
// Calculation
for i = 1 to length + 1
mult = 0.0
if i <= peak
mult := i / peak
else
mult := (length + 1 - i) / (length + 1 - peak)
num := num + src[i - 1] * mult
denom := denom + mult
ma := (denom != 0.0) ? (num / denom) : src
// Output
ma
//
export qma(float src, series int length) =>
// Input
ma = src
peak = length / 3
num = 0.0
denom = 0.0
// Calculation
for i = 1 to length + 1
mult = 0.0
if i <= peak
mult := i / peak
else
mult := (length + 1 - i) / (length + 1 - peak)
num := num + src[i - 1] * mult
denom := denom + mult
ma := (denom != 0.0) ? (num / denom) : src
// Output
ma
//
// Repulsion MA
export rpma(float src, simple int len) =>
// Input
ma = src
// Calculation
ma := ta.sma(close, len * 3) + ta.sma(close, len * 2) - ta.sma(close, len)
// Output
ma
//
export rpma(float src, series int len) =>
// Input
ma = src
// Calculation
ma := ta.sma(close, len * 3) + ta.sma(close, len * 2) - ta.sma(close, len)
// Output
ma
//
// Right Sided Ricker MA
export rsrma(float src, simple int length) =>
// Input
ma = src
rsrma_sum = 0.0
rsrma_sumw = 0.0
rsrma_pw = 60.0
rsrma_width = rsrma_pw / 100 * length
// Calculation
for i = 0 to length - 1
w = (1 - math.pow(i/rsrma_width,2))*math.exp(-(i*i/(2*math.pow(rsrma_width,2))))
rsrma_sumw := rsrma_sumw + w
rsrma_sum := rsrma_sum + src[i] * w
ma := rsrma_sum/rsrma_sumw
// Output
ma
//
export rsrma(float src, series int length) =>
// Input
ma = src
rsrma_sum = 0.0
rsrma_sumw = 0.0
rsrma_pw = 60.0
rsrma_width = rsrma_pw / 100 * length
// Calculation
for i = 0 to length - 1
w = (1 - math.pow(i/rsrma_width,2))*math.exp(-(i*i/(2*math.pow(rsrma_width,2))))
rsrma_sumw := rsrma_sumw + w
rsrma_sum := rsrma_sum + src[i] * w
ma := rsrma_sum/rsrma_sumw
// Output
ma
//
// Zero Lag Exponential Moving Average
export zlema(float src, simple int length) =>
// Input
ma = src
// Calculation
linreg = ta.linreg(src, length, 0)
linregZ = ta.linreg(src, length, 1)
lrs = linreg - linregZ
ma := ta.linreg(src, length, 0) + lrs
// Output
ma
//
export zlema(float src, series int length) =>
// Input
ma = src
// Calculation
linreg = ta.linreg(src, length, 0)
linregZ = ta.linreg(src, length, 1)
lrs = linreg - linregZ
ma := ta.linreg(src, length, 0) + lrs
// Output
ma
//
// @function This function gives trader an instrument to test different kinds of moving averages on their strategy.
// @returns user selected moving average
export selector(float src, simple int length, string selectMA) =>
// MA selection
ma = src
if selectMA == 'SMA'
ma := ta.sma(src, length)
else if selectMA == 'EMA'
ma := ema(src, length)
else if selectMA == 'EIT'
ma := eit(src)
else if selectMA == 'ALMA'
ma := ta.alma(src, length, 0.85, 6)
else if selectMA == 'AHMA'
ma := ahma(src, length)
else if selectMA == 'BMF'
ma := bmf(src, length)
else if selectMA == 'CMA'
ma := cma(src, length)
else if selectMA == 'DEMA'
ma := dema(src, length)
else if selectMA == 'DSWF'
ma := dswf(src, length)
else if selectMA == 'ESD'
ma := esd(src, length)
else if selectMA == 'FRAMA'
ma := frama(src, length)
else if selectMA == 'FLSMA'
ma := flsma(src, length)
else if selectMA == 'GMMA'
ma := gmma(src, length)
else if selectMA == 'HCF'
ma := hcf(src, length)
else if selectMA == 'HMA'
ma := ta.hma(src, length)
else if selectMA == 'JMA'
ma := jma(src, length)
else if selectMA == 'KAMA'
ma := kama(src, length)
else if selectMA == 'KIJUN'
ma := kijun(src, length)
else if selectMA == 'LSMA'
ma := lsma(src, length)
else if selectMA == 'LMA'
ma := lma(src, length)
else if selectMA == 'MD'
ma := md(src, length)
else if selectMA == 'MF'
ma := mf(src, length)
else if selectMA == 'MM'
ma := mm(src, length)
else if selectMA == 'SMMA'
ma := smma(src, length)
else if selectMA == 'SSMA'
ma := ssma(src, length)
else if selectMA == 'SWMA'
ma := swma(src, length)
else if selectMA == 'TMA'
ma := tma(src, length)
else if selectMA == 'TEMA'
ma := tema(src, length)
else if selectMA == 'TSF'
ma := tsf(src, length)
else if selectMA == 'VAR'
ma := varma(src, length)
else if selectMA == 'VAMA'
ma := vama(src, length)
else if selectMA == 'VBMA'
ma := vbma(src, length)
else if selectMA == 'VIDA'
ma := vida(src, length)
else if selectMA == 'VMA'
ma := vma(src, length)
else if selectMA == 'VAMA'
ma := vama(src, length)
else if selectMA == 'VWMA'
ma := ta.vwma(src, length)
else if selectMA == 'WMA'
ma := ta.wma(src, length)
else if selectMA == 'QMA'
ma := qma(src, length)
else if selectMA == 'RPMA'
ma := rpma(src, length)
else if selectMA == 'RSRMA'
ma := rsrma(src, length)
else if selectMA == 'ZLEMA'
ma := zlema(src, length)
// Output
ma
//
export selector(float src, series int length, string selectMA) =>
// MA selection
ma = src
if selectMA == 'SMA'
ma := sma(src, length)
else if selectMA == 'EMA'
ma := ema(src, length)
else if selectMA == 'EIT'
ma := eit(src)
else if selectMA == 'ALMA'
ma := ta.alma(src, length, 0.85, 6)
else if selectMA == 'AHMA'
ma := ahma(src, length)
else if selectMA == 'BMF'
ma := bmf(src, length)
else if selectMA == 'CMA'
ma := cma(src, length)
else if selectMA == 'DEMA'
ma := dema(src, length)
else if selectMA == 'DSWF'
ma := dswf(src, length)
else if selectMA == 'ESD'
ma := esd(src, length)
else if selectMA == 'FRAMA'
ma := frama(src, length)
else if selectMA == 'FLSMA'
ma := flsma(src, length)
else if selectMA == 'GMMA'
ma := gmma(src, length)
else if selectMA == 'HCF'
ma := hcf(src, length)
// else if selectMA == 'HMA'
// ma := ta.hma(src, length)
else if selectMA == 'JMA'
ma := jma(src, length)
else if selectMA == 'KAMA'
ma := kama(src, length)
else if selectMA == 'KIJUN'
ma := kijun(src, length)
else if selectMA == 'LSMA'
ma := lsma(src, length)
else if selectMA == 'LMA'
ma := lma(src, length)
else if selectMA == 'MD'
ma := md(src, length)
else if selectMA == 'MF'
ma := mf(src, length)
else if selectMA == 'MM'
ma := mm(src, length)
else if selectMA == 'SMMA'
ma := smma(src, length)
else if selectMA == 'SSMA'
ma := ssma(src, length)
else if selectMA == 'SWMA'
ma := swma(src, length)
else if selectMA == 'TMA'
ma := tma(src, length)
else if selectMA == 'TEMA'
ma := tema(src, length)
else if selectMA == 'TSF'
ma := tsf(src, length)
else if selectMA == 'VAR'
ma := varma(src, length)
else if selectMA == 'VAMA'
ma := vama(src, length)
else if selectMA == 'VBMA'
ma := vbma(src, length)
else if selectMA == 'VIDA'
ma := vida(src, length)
else if selectMA == 'VMA'
ma := vma(src, length)
else if selectMA == 'VAMA'
ma := vama(src, length)
else if selectMA == 'VWMA'
ma := ta.vwma(src, length)
else if selectMA == 'WMA'
ma := ta.wma(src, length)
else if selectMA == 'QMA'
ma := qma(src, length)
else if selectMA == 'RPMA'
ma := rpma(src, length)
else if selectMA == 'RSRMA'
ma := rsrma(src, length)
else if selectMA == 'ZLEMA'
ma := zlema(src, length)
// Output
ma
//
selectMA = input.string("VWMA", options = ['SMA', 'EMA', 'ALMA', 'AHMA', 'BMF', 'DEMA', 'DSWF'
, 'EVWMA', 'ESD', 'FRAMA', 'FLSMA', 'GMMA', 'HCF', 'HMA', 'JMA', 'KAMA', 'KIJUN'
, 'LSMA', 'LMA', 'MD', 'MF', 'MM', 'SMMA', 'SSMA', 'SWMA', 'TEMA', 'TSF'
, 'VAR', 'VAMA', 'VMA', 'VBMA', 'VIDA', 'VWMA', 'WMA', 'QMA', 'RPMA'
, 'RSRMA', 'ZLEMA'], title = "General", group = 'Moving Averages')
sma = selector(close, 30, 'SMA')
ema = selector(close, 30, 'EMA')
vwma = selector(close, 30, 'VWMA')
jma = selector(close, 30, 'JMA')
selector = selector(close, 30, selectMA)
plot(sma, color = color.green)
plot(ema, color = color.teal)
plot(vwma, color = color.lime)
plot(jma, color = color.olive)
plot(selector, color = color.red) |
Volatility Trend (Zeiierman) | https://www.tradingview.com/script/ZrEdJ42P-Volatility-Trend-Zeiierman/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 296 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=5
indicator("Volatility Trend (Zeiierman)", overlay = true)
t1 = "Controls the period over which the trend is calculated. Lower values will make the trend more sensitive to price changes, while higher values will make it smoother."
t2 = "Controls the dynamic responsiveness of the trend. Higher values will make the trend adjust more slowly to price changes."
t3 = "The first value sets the scaling factor for volatility. A higher value will widen the distance between the trend lines and the price. \n\nThe second value: Sensitivity for volatility adjustment. Values range from 0 to 1; higher values make the bands more sensitive to volatility changes."
t4 = "Controls the degree of market squeeze taken into account. Higher values increase sensitivity."
t5 = "If enabled, the algorithm will focus on short-term trends suitable for scalping strategies."
trendControl = input.int(20, title="Trend Control", minval=1, maxval=500, inline="", group="Trend Settings", tooltip=t1)
trendDynamicControl = input.float(100, title="Trend Dynamic", minval = 8, maxval=500, inline="", group="Trend Settings", tooltip=t2)
volatilityControl = input.float(10, title="Volatility", minval = 0, inline="vol", group="Volatility Settings")
volatilitySensitivity = input.float(0.5, title= "Sensitivity", minval = 0, maxval = 1, step=0.1, inline="vol", group="Volatility Settings", tooltip=t3)
squeezeControl = input.int(1, title="Squeeze Control", minval=1, maxval=200, group="Advanced Settings", tooltip=t4)
shorttermtrend = input.bool(false, title="Enable Scalping Trend (For BTC)", group="Advanced Settings", tooltip=t5)
color_up = input.color(color.navy, title="Line ", inline="Line", group="Style")
color_dn = input.color(color.maroon, title="", inline="Line", group="Style")
color_upper = input.color(color.new(#862458, 10), title="Cloud ", inline="Cloud", group="Style")
color_lower = input.color(color.new(#493893, 10),title="", inline="Cloud", group="Style")
// Var
var float trend = 0.0
var int trendDirection = 0
// Function to calculate standard deviation
stddev_function(src_, p) =>
if bar_index < p - 1
0.0
else
sum = 0.0
for i = 0 to p - 1
sum := sum + src_[i]
mean = sum / p
sum_diff_sq = 0.0
for i = 0 to p - 1
sum_diff_sq := sum_diff_sq + math.pow(src_[i] - mean, 2)
stdev = shorttermtrend?math.sqrt(sum_diff_sq / close * p * squeezeControl) : math.sqrt(sum_diff_sq / p * squeezeControl)
// Function to determine the trend direction
trendDirectionFunction(dir) =>
dir - dir[1] > 0 ? 1 : (dir - dir[1] < 0 ? -1 : 0)
// Call Trend Direction
trendDirection := trendDirectionFunction(trend)
// Call Scaled StdDev
scaledStdDev = stddev_function(trend, trendControl) * volatilityControl
priceTrend = close - trend > 0 ? close - trend : trend - close
// Calculate the Trend
trendAdjustment = priceTrend>scaledStdDev?math.avg(close,trend):trendDirection * (scaledStdDev * (1/volatilityControl) * (1/trendDynamicControl)) + trend
trend := trendAdjustment
// Get Upper and Lower Bands
upper = trend + (volatilitySensitivity * scaledStdDev)
lower = trend - (volatilitySensitivity * scaledStdDev)
//Plot
trueTrend = trendDirection == trendDirection[1]
color_ = trendDirection == 1 ? color_up : color_dn
trend_ = plot(trueTrend?trend:na, title="Trend Line", color=color_)
upper_ = plot(trueTrend?upper:na, title="Upper Circle Line", color = color.new(color.black,100))
lower_ = plot(trueTrend?lower:na, title="Lower Circle Line", color = color.new(color.black,100))
fill(upper_, trend_, top_color = color_upper, bottom_color =color.new(na,100), top_value = upper, bottom_value = trend, title="Bg Upper Circle")
fill(trend_, lower_, top_color = color.new(na,100), bottom_color = color_lower, top_value = trend, bottom_value = lower, title="Bg Lower Circle")
|
Logical Trading Indicator V.1 | https://www.tradingview.com/script/QOYy2Xqt-Logical-Trading-Indicator-V-1/ | thelogicaldude | https://www.tradingview.com/u/thelogicaldude/ | 103 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thelogicaldude
// Logical Trading Indicator version 1.3 Release
//@version=5
indicator(title='Logical Trading Indicator V.1', shorttitle='LT Indicator V.1', overlay=true, timeframe="", timeframe_gaps=true)
// *********** ATR Settings for Trailing Stop Loss *************
// Input Variables
atr_multiple = input.float(2.0, title='ATR Multiple', group="ATR Options", step=0.5, tooltip="The ATR Multiple determines the sensitivity of the alerts. A higher value will result in tighter stops, while a lower value will create wider stops. Suggested settings for 5min-1HR timeframes: 1.0-3.0. For 2HR and above: 2.0-5.0. Default value set to 3.0")
atr_per = input(4, title='ATR Period', group="ATR Options", tooltip='The ATR Period determines the number of periods used to calculate the Average True Range (ATR). A higher value will consider more historical data, providing a smoother ATR line, but it may respond more slowly to recent price changes. A lower value will make the ATR line more sensitive to recent price changes, but it might generate more false signals. Suggested settings for 5min-1HR timeframes: 5-15. 2HR and above: 20-50. Default value set to 7')
// Calculate ATR (Average True Range) and determine the loss value
atr_val = ta.atr(atr_per)
stopLoss = atr_multiple * atr_val
// Use regular candlesticks as the data source
hsrc = close
// Calculate the trailing stop based on price movements
ATRTrailingStop = 0.0
val_1 = hsrc > nz(ATRTrailingStop[1], 0) ? hsrc - stopLoss : hsrc + stopLoss
val_2 = hsrc < nz(ATRTrailingStop[1], 0) and hsrc[1] < nz(ATRTrailingStop[1], 0) ? math.min(nz(ATRTrailingStop[1]), hsrc + stopLoss) : val_1
ATRTrailingStop := hsrc > nz(ATRTrailingStop[1], 0) and hsrc[1] > nz(ATRTrailingStop[1], 0) ? math.max(nz(ATRTrailingStop[1]), hsrc - stopLoss) : val_2
// Determine the position (buy, sell, or hold)
pos = 0
val_3 = hsrc[1] > nz(ATRTrailingStop[1], 0) and hsrc < nz(ATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)
pos := hsrc[1] < nz(ATRTrailingStop[1], 0) and hsrc > nz(ATRTrailingStop[1], 0) ? 1 : val_3
// ************ Bollinger Bands ***************
// Bollinger Bands Options
basis_type = input.string("EMA", title="Basis Type", options=["SMA", "EMA"], group = "Bollinger Band Options", tooltip = 'Choose if you want the Bollinger Band to be based on a simple or exponential moving average.')
basis_length = input.int(18, minval=1, group = "Bollinger Band Options", tooltip = 'Set the length of the Bollinger Band basis moving average. The lower the number, the more sensitive to price action. Default value is 20.')
BB_src = input(close, title="BB Source")
mult = input.float(2, minval=0.001, maxval=50, title="StdDev", group = "Bollinger Band Options", step = 0.25, tooltip='Standard deviation multiplier for calculating the upper and lower Bollinger Bands. Lower values make the bands more sensitive to price action. Default value: 2.')
mult2 = mult + 1
offset = input.int(0, "Offset", minval = -500, maxval = 500, group = "Bollinger Band Options", tooltip="Bollinger Band offset. Enter a positive value to shift the bands to the right, a negative value to shift them to the left, and 0 to keep them at their original position. This can be used to prevent overlap of other indicators, anticipate price action, and can be used in backtesting.")
// Calculate the basis based on the selected basis type
basis = basis_type == "EMA" ? ta.ema(BB_src, basis_length) : ta.sma(BB_src, basis_length)
dev = mult * ta.stdev(BB_src, basis_length)
dev2 = mult2 * ta.stdev(BB_src, basis_length)
upper = basis + dev
upper2 = basis + dev2
lower = basis - dev
lower2 = basis - dev2
// Input variable to toggle Bollinger Bands visibility
showBollingerBands = input(true, title="Show Bollinger Bands", group = "Bollinger Band Options", tooltip="Toggle the visibility of the upper and lower Bollinger Bands. The basis line will remain and can be toggled in the style settings.")
// Input variables for Bollinger Bands colors
upperBandColor = input(color.rgb(255, 255, 255, 80), title="Upper Band Color", group = "Bollinger Band Options", inline="1")
lowerBandColor = input(color.rgb(255, 255, 255, 80), title="Lower Band Color", group = "Bollinger Band Options", inline="1")
// Plotting Bollinger Bands on the chart
basis_color = close > basis ? color.green : color.red
plot(basis, "Basis", color=basis_color, offset = offset, linewidth = 3)
p1 = plot(showBollingerBands ? upper : na, "Upper", color=upperBandColor, offset = offset)
p2 = plot(showBollingerBands ? lower : na, "Lower", color=lowerBandColor, offset = offset)
p3 = plot(showBollingerBands ? upper2 : na, "Upper2", color=upperBandColor, offset = offset)
p4 = plot(showBollingerBands ? lower2 : na, "Lower2", color=lowerBandColor, offset = offset)
// Setting fill colors of the upper and lower bands
fill(p1, p2, title = "Main Background", color=color.rgb(33, 149, 243, 96))
fill(p1, p3, title = "Upper Background", color= upperBandColor)
fill(p2, p4, title = "Lower Background", color= lowerBandColor)
// Setting crossover points based on the moving average from the Bolliner Band and the calculations from the trailing stop loss.
BasisEMA = ta.ema(hsrc, basis_length)
aboveBasis = ta.crossover(BasisEMA, ATRTrailingStop)
belowBasis = ta.crossunder(BasisEMA, ATRTrailingStop)
// ************ Momentum Indicator settings ************
// Additional Input to Enable/Disable Momentum Indicator Options
showBarColor = input(true, title='Show Momentum Bar Color', group="Momentum Indicator Options", tooltip = "Show bar color based on market momentum, bullish, bearish, or neutral which is consolidation.")
enable_consolidation = input.bool(false, "Enable Consolidation Filter", group="Momentum Indicator Options", tooltip="Enable this to turn off BUY and SELL signals during market consolidation. This keeps you out of trades during tight ranges.")
// Momentum Variables - Bollinger Band and Keltner Channel Squeeze
bbLength = basis_length
kcLength = basis_length
bbMult = 2.25
kcMult = 1.25
plot_length = 2000
// Making Calculations based on the Bollinger band and Keltner Channel settings. This shows consolidation in the market
[_, bbUpper, bbLower] = ta.bb(hsrc, bbLength, bbMult)
[_, kcUpper, kcLower] = ta.kc(hsrc, kcLength, kcMult)
bbkcSqueeze = bbLower > kcLower and bbUpper < kcUpper
momentum = bbLower < kcLower and bbUpper > kcUpper
noSqueeze = bbkcSqueeze == false and momentum == false
osc2 = ta.linreg(hsrc - math.avg(math.avg(ta.highest(high, kcLength), ta.lowest(low, kcLength)), ta.sma(hsrc, kcLength)), kcLength, 0)
signal = ta.sma(osc2, basis_length)
dir = osc2 - signal
// Determine the bar color based on the position status and squeeze status
candleColor = bbkcSqueeze or noSqueeze
barcolor(showBarColor ? (candleColor ? color.white : pos == 1 ? color.green : pos == -1 ? color.red : na) : na)
// ************ BUY and SELL Signals **************
// Define initial position
var int position = na
// Modify the buy and sell conditions to include the ATR-based filter and momentum condition
buy = hsrc > ATRTrailingStop and aboveBasis and (enable_consolidation == false or momentum)
sell = hsrc < ATRTrailingStop and belowBasis and (enable_consolidation == false or momentum)
// Check for position and generate signals accordingly
if buy
position := 1
else if sell
position := -1
// Filter multiple signals
buy := position[1] == -1 and buy
sell := position[1] == 1 and sell
// Plot buy and sell signals as shapes on the chart
plotshape(buy, title='Buy', style=shape.labelup, location=location.belowbar, color=color.green, size=size.small)
plotshape(sell, title='Sell', style=shape.labeldown, location=location.abovebar, color=color.red, size=size.small)
// ************ Take Profit Signals ***************
// Setting the Take Profit markers based on crossover or crossunder of the lower or upper bollinger band lines
longTakeProfit = ta.crossunder(hsrc, upper)
shortTakeProfit = ta.crossover(hsrc, lower)
// Variables to track if a longTakeProfit or shortTakeProfit has been plotted for the current buy or sell signal
var bool longTakeProfitPlotted = false
var bool shortTakeProfitPlotted = false
bool plotLongTakeProfit = false
bool plotShortTakeProfit = false
// Check for longTakeProfit condition and plotshape if it's true and not already plotted
if (longTakeProfit and not longTakeProfitPlotted)
plotLongTakeProfit := true
// Check for shortTakeProfit condition and plotshape if it's true and not already plotted
if (shortTakeProfit and not shortTakeProfitPlotted)
plotShortTakeProfit := true
// Update the longTakeProfitPlotted and shortTakeProfitPlotted
if (buy)
longTakeProfitPlotted := false
else
longTakeProfitPlotted := longTakeProfitPlotted or plotLongTakeProfit
if (sell)
shortTakeProfitPlotted := false
else
shortTakeProfitPlotted := shortTakeProfitPlotted or plotShortTakeProfit
// Plot take profit markers
plotshape(plotLongTakeProfit, title='Long Take Profit', text='TP', textcolor = color.green, style=shape.xcross, location=location.abovebar, color=color.green, size=size.tiny)
plotshape(plotShortTakeProfit, title='Short Take Profit', text='TP', textcolor = color.red, style=shape.xcross, location=location.belowbar, color=color.red, size=size.tiny)
// ************ Alert Conditions **************
alertcondition(buy, 'Buy Signal', '{{ticker}} | {{interval}} | Buy signal alert. Time to open a long position or close a short position, or both... Make sure the price is closing above the moving average.')
alertcondition(sell, 'Sell Signal', '{{ticker}} | {{interval}} | Sell signal alert. Time to close your long position or open short position, or both...Make sure the price is closing below the moving average.')
alertcondition(longTakeProfit, "Long Take Profit", "{{ticker}} | {{interval}} | Price has closed below the upper zone line of Bollinger Bands. Suggested Take Profit point for a LONG trade or early SHORT signal")
alertcondition(shortTakeProfit, "Short Take Profit", "{{ticker}} | {{interval}} | Price has closed above the lower zone line of Bollinger Bands. Suggested Take Profit point for SHORT trade or early LONG signal")
alertcondition(close > basis, "Bullish cross of basis line", "{{ticker}} | {{interval}} | Price has closed above the basis line of Bollinger Bands. Time to start paying attention for buy signals")
alertcondition(close < basis, "Bearish cross of basis line", "{{ticker}} | {{interval}} | Price has closed below the basis line of Bollinger Bands. Time to start paying attention for sell signals")
alertcondition(momentum and momentum[1] != momentum, "Momentum Release", "Momentum Release : {{ticker}} | {{interval}} | Momentum has picked up, check the direction of the release.") |
Blockunity Stablecoin Liquidity (BSL) | https://www.tradingview.com/script/PfKXjR25-Blockunity-Stablecoin-Liquidity-BSL/ | Blockunity | https://www.tradingview.com/u/Blockunity/ | 103 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Blockunity & HYVI LDA
//@version=5
indicator("Blockunity Stablecoin Liquidity (BSL)", format = format.volume, overlay = true, scale = scale.left)
//Inputs
display_mode = input.string(title = "Display Mode", defval = "Cumulative", options = ["Aggregated", "Cumulative", "Independent"], tooltip = "In Cumulative mode (default), the different capitalizations are displayed one on top of the other with colored bands. The Independent mode also displays the different capitalizations, but detached from each other with labels. Aggregated mode displays a single line, which is the sum of the different capitalizations, varying between green and red depending on the state of this data according to its moving average declared in the 'Aggregated MA Lengh' field.", group = "Global Settings")
USDT_color = input(color.new(#0c9b58, 50), title = "", inline = "11", group = "Data Settings")
USDT_input = input.bool(true, title = 'Tether (USDT)', inline = "11", tooltip = "Here you can choose whether or not to include Tether data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
USDC_color = input(color.new(#5085e0, 50), title = "", inline = "12", group = "Data Settings")
USDC_input = input.bool(true, title = 'USD Coin (USDC)', inline = "12", tooltip = "Here you can choose whether or not to include USD Coin data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
DAI_color = input(color.new(#cea315, 50), title = "", inline = "13", group = "Data Settings")
DAI_input = input.bool(true, title = 'Dai (DAI)', inline = "13", tooltip = "Here you can choose whether or not to include Dai data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
TUSD_color = input(color.new(#3639e9, 50), title = "", inline = "14", group = "Data Settings")
TUSD_input = input.bool(true, title = 'TrueUSD (TUSD)', inline = "14", tooltip = "Here you can choose whether or not to include TrueUSD data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
BUSD_color = input(color.new(#8b2dc2, 50), title = "", inline = "15", group = "Data Settings")
BUSD_input = input.bool(true, title = 'Binance USD (BUSD)', inline = "15", tooltip = "Here you can choose whether or not to include Binance USD data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
FRAX_color = input(color.new(#8d8c88, 50), title = "", inline = "16", group = "Data Settings")
FRAX_input = input.bool(true, title = 'Frax (FRAX)', inline = "16", tooltip = "Here you can choose whether or not to include Frax data, and configure its display color. Note that in 'Cumulative' display mode, the data is taken into account even if the box is unchecked.", group = "Data Settings")
BSL_ma_len = input.int(defval = 100, title = "Aggregated MA Lengh (Days)", tooltip = "Allows you to configure the length (in days) of the moving average, varying the color of the line when the display mode selected is 'Aggregated'. The green color is intended to indicate a positive recovery/upward trend in the overall capitalization of Stablecoins, while a red color shows a decrease/bearish trend.", display = display.none, group = "Aggregated Settings")
showLabels = input.bool(defval = true, title = "Display Line Labels", tooltip = "Display or not labels. Works only when 'Display Mode' is set to 'Independent'.", group = "Labels Settings")
labels_offset = input.int(defval = 8, title = "Labels Offset", tooltip = "Indicate here the desired offset in the display of the labels. 8 by default.", display = display.none, group = "Labels Settings")
//Table Inputs
tableShow = input.bool(defval = true, title = "Display Table", group = "Table Settings")
table_position = input.string(title = 'Table Position', defval = 'Top Right', options = ['Top Right', 'Top Center', 'Top Left', 'Middle Right', 'Middle Center', 'Middle Left', 'Bottom Right', 'Bottom Center', 'Bottom Left'], display = display.none, group = "Table Settings")
tableTextSize = input.string(title = 'Table Text Size', defval = 'Normal', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], display = display.none, group = "Table Settings")
positiveColor = input(color.rgb(8, 153, 129, 30), title = "Positive Color", group = "Table Settings")
negativeColor = input(color.rgb(242, 54, 69, 30), title = "Negative Color", group = "Table Settings")
bgTopCellColor = input(color.rgb(120, 123, 134, 20), title = "Top Cell Background Color", group = "Table Settings")
bgCellColor = input(color.rgb(120, 123, 134, 40), title = "Cell Background Color", group = "Table Settings")
tableTextColor = input(color.rgb(255, 255, 255), title = "Text Color", group = "Table Settings")
tableSpace = input.int(defval = 2, minval = 0, step = 1, title = "Table Spacing", display = display.none, group = "Table Settings")
script_version = input.string(defval = "v1.0", title = "Script Version", options = ["v1.0"], display = display.none, tooltip = "This parameter is only there to indicate the version of the script for support purposes, it cannot be modified.", group = "Version")
//Inputs Override
if display_mode == "Cumulative"
USDT_input := true
USDC_input := true
DAI_input := true
TUSD_input := true
BUSD_input := true
FRAX_input := true
//Data
get_data(input, mcap_data) =>
mcap = input ? nz(request.security(mcap_data, "D", close)) : 0
USDT_mcap = get_data(USDT_input, "USDT_MARKETCAP")
USDC_mcap = get_data(USDC_input, "USDC_MARKETCAP")
DAI_mcap = get_data(DAI_input, "DAI_MARKETCAP")
TUSD_mcap = get_data(TUSD_input, "CRYPTOCAP:TUSD")
BUSD_mcap = get_data(BUSD_input, "BUSD_MARKETCAP")
FRAX_mcap = get_data(FRAX_input, "CRYPTOCAP:FRAX")
BSL_sum = USDT_mcap + USDC_mcap + DAI_mcap + TUSD_mcap + BUSD_mcap + FRAX_mcap
//Value
BSL_value = display_mode == "Aggregated" ? BSL_sum : na
[USDT_value, USDC_value, DAI_value, TUSD_value, BUSD_value, FRAX_value] = switch display_mode
"Independent" => [USDT_mcap, USDC_mcap, DAI_mcap, TUSD_mcap, BUSD_mcap, FRAX_mcap]
"Cumulative" => [USDT_mcap, USDT_mcap + USDC_mcap, USDT_mcap + USDC_mcap + DAI_mcap, USDT_mcap + USDC_mcap + DAI_mcap + TUSD_mcap, USDT_mcap + USDC_mcap + DAI_mcap + TUSD_mcap + BUSD_mcap, USDT_mcap + USDC_mcap + DAI_mcap + TUSD_mcap + BUSD_mcap + FRAX_mcap]
"Aggregated" => [na, na, na, na, na, na]
//MA
BSL_ma = request.security(syminfo.tickerid, "D", ta.sma(BSL_sum, BSL_ma_len))
agg_color = BSL_sum > BSL_ma ? positiveColor : negativeColor
//Plot
plot_style = plot.style_line
plot(BSL_value, style = plot.style_line, linewidth = 2, color = agg_color, title = "Aggregated Stablecoin Marketcap")
USDT_plot = plot(USDT_input ? USDT_value : na, style = plot_style, linewidth = 2, color = USDT_color, title = "Tether (USDT) Marketcap")
USDC_plot = plot(USDC_input ? USDC_value : na, style = plot_style, linewidth = 2, color = USDC_color, title = "USD Coin (USDC) Marketcap")
DAI_plot = plot(DAI_input ? DAI_value : na, style = plot_style, linewidth = 2, color = DAI_color, title = "Dai (DAI) Marketcap")
TUSD_plot = plot(TUSD_input ? TUSD_value : na, style = plot_style, linewidth = 2, color = TUSD_color, title = "TrueUSD (TUSD) Marketcap")
BUSD_plot = plot(BUSD_input ? BUSD_value : na, style = plot_style, linewidth = 2, color = BUSD_color, title = "Binance USD (BUSD) Marketcap")
FRAX_plot = plot(FRAX_input ? FRAX_value : na, style = plot_style, linewidth = 2, color = FRAX_color, title = "Frax (FRAX) Marketcap")
//Fill
zero_value = 0
plot0 = plot(zero_value, color = color.black, title = "Zero Value", display = display.none)
fill(plot0, USDT_plot, color = USDT_color, title = "Tether (USDT) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
fill(USDT_plot, USDC_plot, color = USDC_color, title = "USD Coin (USDC) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
fill(USDC_plot, DAI_plot, color = DAI_color, title = "Dai (DAI) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
fill(DAI_plot, TUSD_plot, color = TUSD_color, title = "TrueUSD (TUSD) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
fill(TUSD_plot, BUSD_plot, color = BUSD_color, title = "Binance USD (BUSD) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
fill(BUSD_plot, FRAX_plot, color = FRAX_color, title = "Frax (FRAX) Marketcap", display = display_mode == "Cumulative" ? display.all : display.none)
//Labels
if showLabels and display_mode == "Independent"
if USDT_mcap > 0
USDT_label = label.new(x = bar_index + labels_offset, y = USDT_value, text = "Tether (USDT)", color = USDT_color, textcolor = tableTextColor)
label.delete(USDT_label[1])
if USDC_mcap > 0
USDC_label = label.new(x = bar_index + labels_offset, y = USDC_value, text = "USD Coin (USDC)", color = USDC_color, textcolor = tableTextColor)
label.delete(USDC_label[1])
if DAI_mcap > 0
DAI_label = label.new(x = bar_index + labels_offset, y = DAI_value, text = "Dai (DAI)", color = DAI_color, textcolor = tableTextColor)
label.delete(DAI_label[1])
if TUSD_mcap > 0
TUSD_label = label.new(x = bar_index + labels_offset, y = TUSD_value, text = "TrueUSD (TUSD)", color = TUSD_color, textcolor = tableTextColor)
label.delete(TUSD_label[1])
if BUSD_mcap > 0
BUSD_label = label.new(x = bar_index + labels_offset, y = BUSD_value, text = "Binance USD (BUSD)", color = BUSD_color, textcolor = tableTextColor)
label.delete(BUSD_label[1])
if FRAX_mcap > 0
FRAX_label = label.new(x = bar_index + labels_offset, y = FRAX_value, text = "Frax (FRAX)", color = FRAX_color, textcolor = tableTextColor)
label.delete(FRAX_label[1])
//Table
_table_position = switch table_position
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
=> position.bottom_right
_tableTextSize = switch tableTextSize
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
"Huge" => size.huge
=> size.normal
if tableShow == true
var Table = table.new(_table_position, columns = 3, rows = 8, border_width = tableSpace, border_color = color.new(color.white, 100))
table.cell(table_id = Table, column = 0, row = 0, bgcolor = bgTopCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Stablecoin Liquidity (BSL) by Blockunity")
table.merge_cells(Table, 0, 0, 2, 0)
table.cell(table_id = Table, column = 0, row = 1, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Aggregated")
table.cell(table_id = Table, column = 2, row = 1, bgcolor = agg_color, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", BSL_sum)))
table.merge_cells(Table, 0, 1, 1, 1)
table.cell(table_id = Table, column = 0, row = 2, bgcolor = USDT_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 2, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Tether (USDT)")
table.cell(table_id = Table, column = 2, row = 2, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", USDT_mcap)))
table.cell(table_id = Table, column = 0, row = 3, bgcolor = USDC_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 3, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "USD Coin (USDC)")
table.cell(table_id = Table, column = 2, row = 3, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", USDC_mcap)))
table.cell(table_id = Table, column = 0, row = 4, bgcolor = DAI_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 4, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Dai (DAI)")
table.cell(table_id = Table, column = 2, row = 4, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", DAI_mcap)))
table.cell(table_id = Table, column = 0, row = 5, bgcolor = TUSD_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 5, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "TrueUSD (TUSD)")
table.cell(table_id = Table, column = 2, row = 5, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", TUSD_mcap)))
table.cell(table_id = Table, column = 0, row = 6, bgcolor = BUSD_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 6, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Binance USD (BUSD)")
table.cell(table_id = Table, column = 2, row = 6, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", BUSD_mcap)))
table.cell(table_id = Table, column = 0, row = 7, bgcolor = FRAX_color, text_color = tableTextColor, text_size = _tableTextSize, text = " ")
table.cell(table_id = Table, column = 1, row = 7, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = "Frax (FRAX)")
table.cell(table_id = Table, column = 2, row = 7, bgcolor = bgCellColor, text_color = tableTextColor, text_size = _tableTextSize, text = str.tostring(str.format("{0,number,currency}", FRAX_mcap)))
|
multidata | https://www.tradingview.com/script/99bYm1PC-multidata/ | faiyaz7283 | https://www.tradingview.com/u/faiyaz7283/ | 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/
// © faiyaz7283
//@version=5
// @description A library for multi-dimensional data arrays.
library("multidata", overlay=true)
// Imports
import faiyaz7283/tools/9 as tools
import faiyaz7283/printer/6 as p
var ALT_ERROR = "Wrong data type is being used to set altVal. The altVal must match the original val type of "
var SET_ERROR = "Wrong data type is being used to set value. The value must match the original value type of "
var DK_PUSH_ERROR = "Total data key value missmatch. There must be a total of {0} new data key values, {1} provided."
// { Comparison calculation:
__et(orgVal, altVal) =>
// @function For *INTERNAL* use only.
tools._bool(orgVal == altVal)
__lte(orgVal, altVal) =>
// @function For *INTERNAL* use only.
tools._bool(orgVal <= altVal)
__lt(orgVal, altVal) =>
// @function For *INTERNAL* use only.
tools._bool(orgVal < altVal)
__gte(orgVal, altVal) =>
// @function For *INTERNAL* use only.
tools._bool(orgVal >= altVal)
__gt(orgVal, altVal) =>
// @function For *INTERNAL* use only.
tools._bool(orgVal > altVal)
__change(orgVal, altVal, bool percent) =>
// @function For *INTERNAL* use only.
result = orgVal - altVal
if percent
result := result / altVal * 100
result
__changeF(orgVal, altVal, bool percent, _type) =>
// @function For *INTERNAL* use only.
_else = _type == 'float' ? '{0,number,currency}' : '{0}'
format = percent ? "{0,number,0.00}%" : (_type == "timestamp" ? tools._getTimeDifference(tools._int(orgVal), tools._int(altVal)) : _else)
str.format(format, __change(orgVal, altVal, percent))
// }
// { Custom Key & Value Objects:
// Define `val` - A value storage. Allowed data types are string, float, int, bool.
// stringValue (string) A string value. Also, color values are converted and stored as string values. (`na` is used if no argument is supplied).
// floatValue (string) A float value. (`na` is used if no argument is supplied).
// intValue (string) An integer value. Both regular integer values as well as unix timestamp values (milliseconds), are stored as integer values. (`na` is used if no argument is supplied).
// boolValue (string) A boolean value. (`na` is used if no argument is supplied).
export type val
string stringValue = na
float floatValue = na
int intValue = na
bool boolValue = na
// Define `kv` - A key value pair storage.
// key (string) The key identifier.
// val (val) A value represented by the val object. Must contain one of the val properties: val.stringValue, val.floatValue, val.intValue, or val.boolValue.
// altVal (val) An alternate value represented by the val object. Must contain one of the val properties: val.stringValue, val.floatValue, val.intValue, or val.boolValue. (`na` is used if no argument is supplied).
// format (string) A custom string format for the val object. (`na` is used if no argument is supplied).
// changeFormat (string) A custom string format targeting the change value between original and alt value. (`na` is used if no argument is supplied).
// changePercentFormat (string) A custom string format targeting the change percent value between original and alt value. (`na` is used if no argument is supplied).
// dataType (string) The data type for the value. Possible values are string, float, int, bool, color, and timestamp. (`na` is used if no argument is supplied).
// value (string) The string version of the original value. (`na` is used if no argument is supplied).
// altValue (string) The string version of the original alt value. (`na` is used if no argument is supplied).
// formatValue (string) The formatted version of the original value. If no format is available, just uses string version.. (`na` is used if no argument is supplied).
// formatAltValue (string) The formatted version of the alternate value. If no format is available, just uses string version. (`na` is used if no argument is supplied).
// changeValue (float) The change between original and alt value. (`na` is used if no argument is supplied).
// changePercentValue (float) The change percent between original and alt value. (`na` is used if no argument is supplied).
// formatChangeValue (string) The formatted version of change between original and alt value. (`na` is used if no argument is supplied).
// formatChangePercentValue (string) The formatted version of change percent between original and alt value. (`na` is used if no argument is supplied).
// etValue (bool) Comparing 'equal to' between original and alt value. (`na` is used if no argument is supplied).
// ltValue (bool) Comparing 'less than' between original and alt value. (`na` is used if no argument is supplied).
// lteValue (bool) Comparing 'less than or equal to' between original and alt value. (`na` is used if no argument is supplied).
// gtValue (bool) Comparing 'greater than' between original and alt value. (`na` is used if no argument is supplied).
// gteValue (bool) Comparing 'greater than or equal to' between original and alt value. (`na` is used if no argument is supplied).
// timezone (string) A custom timezone for the value. Applies only for timestamp data types. (`na` is used if no argument is supplied).
// _tz (bool) An internal switch to determine if custom timezone is set for this object. (`false` is used if no argument is supplied).
export type kv
string key
val val
val altVal = na
string format = na
string changeFormat = na
string changePercentFormat = na
string dataType = na
string value = na
string altValue = na
string formatValue = na
string formatAltValue = na
float changeValue = na
float changePercentValue = na
string formatChangeValue = na
string formatChangePercentValue = na
bool etValue = na
bool ltValue = na
bool lteValue = na
bool gtValue = na
bool gteValue = na
string timezone = na
bool _tz = false
// Define `pkv` - A primary key value pair storage.
// primaryKey (string) The primary key identifier.
// dataKeys (array<string>) An array of data key identifiers.
// dataKeyTypes (array<string>) An array of data types asscociated with the object's data keys.
// kvs (array<kv>) An array of kv objects. They must adhere to this objects data keys and data key types.
export type pkv
string primaryKey
array<string> dataKeys
array<string> dataKeyTypes
array<kv> kvs
// }
// { kv() and alt() methods:
// @function The kv() method is utilized to construct a kv object. This method systematically constructs the kv object, ensuring that all of its properties are properly satisfied.
// @param this (string) A string object, representing a unique key identifier.
// @param val Any object of data type string, float, integer (including Unix timestamp), boolean and color.
// @param altVal Any object of data type string, float, integer (including Unix timestamp), boolean and color. (`na` is used if no argument is supplied).
// @param timestamp (bool) A boolean A boolean flag to indicate if the integer value is of timestamp data type. Use true for timestamp values. This parameter is only available with integer values (includes timestamps); for all other cases, not available. (`na` is used if no argument is supplied).
// @param timezone (string) A string representing timezone in UTC/GMT notation (e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). This parameter is only available with integer values (includes timestamps); for all other cases, not available. (`na` is used if no argument is supplied).
// @param format (string) A custom format. (`na` is used if no argument is supplied).
// @param changeFormat (string) A custom change format. (`na` is used if no argument is supplied).
// @param changePercentFormat (string) A custom change percent format. (`na` is used if no argument is supplied).
// @returns (kv) The `kv` object.
export method kv(string this, int val, int altVal=na, bool timestamp=na, string timezone=na, string format=na, string changeFormat=na, string changePercentFormat=na) =>
strVl = tools._str(val)
strAvl = not na(altVal) ? tools._str(altVal) : na
_timestamp = not na(timestamp) ? timestamp : false
_timezone = not na(timezone) ? timezone : syminfo.timezone
_tz = not na(timezone) ? true : false
vl = val.new(intValue = val)
avl = val.new(intValue = altVal)
vt = _timestamp ? "timestamp" : "int"
frmtVal = na(format) ? strVl : (_timestamp ? str.format_time(val, format, _timezone) : str.format(format, val))
frmtAltValue = (not na(altVal) and not na(format)) ? (_timestamp ? str.format_time(altVal, format, _timezone) : str.format(format, altVal)) : strAvl
float chngValue = na
float chngPercentValue = na
string frmtChngValue = na
string frmtChngPercentValue = na
bool etValue = na
bool ltValue = na
bool lteValue = na
bool gtValue = na
bool gteValue = na
if not na(altVal)
chngValue := __change(val, altVal, false)
chngPercentValue := __change(val, altVal, true)
if _timestamp
_cfKeys = not na(changeFormat) ? tools._commaSplit(changeFormat) : array.from('year', 'month', 'week', 'day', 'hour', 'minute', 'second')
years = _cfKeys.includes('year')
months = _cfKeys.includes('month')
weeks = _cfKeys.includes('week')
days = _cfKeys.includes('day')
hours = _cfKeys.includes('hour')
minutes = _cfKeys.includes('minute')
seconds = _cfKeys.includes('second')
frmtChngValue := tools._getTimeDifference(val, altVal, years, months, weeks, days, hours, minutes, seconds)
else
frmtChngValue := not na(changeFormat) ? str.format(changeFormat, chngValue) : __changeF(val, altVal, false, 'int')
frmtChngPercentValue := not na(changePercentFormat) ? str.format(changePercentFormat, chngValue) : __changeF(val, altVal, true, 'int')
etValue := __et(val, altVal)
ltValue := __lt(val, altVal)
lteValue := __lte(val, altVal)
gtValue := __gt(val, altVal)
gteValue := __gte(val, altVal)
kv.new(this, vl, avl, format, changeFormat, changePercentFormat, vt, strVl, strAvl, frmtVal, frmtAltValue, chngValue, chngPercentValue, frmtChngValue, frmtChngPercentValue, etValue, ltValue, lteValue, gtValue, gteValue, timezone, _tz)
export method kv(string this, string val, string altVal=na, string format=na, string changeFormat=na, string changePercentFormat=na) =>
vl = val.new(stringValue = val)
avl = val.new(stringValue = altVal)
frmtValue = not na(format) ? str.format(format, val) : val
frmtAltValue = not na(format) ? str.format(format, altVal) : altVal
float chngValue = na
float chngPercentValue = na
string frmtChngValue = na
string frmtChngPercentValue = na
bool etValue = na
bool ltValue = na
bool lteValue = na
bool gtValue = na
bool gteValue = na
if not na(altVal)
_val = str.length(val)
_altVal = str.length(altVal)
chngValue := __change(_val, _altVal, false)
chngPercentValue := __change(_val, _altVal, true)
frmtChngValue := not na(changeFormat) ? str.format(changeFormat, chngValue) : __changeF(_val, _altVal, false, 'string')
frmtChngPercentValue := not na(changePercentFormat) ? str.format(changePercentFormat, chngValue) : __changeF(_val, _altVal, true, 'string')
etValue := __et(_val, _altVal)
ltValue := __lt(_val, _altVal)
lteValue := __lte(_val, _altVal)
gtValue := __gt(_val, _altVal)
gteValue := __gte(_val, _altVal)
kv.new(this, vl, avl, format, changeFormat, changePercentFormat, 'string', val, altVal, frmtValue, frmtAltValue, chngValue, chngPercentValue, frmtChngValue, frmtChngPercentValue, etValue, ltValue, lteValue, gtValue, gteValue)
export method kv(string this, float val, float altVal=na, string format=na, string changeFormat=na, string changePercentFormat=na) =>
strVl = tools._str(val)
strAvl = tools._str(altVal)
vl = val.new(floatValue = val)
avl = val.new(floatValue = altVal)
frmtValue = not na(format) ? str.format(format, val) : strVl
frmtAltValue = not na(format) ? str.format(format, altVal) : strAvl
float chngValue = na
float chngPercentValue = na
string frmtChngValue = na
string frmtChngPercentValue = na
bool etValue = na
bool ltValue = na
bool lteValue = na
bool gtValue = na
bool gteValue = na
if not na(altVal)
chngValue := __change(val, altVal, false)
chngPercentValue := __change(val, altVal, true)
frmtChngValue := not na(changeFormat) ? str.format(changeFormat, chngValue) : __changeF(val, altVal, false, 'float')
frmtChngPercentValue := not na(changePercentFormat) ? str.format(changePercentFormat, chngValue) : __changeF(val, altVal, true, 'float')
etValue := __et(val, altVal)
ltValue := __lt(val, altVal)
lteValue := __lte(val, altVal)
gtValue := __gt(val, altVal)
gteValue := __gte(val, altVal)
kv.new(this, vl, avl, format, changeFormat, changePercentFormat, 'float', strVl, strAvl, frmtValue, frmtAltValue, chngValue, chngPercentValue, frmtChngValue, frmtChngPercentValue, etValue, ltValue, lteValue, gtValue, gteValue)
export method kv(string this, bool val, bool altVal=na, string format=na) =>
strVl = tools._str(val)
strAvl = tools._str(altVal)
vl = val.new(boolValue = val)
avl = val.new(boolValue = altVal)
frmtValue = not na(format) ? str.format(format, strVl) : strVl
frmtAltValue = not na(format) ? str.format(format, strAvl) : strAvl
kv.new(this, vl, avl, format, "bool", strVl, strAvl, frmtValue, frmtAltValue)
export method kv(string this, color val, color altVal=na, string format=na) =>
strVl = tools._str(val)
strAvl = tools._str(altVal)
vl = val.new(stringValue = strVl)
avl = val.new(stringValue = strAvl)
frmtValue = not na(format) ? str.format(format, strVl) : strVl
frmtAltValue = not na(format) ? str.format(format, strAvl) : strAvl
kv.new(this, vl, avl, format, "color", strVl, strAvl, frmtValue, frmtAltValue)
// @function Set alternate value for a `kv` object.
// @param this (kv) A `kv` object.
// @param altVal An object of type string, float, integer (including Unix timestamp), boolean, or color. It must match the data type of the kv object.
// @returns (kv) This `kv` object.
export method alt(kv this, int altVal) =>
if this.dataType != "int" and this.dataType != "timestamp"
runtime.error(ALT_ERROR + "'" + this.dataType + "'.")
strAvl = tools._str(altVal)
this.altVal := val.new(intValue = altVal)
this.altValue := strAvl
orgVal = this.val.intValue
chngValue = __change(orgVal, altVal, false)
chngPercentValue = __change(orgVal, altVal, true)
if this.dataType == "int"
this.formatAltValue := not na(this.format) ? str.format(this.format, altVal) : strAvl
this.formatChangeValue := not na(this.changeFormat) ? str.format(this.changeFormat, chngValue) : __changeF(orgVal, altVal, false, 'int')
else if this.dataType == "timestamp"
this.formatAltValue := not na(this.format) ? str.format_time(altVal, this.format) : strAvl
_cfKeys = not na(this.changeFormat) ? tools._commaSplit(this.changeFormat) : array.from('year', 'month', 'week', 'day', 'hour', 'minute', 'second')
years = _cfKeys.includes('year')
months = _cfKeys.includes('month')
weeks = _cfKeys.includes('week')
days = _cfKeys.includes('day')
hours = _cfKeys.includes('hour')
minutes = _cfKeys.includes('minute')
seconds = _cfKeys.includes('second')
this.formatChangeValue := tools._getTimeDifference(orgVal, altVal, years, months, weeks, days, hours, minutes, seconds)
this.formatChangePercentValue := not na(this.changePercentFormat) ? str.format(this.changePercentFormat, chngValue) : __changeF(orgVal, altVal, true, 'int')
this.etValue := __et(orgVal, altVal)
this.ltValue := __lt(orgVal, altVal)
this.lteValue := __lte(orgVal, altVal)
this.gtValue := __gt(orgVal, altVal)
this.gteValue := __gte(orgVal, altVal)
this
export method alt(kv this, string altVal) =>
if this.dataType != "string"
runtime.error(ALT_ERROR + "'" + this.dataType + "'.")
this.altVal := val.new(stringValue = altVal)
this.altValue := altVal
this.formatAltValue := not na(this.format) ? str.format(this.format, altVal) : altVal
_orgVal = str.length(this.val.stringValue)
_altVal = str.length(altVal)
chngValue = __change(_orgVal, _altVal, false)
chngPercentValue = __change(_orgVal, _altVal, true)
this.formatChangeValue := not na(this.changeFormat) ? str.format(this.changeFormat, chngValue) : __changeF(_orgVal, _altVal, false, 'string')
this.formatChangePercentValue := not na(this.changePercentFormat) ? str.format(this.changePercentFormat, chngValue) : __changeF(_orgVal, _altVal, true, 'string')
this.etValue := __et(_orgVal, _altVal)
this.ltValue := __lt(_orgVal, _altVal)
this.lteValue := __lte(_orgVal, _altVal)
this.gtValue := __gt(_orgVal, _altVal)
this.gteValue := __gte(_orgVal, _altVal)
this
export method alt(kv this, float altVal) =>
if this.dataType != "float"
runtime.error(ALT_ERROR + "'" + this.dataType + "'.")
strAvl = tools._str(altVal)
this.altVal := val.new(floatValue = altVal)
this.altValue := strAvl
this.formatAltValue := not na(this.format) ? str.format(this.format, altVal) : strAvl
orgVal = this.val.floatValue
chngValue = __change(orgVal, altVal, false)
chngPercentValue = __change(orgVal, altVal, true)
this.formatChangeValue := not na(this.changeFormat) ? str.format(this.changeFormat, chngValue) : __changeF(orgVal, altVal, false, 'float')
this.formatChangePercentValue := not na(this.changePercentFormat) ? str.format(this.changePercentFormat, chngValue) : __changeF(orgVal, altVal, true, 'float')
this.etValue := __et(orgVal, altVal)
this.ltValue := __lt(orgVal, altVal)
this.lteValue := __lte(orgVal, altVal)
this.gtValue := __gt(orgVal, altVal)
this.gteValue := __gte(orgVal, altVal)
this
export method alt(kv this, bool altVal) =>
if this.dataType != "bool"
runtime.error(ALT_ERROR + "'" + this.dataType + "'.")
strAvl = tools._str(altVal)
this.altVal := val.new(boolValue = altVal)
this.altValue := strAvl
this.formatAltValue := not na(this.format) ? str.format(this.format, strAvl) : strAvl
this
export method alt(kv this, color altVal) =>
if this.dataType != "color"
runtime.error(ALT_ERROR + "'" + this.dataType + "'.")
strAvl = tools._str(altVal)
this.altVal := val.new(stringValue = strAvl)
this.altValue := strAvl
this.formatAltValue := not na(this.format) ? str.format(this.format, strAvl) : strAvl
this
// @function The pkv() method is utilized to construct a `pkv` object, which is the preferred approach for generating `pkv` object. This method systematically constructs the pkv object, ensuring that all of its properties are properly satisfied.
// @param this (string) A string object, representing a unique primary key identifier.
// @param kvs (array<kv>) An array of `kv` objects.
// @returns (pkv) A `pkv` object.
export method pkv(string this, array<kv> kvs) =>
dataKeys = array.new<string>()
dataKeyTypes = array.new<string>()
for kV in kvs
dataKeys.push(kV.key)
dataKeyTypes.push(kV.dataType)
pkv.new(this, dataKeys, dataKeyTypes, kvs)
// }
// { Data2d:
// Define `data2d` - A two dimensional array of key-value data structure..
// kvs (array<kv>) An array of `kv` objects.
// keys (array<string>) An array of key identifiers. (`na` is used if no argument is supplied).
// values (array<string>) An array of converted main string values, formatted if applicable. (`na` is used if no argument is supplied).
// formatValues (array<string>) An array of string main values, formatted if applicable. (`na` is used if no argument is supplied).
// altValues (array<string>) An array of converted alternate string values, formatted if applicable. (`na` is used if no argument is supplied).
// formatAltValues (array<string>) An array of main string values, formatted if applicable. (`na` is used if no argument is supplied).
// stringValues (array<string>) An array of main string values. (`na` is used if no argument is supplied).
// stringAltValues (array<string>) An array of alternate string values. (`na` is used if no argument is supplied).
// floatValues (array<float>) An array of main float values. (`na` is used if no argument is supplied).
// floatAltValues (array<float>) An array of alternate float values. (`na` is used if no argument is supplied).
// intValues (array<int>) An array of main integer values. (`na` is used if no argument is supplied).
// intAltValues (array<int>) An array of alternate integer values. (`na` is used if no argument is supplied).
// boolValues (array<bool>) An array of main boolean values. (`na` is used if no argument is supplied).
// boolAltValues (array<bool>) An array of alternate boolean values. (`na` is used if no argument is supplied).
// colorValues (array<color>) An array of main color values. (`na` is used if no argument is supplied).
// colorAltValues (array<color>) An array of alternate color values. (`na` is used if no argument is supplied).
// timestampValues (array<int>) An array of main unix timestamp values. (`na` is used if no argument is supplied).
// timestampAltValues (array<int>) An array of alternate unix timestamp values. (`na` is used if no argument is supplied).
// changeValues (array<float>) An array of change values. (`na` is used if no argument is supplied).
// changePercentValues (array<float>) An array of change percent values. (`na` is used if no argument is supplied).
// formatChangeValues (array<string>) An array of formatted change values. (`na` is used if no argument is supplied).
// formatChangePercentValues (array<string>) An array of formatted change percent values. (`na` is used if no argument is supplied).
// etValues (array<bool>) An array of 'equal-to' values. (`na` is used if no argument is supplied).
// ltValues (array<bool>) An array of 'less-than' values. (`na` is used if no argument is supplied).
// lteValues (array<bool>) An array of 'less-than-or-equal-to' values. (`na` is used if no argument is supplied).
// gtValues (array<bool>) An array of 'greater-than' values. (`na` is used if no argument is supplied).
// gteValues (array<bool>) An array of 'greater-than-or-equal-to' values. (`na` is used if no argument is supplied).
// dataTypes (array<string>) An array of data types for each keys. (`na` is used if no argument is supplied).
// dataType (string) The data type representing all keys. Possible values are 'string', 'float', 'int', 'bool', 'color', 'timestamp', or 'mix'. 'mix' (`na` is used if no argument is supplied).
// size (int) Total size of a data2d object. (`na` is used if no argument is supplied).
// sorted (bool) A boolean flag to determine if the data2d object is sorted or not. (`na` is used if no argument is supplied).
// asc (bool) A boolean flag to determine if sorting is in ascending or descending order. Use 'true' for ascending and 'false' for descending. (`true` is used if no argument is supplied).
// change (bool) A boolean flag to determine if sorting uses change percent values. (`false` is used if no argument is supplied).
// format (string) A default string format for values. (`na` is used if no argument is supplied).
// formatTime (string) A default time format for timestamp values. (`yyyy-MM-dd hh:mm:ss a z` is used if no argument is supplied).
// changeFormat (string) A default string format targeting the change value between original and alt values. (`{0,number,currency}` is used if no argument is supplied).
// changePercentFormat (string) A default string format targeting the change percent value between original and alt values. (`{0,number,0.00}%` is used if no argument is supplied).
// changeTimestampFormat (string) A default string format targeting the change timestampr value between original and alt values. (`year,month,week,day,hour,minute,second` is used if no argument is supplied).
// index (array<int>) An array of integer values representing key index. If the object is sorted, the index will be in sorted order. (`na` is used if no argument is supplied).
// timezone (string) A default timezone value for the data2d object. (`syminfo.timezone` is used if no argument is supplied).
export type data2d
array<kv> kvs
array<string> keys = na
array<string> values = na
array<string> formatValues = na
array<string> altValues = na
array<string> formatAltValues = na
array<string> stringValues = na
array<string> stringAltValues = na
array<float> floatValues = na
array<float> floatAltValues = na
array<int> intValues = na
array<int> intAltValues = na
array<bool> boolValues = na
array<bool> boolAltValues = na
array<color> colorValues = na
array<color> colorAltValues = na
array<int> timestampValues = na
array<int> timestampAltValues = na
array<float> changeValues = na
array<float> changePercentValues = na
array<string> formatChangeValues = na
array<string> formatChangePercentValues = na
array<bool> etValues = na
array<bool> ltValues = na
array<bool> lteValues = na
array<bool> gtValues = na
array<bool> gteValues = na
array<string> dataTypes = na
string dataType = na
int size = na
bool sorted = na
bool asc = true
bool change = false
string format = na
string formatTime = "yyyy-MM-dd hh:mm:ss a z"
string changeFormat = "{0,number,currency}"
string changePercentFormat = "{0,number,0.00}%"
string changeTimestampFormat = "year,month,week,day,hour,minute,second"
array<int> index = na
string timezone = syminfo.timezone
// }
// { Data3d:
// Define `data3d` - A three dimensional array of primarykey-datakey-value data structure.
// data (array<data2d>) An array of `data2d` objects.
// primaryKeys (array<string>) An array of primary key identifiers. (`na` is used if no argument is supplied).
// dataKeys (array<string>) An array of data key identifiers. (`na` is used if no argument is supplied).
// dataKeyTypes (array<string>) An array of data types for each data keys. (`na` is used if no argument is supplied).
// dataType (string) The data type representing all data keys. Possible values are string, float, int, bool, color, timestamp, or mix. (`na` is used if no argument is supplied).
// size (int) Total size of the data3d object. (`na` is used if no argument is supplied).
// sorted (bool) A boolean flag to determine if the data3d object is sorted or not. (`na` is used if no argument is supplied).
// sortByKey (string) The data key used for sorting the data3d object. (`na` is used if no argument is supplied).
// asc (bool) A boolean flag to determine if sorting in ascending or descending order. Use true for ascending, and false for descending. (`true` is used if no argument is supplied).
// change (bool) A boolean flag to determine if sorting uses change percent values. (`false` is used if no argument is supplied).
// format (string) A default string format for values. (`na` is used if no argument is supplied).
// formatTime (string) A default time format for timestamp values. (`yyyy-MM-dd hh:mm:ss a z` is used if no argument is supplied).
// changeFormat (string) A default string format targeting the change value between original and alt values. (`{0,number,currency}` is used if no argument is supplied).
// changePercentFormat (string) A default string format targeting the change percent value between original and alt values. (`{0,number,0.00}%` is used if no argument is supplied).
// changeTimestampFormat (string) A default string format targeting the change timestampr value between original and alt values. (`year,month,week,day,hour,minute,second` is used if no argument is supplied).
// index (array<int>) An array of integer values representing primary key index. If the object is sorted, the index will be in sorted order. (`na` is used if no argument is supplied).
// timezone (string) A default timezone value for the data3d object. (`syminfo.timezone` is used if no argument is supplied).
export type data3d
array<data2d> data
array<string> primaryKeys = na
array<string> dataKeys = na
array<string> dataKeyTypes = na
string dataType = na
int size = na
bool sorted = na
string sortByKey = na
bool asc = true
bool change = false
string format = na
string formatTime = "yyyy-MM-dd hh:mm:ss a z"
string changeFormat = "{0,number,currency}"
string changePercentFormat = "{0,number,0.00}%"
string changeTimestampFormat = "year,month,week,day,hour,minute,second"
array<int> index = na
string timezone = syminfo.timezone
// }
// { Get keys and values:
// @function For *INTERNAL* use only.
__keyExist(data2d this, string key) =>
idx = this.keys.indexof(key)
exist = false
if idx != -1
exist := true
[idx, exist]
// @function For *INTERNAL* use only.
__dataKeyExist(data3d this, string key) =>
idx = this.dataKeys.indexof(key)
exist = false
if idx != -1
exist := true
[idx, exist]
// @function For *INTERNAL* use only.
__primaryKeyExist(data3d this, string key) =>
idx = this.primaryKeys.indexof(key)
exist = false
if idx != -1
exist := true
[idx, exist]
// @function For *INTERNAL* use only.
__existErrorCheck(bool exist, string key) =>
if not exist
runtime.error(str.format('Key "{0}" does not exist.', key))
// @function Get all the keys. Maintains sort order, if applicable.
// @param this (data2d) The `data2d` object.
// @returns (array<string>) All keys of a data2d object.
export method getKeys(data2d this) =>
keys = this.keys
result = keys
if this.sorted
result := array.new<string>()
for i in this.index
result.push(keys.get(i))
result
// @function Get all the key types. Maintains sort order, if applicable.
// @param this (data2d) The `data2d` object.
// @returns (array<string>) All key types of a data2d object.
export method keyTypes(data2d this) =>
types = this.dataTypes
result = types
if this.sorted
result := array.new<string>()
for i in this.index
result.push(types.get(i))
result
// @function Get all the primary keys. Maintains sort order, if applicable.
// @param this (data3d) The `data3d` object.
// @returns (array<string>) All primary keys of a data3d object.
export method primaryKeys(data3d this) =>
pks = this.primaryKeys
result = pks
if this.sorted
result := array.new<string>()
for i in this.index
result.push(pks.get(i))
result
// @function Get all the data keys.
// @param this (data3d) The `data3d` object.
// @returns (array<string>) All data keys of a data3d object.
export method dataKeys(data3d this) =>
this.dataKeys
// @function Get all the data key types.
// @param this (data3d) The `data3d` object.
// @returns (array<string>) All data key types of a data3d object.
export method dataKeyTypes(data3d this) =>
this.dataKeyTypes
// @function Get all values in string representation. Formatted and sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) All values from the data2d object.
export method values(data2d this, bool alt=false) =>
vals = alt ? this.formatAltValues : this.formatValues
result = vals
if this.sorted
result := array.new<string>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all values from the primary key in string representation. Formatted and sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Primary key values.
export method pkValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.formatAltValues : d2d.formatValues
// @function Get all values from the data key in string representation. Formatted, if applicable.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Data key values.
export method dkValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<string>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.formatAltValues.get(idx))
else
vals.push(d2d.formatValues.get(idx))
vals
// @function Get all string values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) All string values from the data2d object.
export method stringValues(data2d this, bool alt=false) =>
vals = alt ? this.stringAltValues : this.stringValues
result = vals
if this.sorted
result := array.new<string>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all string values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Primary key string values from the data3d object.
export method pkStringValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.stringAltValues : d2d.stringValues
// @function Get all string values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Primary key string values from the data3d object.
export method dkStringValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<string>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.stringAltValues.get(idx))
else
vals.push(d2d.stringValues.get(idx))
vals
// @function Get all float values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) All float values from the data2d object.
export method floatValues(data2d this, bool alt=false) =>
vals = alt ? this.floatAltValues : this.floatValues
result = vals
if this.sorted
result := array.new<float>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all float values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) Primary key float values from the data3d object.
export method pkFloatValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.floatAltValues : d2d.floatValues
// @function Get all float values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) Primary key float values from the data3d object.
export method dkFloatValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<float>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.floatAltValues.get(idx))
else
vals.push(d2d.floatValues.get(idx))
vals
// @function Get all integer values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) All integer values from the data2d object.
export method intValues(data2d this, bool alt=false) =>
vals = alt ? this.intAltValues : this.intValues
result = vals
if this.sorted
result := array.new<int>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all integer values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) Primary key integer values from the data3d object.
export method pkIntValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.intAltValues : d2d.intValues
// @function Get all integer values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) Primary key integer values from the data3d object.
export method dkIntValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<int>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.intAltValues.get(idx))
else
vals.push(d2d.intValues.get(idx))
vals
// @function Get all boolean values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<bool>) All boolean values from the data2d object.
export method boolValues(data2d this, bool alt=false) =>
alt ? this.boolAltValues : this.boolValues
// @function Get all boolean values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<bool>) Primary key boolean values from the data3d object.
export method pkBoolValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.boolAltValues : d2d.boolValues
// @function Get all boolean values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<bool>) Primary key boolean values from the data3d object.
export method dkBoolValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<bool>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.boolAltValues.get(idx))
else
vals.push(d2d.boolValues.get(idx))
vals
// @function Get all color values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<color>) All color values from the data2d object.
export method colorValues(data2d this, bool alt=false) =>
alt ? this.colorAltValues : this.colorValues
// @function Get all color values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<color>) Primary key color values from the data3d object.
export method pkColorValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.colorAltValues : d2d.colorValues
// @function Get all color values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<color>) Primary key color values from the data3d object.
export method dkColorValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<color>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.colorAltValues.get(idx))
else
vals.push(d2d.colorValues.get(idx))
vals
// @function Get all unix timestamp values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) All Unix timestamp values from the data2d object.
export method timestampValues(data2d this, bool alt=false) =>
vals = alt ? this.timestampAltValues : this.timestampValues
result = vals
if this.sorted
result := array.new<int>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all unix timestamp values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) Primary key timestamp values from the data3d object.
export method pkTimestampValues(data3d this, string primaryKey, bool alt=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
alt ? d2d.timestampAltValues : d2d.timestampValues
// @function Get all unix timestamp values from the data key.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param alt (bool) Set to true to obtain the alternate values instead. (`false` is used if no argument is supplied).
// @returns (array<int>) Primary key timestamp values from the data3d object.
export method dkTimestampValues(data3d this, string dataKey, bool alt=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<int>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
if alt
vals.push(d2d.timestampAltValues.get(idx))
else
vals.push(d2d.timestampValues.get(idx))
vals
// }
// { Get, getString, getFloat, getInt, getBool, getColor, getTimestamp
// @function Get string value from a specific key, formatted if applicable.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (string) A string value or `na` if not found.
export method get(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.formatAltValues.get(idx) : this.formatValues.get(idx)
// @function Get string value from a specific primary and data key, formatted if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (string) A string value or `na` if not found.
export method get(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.formatAltValues.get(dkIdx) : d2d.formatValues.get(dkIdx)
// @function Get string value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (string) A string value or `na` if not found.
export method getString(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.stringAltValues.get(idx) : this.stringValues.get(idx)
// @function Get string value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (string) A string value or `na` if not found.
export method getString(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.stringAltValues.get(dkIdx) : d2d.stringValues.get(dkIdx)
// @function Get float value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (float) A float value or `na` if not found.
export method getFloat(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.floatAltValues.get(idx) : this.floatValues.get(idx)
// @function Get float value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (float) A float value or `na` if not found.
export method getFloat(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.floatAltValues.get(dkIdx) : d2d.floatValues.get(dkIdx)
// @function Get integer value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (int) An integer value or `na` if not found.
export method getInt(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.intAltValues.get(idx) : this.intValues.get(idx)
// @function Get integer value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (int) An integer value or `na` if not found.
export method getInt(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.intAltValues.get(dkIdx) : d2d.intValues.get(dkIdx)
// @function Get boolean value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (bool) A bool value or `na` if not found.
export method getBool(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.boolAltValues.get(idx) : this.boolValues.get(idx)
// @function Get boolean value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (bool) A boolean value or `na` if not found.
export method getBool(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.boolAltValues.get(dkIdx) : d2d.boolValues.get(dkIdx)
// @function Get color value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (color) A color value or `na` if not found.
export method getColor(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.colorAltValues.get(idx) : this.colorValues.get(idx)
// @function Get color value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (color) A color value or `na` if not found.
export method getColor(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.colorAltValues.get(dkIdx) : d2d.colorValues.get(dkIdx)
// @function Get unix timestamp value from a specific key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (int) A unix timestamp value or `na` if not found.
export method getTimestamp(data2d this, string key, bool alt=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
alt ? this.timestampAltValues.get(idx) : this.timestampValues.get(idx)
// @function Get unix timestamp value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param alt (bool) Use true to get the alternate value instead. (`false` is used if no argument is supplied).
// @returns (int) A unix timestamp value or `na` if not found.
export method getTimestamp(data3d this, string primaryKey, string dataKey, bool alt=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
alt ? d2d.timestampAltValues.get(dkIdx) : d2d.timestampValues.get(dkIdx)
// }
// { Comparison:
__getTimestampChangeF(data2d this, int idx, bool years, bool months, bool weeks, bool days, bool hours, bool minutes, bool seconds) =>
// @function For *INTERNAL* use only.
keyType = this.kvs.get(idx).dataType
if keyType != 'timestamp'
runtime.error("Data type is not a (int) unix timestamp. Only (int) 'timestamp' data type allowed.")
tools._getTimeDifference(this.timestampValues.get(idx), this.timestampAltValues.get(idx), years, months, weeks, days, hours, minutes, seconds)
__getTimestampChangeF(data2d this, bool years, bool months, bool weeks, bool days, bool hours, bool minutes, bool seconds) =>
// @function For *INTERNAL* use only.
result = array.new<string>()
for key in this.getKeys()
idx = this.keys.indexof(key)
result.push(__getTimestampChangeF(this, idx, years, months, weeks, days, hours, minutes, seconds))
result
// @function Get segmented time difference value of a single key.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param years Switch to turn on/off the years segment. Off by default. (`false` is used if no argument is supplied).
// @param months Switch to turn on/off the months segment. Off by default. (`false` is used if no argument is supplied).
// @param weeks Switch to turn on/off the weeks segment. Off by default. (`false` is used if no argument is supplied).
// @param days Switch to turn on/off the days segment. On by default. (`true` is used if no argument is supplied).
// @param hours Switch to turn on/off the hours segment. On by default. (`true` is used if no argument is supplied).
// @param minutes Switch to turn on/off the minutes segment. On by default. (`true` is used if no argument is supplied).
// @param seconds Switch to turn on/off the seconds segment. On by default. (`true` is used if no argument is supplied).
// @returns (string) A string value.
export method timestampChange(data2d this, string key, bool years=false, bool months=false, bool weeks=false, bool days=true, bool hours=true, bool minutes=true, bool seconds=true) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
__getTimestampChangeF(this, idx, years, months, weeks, days, hours, minutes, seconds)
// @function Get segmented time difference value of all the keys.
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param years Switch to turn on/off the years segment. Off by default. (`false` is used if no argument is supplied).
// @param months Switch to turn on/off the months segment. Off by default. (`false` is used if no argument is supplied).
// @param weeks Switch to turn on/off the weeks segment. Off by default. (`false` is used if no argument is supplied).
// @param days Switch to turn on/off the days segment. On by default. (`true` is used if no argument is supplied).
// @param hours Switch to turn on/off the hours segment. On by default. (`true` is used if no argument is supplied).
// @param minutes Switch to turn on/off the minutes segment. On by default. (`true` is used if no argument is supplied).
// @param seconds Switch to turn on/off the seconds segment. On by default. (`true` is used if no argument is supplied).
// @returns (array<string>) A string array.
export method timestampChange(data2d this, bool years=false, bool months=false, bool weeks=false, bool days=true, bool hours=true, bool minutes=true, bool seconds=true) =>
__getTimestampChangeF(this, years, months, weeks, days, hours, minutes, seconds)
// @function Get segmented time difference value of a single primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param years Switch to turn on/off the years segment. Off by default. (`false` is used if no argument is supplied).
// @param months Switch to turn on/off the months segment. Off by default. (`false` is used if no argument is supplied).
// @param weeks Switch to turn on/off the weeks segment. Off by default. (`false` is used if no argument is supplied).
// @param days Switch to turn on/off the days segment. On by default. (`true` is used if no argument is supplied).
// @param hours Switch to turn on/off the hours segment. On by default. (`true` is used if no argument is supplied).
// @param minutes Switch to turn on/off the minutes segment. On by default. (`true` is used if no argument is supplied).
// @param seconds Switch to turn on/off the seconds segment. On by default. (`true` is used if no argument is supplied).
// @returns (string) A string value.
export method timestampChange(data3d this, string primaryKey, string dataKey, bool years=false, bool months=false, bool weeks=false, bool days=true, bool hours=true, bool minutes=true, bool seconds=true) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
__getTimestampChangeF(d2d, dkIdx, years, months, weeks, days, hours, minutes, seconds)
// @function Get segmented time difference value of all the data keys for the primary key. (main == alt)
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param years Switch to turn on/off the years segment. Off by default. (`false` is used if no argument is supplied).
// @param months Switch to turn on/off the months segment. Off by default. (`false` is used if no argument is supplied).
// @param weeks Switch to turn on/off the weeks segment. Off by default. (`false` is used if no argument is supplied).
// @param days Switch to turn on/off the days segment. On by default. (`true` is used if no argument is supplied).
// @param hours Switch to turn on/off the hours segment. On by default. (`true` is used if no argument is supplied).
// @param minutes Switch to turn on/off the minutes segment. On by default. (`true` is used if no argument is supplied).
// @param seconds Switch to turn on/off the seconds segment. On by default. (`true` is used if no argument is supplied).
// @returns (array<string>) A string value.
export method pkTimestampChange(data3d this, string primaryKey, bool years=false, bool months=false, bool weeks=false, bool days=true, bool hours=true, bool minutes=true, bool seconds=true) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
d2d = this.data.get(pkIdx)
__getTimestampChangeF(d2d, years, months, weeks, days, hours, minutes, seconds)
// @function Get segmented time difference value of all the primary keys for the data key. (main == alt)
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param years Switch to turn on/off the years segment. Off by default. (`false` is used if no argument is supplied).
// @param months Switch to turn on/off the months segment. Off by default. (`false` is used if no argument is supplied).
// @param weeks Switch to turn on/off the weeks segment. Off by default. (`false` is used if no argument is supplied).
// @param days Switch to turn on/off the days segment. On by default. (`true` is used if no argument is supplied).
// @param hours Switch to turn on/off the hours segment. On by default. (`true` is used if no argument is supplied).
// @param minutes Switch to turn on/off the minutes segment. On by default. (`true` is used if no argument is supplied).
// @param seconds Switch to turn on/off the seconds segment. On by default. (`true` is used if no argument is supplied).
// @returns (array<string>) A string value.
export method dkTimestampChange(data3d this, string dataKey, bool years=false, bool months=false, bool weeks=false, bool days=true, bool hours=true, bool minutes=true, bool seconds=true) =>
result = array.new<string>()
for pk in this.primaryKeys()
result.push(this.timestampChange(pk, dataKey, years, months, weeks, days, hours, minutes, seconds))
result
// @function Get all change values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) All values from the data2d object.
export method changeValues(data2d this, bool percent=false) =>
vals = percent ? this.changePercentValues : this.changeValues
result = vals
if this.sorted
result := array.new<float>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all change values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) Primary key values.
export method pkChangeValues(data3d this, string primaryKey, bool percent=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
percent ? d2d.changePercentValues : d2d.changeValues
// @function Get all change values from the data key. Formatted, if applicable.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<float>) Data key values.
export method dkChangeValues(data3d this, string dataKey, bool percent=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<float>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
vals.push(percent ? d2d.changePercentValues.get(idx) : d2d.changeValues.get(idx))
vals
// @function Get change value from a specific key..
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (float) A change value or `na` if not found.
export method getChange(data2d this, string key, bool percent=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
percent ? this.changePercentValues.get(idx) : this.changeValues.get(idx)
// @function Get change value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (float) A change value or `na` if not found.
export method getChange(data3d this, string primaryKey, string dataKey, bool percent=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
percent ? d2d.changePercentValues.get(dkIdx) : d2d.changeValues.get(dkIdx)
// @function Get all formatted change values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) All values from the data2d object.
export method formatChangeValues(data2d this, bool percent=false) =>
vals = percent ? this.formatChangePercentValues : this.formatChangeValues
result = vals
if this.sorted
result := array.new<string>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all formatted change values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Primary key values.
export method pkFormatChangeValues(data3d this, string primaryKey, bool percent=false) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
percent ? d2d.formatChangePercentValues : d2d.formatChangeValues
// @function Get all formatted change values from the data key. Formatted, if applicable.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (array<string>) Data key values.
export method dkFormatChangeValues(data3d this, string dataKey, bool percent=false) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<string>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
vals.push(percent ? d2d.formatChangePercentValues.get(idx) : d2d.formatChangeValues.get(idx))
vals
// @function Get formatted change value from a specific key..
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (string) A change value or `na` if not found.
export method getFormatChange(data2d this, string key, bool percent=false) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
percent ? this.formatChangePercentValues.get(idx) : this.formatChangeValues.get(idx)
// @function Get formatted change value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @param percent (bool) Set to true to obtain the percent change values instead. (`false` is used if no argument is supplied).
// @returns (string) A change value or `na` if not found.
export method getFormatChange(data3d this, string primaryKey, string dataKey, bool percent=false) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
percent ? d2d.formatChangePercentValues.get(dkIdx) : d2d.formatChangeValues.get(dkIdx)
// @function Get all 'et' compare values. Sorted, if applicable.
// @param this (data2d) The `data2d` object.
// @returns (array<bool>) All values from the data2d object.
export method compareValues(data2d this, string compare) =>
vals = switch compare
'et' => this.etValues
'lt' => this.ltValues
'lte' => this.lteValues
'gt' => this.gtValues
'gte' => this.gteValues
result = vals
if this.sorted
result := array.new<bool>()
for i in this.index
result.push(vals.get(i))
result
// @function Get all 'et' compare values from the primary key. Sorted, if applicable.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @returns (array<bool>) Primary key values.
export method pkCompareValues(data3d this, string primaryKey, string compare) =>
[idx, exist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(exist, primaryKey)
d2d = this.data.get(idx)
vals = switch compare
'et' => d2d.etValues
'lt' => d2d.ltValues
'lte' => d2d.lteValues
'gt' => d2d.gtValues
'gte' => d2d.gteValues
// @function Get all 'et' compare values from the data key. Formatted, if applicable.
// @param this (data3d) The `data3d` object.
// @param dataKey (string) The data key.
// @returns (array<bool>) Data key values.
export method dkCompareValues(data3d this, string dataKey, string compare) =>
[idx, exist] = __dataKeyExist(this, dataKey)
__existErrorCheck(exist, dataKey)
vals = array.new<bool>()
d3dIdx = this.index
for _idx in d3dIdx
d2d = this.data.get(_idx)
_val = switch compare
'et' => d2d.etValues.get(idx)
'lt' => d2d.ltValues.get(idx)
'lte' => d2d.lteValues.get(idx)
'gt' => d2d.gtValues.get(idx)
'gte' => d2d.gteValues.get(idx)
vals.push(_val)
vals
// @function Get 'et' compare value from a specific key..
// @param this (data2d) The `data2d` object.
// @param key (string) The key identifier.
// @returns (bool) A compare value or `na` if not found.
export method getCompare(data2d this, string key, string compare) =>
[idx, exist] = __keyExist(this, key)
__existErrorCheck(exist, key)
switch compare
'et' => this.etValues.get(idx)
'lt' => this.ltValues.get(idx)
'lte' => this.lteValues.get(idx)
'gt' => this.gtValues.get(idx)
'gte' => this.gteValues.get(idx)
// @function Get 'et' compare value from a specific primary and data key.
// @param this (data3d) The `data3d` object.
// @param primaryKey (string) The primary key.
// @param dataKey (string) The data key.
// @returns (bool) A compare value or `na` if not found.
export method getCompare(data3d this, string primaryKey, string dataKey, string compare) =>
[pkIdx, pkExist] = __primaryKeyExist(this, primaryKey)
__existErrorCheck(pkExist, primaryKey)
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
d2d = this.data.get(pkIdx)
switch compare
'et' => d2d.etValues.get(dkIdx)
'lt' => d2d.ltValues.get(dkIdx)
'lte' => d2d.lteValues.get(dkIdx)
'gt' => d2d.gtValues.get(dkIdx)
'gte' => d2d.gteValues.get(dkIdx)
// }
// { Mechanics:
// @function Set custom format for a `kv` object.
// @param this (kv) A `kv` object.
// @param format (string) A custom format.
// @param timezone (string) A timezone for timestamp value. (`na` is used if no argument is supplied).
// @returns (kv) The `kv` object.
export method format(kv this, string format, string timezone=na) =>
this.format := format
alt = tools._bool(this.formatAltValue)
string fv = na
string afv = na
switch this.dataType
"float" =>
fv := str.format(format, this.val.floatValue)
afv := alt ? str.format(format, this.altVal.floatValue) : afv
"int" =>
fv := str.format(format, this.val.intValue)
afv := alt ? str.format(format, this.altVal.intValue) : afv
"timestamp" =>
tz = syminfo.timezone
if not na(timezone)
this.timezone := timezone
this._tz := true
tz := timezone
else
tz := this._tz ? this.timezone : tz
fv := str.format_time(this.val.intValue, format, tz)
afv := alt ? str.format_time(this.altVal.intValue, format, tz) : afv
"bool" =>
fv := str.format(format, this.val.boolValue)
afv := alt ? str.format(format, this.altVal.boolValue) : afv
=>
fv := str.format(format, this.val.stringValue)
afv := alt ? str.format(format, this.altVal.stringValue) : afv
this.formatValue := fv
this.formatAltValue := afv
this
// @function Set custom change format or change percent format for a `kv` object.
// @param this (kv) A `kv` object.
// @param format (string) A custom format.
// @param percent (bool) If set to true, the format will be used for change percent, rather than change. (`false` is used if no argument is supplied).
// @returns (kv) The `kv` object.
export method changeFormat(kv this, string format, bool percent=false) =>
this.changePercentFormat := percent ? format : this.changePercentFormat
this.changeFormat := not percent ? format : this.changeFormat
if tools._bool(this.formatAltValue)
switch this.dataType
"float" =>
if percent
this.formatChangePercentValue := str.format(format, __change(this.val.floatValue, this.altVal.floatValue, true))
else
this.formatChangeValue := str.format(format, __change(this.val.floatValue, this.altVal.floatValue, false))
"int" =>
if percent
this.formatChangePercentValue := str.format(format, __change(this.val.intValue, this.altVal.intValue, true))
else
this.formatChangeValue := str.format(format, __change(this.val.intValue, this.altVal.intValue, false))
"timestamp" =>
if percent
this.formatChangePercentValue := str.format(format, __change(this.val.intValue, this.altVal.intValue, true))
else
_cfKeys = tools._commaSplit(this.changeFormat)
years = _cfKeys.includes('year')
months = _cfKeys.includes('month')
weeks = _cfKeys.includes('week')
days = _cfKeys.includes('day')
hours = _cfKeys.includes('hour')
minutes = _cfKeys.includes('minute')
seconds = _cfKeys.includes('second')
this.formatChangeValue := tools._getTimeDifference(this.val.intValue, this.altVal.intValue, years, months, weeks, days, hours, minutes, seconds)
"string" =>
if percent
this.formatChangePercentValue := str.format(format, __change(str.length(this.val.stringValue), str.length(this.altVal.stringValue), true))
else
this.formatChangeValue := str.format(format, __change(str.length(this.val.stringValue), str.length(this.altVal.stringValue), false))
this
// @function For *INTERNAL* use only.
__format(multidata, string format) =>
switch multidata.dataType
"timestamp" =>
multidata.formatTime := format
=>
multidata.format := format
multidata
// @function Set custom format for a multidata object.
// @param this A data2d or data3d object.
// @param format (string) A custom format.
// @returns This object.
export method format(data2d this, string format) =>
__format(this, format)
frmtVals = this.formatValues
frmtAltVals = this.formatAltValues
for [i,kV] in this.kvs
if na(kV.format)
tz = kV._tz ? kV.timezone : this.timezone
kV.format(format, tz)
frmtVals.set(i, kV.formatValue)
frmtAltVals.set(i, kV.formatAltValue)
this
export method format(data3d this, string format) =>
__format(this, format)
for data in this.data
data.format(format)
this
// @function Set custom change format or change percent format for a multidata object.
// @param this A data2d or data3d object.
// @param format (string) A custom format.
// @param percent (bool) If set to true, the format will be used for change percent, rather than change. (`false` is used if no argument is supplied).
// @returns This object.
export method changeFormat(data2d this, string format, bool percent=false) =>
this.changePercentFormat := percent ? format : this.changePercentFormat
this.changeFormat := not percent ? format : this.changeFormat
frmtChangeVals = this.formatChangeValues
frmtChangePercentVals = this.formatChangePercentValues
for [i,kV] in this.kvs
if kV.dataType != 'timestamp'
if percent and na(kV.changePercentFormat)
kV.changeFormat(format, true)
else if not percent and na(kV.changePercentFormat)
kV.changeFormat(format, false)
frmtChangeVals.set(i, kV.formatChangeValue)
frmtChangePercentVals.set(i, kV.formatChangePercentValue)
this
export method changeFormat(data3d this, string format, bool percent=false) =>
for data in this.data
data.changeFormat(format, percent)
this
// @function Set custom change timestamp format for a multidata object.
// @param this A data2d or data3d object.
// @param format (string) A custom format.
// @returns This object.
export method changeTimestampFormat(data2d this, string format) =>
this.changeTimestampFormat := format
frmtChangeVals = this.formatChangeValues
for [i,kV] in this.kvs
if kV.dataType == 'timestamp'
kV.changeFormat(format, false)
frmtChangeVals.set(i, kV.formatChangeValue)
this
export method changeTimestampFormat(data3d this, string format) =>
for data in this.data
data.changeFormat(format)
this
// @function For *INTERNAL* use only.
__index(multidata) =>
size = multidata.size
index = array.new<int>(size)
for i=0 to size - 1
index.set(i, i)
multidata.index := index
// @function For *INTERNAL* use only.
__sort2d(data2d this, order, bool change) =>
if this.dataType != "mix"
if change
this.index := this.changeValues(true).sort_indices(order)
else
switch this.dataType
"float" =>
this.index := this.floatValues.sort_indices(order)
"int" =>
this.index := this.intValues.sort_indices(order)
"timestamp" =>
this.index := this.timestampValues.sort_indices(order)
=>
this.index := this.values.sort_indices(order)
this.sorted := true
this
// @function For *INTERNAL* use only.
__sort3d(data3d this, string dataKey, order, bool change) =>
[dkIdx, dkExist] = __dataKeyExist(this, dataKey)
__existErrorCheck(dkExist, dataKey)
dataType = this.dataKeyTypes.get(dkIdx)
if change
changeValues = array.new<float>()
for d2d in this.data
changeValues.push(d2d.changeValues(true).get(dkIdx))
this.index := changeValues.sort_indices(order)
else
switch dataType
"float" =>
floatValues = array.new<float>()
for d2d in this.data
floatValues.push(d2d.floatValues.get(dkIdx))
this.index := floatValues.sort_indices(order)
"int" =>
intValues = array.new<int>()
for d2d in this.data
intValues.push(d2d.intValues.get(dkIdx))
this.index := intValues.sort_indices(order)
"timestamp" =>
timestampValues = array.new<int>()
for d2d in this.data
timestampValues.push(d2d.timestampValues.get(dkIdx))
this.index := timestampValues.sort_indices(order)
=>
values = array.new<string>()
for d2d in this.data
values.push(d2d.values.get(dkIdx))
this.index := values.sort_indices(order)
this.sorted := true
this
// @function Sort a `data2d` object.
// @param this (data2d) The `data2d` object.
// @param asc (bool) Use true for ascending order, false for Descending order.
// @param change (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @returns (data2d) The `data2d` object.
export method sort(data2d this, bool asc, bool change = na) =>
order = asc ? order.ascending : order.descending
this.asc := asc
this.change := not na(change) ? change : this.change
__sort2d(this, order, this.change)
// @function Sort a `data2d` object using it's default sorting order.
// @param this (data2d) The `data2d` object.
// @param change (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @returns (data2d) The `data2d` object.
export method sort(data2d this, bool change = na) =>
order = this.asc ? order.ascending : order.descending
this.change := not na(change) ? change : this.change
__sort2d(this, order, this.change)
// @function Sort a `data3d` object.
// @param this (data3d) The `data3d` object.
// @param dataKey (dataKey) The data key values used for sorting.
// @param asc (bool) Use true for ascending order, false for Descending order.
// @param change (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @returns (data3d) The `data3d` object.
export method sort(data3d this, string dataKey, bool asc, bool change = na) =>
order = asc ? order.ascending : order.descending
this.asc := asc
this.change := not na(change) ? change : this.change
__sort3d(this, dataKey, order, this.change)
// @function Sort a `data3d` object using it's default sorting order.
// @param this (data3d) The `data3d` object.
// @param dataKey (dataKey) The data key values used for sorting.
// @param change (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @returns (data3d) The `data3d` object.
export method sort(data3d this, string dataKey, bool change = na) =>
order = this.asc ? order.ascending : order.descending
this.change := not na(change) ? change : this.change
__sort3d(this, dataKey, order, this.change)
// @function For *INTERNAL* use only.
__init2d(data2d this, bool sort=false, bool asc=true, bool change=na) =>
kvs = this.kvs
size = kvs.size()
this.size := size
this.asc := asc
this.change := not na(change) ? change : this.change
vt = kvs.first().dataType
countDiffValType = 0
keys = array.new<string>(size)
vals = array.new<string>(size)
frmtVals = array.new<string>(size)
altVals = array.new<string>(size)
frmtAltVals = array.new<string>(size)
stringValues = array.new<string>(size)
stringAltVals = array.new<string>(size)
floatValues = array.new<float>(size)
floatAltVals = array.new<float>(size)
intValues = array.new<int>(size)
intAltVals = array.new<int>(size)
boolValues = array.new<bool>(size)
boolAltVals = array.new<bool>(size)
colorVals = array.new<color>(size)
colorAltVals = array.new<color>(size)
timestampVals = array.new<int>(size)
timestampAltVals = array.new<int>(size)
changeValues = array.new<float>(size)
changePercentValues = array.new<float>(size)
formatChangeValues = array.new<string>(size)
formatChangePercentValues = array.new<string>(size)
etValues = array.new<bool>(size)
ltValues = array.new<bool>(size)
lteValues = array.new<bool>(size)
gtValues = array.new<bool>(size)
gteValues = array.new<bool>(size)
dataTypes = array.new<string>(size)
__index(this)
for [i, kV] in kvs
key = kV.key
if keys.includes(key)
msg = str.format("Key \"{0}\" already exist. Keys must be unique.", key)
runtime.error(msg)
countDiffValType := kV.dataType != vt ? countDiffValType + 1 : countDiffValType
keys.set(i, key)
vals.set(i, kV.value)
frmtVals.set(i, kV.formatValue)
altVals.set(i, kV.altValue)
frmtAltVals.set(i, kV.formatAltValue)
dataTypes.set(i, kV.dataType)
changeValues.set(i, kV.changeValue)
changePercentValues.set(i, kV.changePercentValue)
formatChangeValues.set(i, kV.formatChangeValue)
formatChangePercentValues.set(i, kV.formatChangePercentValue)
etValues.set(i, kV.etValue)
ltValues.set(i, kV.ltValue)
lteValues.set(i, kV.lteValue)
gtValues.set(i, kV.gtValue)
gteValues.set(i, kV.gteValue)
if kV.dataType == "string"
stringValues.set(i, kV.val.stringValue)
stringAltVals.set(i, kV.altVal.stringValue)
else if kV.dataType == "float"
floatValues.set(i, kV.val.floatValue)
floatAltVals.set(i, kV.altVal.floatValue)
else if kV.dataType == "int"
intValues.set(i, kV.val.intValue)
intAltVals.set(i, kV.altVal.intValue)
else if kV.dataType == "bool"
boolValues.set(i, kV.val.boolValue)
boolAltVals.set(i, kV.altVal.boolValue)
else if kV.dataType == "color"
colorVals.set(i, tools._clr(kV.val.stringValue))
colorAltVals.set(i, tools._clr(kV.altVal.stringValue))
else if kV.dataType == "timestamp"
timestampVals.set(i, kV.val.intValue)
timestampAltVals.set(i, kV.altVal.intValue)
if na(kV.format)
tz = kV._tz ? kV.timezone : this.timezone
frmtTimeVal = str.format_time(kV.val.intValue, this.formatTime, tz)
frmtVals.set(i, frmtTimeVal)
if not na(kV.altValue)
frmtTimeAltVal = str.format_time(kV.altVal.intValue, this.formatTime, tz)
frmtAltVals.set(i, frmtTimeAltVal)
this.dataTypes := dataTypes
this.dataType := countDiffValType > 0 ? "mix" : vt
this.keys := keys
this.values := vals
this.formatValues := frmtVals
this.altValues := altVals
this.formatAltValues := frmtAltVals
this.stringValues := stringValues
this.stringAltValues := stringAltVals
this.floatValues := floatValues
this.floatAltValues := floatAltVals
this.intValues := intValues
this.intAltValues := intAltVals
this.boolValues := boolValues
this.boolAltValues := boolAltVals
this.colorValues := colorVals
this.colorAltValues := colorAltVals
this.timestampValues := timestampVals
this.timestampAltValues := timestampAltVals
this.changeValues := changeValues
this.changePercentValues := changePercentValues
this.formatChangeValues := formatChangeValues
this.formatChangePercentValues := formatChangePercentValues
this.etValues := etValues
this.ltValues := ltValues
this.lteValues := lteValues
this.gtValues := gtValues
this.gteValues := gteValues
if sort
__sort2d(this, asc ? order.ascending : order.descending, change)
this
// @function Create and initialize a data2d object.
// @param kvs (array<kv> ) An array of `kv` objects.
// @param sort (bool) Use true for sorting, false otherwise. (`false` is used if no argument is supplied).
// @param asc (bool) Use true for sort order.ascending, false for sort order.descending. (`true` is used if no argument is supplied).
// @param sortByChange (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @param format (string) The default format. (`na` is used if no argument is supplied).
// @param timezone (string) The default timezone. (`syminfo.timezone` is used if no argument is supplied).
// @returns (data2d) The `data2d` object.
export data2d(array<kv> kvs, bool sort=false, bool asc=true, bool sortByChange=na, string format=na, string timezone=na) =>
d2d = data2d.new(kvs=kvs)
d2d.timezone := not na(timezone) ? timezone : d2d.timezone
__init2d(d2d, sort, asc, sortByChange)
if not na(format)
d2d.format(format)
d2d
// @function Create a data3d object.
// @param pkvs (array<pkv> ) An array of `pkv` objects.
// @param sort (bool) Use true for sorting, false otherwise. (`false` is used if no argument is supplied).
// @param sortByKey (string) The data key used for sorting. (`na` is used if no argument is supplied).
// @param asc (bool) Use true for sort order.ascending, false for sort order.descending. (`true` is used if no argument is supplied).
// @param sortByChange (bool) Sorts using change percent if true. (`na` is used if no argument is supplied).
// @param format (string) The default format. (`na` is used if no argument is supplied).
// @param timezone (string) The default timezone. (`syminfo.timezone` is used if no argument is supplied).
// @returns (data2d) The `data2d` object.
export data3d(array<pkv> pkvs, bool sort=false, string sortByKey=na, bool asc=true, bool sortByChange=na, string format=na, string timezone=na) =>
primaryKeys = array.new<string>()
dataKeys = pkvs.first().dataKeys
dataKeyTypes = pkvs.first().dataKeyTypes
data = array.new<data2d>()
string dataType = na
// For matching all other data keys and their types
flatDks = tools._join(dataKeys)
for [i, pKv] in pkvs
for [x,dkt] in dataKeyTypes
if dkt != pKv.dataKeyTypes.get(x)
runtime.error("Data key type does not match. Please make sure data key types match across all `pkv` objects.")
d2d = data2d(pKv.kvs, format=format, timezone=timezone)
if flatDks != tools._join(d2d.keys)
runtime.error("Data keys does not match. Please make sure data keys match across all `pkv` objects.")
primaryKeys.push(pKv.primaryKey)
data.push(d2d)
if i == 0
dataType := d2d.dataType
d3d = data3d.new(
data=data,
primaryKeys=primaryKeys,
dataKeys=dataKeys,
dataKeyTypes=dataKeyTypes,
dataType=dataType,
size=pkvs.size(),
sorted=sort,
sortByKey=sortByKey,
asc=asc)
d3d.change := not na(sortByChange) ? sortByChange : d3d.change
d3d.index := __index(d3d)
d3d.timezone := not na(timezone) ? timezone : d3d.timezone
d3d.formatTime := not na(format) and dataType == "timestamp" ? format : d3d.formatTime
d3d.format := not na(format) and dataType != "timestamp" ? format : d3d.format
if not na(sortByKey) and sort
__sort3d(d3d, sortByKey, asc ? order.ascending : order.descending, d3d.change)
d3d
// }
// { Printer Extend:
_rawValue(data2d data2d, key, _type) =>
switch _type
'string' => p.kdv(key, data2d.getString(key))
'float' => p.kdv(key, data2d.getFloat(key))
'int' => p.kdv(key, data2d.getInt(key))
'bool' => p.kdv(key, data2d.getBool(key))
'color' => p.kdv(key, data2d.getColor(key))
'timestamp' => p.kdv(key, data2d.getTimestamp(key))
_rawValue(data3d data3d, pk, dk, _type) =>
switch _type
'string' => p.kdv(dk, data3d.getString(pk, dk))
'float' => p.kdv(dk, data3d.getFloat(pk, dk))
'int' => p.kdv(dk, data3d.getInt(pk, dk))
'bool' => p.kdv(dk, data3d.getBool(pk, dk))
'color' => p.kdv(dk, data3d.getColor(pk, dk))
'timestamp' => p.kdv(dk, data3d.getTimestamp(pk, dk))
__displayValues(data2d data2d, string name) =>
_vals = array.new<p.kdv>()
for [i, key] in data2d.getKeys()
switch name
'alt' =>
_val = data2d.get(key, true)
_vals.push(p.kdv(key, _val))
'change' =>
_val = data2d.getChange(key)
_vals.push(p.kdv(key, _val))
'change_format' =>
_val = data2d.getFormatChange(key)
_vals.push(p.kdv(key, _val))
'change_percent' =>
_val = data2d.getChange(key, true)
_vals.push(p.kdv(key, _val))
'change_percent_format' =>
_val = data2d.getFormatChange(key, true)
_vals.push(p.kdv(key, _val))
'et' =>
_val = data2d.getCompare(key, 'et')
_vals.push(p.kdv(key, _val))
'lt' =>
_val = data2d.getCompare(key, 'lt')
_vals.push(p.kdv(key, _val))
'lte' =>
_val = data2d.getCompare(key, 'lte')
_vals.push(p.kdv(key, _val))
'gt' =>
_val = data2d.getCompare(key, 'gt')
_vals.push(p.kdv(key, _val))
'gte' =>
_val = data2d.getCompare(key, 'gte')
_vals.push(p.kdv(key, _val))
'raw' =>
_vals.push(_rawValue(data2d, key, data2d.dataTypes.get(i)))
=>
_vals.push(p.kdv(key, data2d.get(key)))
p.kdvs(_vals)
__displayValues(data3d data3d, string name) =>
_vals = array.new<p.pkdv>()
for [i, pk] in data3d.primaryKeys()
_kdvs = array.new<p.kdv>()
for [n, dk] in data3d.dataKeys()
switch name
'alt' => _kdvs.push(p.kdv(dk, data3d.get(pk, dk, true)))
'change' => _kdvs.push(p.kdv(dk, data3d.getChange(pk, dk)))
'change_format' => _kdvs.push(p.kdv(dk, data3d.getFormatChange(pk, dk)))
'change_percent' => _kdvs.push(p.kdv(dk, data3d.getChange(pk, dk, true)))
'change_percent_format' => _kdvs.push(p.kdv(dk, data3d.getFormatChange(pk, dk, true)))
'et' => _kdvs.push(p.kdv(dk, data3d.getCompare(pk, dk, 'et')))
'lt' => _kdvs.push(p.kdv(dk, data3d.getCompare(pk, dk, 'lt')))
'lte' => _kdvs.push(p.kdv(dk, data3d.getCompare(pk, dk, 'lte')))
'gt' => _kdvs.push(p.kdv(dk, data3d.getCompare(pk, dk, 'gt')))
'gte' => _kdvs.push(p.kdv(dk, data3d.getCompare(pk, dk, 'gte')))
'raw' => _kdvs.push(_rawValue(data3d, pk, dk, data3d.dataKeyTypes.get(n)))
=> _kdvs.push(p.kdv(dk, data3d.get(pk, dk)))
_vals.push(p.pkdv(pk, p.kdvs(_kdvs)))
p.pkdvs(_vals)
// @function Print data on screen.
// @param this (_printer) A tools._printer object.
// @param values Multidatas object to use for print.
// @param displayValues Override default data printing.
// @param title (string) A title for the value. (`na` is used if no argument is supplied).
// @param titleStyle (titleStyle) Add a custom `titleStyle` for this print only. (`na` is used if no argument is supplied).
// @param styles (map<string, p.cellStyle>) Add custom cellStyles for this print only. (`na` is used if no argument is supplied).
// @param theme (string) The name of the theme. Choices: gray, blue, green, orange, green, red, purple, pink and white. (`na` is used if no argument is supplied).
// @param dynamicValues (map<string, p.dvs>) Add custom dynamic values to use for dynamic colors. (`na` is used if no argument is supplied).
// @param dynamicKey A bool value for data2d, and primary key value for data3d. When set, the key or primary key cells will match dynamic colors of value cell. (`false` or `na` is used if no argument is supplied).
// @returns (_printer) Returns the _printer UDT object.
export method print(p._printer this, data2d values, string displayValues=na, string title=na, p.titleStyle titleStyle=na, map<string, p.cellStyle> styles=na, string theme=na, map<string, p.dvs> dynamicValues=na, bool dynamicKey=false) =>
p.print2d(this=this, values=__displayValues(values, displayValues), title=title, titleStyle=titleStyle, styles=styles, theme=theme, dynamicValues=dynamicValues, dynamicKey=dynamicKey)
export method print(p._printer this, data3d values, string displayValues=na, string title=na, p.titleStyle titleStyle=na, map<string, p.cellStyle> styles=na, string theme=na, map<string, p.dvs> dynamicValues=na, string dynamicKey=na) =>
p.print3d(this=this, values=__displayValues(values, displayValues), title=title, titleStyle=titleStyle, styles=styles, theme=theme, dynamicValues=dynamicValues, dynamicKey=dynamicKey)
// }
// var d2d1 = array.from(
// '- Key-Value data structure: key -> [ main-value | alternate-value ].',
// '- Ability to store multiple data types.',
// '- Add a second alternate value, enabling two values under one key.',
// '- Built in comparison methods to compare main values with their alternate values.',
// '- Efforlessly store, retrieve and display Unix timestamps.',
// '- Automaticaly format stored data.',
// '- Sort all data types.',
// '- Familiar array functions for intuitive data manipulation.',
// '- You can now print a data2d object directly, using the `tools` print() method.')
// var d3d1 = array.from(
// '- A nested data structure: primary key -> data key -> [ main-value | alternate-value ].',
// '- Sorting based on a data key.',
// '- Plus, shares most features of data2d.',
// '- Similar to data2d, you can print data3d objects using the `tools` print() method.')
// General printer setup and styling:
var tbs = p.tableStyle.new(bgColor=na, frameColor=na)
var hdr = "Multidimensional Data Structures."
var ftr = "Full Documentation: https://faiyaz7283.github.io/multidata"
var hs = p.headerStyle.new(textSize=size.large, textColor=tools._color('purple_bright'))
var fs = p.footerStyle.new(textSize=size.large, textHalign=text.align_right, textColor=tools._color('green_bright'))
var ts = p.titleStyle.new(top=false, textHalign=text.align_left, textValign=text.align_center, textSize=size.normal,
textColor=tools._color('yellow_bright'))
var cs = p.cellStyle.new(horizontal=true, textHalign=text.align_left, textSize=size.normal,
textColor=tools._color('white_bright'))
// if barstate.islast
// printer = p.printer(header=hdr, footer=ftr, tableStyle=tbs, headerStyle=hs, footerStyle=fs, titleStyle=ts,
// cellStyle=cs).gutter(true).stack(true)
// printer.print(d2d1, title='data2d')
// printer.print(d3d1, title='data3d')
// Test {
// getOHLC(simple string ticker) =>
// m = array.from(open, high, low, close, volume, time)
// a = array.from(open[1], high[1], low[1], close[1], volume[1], time[1])
// tckr = ticker.new(syminfo.prefix(ticker), syminfo.ticker(ticker), syminfo.session)
// [main, alt] = request.security(tckr, '', [m, a])
// kvs = array.new<kv>()
// for [idx, dk] in array.from('open', 'high', 'low', 'close', 'volume', 'time')
// _val = main.get(idx)
// _alt = alt.get(idx)
// format = dk == 'volume' ? tools.numCompact(_val): '{0,number,currency}'
// if dk == 'time'
// curr_tf = timeframe.period
// frmt = switch
// str.endswith(curr_tf, 'S') => 'second'
// str.endswith(curr_tf, 'D') => 'day'
// str.endswith(curr_tf, 'W') => 'day'
// str.endswith(curr_tf, 'M') => 'day'
// => 'minute'
// kvs.push(dk.kv(val=tools._int(_val), altVal=tools._int(_alt), timestamp=true, changeFormat=frmt))
// else
// kvs.push(dk.kv(val=_val, altVal=_alt, format=format, changeFormat=format, changePercentFormat='{0,number,0.000} %'))
// kvs
// if barstate.islast
// printer = p.printer(tableStyle=tbs, headerStyle=hs, footerStyle=fs, titleStyle=ts, cellStyle=cs, theme=na, debug=true).gutter(false).stack(true)
// // Setup Data:
// aapl = pkv('AAPL', getOHLC('NASDAQ:AAPL'))
// msft = pkv('MSFT', getOHLC('NASDAQ:MSFT'))
// nvda = pkv('NVDA', getOHLC('NASDAQ:NVDA'))
// nflx = pkv('NFLX', getOHLC('NASDAQ:NFLX'))
// tsla = pkv('TSLA', getOHLC('NASDAQ:TSLA'))
// goog = pkv('GOOG', getOHLC('NASDAQ:GOOG'))
// pkvs = array.from(aapl, msft, nvda, nflx, tsla, goog)
// // Create Data2d storage:
// d2d = data2d(getOHLC(syminfo.tickerid))
// // Dynamic values
// _valDv = d2d.changeValues(true)
// d2dDv = map.new<string, p.dvs>()
// d2dDv.put('key', _valDv.dvs())
// d2dDv.put('val', _valDv.dvs())
// // Styling key cells
// d2d_styles = map.new<string, p.cellStyle>()
// styleKey = p.cellStyle.copy(printer.keyCellStyle)
// styleKey.dynamicColor := p.dynamicColor.new(numberUp=_valDv.max(), numberDown=_valDv.min(), offsetItem='text', offsetColor=#000000)
// styleKey.gradient := true
// d2d_styles.put('key', styleKey)
// // Styling val cells
// styleVal = p.cellStyle.copy(cs)
// styleVal.dynamicColor := p.dynamicColor.new(numberUp=_valDv.max(), numberDown=_valDv.min(), offsetItem='bg')
// styleVal.gradient := true
// d2d_styles.put('val', styleVal)
// // Create Data3d storage:
// d3d = data3d(pkvs, sort=true, asc=false, sortByKey='close', sortByChange=true)
// // Dynamic values
// _openDv = d3d.dkChangeValues('open', true)
// _highDv = d3d.dkChangeValues('high', true)
// _lowDv = d3d.dkChangeValues('low', true)
// _closeDv = d3d.dkChangeValues('close', true)
// _volumeDv = d3d.dkChangeValues('volume', true)
// _timeDv = d3d.dkChangeValues('time', true)
// d3dDv = map.new<string, p.dvs>()
// d3dDv.put('open', _openDv.dvs())
// d3dDv.put('high', _highDv.dvs())
// d3dDv.put('low', _lowDv.dvs())
// d3dDv.put('close', _closeDv.dvs())
// d3dDv.put('volume', _volumeDv.dvs())
// d3dDv.put('time', _timeDv.dvs())
// d3dDv.put('dk', array.from(color.silver, color.silver, color.silver, color.lime, color.orange, color.silver).dvs())
// d3d_styles = map.new<string, p.cellStyle>()
// stylePk = p.cellStyle.copy(printer.keyCellStyle)
// stylePk.dynamicColor := p.dynamicColor.new(numberUp=_closeDv.max(), numberDown=_closeDv.min(), offsetItem='text', offsetColor=#000000)
// stylePk.gradient := true
// d3d_styles.put('pk', stylePk)
// styleDk = p.cellStyle.copy(printer.keyCellStyle)
// styleDk.dynamicColor := p.dynamicColor.new(offsetItem='bg', offsetColor=na)
// d3d_styles.put('dk', styleDk)
// styleOpen = p.cellStyle.copy(cs)
// styleOpen.dynamicColor := p.dynamicColor.new(numberUp=_openDv.max(), numberDown=_openDv.min(), offsetItem='bg')
// styleOpen.gradient := true
// d3d_styles.put('open', styleOpen)
// styleHigh = p.cellStyle.copy(cs)
// styleHigh.dynamicColor := p.dynamicColor.new(numberUp=_highDv.max(), numberDown=_highDv.min(), offsetItem='bg')
// styleHigh.gradient := true
// d3d_styles.put('high', styleHigh)
// styleLow = p.cellStyle.copy(cs)
// styleLow.dynamicColor := p.dynamicColor.new(numberUp=_lowDv.max(), numberDown=_lowDv.min(), offsetItem='bg')
// styleLow.gradient := true
// d3d_styles.put('low', styleLow)
// styleClose = p.cellStyle.copy(cs)
// styleClose.dynamicColor := p.dynamicColor.new(numberUp=_closeDv.max(), numberDown=_closeDv.min(), offsetItem='text', offsetColor = #000000)
// styleClose.gradient := true
// d3d_styles.put('close', styleClose)
// styleVolume = p.cellStyle.copy(cs)
// styleVolume.dynamicColor := p.dynamicColor.new(numberUp=_volumeDv.max(), numberDown=_volumeDv.min(), offsetItem='bg')
// styleVolume.gradient := true
// d3d_styles.put('volume', styleVolume)
// styleTime = p.cellStyle.copy(cs)
// styleTime.dynamicColor := p.dynamicColor.new(numberUp=_timeDv.max(), numberDown=_timeDv.min(), offsetItem='bg')
// styleTime.gradient := true
// d3d_styles.put('date', styleTime)
// // Output
// // printer.print(d2d, displayValues='change_percent_format', styles=d2d_styles, dynamicValues=d2dDv, dynamicKey=true)
// printer.print(d3d, styles=d3d_styles, displayValues='change_format', dynamicValues=d3dDv, dynamicKey='close')
// } |
PhantomFlow TrendDetector | https://www.tradingview.com/script/AuFIke86-PhantomFlow-TrendDetector/ | PhantomFlow | https://www.tradingview.com/u/PhantomFlow/ | 263 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PhantomFlow_s666ex_
//@version=5
indicator("PhantomFlow Trend Detector", "PhantomFlow TrendDetector", true, max_lines_count = 500)
type fractal
int fractal_bar
box bx
type wave
bool isActive
bool isSearchCountertrendFormation
bool isSearchTrendFormation
int bar_start
int bar_end
float high_price
float low_price
array<line> lines
var array<wave> waves_down = array.new<wave>()
var array<wave> waves_up = array.new<wave>()
var array<int> fractals_down_zigzag = array.new<int>()
var array<int> fractals_up_zigzag = array.new<int>()
var array<bool> listFractals = array.new<bool>()
var array<fractal> LevelsShort = array.new<fractal>()
var array<fractal> LevelsLong = array.new<fractal>()
var array<fractal> LevelsShortHTF = array.new<fractal>()
var array<fractal> LevelsLongHTF = array.new<fractal>()
var array<int> levelsToCoef = array.new<int>()
ltf = timeframe.period
up_trend_start = input.color(title='Low', defval = color.rgb(255, 253, 106), group="Up Trend Power", inline = "up_trend")
up_trend_end = input.color(title='High', defval = color.rgb(0, 255, 0), group="Up Trend Power", inline = "up_trend")
down_trend_start = input.color(title='Low', defval = color.rgb(255, 89, 255), group="Down Trend Power", inline = "down_trend")
down_trend_end = input.color(title='High', defval = color.rgb(255, 0, 0), group="Down Trend Power", inline = "down_trend")
n_zigzag = 2
is_down_fractal_zigzag() =>
bool isConfirmFractal = false
for i = 0 to n_zigzag + n_zigzag
if low[n_zigzag] > low[i]
break
if (i == n_zigzag + n_zigzag)
isConfirmFractal := true
isConfirmFractal
is_up_fractal_zigzag() =>
bool isConfirmFractal = false
for i = 0 to n_zigzag + n_zigzag
if high[n_zigzag] < high[i]
break
if (i == n_zigzag + n_zigzag)
isConfirmFractal := true
isConfirmFractal
check_is_add_up_liquidity() =>
if array.size(fractals_up_zigzag) > 2
item1 = array.last(fractals_up_zigzag)
item2 = array.get(fractals_up_zigzag, array.size(fractals_up_zigzag) - 2)
item3 = array.get(fractals_up_zigzag, array.size(fractals_up_zigzag) - 3)
if (high[bar_index - item1] < high[bar_index - item2] and high[bar_index - item2] < high[bar_index - item3])
if array.size(waves_up) == 0
array.push(waves_up, wave.new(true, true, true, item3, item1, high[bar_index - item3], high[bar_index - item1], array.new<line>()))
true
else
wave last_wave = array.last(waves_up)
if (item3 >= last_wave.bar_start and item3 < last_wave.bar_end)
last_wave.bar_end := item1
last_wave.low_price := high[bar_index - item1]
last_wave.isActive := false
true
else
array.push(waves_up, wave.new(true, true, true, item3, item1, high[bar_index - item3], high[bar_index - item1], array.new<line>()))
true
check_is_add_down_liquidity() =>
if array.size(fractals_down_zigzag) > 2
item1 = array.last(fractals_down_zigzag)
item2 = array.get(fractals_down_zigzag, array.size(fractals_down_zigzag) - 2)
item3 = array.get(fractals_down_zigzag, array.size(fractals_down_zigzag) - 3)
if (low[bar_index - item1] > low[bar_index - item2] and low[bar_index - item2] > low[bar_index - item3])
if array.size(waves_down) == 0
array.push(waves_down, wave.new(true, true, true, item3, item1, low[bar_index - item1], low[bar_index - item3], array.new<line>()))
true
else
wave last_wave = array.last(waves_down)
if (item3 >= last_wave.bar_start and item3 < last_wave.bar_end)
last_wave.bar_end := item1
last_wave.high_price := low[bar_index - item1]
last_wave.isActive := false
true
else
array.push(waves_down, wave.new(true, true, true, item3, item1, low[bar_index - item1], low[bar_index - item3], array.new<line>()))
true
bool is_search_fractal_zigzag = bar_index - n_zigzag * 2 >= 0
if is_search_fractal_zigzag and true
if is_up_fractal_zigzag()
if array.size(fractals_up_zigzag) == 0
array.push(fractals_up_zigzag, bar_index - (n_zigzag))
array.push(listFractals, true)
else
isUpLastFractal = array.last(listFractals)
lastFractal = array.last(fractals_up_zigzag)
if isUpLastFractal and high[bar_index - lastFractal] < high[n_zigzag]
array.pop(fractals_up_zigzag)
array.push(fractals_up_zigzag, bar_index - (n_zigzag))
check_is_add_up_liquidity()
if not isUpLastFractal
lastFractalDown = array.last(fractals_down_zigzag)
if (low[bar_index - lastFractalDown] < high[n_zigzag])
array.push(fractals_up_zigzag, bar_index - (n_zigzag))
array.push(listFractals, true)
check_is_add_up_liquidity()
if is_down_fractal_zigzag()
if array.size(fractals_down_zigzag) == 0
array.push(fractals_down_zigzag, bar_index - (n_zigzag))
array.push(listFractals, false)
else
isUpLastFractal = array.last(listFractals)
lastFractal = array.last(fractals_down_zigzag)
if not isUpLastFractal and low[bar_index - lastFractal] > low[n_zigzag]
array.pop(fractals_down_zigzag)
array.push(fractals_down_zigzag, bar_index - (n_zigzag))
check_is_add_down_liquidity()
if isUpLastFractal
lastFractalUp = array.last(fractals_up_zigzag)
if (high[bar_index - lastFractalUp] > low[n_zigzag])
array.push(fractals_down_zigzag, bar_index - (n_zigzag))
array.push(listFractals, false)
check_is_add_down_liquidity()
bool isDownTrend = false
bool isUpTrend = false
var float last_low = na
var float last_high = na
if (array.size(waves_up) != 0 and array.size(waves_down) != 0)
wave lastWaveUp = array.last(waves_up)
wave lastWaveDown = array.last(waves_down)
if (close < lastWaveDown.high_price and close > lastWaveUp.low_price)
if (lastWaveDown.bar_end < lastWaveUp.bar_end)
isUpTrend := true
last_low := lastWaveUp.low_price
last_high := lastWaveUp.high_price
else
isDownTrend := true
last_low := lastWaveDown.low_price
last_high := lastWaveDown.high_price
if (close >= lastWaveDown.high_price and close > lastWaveUp.low_price)
isUpTrend := true
last_low := lastWaveUp.low_price
last_high := lastWaveUp.high_price
if (close < lastWaveDown.high_price and close <= lastWaveUp.low_price)
isDownTrend := true
last_low := lastWaveDown.low_price
last_high := lastWaveDown.high_price
if (array.size(waves_up) != 0 and array.size(waves_down) == 0)
wave lastWave = array.last(waves_up)
if (close > lastWave.low_price)
isUpTrend := true
last_low := lastWave.low_price
last_high := lastWave.high_price
if (array.size(waves_down) != 0 and array.size(waves_up) == 0)
wave lastWave = array.last(waves_down)
if (close < lastWave.high_price)
isDownTrend := true
last_low := lastWave.low_price
last_high := lastWave.high_price
var color trend_css = na
float signal = ta.ema(close, 1)
color signalColorDown = color.from_gradient(signal, last_low, last_high, up_trend_start, up_trend_end)
color signalColorUp = color.from_gradient(signal, last_low, last_high, down_trend_end, down_trend_start)
if isDownTrend
trend_css := signalColorUp
if isUpTrend
trend_css := signalColorDown
plotcandle(open, high, low, close
, color = trend_css
, wickcolor = trend_css
, bordercolor = trend_css
, editable = false
, display = display.pane) |
Stablecoin Dominance | https://www.tradingview.com/script/J92vFESl-Stablecoin-Dominance/ | VanHe1sing | https://www.tradingview.com/u/VanHe1sing/ | 91 | 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/
// © VanHe1sing
//@version=5
indicator(title="Stablecoin Dominance (Logarithmic Regression)",
shorttitle="StableDom", format=format.percent, precision=3, max_lines_count = 500)
// Data Sources
usdt = request.security('USDT.D', timeframe.period, close)
usdc = request.security('USDC.D', timeframe.period, close)
busd = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, close)
dai = request.security('DAI.D', timeframe.period, close)
usdt_o = request.security('USDT.D', timeframe.period, open)
usdc_o = request.security('USDC.D', timeframe.period, open)
busd_o = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, open)
dai_o = request.security('DAI.D', timeframe.period, open)
usdt_h = request.security('USDT.D', timeframe.period, high)
usdc_h = request.security('USDC.D', timeframe.period, high)
busd_h = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, high)
dai_h = request.security('DAI.D', timeframe.period, high)
usdt_l = request.security('USDT.D', timeframe.period, low)
usdc_l = request.security('USDC.D', timeframe.period, low)
busd_l = request.security('(BUSD_MARKETCAP*100)/CRYPTOCAP:TOTAL', timeframe.period, low)
dai_l = request.security('DAI.D', timeframe.period, low)
// User Inputs
include_usdt = input.bool(true, 'Include USDT', group='Total Dominance')
include_usdc = input.bool(true, 'Include USDC', group='Total Dominance')
include_busd = input.bool(true, 'Include BUSD', group='Total Dominance')
include_dai = input.bool(true, 'Include DAI', group='Total Dominance')
plotcandl = input.bool(false, "Plot Candles?")
// Math
include = array.new_bool(4,na)
array.insert(include, 0, include_usdt)
array.insert(include, 1, include_usdc)
array.insert(include, 2, include_busd)
array.insert(include, 3, include_dai)
totalDom = 0.00
totalDom_open = 0.00
totalDom_high = 0.00
totalDom_low = 0.00
g=0
for boolean in include
if boolean
switch g
0 =>
totalDom += usdt
totalDom_open += usdt_o
totalDom_high += usdt_h
totalDom_low += usdt_l
1 =>
totalDom += usdc
totalDom_open += usdc_o
totalDom_high += usdc_h
totalDom_low += usdc_l
2 =>
totalDom += busd
totalDom_open += busd_o
totalDom_high += busd_h
totalDom_low += busd_l
3 =>
totalDom += dai
totalDom_open += dai_o
totalDom_high += dai_h
totalDom_low += dai_l
g += 1
// Plotting
plot(plotcandl ? na : totalDom, color = color.white)
color = totalDom_open < totalDom ? color.blue : color.red
plotcandle(plotcandl ? totalDom_open : na,
plotcandl ? totalDom_high : na,
plotcandl ? totalDom_low : na,
plotcandl ? totalDom : na,
color = color, wickcolor = color, bordercolor = color)
// Log Regression from @rumpypumpydumpy
f_loglog_regression_from_arrays(_time_array, _price_array) =>
int _size_y = array.size(_price_array)
int _size_x = array.size(_time_array)
float[] _y_array = array.new_float(_size_y)
float[] _x_array = array.new_float(_size_x)
for _i = 0 to _size_y - 1
array.set(_y_array, _i, math.log(array.get(_price_array, _i)))
array.set(_x_array, _i, math.log(array.get(_time_array, _i)))
float _sum_x = array.sum(_x_array)
float _sum_y = array.sum(_y_array)
float _sum_xy = 0.0
float _sum_x2 = 0.0
float _sum_y2 = 0.0
if _size_y == _size_x
for _i = 0 to _size_y - 1
float _x_i = nz(array.get(_x_array, _i))
float _y_i = nz(array.get(_y_array, _i))
_sum_xy := _sum_xy + _x_i * _y_i
_sum_x2 := _sum_x2 + math.pow(_x_i, 2)
_sum_y2 := _sum_y2 + math.pow(_y_i, 2)
_sum_y2
float _a = (_sum_y * _sum_x2 - _sum_x * _sum_xy) / (_size_x * _sum_x2 - math.pow(_sum_x, 2))
float _b = (_size_x * _sum_xy - _sum_x * _sum_y) / (_size_x * _sum_x2 - math.pow(_sum_x, 2))
float[] _f = array.new_float()
for _i = 0 to _size_y - 1
float _vector = _a + _b * array.get(_x_array, _i)
array.push(_f, _vector)
_slope = (array.get(_f, 0) - array.get(_f, _size_y - 1)) / (array.get(_x_array, 0) - array.get(_x_array, _size_x - 1))
_y_mean = array.avg(_y_array)
float _SS_res = 0.0
float _SS_tot = 0.0
for _i = 0 to _size_y - 1
float _f_i = array.get(_f, _i)
float _y_i = array.get(_y_array, _i)
_SS_res := _SS_res + math.pow(_f_i - _y_i, 2)
_SS_tot := _SS_tot + math.pow(_y_mean - _y_i, 2)
_SS_tot
_r_sq = 1 - _SS_res / _SS_tot
float _sq_err_sum = 0
for _i = 0 to _size_y - 1
_sq_err_sum += math.pow(array.get(_f, _i) - array.get(_y_array, _i), 2)
_dev = math.sqrt(_sq_err_sum / _size_y)
[_f, _slope, _r_sq, _dev]
src = totalDom
n = input(1500, title='Length')
mult = input(2.000, title='dev mult')
var float[] price_array = array.new_float(n)
var int[] x_array = array.new_int(n)
array.unshift(price_array, src)
array.pop(price_array)
array.unshift(x_array, bar_index)
array.pop(x_array)
var line[] reg_line_array = array.new_line()
var line[] dev_up_line_array = array.new_line()
var line[] dev_dn_line_array = array.new_line()
var label r2_label = label.new(x = na, y = na, style = label.style_label_lower_left, color = #00000000, textcolor = color.blue, size=size.normal, textalign = text.align_left)
float[] dev_up_array = array.new_float()
float[] dev_dn_array = array.new_float()
var int step = na
var int line_n = na
if barstate.isfirst
line_n := math.min(n, 250)
for i = 0 to line_n - 1
array.unshift(reg_line_array, line.new(x1=na, y1=na, x2=na, y2=na, color=color.red))
if n > 250
step := math.ceil(n / 250)
else
step := 1
for i = 0 to math.floor(line_n / 2) - 1
array.unshift(dev_up_line_array, line.new(x1=na, y1=na, x2=na, y2=na, color=color.blue))
array.unshift(dev_dn_line_array, line.new(x1=na, y1=na, x2=na, y2=na, color=color.blue))
if barstate.islast
[predictions, slope, r_sq, dev] = f_loglog_regression_from_arrays(x_array, price_array)
for i = 0 to array.size(predictions) - 1
array.push(dev_up_array, math.exp(array.get(predictions, i) + mult * dev))
array.push(dev_dn_array, math.exp(array.get(predictions, i) - mult * dev))
for i = 0 to array.size(predictions) - 2 - step by step
line.set_xy1(array.get(reg_line_array, i / step), x=bar_index - i, y=math.exp(array.get(predictions, i)))
line.set_xy2(array.get(reg_line_array, i / step), x=bar_index - i - step, y=math.exp(array.get(predictions, i + step)))
for i = 0 to array.size(dev_up_array) - 2 - step by step * 2
line.set_xy1(array.get(dev_up_line_array, i / (step * 2)), x=bar_index - i, y=array.get(dev_up_array, i))
line.set_xy2(array.get(dev_up_line_array, i / (step * 2)), x=bar_index - i - step, y=array.get(dev_up_array, i + step))
line.set_xy1(array.get(dev_dn_line_array, i / (step * 2)), x=bar_index - i, y=array.get(dev_dn_array, i))
line.set_xy2(array.get(dev_dn_line_array, i / (step * 2)), x=bar_index - i - step, y=array.get(dev_dn_array, i + step))
|
TPG.Buy sell RSI Scapl XAU | https://www.tradingview.com/script/UIsbTtzD-TPG-Buy-sell-RSI-Scapl-XAU/ | TrungChuThanh | https://www.tradingview.com/u/TrungChuThanh/ | 486 | 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/
// © TrungChuThanh
//@version=4
study("RSI Signals", overlay=true, shorttitle="TPG.Buy sell RSI Scapl XAU")
//Inputs
rsiL = input(title="RSI Length", type=input.integer, defval=7)
rsiOBI = input(title="RSI Overbought", type=input.integer, defval=70)
rsiOSI = input(title="RSI Oversold", type=input.integer, defval=30)
fibLevel = input(title="Hammer Body Size", type=input.float, defval=0.333, step=0.01)
BullBearEngulf = input(title="Bullish Bearish Engulfing", type=input.bool, defval=true)
hammerShooting = input(title="Hammer Shooting Bar", type=input.bool, defval=false)
twoBullBearBar = input(title="Two Bull Bear Bar", type=input.bool, defval=false)
//RSI VALUE
myRsi = rsi(close , rsiL)
//RSI OVERBOUGHT / OVERSOLD
rsiOB = myRsi >= rsiOBI
rsiOS = myRsi <= rsiOSI
///////////=Hammer & Shooting star=/////////////
bullFib = (low - high) * fibLevel + high
bearFib = (high - low) * fibLevel + low
// Determine which price source closses or open highest/lowest
bearCandle = close < open ? close : open
bullCandle = close > open ? close : open
// Determine if we have a valid hammer or shooting star
hammer = (bearCandle >= bullFib) and rsiOS
shooting = (bullCandle <= bearFib) and rsiOB
twoGreenBars = (close > open and close[1] > open[1]) and rsiOS
twoRedBars = (close < open and close[1] < open[1]) and rsiOB
/////////////////////////////////////////////
// Engulfing candles
bullE = (close > open[1] and close[1] < open[1])
//or hammer or twoGreenBars
bearE = close < open[1] and close[1] > open[1]
//or shooting or twoRedBars
///////////////////////////////////////////
// ((x) y) farmula defination is: X is gona be executed before Y,
TradeSignal = ((rsiOS or rsiOS[1]) and bullE) or ((rsiOB or rsiOB[1]) and bearE)
if (TradeSignal and bearE and BullBearEngulf)
label.new(x= bar_index, y= na, text="Sell", yloc= yloc.abovebar,color= color.maroon, textcolor= color.white, style= label.style_label_down, size=size.normal)
plotshape(TradeSignal and bearE and BullBearEngulf, title="Overbought", location=location.abovebar, color=color.orange, style=shape.triangleup, size=size.auto, text="")
if (TradeSignal and bullE and BullBearEngulf)
label.new(x= bar_index, y= na, text="Buy", yloc= yloc.belowbar,color= color.green, textcolor= color.white, style= label.style_label_up, size=size.normal)
plotshape(TradeSignal and bullE and BullBearEngulf, title="Oversold", location=location.belowbar, color=color.lime, style=shape.triangleup, size=size.auto, text="")
//////////////////////////////
if (shooting and hammerShooting)
label.new(x= bar_index, y= na, text="SS", yloc= yloc.abovebar,color= color.purple, textcolor= color.white, style= label.style_label_down, size=size.normal)
plotshape(shooting and hammerShooting, title="Overbought + hammer/shooting", location=location.abovebar, color=color.purple, style=shape.triangledown, size=size.auto, text="")
if (hammer and hammerShooting)
label.new(x= bar_index, y= na, text="HMR", yloc= yloc.belowbar,color= color.blue, textcolor= color.white, style= label.style_label_up, size=size.normal)
plotshape(hammer and hammerShooting, title="Oversold + hammer/shooting", location=location.belowbar, color=color.lime, style=shape.triangledown, size=size.auto, text="")
///////////////////////////
if (twoGreenBars and twoBullBearBar)
label.new(x= bar_index, y= na, text="2Bull", yloc= yloc.belowbar,color= color.olive, textcolor= color.white, style= label.style_label_up, size=size.normal)
plotshape(twoGreenBars and twoBullBearBar, title="Oversold + 2bulls", location=location.belowbar, color=color.lime, style=shape.triangledown, size=size.auto, text="")
if (twoRedBars and twoBullBearBar)
label.new(x= bar_index, y= na, text="2Bear", yloc= yloc.abovebar,color= color.red, textcolor= color.white, style= label.style_label_down, size=size.normal)
plotshape(twoRedBars and twoBullBearBar, title="Overbought + 2bears", location=location.abovebar, color=color.blue, style=shape.triangledown, size=size.auto, text="")
// Send Alert if Candle meets our condition
alertcondition(TradeSignal, title="RSI SIGNAL", message="RSI Signal Detected fot {{ticker}}")
|
Extended Parallel Channels | https://www.tradingview.com/script/Rza68dON-Extended-Parallel-Channels/ | algotraderdev | https://www.tradingview.com/u/algotraderdev/ | 122 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © algotraderdev
//@version=5
indicator('Extended Parallel Channels', overlay = true, max_lines_count = 500)
const string ANCHORS_GROUP = 'Anchors'
int T1 = input.time(0, 'X1', confirm = true, inline = 'First Anchor', group = ANCHORS_GROUP, display = display.none)
float Y1 = input.price(0, 'Y1', confirm = true, inline = 'First Anchor', group = ANCHORS_GROUP, display = display.none)
int T2 = input.time(0, 'X2', confirm = true, inline = 'Second Anchor', group = ANCHORS_GROUP, display = display.none)
float Y2 = input.price(0, 'Y2', confirm = true, inline = 'Second Anchor', group = ANCHORS_GROUP, display = display.none)
int T3 = input.time(0, 'X3', confirm = true, inline = 'Third Anchor', group = ANCHORS_GROUP, display = display.none)
float Y3 = input.price(0, 'Y3', confirm = true, inline = 'Third Anchor', group = ANCHORS_GROUP, display = display.none)
const string QUANTITIES_GROUP = 'Quantities'
int NUM_LINES = input.int(10, 'Number of Lines to Extend in Each Direction', group = QUANTITIES_GROUP, display = display.none)
int DIVISION_FACTOR = input.int(1, 'Sub-Channel Division Factor',
minval = 1,
tooltip = 'Number of sub-channels to divide each channel into.',
group = QUANTITIES_GROUP,
display = display.none)
const string THEME_GROUP = 'Theme'
string STYLE_SOLID = '⎯⎯'
string STYLE_DASHED = '- - -'
string STYLE_DOTTED = '·······'
string STYLE_STRING = input.string(STYLE_DASHED, 'Line Style',
options = [
STYLE_SOLID,
STYLE_DASHED,
STYLE_DOTTED
],
group = THEME_GROUP,
display = display.none)
string STYLE = switch STYLE_STRING
STYLE_SOLID => line.style_solid
STYLE_DASHED => line.style_dashed
STYLE_DOTTED => line.style_dotted
color LINE_COLOR = input.color(#5d606b, title = 'Line Color', group = THEME_GROUP, display = display.none)
color ANCHOR_COLOR = input.color(#2962ffaa, 'Anchor Color', group = THEME_GROUP, display = display.none)
color BG_COLOR = input.color(#5d606b33, 'Background Color', group = THEME_GROUP, display = display.none)
// @function Highlights the anchor points so that it's easier to spot them in the chart.
// @param x The x coordinate (UNIX timestamp).
// @param y The y coordinate (price).
highlight(int x, float y) =>
label.new(x, y, xloc = xloc.bar_time, style = label.style_circle, size = size.tiny, color = ANCHOR_COLOR)
// Converts the X coordinates from UNIX timestamp into bar_index.
// Using bar_index is necessary here since the index delta between adjacent bars is a constant (1), whereas the UNIX
// timestamp delta between adjacent bars can be variable, which can cause troubles in the slope calculation later.
var int x1 = na
var int x2 = na
var int x3 = na
if na(x1) and time >= T1
x1 := bar_index
if na(x2) and time >= T2
x2 := bar_index
if na(x3) and time >= T3
x3 := bar_index
var plotted = false
if barstate.islast and not plotted
plotted := true
highlight(T1, Y1)
highlight(T2, Y2)
highlight(T3, Y3)
int dx = x2 - x1
float dy = Y2 - Y1
if dx != 0
// Calculate the slope and intercept using the line equation: y = kx + b.
float k = dy / dx
float b1 = Y1 - k * x1
float b3 = Y3 - k * x3
// Plot the channels
float db = (b3 - b1) / DIVISION_FACTOR
int num = NUM_LINES * DIVISION_FACTOR
for i = -num to num + 1
line.new(x1, Y1 + db * i, x2, Y2 + db * i, xloc.bar_index, extend.both, LINE_COLOR, STYLE)
// Fill the background for the main channel.
line a = line.new(x1, Y1, x2, Y2, xloc.bar_index, extend.both, #00000000)
line b = line.new(x1, k * x1 + b3, x2, k * x2 + b3, xloc.bar_index, extend.both, #00000000)
linefill.new(a, b, BG_COLOR)
|
Risk Reward Optimiser [ChartPrime] | https://www.tradingview.com/script/cuWPYbhn-Risk-Reward-Optimiser-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 641 | 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/
// © ChartPrime
//@version=5
indicator("Risk Reward Optimiser [ChartPrime]",overlay = true,max_lines_count = 500,max_labels_count = 500)
// --- { Matrix & arrays
type Dat
matrix<int> MTX
matrix<float> PNL
matrix<float> PLOT
matrix<float> Maxprofit
array<color> Col
array<float> MAXPF
array<float> MAXPNL
array<float> MAXWin
array<bool> Signals
array<float> MAXBOX
array<box> Box
array<float> Highs
array<float> LOWS
array<label> Labels
map<string, color> Colors
var BackTest = Dat.new(
matrix.new<int>(7, 2, 0),
matrix.new<float>(7, 2, 0),
matrix.new<float>(7, 3, 0),
matrix.new<float>(7, 3, 0),
array.new_color(7,color.black),
array.new_float(7),
array.new_float(7),
array.new_float(7),
array.new_float(7),
array.new_float(1,0),
array.new_box(14),
array.new_float(50),
array.new_float(50),
array.new_label(7),
map.new<string, color>()
)
if barstate.isfirst
BackTest.Colors.put("White" , color.new(chart.fg_color,30))
BackTest.Colors.put("Green" , color.rgb(21, 112, 5, 42))
BackTest.Colors.put("Red" , color.rgb(136, 11, 11, 39))
BackTest.Colors.put("Select" , color.rgb(23, 238, 216, 26))
array<string> columns =
array.from('Ratio','Total Trades','Wins','Losses','Winrate','PF','PNL % ')
// -- }
// --- { Inputs and Vars
EXTDeal = false
var bool Shape = false
string ENTRYG = "➞ Entry Setup Settings 🔸"
string SLGROUP = "➞ Risk Setup Settings 🔸"
string BACKDATE = "➞ Backtest date range 🔸"
string RISKGROUP = "➞ Risk to Reward Settings 🔸"
string DASHGROUP = "➞ DASHGROUP Settings 🔸"
string DYNAMICSLG = "➞ Stoploss Settings 🔸"
string VISUAL = "➞ Visuals Settings🔸"
string EXT = " 🔽 External indicator Settings 🔸"
string INT = " 🔽 Internal Settings 🔸⮯"
string _AROON = " 🔸 Aroon Settings 🔸⭝"
string _AO = " 🔸 AO Settings 🔸⭝"
string _RSI = " 🔸 RSI Settings 🔸⭝"
string _MACD = " 🔸 MACD Settings 🔸⭝"
string _PSAR = " 🔸 PSAR Settings 🔸⭝"
string _STOCH = " 🔸 STOCH Settings 🔸⭝"
string _STOCHRSI = " 🔸 STOCH RSI Settings 🔸⭝"
string _MA = " 🔸 Moving Avg Settings 🔸⭝"
string _ST = " 🔸 SuperTrend Settings 🔸⭝"
string NAME = "RRO Backtester [ChartPrime]"
string SLZ2TOOL = "Select Which SL Type you wanna use ?! Dynamic SL or Fixed SL input"
string RRTPTIP = "When Dynamic system is selected this acts as RR Ratio , else its Fixed TP input"
string EXTIP = "Select external indicator plot"
string position = input.string("Top Right",
options = [
"Middle Right",
"Top Center",
"Top Right",
"Middle Left",
"Middle Center",
"Bottom Left",
"Bottom Center",
"Bottom Right"],
title = 'Position',
inline = "001",
group = DASHGROUP
)
string textSize = input.string("Small",
options = [
"Tiny",
"Small",
"Normal",
"Auto"],
title = 'Size',
inline = "001",
group = DASHGROUP
)
string MAXWHAT = input.string("Winrate",
options = [
"Winrate",
"Profit Factor",
"PNL"],
title = '♻️ Highlight Max',
inline = "002",
group = DASHGROUP
)
// Date Range inputs
bool limitRange = input.bool(title='Backtest Date', defval=false, group=BACKDATE)
int Stime = input.time(defval=timestamp('11 OCT 2010 00:00 +0000'), title='Start Time', group=BACKDATE)
int Etime = input.time(defval=timestamp('31 Dec 2080 00:00 +0000'), title='End Time', group=BACKDATE)
// Entry Inputs
bool EntryType = input.string("Internal", title="🌀 Entry Type ",
options=["External", "Internal"],
group=ENTRYG,
inline = "00",
tooltip = "Internal")
== "Internal"
float external_indicator = input.source(defval=close, title=' External indicator ',
group=EXT,
tooltip=EXTIP,
inline = "01")
float deal_start_value = input.int(defval=100, title=' External Value ',
group=EXT,
tooltip="Plot Value",
inline = "02")
//////////////////// INTERNAL /////////////////////////
bool AOActive = input.bool(false,"AO",group = INT,inline = "02")
bool MAActive = input.bool(false,"MA",group = INT,inline = "02")
bool RSIActive = input.bool(true,"RSI",group = INT,inline = "02")
bool MACDActive = input.bool(false,"MACD",group = INT,inline = "02")
bool AroonActive = input.bool(false,"Aroon",group = INT,inline = "06")
bool STActive = input.bool(false,"SuperTrend",group = INT,inline = "06")
bool StochActive = input.bool(false,"Stochastic",group = INT,inline = "06")
bool StochRSIActive = input.bool(false,"Stochastic RSI",group = INT,inline = "06",tooltip = "Indicators Activation")
// ---- { External indicator built in code
// -- ARoon
int Aroonlength = input.int(14, minval=1,group = _AROON,title = "length",inline = "0001")
string AroonType = input.string("Crossover", title="Type",
options=["Crossover", ">","<"],
group=_AROON,inline = "0001"
)
float AroonValue = input.float(40,"Value",group = _AROON,inline = "0001")
// -- AO
string AOType = input.string("Change to Green", title="Type",
options=["Change to Green", ">","<"],
group=_AO,inline = "0001"
)
float AOValue = input.float(0.002,"Value",group = _AO,inline = "0001")
// -- RSI
int RSIlength = input.int(14, minval=1,group = _RSI,title = "length",inline = "0001")
string RSIType = input.string("Crossover", title="Type",
options=["Crossover", ">","<"],
group=_RSI,inline = "0001"
)
float RSIValue = input.float(40,"Value",group = _RSI,inline = "0001")
// -- MACD
int MACDFast = input.int(12, minval=1,group = _MACD,title = "Fast",inline = "0001")
int MACDslow = input.int(26, minval=1,group = _MACD,title = "Slow",inline = "0001")
int MACDSmooth = input.int(9, minval=1,group = _MACD,title = "Smooth",inline = "0001")
string MACDType = input.string("Crossover", title="Type",
options=["Crossover", ">","<"],
group=_MACD,inline = "0002"
)
float MACDValue = input.float(0.002,"Value",group = _MACD,inline = "0002")
//--- Stoch
int StochK = input.int(14, title="%K Length", minval=1,group = _STOCH,inline = "0001")
int StochSM = input.int(1, title="%K ", minval=1,group = _STOCH,inline = "0001")
int StochD = input.int(3, title="%D", minval=1,group = _STOCH,inline = "0001")
string StochType = input.string("Crossover", title="Type",
options=["Crossover", ">","<"],
group=_STOCH,inline = "0002"
)
float StochValue = input.float(40,"Value",group = _STOCH,inline = "0002")
// --- StochRSI
int StochRSIK = input.int(14, title="K Smooth", minval=1,group = _STOCHRSI,inline = "0001")
int StochRSID = input.int(1, title="D Smooth ", minval=1,group = _STOCHRSI,inline = "0001")
int StochRSILen = input.int(3, title="Length", minval=1,group = _STOCHRSI,inline = "0001")
string StochRSIType = input.string("Crossover", title="Type",
options=["Crossover", ">","<"],
group=_STOCHRSI,inline = "0002"
)
float StochRSIValue = input.float(40,"Value",group = _STOCHRSI,inline = "0002")
int MA1 = input.int(7, title="MA1 Length", minval=1,group = _MA,inline = "0001")
string MAType = input.string("SMA", title="Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"],inline="0001",group=_MA)
int MA2 = input.int(13, title="MA2 Length", minval=1,group = _MA,inline = "0001")
string MAType2 = input.string("SMA", title="Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"],inline="0001",group=_MA)
// --- SuperTrend
float factor = input.float(3,"Factor",group = _ST,inline = "0001")
int atrPeriod = input.int(14,"Period",group = _ST,inline = "0001")
///---- Stop loss inputs
string dynamicSelect = input.string("ATR SL", title="SL Type ",
options=["ATR SL", "Pivot low", "VWAP SL"],
group=DYNAMICSLG,inline = "02",
tooltip = "Select how you want your Stoploss to be calculated")
float ATRSL = input.float(1.4,"ATR Factor ",step = 0.1,
group = DYNAMICSLG,
inline = "03",
tooltip = "Only used with ATR SL")
int LB = input.int(8, minval=0,title="Pivot Lookback ",
group=DYNAMICSLG,
inline = "04",
tooltip = "looks for lower low ,Only used with Pivot Low")
float VWAPSL = input.float(2.5,"Vwap Multiplier ",step = 0.1,
group=DYNAMICSLG,
inline = "05",
tooltip = "Gets the Vwap value ,Only used with Vwap SL")
// RR Values
CASH = input.int(10000,"Capital",group = RISKGROUP)
RR1 = input.float(1.0, step=0.1,title = "RR 1",group = RISKGROUP)
RR2 = input.float(1.5, step=0.1,title = "RR 2",group = RISKGROUP)
RR3 = input.float(2.0, step=0.1,title = "RR 3",group = RISKGROUP)
RR4 = input.float(2.5, step=0.1,title = "RR 4",group = RISKGROUP)
RR5 = input.float(3.0, step=0.1,title = "RR 5",group = RISKGROUP)
RR6 = input.float(3.5, step=0.1,title = "RR 6",group = RISKGROUP)
RR7 = input.float(5.0, step=0.1,title = "RR 7",group = RISKGROUP)
// visuals
ShowTrades = input.bool(true,"Show Trades" ,inline = "002",group = VISUAL)
ShowTP = input.bool(true,"Show TP" ,inline = "004",group = VISUAL)
ShowHist = input.bool(true,"Show histogram" ,inline = "005",group = VISUAL)
////////////////////////////////////////////////////////
// -- }
// { General Functions
// @function Switch between various type of MA as per use selection.
// @param source (series float) the series needed to calculate the wanted MA.
// @param length (simple int) the length of the wanted MA
// @returns (float) series of the wanted MA
MAVG(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"RMA" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
// @function function to switch condition for each indicator
// @param type (string) the selected string by the user drop menu.
// @param val1 (series float) the first indicator value
// @param val2 (series float) the 2nd indicator value
// @param val3 (simple float) user input value
// @returns (bool) indicator conditional entry
ConditionSwitcher(type,val1,val2,val3)=>
switch type
"Crossover" => ta.crossover(val1,val2)
"Change to Green" => ta.crossover(val1,val2)
">" => val1 > val3
"<" => val1 < val3
//--- > replaced with str.format() it gives a better time string
// @function function to return time string from seconds
// @param seconds (int) seconds that we want to convert to string
// @returns (string) Time string
TIMEfrom_seconds(seconds) =>
if seconds >= 86400
string string = str.tostring(math.round(seconds / 86400, 1)) + ' days'
else if seconds >= 3600
string string = str.tostring(math.round(seconds / 3600, 1)) + ' hours'
else
string string = str.tostring(math.round(seconds / 60, 1)) + ' mins'
// -- }
// @function function to switch text & table size
// @param size (string) the selected string by the user drop menu.
// @returns (string) table & table size
// --- { Dashboard
switchsize(size) =>
switch size
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Auto' => size.auto
// @function function to switch & change table position
// @param Pos (string) the selected string by the user drop menu.
// @returns (string) table position
switchPos(Pos) =>
switch Pos
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
// initiate table
var DataTable = table.new(switchPos(position),
15,
50,
frame_color = #56555bd5,
frame_width = 0,
border_width = 0
)
// @function function to generate row colors depend on a condition
// @param val (float) the Calculation main point coming from the PNL on each table row
// @returns (color) color
G_Color(val)=>
Pos = color.from_gradient(val,
0,
400,
color.rgb(1, 165, 124),
color.rgb(2, 85, 46, 24))
Nig = color.from_gradient(val,
-0,
-400,
color.red,
color.rgb(68, 5, 4))
Col = val > 0 ? Pos : Nig
// @function function to generate rows for a predefined table
// @param c (int) the column number
// @param r (int) the Row number
// @param Text (string) the text that we need to show in the Row
// @param bg (color) the background color for the Row
// @returns table cell with a predefined values
Cell(c,r,Text,bg)=>
table.cell(DataTable,c,r,Text,
bgcolor=bg,text_color = color.white,text_size = switchsize(textSize))
// -- }
// -- }
//----- { SL Calculation
// -- ATR
x2 = low - ta.rma(ta.tr(true), 14) * ATRSL
// -- Pivot Low
PVLOW = ta.lowest(low,LB)
// -- VWAP
vwap = math.sum(ta.vwap(ta.tr(true)),14) * volume
volumz = math.sum(volume,14)
atr_vwap_volume = math.abs(vwap / volumz)
VWAPSLZ = low - atr_vwap_volume * VWAPSL
// @function function to switch between SL values depend on the selected SL type
// @param SLC (string) the selected string by the user drop menu.
// @returns (float) gives the wanted type stoploss value
my_stop(SLC) =>
switch SLC
"ATR SL" => x2
"Pivot low" => PVLOW
"VWAP SL" => VWAPSLZ
sl = my_stop(dynamicSelect)
// }
// ---- { Deal Condition
// ------ Internal indicators
// -- Aroon
Aroonupper = 100 * (ta.highestbars(high, Aroonlength) + Aroonlength)/Aroonlength
Aroonlower = 100 * (ta.lowestbars(low, Aroonlength) + Aroonlength)/Aroonlength
ArronLONG = ConditionSwitcher(AroonType,Aroonupper,Aroonlower,AroonValue)
// -- AO
ao = ta.sma(hl2,5) - ta.sma(hl2,34)
diff = ao - ao[1]
AOLONG = ConditionSwitcher(AOType,diff,0,AOValue)
// --- RSI
RSI = ta.rsi(close,RSIlength)
RMA = ta.sma(RSI,RSIlength)
RSILONG = ConditionSwitcher(RSIType,RSI,RMA,RSIValue)
// --- MACD
[macdLine, signalLine, _] = ta.macd(close, MACDFast, MACDslow, MACDSmooth)
MACDLong = ConditionSwitcher(MACDType,macdLine,signalLine,MACDValue)
// --- Stoch
Stochk = ta.sma(ta.stoch(close, high, low, StochK), StochSM)
Stochd = ta.sma(Stochk, StochD)
StochLong = ConditionSwitcher(StochType,Stochk,Stochd,StochValue)
// --- StochRSI
rsi1 = ta.rsi(close, StochRSILen)
StochRSIk11 = ta.sma(ta.stoch(rsi1, rsi1, rsi1, StochRSILen), StochRSIK)
StochRSId11 = ta.sma(StochRSIk11, StochRSID)
StochRSILong = ConditionSwitcher(StochRSIType,StochRSIk11,StochRSId11,StochRSIValue)
//--- MA
_MA1 = MAVG(close,MA1,MAType)
_MA2 = MAVG(close,MA2,MAType2)
MALong = ta.crossover(_MA1,_MA2)
// --- SuperTrend
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
STlong = ta.crossunder(direction , 0)
// Internal Conditions
internal = (MACDActive ? MACDLong : true) and
(AroonActive ? ArronLONG : true) and
(AOActive ? AOLONG : true) and
(RSIActive ? RSILONG : true) and
(StochActive ? StochLong : true) and
(StochRSIActive ? StochRSILong : true) and
(MAActive ? MALong : true) and
(STActive ? STlong : true)
// ------ Internal indicators
EXTDeal := if external_indicator == deal_start_value
true
// do we need to test within a range ?!
// @function function to limit the Backtesting within a range if needed
// @returns (bool) time == certain time we want the Backtester to operate in OR if its not active it gives True
Backdate() =>
in_date_range = true
if limitRange
in_date_range := time >= Stime and time <= Etime
else
in_date_range := true
// get the abs between entry and sl
longDiffSL = math.abs(close - sl)
// final entry condition is it going to be Internal or External ?!
ENTRY = switch
EntryType => internal and Backdate()
not EntryType => EXTDeal and Backdate()
// }
// ---- { Backtester
// function to generate a diff color for each RR trade , to know which has ended and which RR still open
GenCol(i)=>
ColGen = color.new(color.rgb((23 * (i + 4)) % 255, (79 * (i + 4)) % 255, (127 * (i + 4)) % 255), 30)
ColGen
// COLoR = color.rgb(math.random(10,150),math.random(10,150),math.random(10,150))
// Backtester function , runs the RR values on the trades
Backtest(bool sig,tp,i) =>
var active_trade = false
var TP1 = 0.0
var SL = 0.0
var En = 0.0
var label TO_lab = na
if sig and not active_trade
// set tps
TP1 := close + (tp * longDiffSL)
SL := close - longDiffSL
En := close
active_trade:= true
BackTest.Col.set(i,color.new(GenCol(bar_index), 40))
if active_trade
// get the active trade signal for plotting
BackTest.Signals.set(i,true)
// get the data needed for plotting
BackTest.PLOT.set(i,0,En)
BackTest.PLOT.set(i,1,TP1)
BackTest.PLOT.set(i,2,SL)
if high >= TP1
// lets show which RR ratio hit the TP on chart
if ShowTP
TO_lab:=label.new(bar_index - 5 ,
TP1,
"RR " + str.tostring(float(tp),format= "#.00"),
color = color.red,
style = label.style_none,
textcolor = chart.fg_color,
size = size.small)
tpValue = ((TP1 - En) / En) * 100
// lets calculate the return in USD value
PnlV = math.round(tpValue * CASH / 100,2)
// lets get the max profitable trade
if BackTest.Maxprofit.get(i,0) < PnlV
BackTest.Maxprofit.set(i,0,PnlV)
BackTest.Maxprofit.set(i,1,bar_index)
BackTest.Maxprofit.set(i,2,time)
// label.new(bar_index,high,"BIG ONE " + str.tostring(i),size = size.huge,color = color.maroon)
BackTest.MTX.set(i,0,BackTest.MTX.get(i,0)+1)
BackTest.PNL.set(i,0,BackTest.PNL.get(i,0)+PnlV)
active_trade := false
BackTest.Signals.set(i,false)
else if low <= SL
slValue = -((En - SL) / En) * 100
PnlV = math.round(slValue * CASH / 100,2)
BackTest.MTX.set(i,1,BackTest.MTX.get(i,1)+1)
BackTest.PNL.set(i,1,BackTest.PNL.get(i,1)+(PnlV))
active_trade := false
BackTest.Signals.set(i,false)
Backtest(ENTRY,RR1,0)
Backtest(ENTRY,RR2,1)
Backtest(ENTRY,RR3,2)
Backtest(ENTRY,RR4,3)
Backtest(ENTRY,RR5,4)
Backtest(ENTRY,RR6,5)
Backtest(ENTRY,RR7,6)
// function to calculate the PNL
ReturnCal(val,val2) =>
rtn = val + val2
math.round((rtn / CASH) * 100,2)
// function to calculate the Profit factor
PFCal(x,y)=>
math.round(x/(-y),2)
array<string> Ratios =
array.from(
str.tostring(RR1),
str.tostring(RR2),
str.tostring(RR3),
str.tostring(RR4),
str.tostring(RR5),
str.tostring(RR6),
str.tostring(RR7)
)
// -- }
// ---- { DashBoard Build
if barstate.islast
// lets build the name
for i = 2 to 8
Cell(i,0,i == 2 ? NAME : "",color.rgb(45, 45, 119))
table.merge_cells(DataTable, 2, 0, 8, 0)
// lets build the columns
for i = 0 to columns.size() -1
Cell(i+2,1,columns.get(i),#126e79)
// for i = 0 to BackTest.MTX.rows() -1
// Col2 = color.from_gradient(math.random(10,100),
// 10,
// 120,
// bottom_color = color.rgb(100, 156, 219,36),
// top_color = color.rgb(154, 18, 127,36))
// lets set the RR ratio into the table
for i = 0 to Ratios.size() -1
Col = color.from_gradient(i,
0,
Ratios.size(),
bottom_color = color.rgb(20, 30, 48,36),
top_color = color.rgb(36, 59, 85,36))
Cell(2,i+2,Ratios.get(i),Col)
for i = 0 to BackTest.MTX.rows() - 1
Nut = color.from_gradient(
i,
0,
BackTest.MTX.rows(),
bottom_color = #243B55,
top_color = #37383b
)
// stats data into the table
for j = 0 to BackTest.MTX.columns() - 1
Total = BackTest.MTX.get(i, 0) + BackTest.MTX.get(i, j)
Cell(3,(i+1)+ 1,str.tostring(Total),Nut)
if BackTest.MAXBOX.get(0)< Total
BackTest.MAXBOX.set(0,Total)
if j == 0
Cell(4,(i+1)+ 1,str.tostring(BackTest.MTX.get(i, 0)),Nut)
else
Cell(5,(i+1)+ 1,str.tostring(BackTest.MTX.get(i, j)),Nut)
Cell(6,(i+1)+ 1,str.tostring(math.round((BackTest.MTX.get(i, 0) / (BackTest.MTX.get(i, 0) + BackTest.MTX.get(i, j))) * 100,2)) +" %",Nut)
BackTest.MAXWin.set(i,math.round((BackTest.MTX.get(i, 0) / (BackTest.MTX.get(i, 0) + BackTest.MTX.get(i, j))) * 100,2))
for i = 0 to BackTest.PNL.rows() - 1
Nut = color.from_gradient(
i,
0,
BackTest.PNL.rows(),
bottom_color = #243B55,
top_color = #37383b
)
for j = 0 to BackTest.PNL.columns() - 1
BackTest.MAXPF.set(i,PFCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j)))
BackTest.MAXPNL.set(i,ReturnCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j)))
Cell(7,(i+1)+ 1,str.tostring(PFCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j))) +" %",PFCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j))< 1 ? color.rgb(121, 12, 12, 33): Nut)
Cell(8,(i+1)+ 1,
str.tostring(ReturnCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j))) + " %",
G_Color(ReturnCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j))))
tootip = "Max Profit : " + str.format("{0, number, currency}",BackTest.Maxprofit.get(i,0)) + "\n" +
"Max % : " + str.tostring(math.round(BackTest.Maxprofit.get(i,0) / 100,2)) + " %" + "\n" +
"Bar Index " + str.tostring(BackTest.Maxprofit.get(i,1)) + "\n" +
"Time : " + str.format("{0,date,medium}",BackTest.Maxprofit.get(i,2))
table.cell_set_tooltip(DataTable,2,i+2,tooltip = tootip)
// -- }
// --------{ Histogram
// lets get the ATR needed to calculate the highest point
method volAdj(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
Adj = volAdj(30)
// lets calculate the mid point for the highest and lowest for the boxes
for i = 0 to 49
Hi = high
Lo = low
max_bars_back(Hi,50)
max_bars_back(Lo,50)
BackTest.Highs.set(i,Hi)
BackTest.LOWS.set(i,Lo)
// boxes highest and lowest points
HighPoint = BackTest.Highs.avg() + ( Adj * 60)
LowPoint = BackTest.LOWS.avg()
// lets calculate each space from highest and lowest point for each trade
Spacing = (HighPoint - LowPoint) / BackTest.MAXBOX.sum()
// lets build the boxes
if barstate.islast and ShowHist
var Winspace = 0.0
var LossSpace = 0.0
var Num = 0
var TotalS = 0.0
var avgWin = 0.0
var avgLoss = 0.0
for i = 0 to BackTest.MTX.rows() - 1
label.delete(BackTest.Labels.get(i))
for j = 0 to BackTest.MTX.columns() - 1
// Lets calculate the win trades space
Winspace := (Spacing * BackTest.MTX.get(i, 0)) + LowPoint
// Lets calculate the lost trades space
LossSpace := (Spacing * BackTest.MTX.get(i, j)) + Winspace
// total trades
TotalS := BackTest.MTX.get(i, 0) + BackTest.MTX.get(i, j)
// lets calculate the avg loss and win %
avgWin := math.round(ReturnCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j)) / BackTest.MTX.get(i, 0),2)
avgLoss := math.round(ReturnCal(BackTest.PNL.get(i, 0),BackTest.PNL.get(i, j)) / BackTest.MTX.get(i, j),2)
// lets label the AVG win and loss
Tip = "Average Win : " + str.tostring(avgWin) + " %"+ "\n" + "Average Loss : " + str.tostring(avgLoss) + " %" +"\n"
BackTest.Labels.set(i,label.new(bar_index+52+i+Num,LowPoint - ( Adj * 1),style = label.style_label_up,color = #126e79,tooltip = Tip ,size = size.small))
// Green Winning BOX
BackTest.Box.push(box.new(bar_index+50+i+Num,Winspace,bar_index+53+i+Num,LowPoint,
border_color = color.rgb(0, 187, 212, 100),
bgcolor = #126e79,
text = str.tostring(BackTest.MTX.get(i, 0) / TotalS * 100,"#.00") +" %",
text_color = chart.fg_color,
text_wrap =text.wrap_auto))
// RED Losing BOX
BackTest.Box.push(box.new(bar_index+50+i+Num,LossSpace,bar_index+53+i+Num,Winspace,
border_color = color.rgb(0, 187, 212, 100),
bgcolor = #37383b,
text = str.tostring(Ratios.get(i)),
text_color = chart.fg_color))
Num+=3
//
// lets delete boxes if they are more than needed
if BackTest.Box.size() > 14
for i = 0 to 13
box.delete(BackTest.Box.shift())
// lets reset the num var to avoid pushing the boxes far away from price
Num:=0
// creating a closing box
var box D = na , box.delete(D)
D:=box.new(bar_index+50,LowPoint,bar_index+77,LowPoint - ( Adj * 1),border_color = color.rgb(0, 187, 212, 100),bgcolor = #37383b)
// -- }
// ---- { Plotting with Array and matrix
// lets plot a shape when the SL is hit
// for i = 0 to BackTest.Signals.size() -1
// if (BackTest.Signals.get(i)[1] == true and BackTest.Signals.get(i) == false)
// if low <= BackTest.PLOT.get(i,2)
// // changing shape condition to true
// Shape:=true
// plotshape(ShowSL and Shape,style= shape.labelup,color = color.rgb(208, 11, 11, 37),location = location.belowbar,text = "SL",textcolor = chart.fg_color)
// resetting shape condition to false to prevent printing wrong shapes
// Shape:=false
// lets plot trades
plot(ShowTrades and BackTest.Signals.get(0) ? BackTest.PLOT.get(0,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(0) ? BackTest.PLOT.get(0,1) : na , color = BackTest.Col.get(0) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(0) ? BackTest.PLOT.get(0,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(1) ? BackTest.PLOT.get(1,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(1) ? BackTest.PLOT.get(1,1) : na , color = BackTest.Col.get(1) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(1) ? BackTest.PLOT.get(1,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(2) ? BackTest.PLOT.get(2,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(2) ? BackTest.PLOT.get(2,1) : na , color = BackTest.Col.get(2) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(2) ? BackTest.PLOT.get(2,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(3) ? BackTest.PLOT.get(3,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(3) ? BackTest.PLOT.get(3,1) : na , color = BackTest.Col.get(3) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(3) ? BackTest.PLOT.get(3,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(4) ? BackTest.PLOT.get(4,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(4) ? BackTest.PLOT.get(4,1) : na , color = BackTest.Col.get(4) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(4) ? BackTest.PLOT.get(4,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(5) ? BackTest.PLOT.get(5,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(5) ? BackTest.PLOT.get(5,1) : na , color = BackTest.Col.get(5) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(5) ? BackTest.PLOT.get(5,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(6) ? BackTest.PLOT.get(6,0) : na , color = BackTest.Colors.get("White") ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(6) ? BackTest.PLOT.get(6,1) : na , color = BackTest.Col.get(6) ,style =plot.style_linebr)
plot(ShowTrades and BackTest.Signals.get(6) ? BackTest.PLOT.get(6,2) : na , color = BackTest.Colors.get("Red") ,style =plot.style_linebr)
// Lets highlight the row of the selected result
if MAXWHAT == "PNL"
WinIndex = BackTest.MAXPNL.indexof(BackTest.MAXPNL.max())
for i = 2 to 7
table.cell_set_bgcolor(DataTable,i,(WinIndex+1)+ 1,BackTest.Colors.get("Select"))
if MAXWHAT == "Profit Factor"
MAXS = BackTest.MAXPF.indexof(BackTest.MAXPF.max())
for i = 2 to 7
table.cell_set_bgcolor(DataTable,i,(MAXS+1)+ 1,BackTest.Colors.get("Select"))
if MAXWHAT == "Winrate"
MAXSW = BackTest.MAXWin.indexof(BackTest.MAXWin.max())
for i = 2 to 7
table.cell_set_bgcolor(DataTable,i,(MAXSW+1)+ 1,BackTest.Colors.get("Select"))
// -- }
// ---- { to do
// finish the external indicator config // finished
// finish the SL logic // finished
// Create Hist Boxes showing diff in trades for each RR // finished
// plot(BackTest.MTX.trace() ,display = display.data_window,title = "MAX")
// plot(LOWS.size(),display = display.data_window,title = "DARA")
// -- } |
OI Visible Range Ladder [Kioseff Trading] | https://www.tradingview.com/script/Ah9ODgUB-OI-Visible-Range-Ladder-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 124 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("OI Visible Range [Kioseff Trading]", max_lines_count = 500, max_labels_count = 500, overlay= true, max_polylines_count = 100, max_boxes_count = 500)
import RicardoSantos/MathOperator/2
showBull = input.bool (defval = true, title = "Up OI Up Price " , group = "Profiles", inline = "Up")
showBull2 = input.bool (defval = true, title = "Down OI Up Price" , group = "Profiles", inline = "Up")
showBear = input.bool (defval = true, title = "Up OI Down Price" , group = "Profiles", inline = "Dn")
showBear2 = input.bool (defval = true, title = "Down OI Down Price", group = "Profiles", inline = "Dn")
ROWS = input.int (defval = 2000, maxval = 9998, minval = 10, step = 10, title = "Profile Rows", group = "Profile Settings")
factor = input.float (defval = 3 , minval = 1.1, step = 0.1, title = "Scaling Factor", group = "Profile Settings")
cumu = input.float (defval = 70, title = "Value Area", minval = 5, maxval = 95, group = "Profile Settings")
offset = 1
curve = input.bool (defval = false, title = "Curved Profiles", group = "Profile Settings")
same = input.bool (defval = false, title = "Plot Bull VP and Bear VP At Same X-Point", group = "Profile Settings")
showDelta = input.bool (defval = true, title = "Show Summed OI", group = "Summed Values", inline = "D")
mergeDelta = input.bool (defval = false, title = "Merge Columns (Highest Values Displayed)", group = "Summed Values", inline = "D")
deltaRows = input.int (defval = 50, title = "Rows", group = "Summed Values", inline = "D", maxval = 500, minval = 2)
showVals = input.bool (defval = true, title = "Show Summed Values", group = "Summed Values")
dTranspMin = input.int (defval = 100, minval = 0, maxval = 100, title = "Lower Value Gradient Transparency" , group = "Summed Values")
dTranspMax = input.int (defval = 100, minval = 0, maxval = 100, title = "Higher Value Gradient Transparency" , group = "Summed Values")
dTranspGre = input.int (defval = 25 , minval = 0, maxval = 100, title = "Highest Value Pure Transparency", group = "Summed Values")
poc = input.bool (defval = false, title = "Show POC", group = "POC Settings")
wid = input.int (defval = 1, title ="POC Width", minval = 1, group = "POC Settings")
upCol = input.color (defval = #14D990, title = "Up OI Up Price Color", group = "Colors", inline = "Up3")
upCol2 = input.color (defval = #F2B807, title = "Dn OI Up Price Color", group = "Colors", inline = "Up3")
dnCol = input.color (defval = #6929F2, title = "Up OI Dn Price Color", group = "Colors", inline = "Dn3")
dnCol2 = input.color (defval = #F24968, title = "Dn OI Dn Price Color", group = "Colors", inline = "Dn3")
transp = input.int (defval = 80, minval = 0, maxval = 100, group = "Colors", title = "Pofile Fill Transparency")
transp2 = input.int (defval = 0 , minval = 0, maxval = 100, group = "Colors", title = "Pofile Line Transparency")
transp3 = input.int (defval = 25, minval = 0, maxval = 100, group = "Colors", title = "POC Line Transparency")
transp4 = input.int (defval = 90, minval = 0, maxval = 100, group = "Colors", title = "Non-VA Fill Transparency")
left = chart.left_visible_bar_time, right = chart.right_visible_bar_time
if not mergeDelta
deltaRows := math.min(deltaRows, 125)
var rightIndex = 0, var leftIndex = 0
if time > left and leftIndex == 0
leftIndex := bar_index - 1
if time == right
rightIndex := bar_index
req() =>
cont = switch str.contains(syminfo.ticker, ".P")
true => syminfo.ticker + "_OI"
=> str.endswith(syminfo.ticker, "USDT") ? syminfo.ticker + ".P_OI" : syminfo.ticker + "T.P_OI"
switch syminfo.type
"crypto" => cont
=> string(na)
oi = request.security(req(), timeframe.period, close - close[1] , ignore_invalid_symbol = false)
if curve
ROWS := 60
type dataStore
matrix <float> timeVolMat
matrix <float> HLmat
array <int> retArr
matrix <line> pocs
matrix <float> tickLevels
array <float> priceArr
var data = dataStore.new(matrix.new<float>(2, 0), matrix.new<float>(2, 0), array.new_int(), matrix.new<line>(4, 0), priceArr = array.new_float()), //kioseff
tLevels = dataStore.new(tickLevels = matrix.new<float>(5, ROWS, 0.0))
method Float (int id) => float(id)
method double_binary_search_leftmost_reg(array <float> id, i) =>
n = id .binary_search_leftmost (data.HLmat.get(0, i))
n1 = id .binary_search_leftmost (data.HLmat.get(1, i))
[n, n1]
method double_binary_search_delta(array<float>id, i, val, val2) =>
n = id.binary_search_rightmost(val )
n1 = id.binary_search_leftmost (val2)
[n, n1]
method effSwitchReg(matrix<float> id, i, x, div) =>
if data.priceArr.get(i) == 1
switch data.retArr.get(i)
1 => id.set(1, x, id.get(1, x) + data.timeVolMat.get(1, i) / div)
-1 => id.set(2, x, id.get(2, x) + math.abs(data.timeVolMat.get(1, i) / div))
if data.priceArr.get(i) == -1
switch data.retArr.get(i)
1 => id.set(3, x, id.get(3, x) + data.timeVolMat.get(1, i) / div)
-1 => id.set(4, x, id.get(4, x) + math.abs(data.timeVolMat.get(1, i) / div))
lineDraw(y, col) =>
line.new(left, y, right, y, color = color.new(col, transp3), width =wid , xloc = xloc.bar_time)
method drawPOC(matrix<line>id, idrow, newRowUp, newRowUp2, newRowDn, newRowDn2) =>
maxUp = idrow.get(newRowUp.indexof(newRowUp.max())), maxUp2 = idrow.get(newRowUp2.indexof(newRowUp2.max()))
maxDn = idrow.get(newRowDn.indexof(newRowDn.max())), maxDn2 = idrow.get(newRowDn2.indexof(newRowDn2.max()))
if poc
id.add_col(0, array.from(
lineDraw(maxUp, upCol), lineDraw(maxUp2, upCol2),
lineDraw(maxDn, dnCol), lineDraw(maxDn2, dnCol2)))
method setLevels(matrix<float> id) =>
rows = math.abs(data.HLmat.max() - data.HLmat.min()) / (ROWS - 1)
for i = 0 to ROWS - 1
id.set(0, i, data.HLmat.min() + rows * i)
method createPoly(matrix<chart.point> id, array<float> idrow) =>
index = switch same
false => rightIndex
=> leftIndex
if showBull
polyline.new(id.row(0), fill_color = color.new(upCol , transp), line_color = color.new(upCol , transp2), curved = curve)
if showBull2
polyline.new(id.row(1), fill_color = color.new(upCol2, transp), line_color = color.new(upCol2, transp2), curved = curve)
if showBear
polyline.new(id.row(2), fill_color = color.new(dnCol , transp), line_color = color.new(dnCol , transp2), curved = curve)
if showBear2
polyline.new(id.row(3), fill_color = color.new(dnCol2, transp), line_color = color.new(dnCol2, transp2), curved = curve)
norm(newRowUp, newRowDn, newRowUp2, newRowDn2, oldMin, oldMax, newRange) =>
calcs = matrix.new<float>(4, 0)
for i = 0 to ROWS - 1
calcUp = 1 + ((newRowUp .get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcUp2 = 1 + ((newRowUp2.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcDn = 1 + ((newRowDn .get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcDn2 = 1 + ((newRowDn2.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1)
calcs.add_col(calcs.columns(), array.from(calcUp, calcUp2, calcDn, calcDn2))
[calcs.row(0), calcs.row(1), calcs.row(2), calcs.row(3)]
method findValue(matrix <float> id, id2, highest, r1, r2) =>
for i = 1 to id2.size() - 1
slice = id2.slice(math.max(highest - i, 0), math.min(highest + i + 1, id2.size()))
if slice.sum() / id2.sum() >= cumu / 100
id.set(r1, 0, math.max(highest - i, 0))
id.set(r2, 0, math.min(highest + i, id2.size() - 1))
break
method pushShift (array<chart.point> id, valX, valY1, valY2) =>
id.push (chart.point.from_index(valX, valY1))
id.unshift(chart.point.from_index(valX, valY2))
var maxVals = matrix.new<int>(4, 1, 0)
boxDraw(left, top, right, bottom, txt) =>
txtBox = switch showVals
true => str.tostring(txt, format.volume)
=> string(na)
box.new(left, top, right, bottom, text = txtBox,
text_color = chart.fg_color),
method appendSums (matrix <box> id, id2, i, startBox2, startBox, endBox, endBox2, middle, calc, calc2, sumUU, sumUD, sumDU, sumDD) =>
if not mergeDelta
id.add_col(id.columns(), array.from(
boxDraw(startBox2, calc, startBox, calc2, sumUU),
boxDraw(startBox , calc, middle , calc2, sumUD),
boxDraw(middle , calc, endBox , calc2, sumDU),
boxDraw(endBox , calc, endBox2 , calc2, sumDD)
))
else
if i.Float().equal(0)
for x = 0 to 2
id .remove_row()
id.add_col(id.columns(), array.from(
boxDraw(startBox, calc, endBox, calc2, math.max(sumUU, sumUD, sumDU, sumDD))))
id2.push(math.max(sumUU, sumUD, sumDU, sumDD))
method setCoords(matrix<chart.point> id, newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, timeRow, idrow) =>
detPoc = matrix.new<int>(8, 1)
highestUp = newRowUp.indexof(newRowUp.max()), highestUp2 = newRowUp2.indexof(newRowUp2.max())
highestDn = newRowDn.indexof(newRowDn.max()), highestDn2 = newRowDn2.indexof(newRowDn2.max())
detPoc.findValue(newRowUp , highestUp , 0, 1), detPoc.findValue(newRowUp2, highestUp2, 2, 3)
detPoc.findValue(newRowDn, highestDn , 4, 5), detPoc.findValue(newRowDn2, highestDn2, 6, 7)
coordsUpUpVal = array.new<chart.point>(), coordsUpDnVal = array.new<chart.point>()
coordsUpUpVal2 = array.new<chart.point>(), coordsUpDnVal2 = array.new<chart.point>()
coordsDnUpVal = array.new<chart.point>(), coordsDnDnVal = array.new<chart.point>()
coordsDnUpVal2 = array.new<chart.point>(), coordsDnDnVal2 = array.new<chart.point>()
[calcUp, calcUp2, calcDn, calcDn2] = norm(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange)
for i = 0 to newRowUp.size() - 1
newSwitchUp = math.round(leftIndex + offset + calcUp.get(i))
newXUp = math.max(newSwitchUp, math.round(leftIndex + offset))
newSwitchUp2 = math.round(leftIndex + offset + calcUp2.get(i))
newXUp2 = math.max(newSwitchUp2, math.round(leftIndex + offset))
[newSwitchDn, newSwitchDn2] = switch same
false => [math.round(rightIndex - offset - calcDn.get(i)), math.round(rightIndex - offset - calcDn2.get(i))]
=> [math.round(leftIndex + offset + calcDn.get(i)), math.round(leftIndex + offset + calcDn2.get(i))]
[newXDn, newXDn2] = switch same
false => [math.min(newSwitchDn, math.round(rightIndex - offset)), math.min(newSwitchDn2, math.round(rightIndex - offset))]
=> [math.max(newSwitchDn, math.round(leftIndex + offset)), math.max(newSwitchDn2, math.round(leftIndex + offset))]
if detPoc.get(0, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(0, 0) - 1)
coordsUpDnVal.push(chart.point.from_index(newXUp, idrow.get(i)))
if detPoc.get(1, 0).Float().not_equal(newRowUp.size() - 1)
if i.Float().over_equal(detPoc.get(1, 0) + 1)
coordsUpUpVal.push(chart.point.from_index(newXUp, idrow.get(i)))
if i.Float().over_equal(detPoc.get(0, 0)) and i.Float().under_equal(detPoc.get(1, 0))
id.set(0, i, chart.point.from_index(newXUp, idrow.get(i)))
maxVals.set(0, 0, math.max(maxVals.get(0, 0), int(calcUp.get(i))))
if detPoc.get(2, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(2, 0) - 1)
coordsUpDnVal2.push(chart.point.from_index(newXUp2, idrow.get(i)))
if detPoc.get(3, 0).Float().not_equal(newRowUp2.size() - 1)
if i.Float().over_equal(detPoc.get(3, 0) + 1)
coordsUpUpVal2.push(chart.point.from_index(newXUp2, idrow.get(i)))
if i.Float().over_equal(detPoc.get(2, 0)) and i.Float().under_equal(detPoc.get(3, 0))
id.set(1, i, chart.point.from_index(newXUp2, idrow.get(i)))
maxVals.set(1, 0, math.max(maxVals.get(1, 0), int(calcUp2.get(i))))
if detPoc.get(4, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(4, 0) - 1)
coordsDnDnVal.push(chart.point.from_index(newXDn, idrow.get(i)))
if detPoc.get(5, 0).Float().not_equal(newRowDn.size() - 1)
if i.Float().over_equal(detPoc.get(5, 0) + 1)
coordsDnUpVal.push(chart.point.from_index(newXDn, idrow.get(i)))
if i.Float().over_equal(detPoc.get(4, 0)) and i.Float().under_equal(detPoc.get(5, 0))
id.set(2, i, chart.point.from_index(newXDn, idrow.get(i)))
maxVals.set(2, 0, math.max(maxVals.get(2, 0), int(calcDn.get(i))))
if detPoc.get(6, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(6, 0) - 1)
coordsDnDnVal2.push(chart.point.from_index(newXDn2, idrow.get(i)))
if detPoc.get(7, 0).Float().not_equal(newRowDn2.size() - 1)
if i.Float().over_equal(detPoc.get(7, 0) + 1)
coordsDnUpVal2.push(chart.point.from_index(newXDn2, idrow.get(i)))
if i.Float().over_equal(detPoc.get(6, 0)) and i.Float().under_equal(detPoc.get(7, 0))
id.set(3, i, chart.point.from_index(newXDn2, idrow.get(i)))
maxVals.set(3, 0, math.max(maxVals.get(3, 0), int(calcDn2.get(i))))
index = switch same
false => rightIndex
=> leftIndex
coordsUpDnVal .pushShift(leftIndex, idrow.get(detPoc.get(0, 0)), idrow.min())
coordsUpUpVal .pushShift(leftIndex, idrow.max(), idrow.get(detPoc.get(1, 0)))
coordsUpDnVal2.pushShift(leftIndex, idrow.get(detPoc.get(2, 0)), idrow.min())
coordsUpUpVal2.pushShift(leftIndex, idrow.max(), idrow.get(detPoc.get(3, 0)))
coordsDnDnVal .pushShift(index, idrow.get(detPoc.get(4, 0)), idrow.min())
coordsDnUpVal .pushShift(index, idrow.max(), idrow.get(detPoc.get(5, 0)))
coordsDnDnVal2.pushShift(index, idrow.get(detPoc.get(6, 0)), idrow.min())
coordsDnUpVal2.pushShift(index, idrow.max(), idrow.get(detPoc.get(7, 0)))
id.add_col(id.columns(),
array.from( chart.point.from_index(leftIndex, idrow.get(detPoc.get(1, 0))), chart.point.from_index(leftIndex, idrow.get(detPoc.get(3, 0))),
chart.point.from_index(index, idrow.get(detPoc.get(5, 0))) , chart.point.from_index(index, idrow.get(detPoc.get(7, 0)))))
id.add_col(0,
array.from( chart.point.from_index(leftIndex, idrow.get(detPoc.get(0, 0))), chart.point.from_index(leftIndex, idrow.get(detPoc.get(2, 0))),
chart.point.from_index(index, idrow.get(detPoc.get(4, 0))) , chart.point.from_index(index, idrow.get(detPoc.get(6, 0)))))
if showBull
polyline.new(coordsUpDnVal, fill_color = color.new(upCol, transp4), line_color = color.new(upCol, transp2), curved = curve)
polyline.new(coordsUpUpVal, fill_color = color.new(upCol, transp4), line_color = color.new(upCol, transp2), curved = curve)
if showBull2
polyline.new(coordsUpDnVal2, fill_color = color.new(upCol2, transp4), line_color = color.new(upCol2, transp2), curved = curve)
polyline.new(coordsUpUpVal2, fill_color = color.new(upCol2, transp4), line_color = color.new(upCol2, transp2), curved = curve)
if showBear
polyline.new(coordsDnDnVal, fill_color = color.new(dnCol, transp4), line_color = color.new(dnCol, transp2), curved = curve)
polyline.new(coordsDnUpVal, fill_color = color.new(dnCol, transp4), line_color = color.new(dnCol, transp2), curved = curve)
if showBear2
polyline.new(coordsDnDnVal2, fill_color = color.new(dnCol2, transp4), line_color = color.new(dnCol2, transp2), curved = curve)
polyline.new(coordsDnUpVal2, fill_color = color.new(dnCol2, transp4), line_color = color.new(dnCol2, transp2), curved = curve)
calcDelta(idrow, newRowUp, newRowUp2, newRowDn, newRowDn2) =>
if showDelta
deltaBoxes = matrix.new<box>(4, 0), start = data.HLmat.min(), highestVals = array.new_float()
rows = math.abs(data.HLmat.max() - start) / deltaRows
middle = math.round(math.avg(leftIndex, rightIndex))
scale = (rightIndex - leftIndex) / 30
gradientMat = matrix.new<float>(4, 0)
for i = 0 to deltaRows - 1
calc = start + rows * i, calc2 = start + rows * (i + 1)
[lx1, lx2] = idrow.double_binary_search_delta(i, calc, calc2)
sumUU = 0.0, sumUD = 0.0, sumDU = 0.0, sumDD = 0.0,
for x = lx1 to lx2
sumUU += newRowUp.get(x), sumUD += newRowUp2.get(x)
sumDU += newRowDn.get(x), sumDD += newRowDn2.get(x)
gradientMat.add_col(gradientMat.columns(), array.from(sumUU, sumUD, sumDU, sumDD))
startBox2 = math.round(middle - scale * 2.5 ), endBox2 = math.round(middle + scale * 2.5 )
startBox = math.round(middle - scale * 1.25), endBox = math.round(middle + scale * 1.25)
deltaBoxes.appendSums(highestVals, i, startBox2, startBox, endBox, endBox2, middle, calc, calc2, sumUU, sumUD, sumDU, sumDD)
gradUp = gradientMat.max()
gradDn = gradientMat.min()
for i = 0 to deltaBoxes.columns() - 1
colMat = gradientMat.col(i)
colMax = colMat.max()
if mergeDelta
finCol = switch colMat.indexof(colMax)
0 => upCol
1 => upCol2
2 => dnCol
3 => dnCol2
colLoop = color.from_gradient(colMax, highestVals.min(), highestVals.max(), color.new(finCol, 75), color.new(finCol, 10))
deltaBoxes.get(0, i).set_bgcolor (colLoop)
deltaBoxes.get(0, i).set_border_color(colLoop)
else
for x = 0 to 3
finCol = switch
x.Float().equal(0) => upCol
x.Float().equal(1) => upCol2
x.Float().equal(2) => dnCol
=> dnCol2
boxBgcol = switch math.sign(gradientMat.get(x, i))
1 => color.from_gradient(gradientMat.get(x, i), gradDn, gradUp, color.new(finCol, dTranspMin), color.new(finCol, dTranspMax))
=> #00000000
switch gradientMat.get(x, i).equal(colMax)
false => deltaBoxes.get(x, i).set_bgcolor(boxBgcol), deltaBoxes.get(x, i).set_border_color(color.new(finCol , 50))
=> deltaBoxes.get(x, i).set_bgcolor(color.new(finCol, dTranspGre)), deltaBoxes.get(x, i).set_border_color(finCol)
if not mergeDelta
simRow = deltaBoxes.row(0)
difference = simRow.last().get_bottom() - simRow.last().get_top()
dbcols = deltaBoxes.columns() - 1
//
for i = 0 to 3
[X, COLOR, TEXT] = switch
i == 0 => [math.round(math.avg(simRow.last().get_left(), simRow.last().get_right())), upCol, "Up OI \n Up Price"]
i == 1 => [math.round(math.avg(deltaBoxes.get(1, dbcols).get_left(), deltaBoxes.get(1, dbcols).get_right())), upCol2, "Down OI \n Up Price" ]
i == 2 => [math.round(math.avg(deltaBoxes.get(2, dbcols).get_left(), deltaBoxes.get(2, dbcols).get_right())), dnCol , "Up OI \n Down Price" ]
=> [math.round(math.avg(deltaBoxes.get(3, dbcols).get_left(), deltaBoxes.get(3, dbcols).get_right())), dnCol2, "Down OI \n Down Price"]
label.new(X, simRow.last().get_bottom() + difference * 2, color = COLOR, textcolor = color.white, style = label.style_text_outline, text = TEXT,
size = size.tiny)
method update(matrix<float> id) =>
if time >= left and time <= right
data.timeVolMat.add_col(data.timeVolMat.columns(), array.from(time, oi))
data.HLmat .add_col(data.HLmat.columns(), array.from(high, low))
data.retArr .push(int(math.sign(oi)))
data.priceArr .push(int(math.sign(close - open)))
if time == right
id.setLevels()
timeRow = data.timeVolMat.row(0)
idrow = id.row(0)
for i = 0 to data.retArr.size() - 1
[lx1, lx2] = idrow.double_binary_search_leftmost_reg(i)
div = math.abs(lx1 - lx2) + 1
for x = lx1 to lx2
id.effSwitchReg(i, x, div)
newRange = math.floor((rightIndex - leftIndex) / factor)
newRowUp = id.row(1), newRowUp2 = id.row(2), newRowDn = id.row(3), newRowDn2 = id.row(4)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates = matrix.new<chart.point>(4, newRowUp.size(), chart.point.from_index(na, na))
coordinates.setCoords(newRowUp, newRowUp2, newRowDn, newRowDn2, oldMin, oldMax, newRange, timeRow, idrow)
coordinates.createPoly(idrow)
data.pocs .drawPOC(idrow, newRowUp, newRowUp2, newRowDn, newRowDn2)
calcDelta(idrow, newRowUp, newRowUp2, newRowDn, newRowDn2)
tLevels.tickLevels.update()
|
Bull Vs Bear Visible Range VP [Kioseff Trading] | https://www.tradingview.com/script/bKHBmhYX-Bull-Vs-Bear-Visible-Range-VP-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 140 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KioseffTrading
//@version=5
indicator("Bull Vs Bear Visible Range", max_lines_count = 500, max_labels_count = 500, overlay= true, max_polylines_count = 100, max_boxes_count = 500)
useLTF = input.bool (defval = false, title = "Use Lower Timeframe Data")
showDelta = input.bool (defval = true, title = "Show Delta", group = "Delta", inline = "D")
deltaRows = input.int (defval = 50, title = "Rows", group = "Delta", inline = "D", maxval = 250)
anchor = input.bool (defval = true, title = "Anchor Delta Boxes Towards VP")
showBull = input.bool (defval = true, title = "Show Bull VP", inline = "Show", group = "Profiles To Show")
showBear = input.bool (defval = true, title = "Show Bear VP", inline = "Show", group = "Profiles To Show")
ROWS = input.int (defval = 2000, maxval = 9998, minval = 10, step = 10, title = "Profile Rows", group = "Profile Settings")
factor = input.float (defval = 3 , minval = 1.1, step = 0.1, title = "Scaling Factor", group = "Profile Settings")
cumu = input.float (defval = 70, title = "Value Area", minval = 5, maxval = 95)
offset = 1
curve = input.bool (defval = false, title = "Curved Profiles", group = "Profile Settings")
same = input.bool (defval = false, title = "Plot Bull VP and Bear VP At Same X-Point", group = "Profile Settings")
poc = input.bool (defval = false, title = "Show POC", group = "POC Settings")
poctype = input.string(defval = "Bull & Bear POC", title = "POC Type", options = ["Bull & Bear POC", "Regular POC"], group = "POC Settings")
wid = input.int (defval = 1, title ="POC Width", minval = 1, group = "POC Settings")
upCol = input.color (defval = #14D990, title = "Bull Color", group = "Colors")
dnCol = input.color (defval = #F24968, title = "Bear Color", group = "Colors")
generalPOCcol = input.color (defval = color.yellow, title = "Normal POC Col", group = "Colors")
transp = input.int (defval = 80, minval = 0, maxval = 100, group = "Colors", title = "Pofile Fill Transparency")
transp2 = input.int (defval = 0 , minval = 0, maxval = 100, group = "Colors", title = "Pofile Line Transparency")
transp3 = input.int (defval = 25, minval = 0, maxval = 100, group = "Colors", title = "POC Line Transparency")
left = chart.left_visible_bar_time, right = chart.right_visible_bar_time
import RicardoSantos/MathOperator/2
method Float(int id) =>
float(id)
strMax( float ) =>
seconds = timeframe.in_seconds(timeframe.period)
mult = seconds / 10
timeframe.from_seconds(seconds - mult * float)
req(autoTime) =>
[sign, volLTF, hLTF, lLTF] = request.security_lower_tf(syminfo.tickerid, strMax(autoTime), [math.sign(close - open), volume, high, low], ignore_invalid_timeframe = true)
[s1, v1, h1, l1] = req(1), [s2, v2, h2, l2] = req(2), [s3, v3, h3, l3] = req(3) , [s4, v4, h4, l4] = req(4), [s5, v5, h5, l5 ] = req(5),
[s6, v6, h6, l6] = req(6), [s7, v7, h7, l7] = req(7), [s8, v8, h8, l8] = req(8) , [s9, v9, h9, l9] = req(9) ,[s10, v10, h10, l10] = req(10)
[signSP1, volLTFSP1, hLTFSP1, lLTFSP1] = request.security_lower_tf(syminfo.tickerid, "1", [math.sign(close - open), volume, high, low], ignore_invalid_timeframe = true)
ltfFind = array.from(s1 .size() , s2.size() , s3.size() , s4.size() , s5.size() , s6.size(), s7.size() , s8.size( ), s9.size() , s10.size())
var rightIndex = 0, var leftIndex = 0
if time > left and leftIndex == 0
leftIndex := bar_index - 1
if time == right
rightIndex := bar_index
findLTF () =>
if useLTF
var ltfd = 0
if time == left
for i = ltfFind.size() - 1 to 0
if ltfFind.get(i) > 0
ltfd := i
break
if time >= left and time <= right
[signLTF, volLTF, hLTF, lLTF] = switch
signSP1.size() > 0 => [signSP1, volLTFSP1, hLTFSP1, lLTFSP1]
ltfd == 0 => [s1 , v1 , h1 , l1 ]
ltfd == 1 => [s2 , v2 , h2 , l2 ]
ltfd == 2 => [s3 , v3 , h3 , l3 ]
ltfd == 3 => [s4 , v4 , h4 , l4 ]
ltfd == 4 => [s5 , v5 , h5 , l5 ]
ltfd == 5 => [s6 , v6 , h6 , l6 ]
ltfd == 6 => [s7 , v7 , h7 , l7 ]
ltfd == 7 => [s8 , v8 , h8 , l8 ]
ltfd == 8 => [s9 , v9 , h9 , l9 ]
ltfd == 9 => [s10, v10, h10, l10]
[signLTF, volLTF, hLTF, lLTF]
[signLTF, volLTF, hLTF, lLTF] = findLTF()
if curve
ROWS := 60
type dataStore
matrix <float> timeVolMat
matrix <float> HLmat
array <int> retArr
array <line> pocs
matrix <float> tickLevels
var data = dataStore.new(matrix.new<float>(2, 0), matrix.new<float>(2, 0), array.new_int(), array.new_line()), //kioseff
tLevels = dataStore.new(tickLevels = matrix.new<float>(3, ROWS, 0.0))
method double_binary_search_leftmost_reg(array <float> id, i) =>
n = id .binary_search_leftmost (data.HLmat.get(0, i))
n1 = id .binary_search_leftmost (data.HLmat.get(1, i))
[n, n1]
method double_binary_search_leftmost_ltf(array <float> id, i, LTFh, LTFl) => // broken up for efficiency (hopefully :D)
n = id .binary_search_leftmost (LTFh.get(i))
n1 = id .binary_search_leftmost (LTFl.get(i))
[n, n1]
method double_binary_search_delta(array<float>id, i, val, val2) =>
n = id.binary_search_rightmost(val )
n1 = id.binary_search_leftmost (val2)
[n, n1]
method effSwitchReg(matrix<float> id, i, x, div) =>
switch data.retArr.get(i)
1 => id.set(1, x, id.get(1, x) + data.timeVolMat.get(1, i) / div)
-1 => id.set(2, x, id.get(2, x) + data.timeVolMat.get(1, i) / div)
method effSwitchLTF(matrix<float> id, i, x, div, LTFvol, LTFsign) => // broken up for efficiency (hopefully :D)
switch LTFsign.get(i)
1 => id.set(1, x, id.get(1, x) + LTFvol.get(i) / div)
-1 => id.set(2, x, id.get(2, x) + LTFvol.get(i) / div)
method drawPOC(array<line> id, idrow, newRowUp, newRowDn) =>
maxUp = idrow.get(newRowUp.indexof(newRowUp.max()))
maxDn = idrow.get(newRowDn.indexof(newRowDn.max()))
if poc
if id.size() == 0
if poctype == "Bull & Bear POC"
id.push(line.new(left, maxUp, right, maxUp,
color = color.new(upCol, transp3), width = wid, xloc = xloc.bar_time))
id.push(line.new(left, maxDn, right, maxDn,
color = color.new(dnCol, transp3), width = wid, xloc = xloc.bar_time))
else
for i = 0 to newRowUp.size() - 1
newRowUp.set(i, newRowUp.get(i) + newRowDn.get(i))
id.push(line.new(left, idrow.get(newRowUp.indexof(newRowUp.max())), right, idrow.get(newRowUp.indexof(newRowUp.max())) ,
color = color.new(generalPOCcol, transp3), width = wid, xloc = xloc.bar_time))
else
if poctype == "Bull & Bear POC"
switch poctype
"Bull & Bear POC" => id.last().set_xy2(right, maxDn), id.last().set_y1 (maxDn),
id.get(id.size() - 2).set_xy2(right, maxUp), id.get(id.size() - 2).set_y1(maxUp)
=> id.last().set_xy2(right, idrow.get(newRowUp.indexof(newRowUp.max()))),
id.last().set_y1 (idrow.get(newRowUp.indexof(newRowUp.max())))
method setLevels(matrix<float> id) =>
rows = math.abs(data.HLmat.max() - data.HLmat.min()) / (ROWS - 1)
for i = 0 to ROWS - 1
id.set(0, i, data.HLmat.min() + rows * i)
method createPoly(matrix<chart.point> id, array<float> idrow) =>
index = switch same
false => rightIndex
=> leftIndex
if showBull
polyline.new(id.row(0), fill_color = color.new(upCol, transp), line_color = color.new(upCol, transp2), curved = curve)
if showBear
polyline.new(id.row(1), fill_color = color.new(dnCol, transp), line_color = color.new(dnCol, transp2), curved = curve)
norm(newRowUp, newRowDn, oldMin, oldMax, newRange) =>
calcUp = array.new_float(), calcDn = array.new_float()
for i = 0 to newRowUp.size() - 1
calcUp.push(1 + ((newRowUp.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1))
calcDn.push(1 + ((newRowDn.get(i) - oldMin) / (oldMax - oldMin)) * (newRange - 1))
[calcUp, calcDn]
method findValue(matrix <float> id, id2, highest, r1, r2) =>
for i = 1 to id2.size() - 1
slice = id2.slice(math.max(highest - i, 0), math.min(highest + i + 1, id2.size()))
if slice.sum() / id2.sum() >= cumu /100
id.set(r1, 0, math.max(highest - i, 0))
id.set(r2, 0, math.min(highest + i, id2.size() - 1))
break
method pushShift (array<chart.point> id, valX, valY1, push) =>
switch push
true => id.push (chart.point.from_index(valX, valY1))
=> id.unshift(chart.point.from_index(valX, valY1))
var maxVals = matrix.new<int>(2, 1, 0)
method setCoords(matrix<chart.point> id, newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, idrow) =>
detPoc = matrix.new<int>(4, 1)
highestUp = newRowUp.indexof(newRowUp.max())
highestDn = newRowDn.indexof(newRowDn.max())
detPoc.findValue(newRowUp, highestUp, 0, 1)
detPoc.findValue(newRowDn, highestDn, 2, 3)
coordsUpUpVal = array.new<chart.point>(), coordsUpDnVal = array.new<chart.point>()
coordsDnDnVal = array.new<chart.point>(), coordsDnUpVal = array.new<chart.point>()
[calcUp, calcDn] = norm(newRowUp, newRowDn, oldMin, oldMax, newRange)
for i = 0 to newRowUp.size() - 1
newSwitchUp = math.round(leftIndex + offset + calcUp.get(i))
newXUp = math.max(newSwitchUp, math.round(leftIndex + offset))
newSwitchDn = switch same
false => math.round(rightIndex - offset - calcDn.get(i))
=> math.round(leftIndex + offset + calcDn.get(i))
newXDn = switch same
false => math.min(newSwitchDn, math.round(rightIndex - offset))
=> math.max(newSwitchDn, math.round(leftIndex + offset))
if detPoc.get(0, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(0, 0) - 1)
coordsUpDnVal.push(chart.point.from_index(newXUp, idrow.get(i)))
if detPoc.get(1, 0).Float().not_equal(newRowUp.size() - 1)
if i.Float().over_equal(detPoc.get(1, 0) + 1)
coordsUpUpVal.push(chart.point.from_index(newXUp, idrow.get(i)))
if i.Float().over_equal(detPoc.get(0, 0)) and i.Float().under_equal(detPoc.get(1, 0))
id.set(0, i, chart.point.from_index(newXUp, idrow.get(i)))
maxVals.set(0, 0, math.max(maxVals.get(0, 0), int(calcUp.get(i))))
if detPoc.get(2, 0).Float().not_equal(0)
if i.Float().under_equal(detPoc.get(2, 0) - 1)
coordsDnDnVal.push(chart.point.from_index(newXDn, idrow.get(i)))
if detPoc.get(3, 0).Float().not_equal(newRowDn.size() - 1)
if i.Float().over_equal(detPoc.get(3, 0) + 1)
coordsDnUpVal.push(chart.point.from_index(newXDn, idrow.get(i)))
if i.Float().over_equal(detPoc.get(2, 0)) and i.Float().under_equal(detPoc.get(3, 0))
id.set(1, i, chart.point.from_index(newXDn, idrow.get(i)))
maxVals.set(1, 0, math.max(maxVals.get(1, 0), int(calcDn.get(i))))
index = switch same
false => rightIndex
=> leftIndex
//
coordsUpDnVal.pushShift(leftIndex, idrow.min(), false)
coordsUpDnVal.pushShift(leftIndex, idrow.get(detPoc.get(0, 0)), true)
coordsUpUpVal.pushShift(leftIndex, idrow.max(), true)
coordsUpUpVal.pushShift(leftIndex, idrow.get(detPoc.get(1, 0)), false)
coordsDnDnVal.pushShift(index, idrow.min(), false)
coordsDnDnVal.pushShift(index, idrow.get(detPoc.get(2, 0)), true)
coordsDnUpVal.pushShift(index, idrow.max(), true)
coordsDnUpVal.pushShift(index, idrow.get(detPoc.get(3, 0)), false)
id.add_col(id.columns(),
array.from(chart.point.from_index(leftIndex, idrow.get(detPoc.get(1, 0))), chart.point.from_index(index, idrow.get(detPoc.get(3, 0)))))
id.add_col(0,
array.from(chart.point.from_index(leftIndex, idrow.get(detPoc.get(0, 0))), chart.point.from_index(index, idrow.get(detPoc.get(2, 0)))))
bullVAcolor = input.color(defval = #14D990, title = "Bull NON-VA color", group = "Bull NON-VA Settings")
transpBull = input.int (defval = 95, minval = 0, maxval = 100, title = "Bull NON-VA Fill Transparency", group = "Bull NON-VA Settings")
transpBull2 = input.int (defval = 25, minval = 0, maxval = 100, title = "Bull NON-VA Line Transparency", group = "Bull NON-VA Settings")
if showBull
polyline.new(coordsUpDnVal, fill_color = color.new(bullVAcolor, transpBull), line_color = color.new(bullVAcolor, transpBull2), curved = curve)
polyline.new(coordsUpUpVal, fill_color = color.new(bullVAcolor, transpBull), line_color = color.new(bullVAcolor, transpBull2), curved = curve)
bearVAcolor = input.color(defval = #F24968, title = "Bear NON-VA color", group = "Bear NON-VA Settings")
transpBear = input.int (defval = 95, minval = 0, maxval = 100, title = "Bear NON-VA Fill Transparency", group = "Bear NON-VA Settings")
transpBear2 = input.int (defval = 25, minval = 0, maxval = 100, title = "Bear NON-VA Line Transparency", group = "Bear NON-VA Settings")
if showBear
polyline.new(coordsDnDnVal, fill_color = color.new(bearVAcolor, transpBear), line_color = color.new(bearVAcolor, transpBear2), curved = curve)
polyline.new(coordsDnUpVal, fill_color = color.new(bearVAcolor, transpBear), line_color = color.new(bearVAcolor, transpBear2), curved = curve)
method updateLTF(array<float> id, id2) =>
for i = 0 to id2.size() - 1
id.unshift(id2.get(i))
calcDelta(idrow, newRowUp, newRowDn) =>
if showDelta
deltaBoxes = array.new_box(), start = data.HLmat.min()
rows = math.abs(data.HLmat.max() - start) / deltaRows
middle = math.round(math.avg(leftIndex, rightIndex))
scale = (rightIndex - leftIndex) / 30
gradientArr = array.new_float()
for i = 0 to deltaRows - 1
calc = start + rows * i, calc2 = start + rows * (i + 1)
[lx1, lx2] = idrow.double_binary_search_delta(i, calc, calc2)
sum = 0.0
for x = lx1 to lx2
sum += newRowUp.get(x) - newRowDn.get(x)
gradientArr.push(sum)
startBox = middle - scale, endBox = middle + scale, cond = math.sign(sum)
if anchor
startBox := switch cond
1 => middle - scale
-1 => middle
endBox := switch cond
1 => middle
-1 => middle + scale
deltaBoxes.push(box.new(startBox, calc, endBox, calc2, text = str.tostring(sum, format.volume),
text_color = chart.fg_color))
gradientArrCopy = gradientArr.copy()
gradientArrCopy.sort(order.ascending)
gradUp = gradientArrCopy.slice(gradientArr.binary_search_rightmost(0), gradientArrCopy.size())
gradDn = gradientArrCopy.slice(0, gradientArrCopy.binary_search_leftmost (0) + 1)
botValU = gradUp.min(), topValU = gradUp.max()
botValD = gradDn.min(), topValD = gradDn.max()
for i = 0 to deltaBoxes.size() - 1
boxBgcol = switch math.sign(gradientArr.get(i))
1 => color.from_gradient(gradientArr.get(i), botValU, topValU, color.new(upCol, 75), color.new(upCol, 25))
-1 => color.from_gradient(gradientArr.get(i), botValD, topValD, color.new(dnCol, 25), color.new(dnCol, 75))
=> color.new(color.white, 75)
deltaBoxes.get(i).set_bgcolor(boxBgcol)
deltaBoxes.get(i).set_border_color(boxBgcol)
method update(matrix<float> id) =>
var LTFvol = array.new_float(), var LTFsig = array.new_float()
var LTFhi = array.new_float(), var LTFlo = array.new_float()
if time >= left and time <= right
data.timeVolMat.add_col(data.timeVolMat.columns(), array.from(time, volume))
data.HLmat .add_col(data.HLmat.columns(), array.from(high, low))
data.retArr .push(int(math.sign(close - open)))
if useLTF and time >= left and time <= right
LTFvol.updateLTF(volLTF), LTFsig.updateLTF(signLTF)
LTFhi .updateLTF(hLTF) , LTFlo .updateLTF(lLTF)
if time == right
id.setLevels()
timeRow = switch useLTF
false => data.timeVolMat.row(0)
=> LTFvol
idrow = id.row(0)
if not useLTF
for i = 0 to data.retArr.size() - 1
[lx1, lx2] = idrow.double_binary_search_leftmost_reg(i)
div = math.abs(lx1 - lx2) + 1
for x = lx1 to lx2
id.effSwitchReg(i, x, div)
if useLTF
for i = 0 to LTFvol.size() - 1
[lx1, lx2] = idrow.double_binary_search_leftmost_ltf(i, LTFhi, LTFlo)
div = math.abs(lx1 - lx2) + 1
for x = lx1 to lx2
id.effSwitchLTF(i, x, div, LTFvol, LTFsig)
newRange = math.floor((rightIndex - leftIndex) / factor)
newRowUp = id.row(1), newRowDn = id.row(2)
oldMin = math.min(newRowUp.min(), newRowDn.min())
oldMax = math.max(newRowUp.max(), newRowDn.max())
coordinates = matrix.new<chart.point>(2, newRowUp.size(), chart.point.from_index(na, na))
coordinates.setCoords(newRowUp, newRowDn, oldMin, oldMax, newRange, timeRow, idrow)
coordinates.createPoly(idrow)
data.pocs .drawPOC(idrow, newRowUp, newRowDn)
calcDelta(idrow, newRowUp, newRowDn)
tLevels.tickLevels.update()
|
Order Block v1 | https://www.tradingview.com/script/T4z6ZLsJ/ | only_fibonacci | https://www.tradingview.com/u/only_fibonacci/ | 918 | 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/
// © only_fibonacci
//@version=5
indicator("Order Block", overlay = true)
// Pivot precision
precision = input.int(defval = 5, title = "Precision")
last_how_ob = input.int(defval = 2, title = "How Many Last OB?", minval = 2)
color_of_ob_bullish = input.color(defval = color.rgb(46,204,113,80), title = "Color of OB Bull", group = "BULL")
color_of_ob_bearish = input.color(defval = color.rgb(231, 76, 60,80), title = "Color of OB Bear", group = "BEAR")
show_bull_ob = input.bool(defval = false, title = "SHOW BULL", group = "BULL")
show_bear_ob = input.bool(defval = false, title = "SHOW BEAR", group = "BEAR")
isBody = input.bool(defval =true, title = "Is Body?", group = "TOOL")
extendRight = input.bool(false,title = "Extend Right", group = "TOOL")
h = isBody ? math.max(open,close) : high
l = isBody ? math.min(open,close) : low
// Conditions for top and bottom
top = ta.pivothigh(precision,precision)
bottom = ta.pivotlow(precision,precision)
// arrays
tops = array.new_float()
bottoms = array.new_float()
// get Funcstions
getTop(i)=>
_index = ta.valuewhen(top,bar_index,i) - precision
_top = high[bar_index - _index]
array.push(tops,_top)
getBottom(i)=>
_index = ta.valuewhen(bottom,bar_index,i) - precision
_bottom = low[bar_index - _index]
array.push(bottoms,_bottom)
getTop(2)
getTop(1)
getTop(0)
getBottom(2)
getBottom(1)
getBottom(0)
is_bull_ob = array.get(tops,0) > array.get(tops,1) and array.get(tops,1) > array.get(tops,2) and ta.crossover(high,array.last(tops))
is_bear_ob = array.get(bottoms,0) < array.get(bottoms,1) and array.get(bottoms,1) < array.get(bottoms,2) and ta.crossunder(low,array.last(bottoms))
index_bull_ob = ta.valuewhen(is_bull_ob,bar_index,0)
index_bear_ob = ta.valuewhen(is_bear_ob,bar_index,0)
redBar = open[1] > close[1] and high[1] < high
greenBar = open[1] < close[1] and low[1] > low
redBarIndex = ta.valuewhen(redBar,bar_index,0)
greenBarIndex = ta.valuewhen(greenBar,bar_index,0)
a_allBoxes = box.all
if array.size(a_allBoxes) > last_how_ob
for i = 0 to array.size(a_allBoxes) - last_how_ob - 1
box.delete(array.get(a_allBoxes, i))
if is_bull_ob and show_bull_ob
box.new(redBarIndex -1,h[bar_index - redBarIndex +1 ],last_bar_index,l[bar_index - redBarIndex +1], bgcolor = color_of_ob_bullish, border_color = color_of_ob_bullish, extend = extendRight ? extend.right : extend.none)
if is_bear_ob and show_bear_ob
box.new(greenBarIndex -1,h[bar_index - greenBarIndex +1 ],last_bar_index,l[bar_index - greenBarIndex +1], bgcolor = color_of_ob_bearish, border_color = color_of_ob_bearish, extend = extendRight ? extend.right : extend.none)
|
Dividend Calendar (Zeiierman) | https://www.tradingview.com/script/eETJcnc8-Dividend-Calendar-Zeiierman/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 79 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=5
// © Zeiierman {
// ~~ Description {
_= "
The Dividend Calendar (Zeiierman) is a financial tool designed to assist investors and analysts in the stock market by providing
a schedule of expected dividend payments from various companies. This tool is essential for investors focusing on dividend income,
as it helps them effectively plan and manage their investment strategies. It offers a comprehensive view of dividend payout dates,
aiding in informed decision-making and optimizing dividend income through timely stock transactions. Additionally, the Dividend Calendar
is useful for forecasting cash flow and evaluating the financial stability and consistency of dividend payments from different companies."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//@version=5
indicator("Dividend Calendar (Zeiierman)",overlay=true)
//~~}
// ~~ Inputs {
// ~~ Tooltips {
t1 = "The first input box is for the currency of the dividends. It is set to USD by default, which means that all dividend values are displayed in USD. You can change this to your local currency. \n\nSelect if you want to show the Ex-dividend day or the Actual Payout day. \n\nEstimate Forward enables traders to predict future dividends."
t2 = "2Choose whether you want to view the full dividend calendar, just the cumulative monthly dividend, or a summary. \n\nEnable dividend growth based on the number of years."
t3 = "The first input field is where you specify the stock from which you want to track the dividend. \n\nThe second input field is the number of shares you hold in that particular stock. \n\nThe third input field enables you to customize the dividend payout amount. \n\nThe fourth input field allows you to customize the payout months. For example, type it like this: 1,2,3,5, which corresponds to January, February, March, and May."
//~~}
// ~~ Inputs {
//General inputs
userCurrency = input.string("USD","Currency ",group="Dividend Calendar", inline="Currency")
xday = input.string("Ex-Date","",options=["Ex-Date","Pay-Date"],group="Dividend Calendar",inline="Currency")
estimate = input.bool(true,"Estimate Forward",group="Dividend Calendar",inline="Currency", tooltip=t1)
//Table
tableDesign = input.string("Full Calendar","Dividend Table",["Full Calendar","Monthly","Summary"],group="Dividend Calendar",inline="Calendar")
showGrowth = input.bool(false,"Growth",group="Dividend Calendar",inline="Calendar")
growthyears = input.int(5,"",minval=2,group="Dividend Calendar",inline="Calendar", tooltip=t2)
//Stocks & user inputs
h1 = input.bool(true,"Customize | Tickers | Shares | Custom Payout | Custom Month (1,4)", group="Dividend Calendar", inline="", tooltip=t3)
show = array.from(
input.bool(true, "", inline = "00"),
input.bool(true, "", inline = "01"),
input.bool(true, "", inline = "02"),
input.bool(true, "", inline = "03"),
input.bool(true, "", inline = "04"),
input.bool(true, "", inline = "05"),
input.bool(true, "", inline = "06"),
input.bool(true, "", inline = "07"),
input.bool(true, "", inline = "08"),
input.bool(true, "", inline = "09"),
input.bool(false, "", inline = "10"),
input.bool(false, "", inline = "11"),
input.bool(false, "", inline = "12"),
input.bool(false, "", inline = "13"),
input.bool(false, "", inline = "14"),
input.bool(false, "", inline = "15"),
input.bool(false, "", inline = "16"),
input.bool(false, "", inline = "17"),
input.bool(false, "", inline = "18"),
input.bool(false, "", inline = "19")
)
s00 = input.symbol("KO", "", inline = "00")
s01 = input.symbol("JNJ", "", inline = "01")
s02 = input.symbol("PG", "", inline = "02")
s03 = input.symbol("AWR", "", inline = "03")
s04 = input.symbol("TXN", "", inline = "04")
s05 = input.symbol("O", "", inline = "05")
s06 = input.symbol("BLK", "", inline = "06")
s07 = input.symbol("LMT", "", inline = "07")
s08 = input.symbol("DOV", "", inline = "08")
s09 = input.symbol("ADP", "", inline = "09")
s10 = input.symbol("MCD", "", inline = "10")
s11 = input.symbol("WMT", "", inline = "11")
s12 = input.symbol("NWN", "", inline = "12")
s13 = input.symbol("VZ", "", inline = "13")
s14 = input.symbol("T", "", inline = "14")
s15 = input.symbol("INTC", "", inline = "15")
s16 = input.symbol("PFE", "", inline = "16")
s17 = input.symbol("CVX", "", inline = "17")
s18 = input.symbol("XOM", "", inline = "18")
s19 = input.symbol("AA", "", inline = "19")
shares = array.from(
input.int(100, title="", inline = "00"),
input.int(100, title="", inline = "01"),
input.int(100, title="", inline = "02"),
input.int(100, title="", inline = "03"),
input.int(100, title="", inline = "04"),
input.int(100, title="", inline = "05"),
input.int(100, title="", inline = "06"),
input.int(100, title="", inline = "07"),
input.int(100, title="", inline = "08"),
input.int(100, title="", inline = "09"),
input.int(100, title="", inline = "10"),
input.int(100, title="", inline = "11"),
input.int(100, title="", inline = "12"),
input.int(100, title="", inline = "13"),
input.int(100, title="", inline = "14"),
input.int(100, title="", inline = "15"),
input.int(100, title="", inline = "16"),
input.int(100, title="", inline = "17"),
input.int(100, title="", inline = "18"),
input.int(100, title="", inline = "19")
)
customPayout = array.from(
input.float(0, title="", inline = "00"),
input.float(0, title="", inline = "01"),
input.float(0, title="", inline = "02"),
input.float(0, title="", inline = "03"),
input.float(0, title="", inline = "04"),
input.float(0, title="", inline = "05"),
input.float(0, title="", inline = "06"),
input.float(0, title="", inline = "07"),
input.float(0, title="", inline = "08"),
input.float(0, title="", inline = "09"),
input.float(0, title="", inline = "10"),
input.float(0, title="", inline = "11"),
input.float(0, title="", inline = "12"),
input.float(0, title="", inline = "13"),
input.float(0, title="", inline = "14"),
input.float(0, title="", inline = "15"),
input.float(0, title="", inline = "16"),
input.float(0, title="", inline = "17"),
input.float(0, title="", inline = "18"),
input.float(0, title="", inline = "19")
)
customMonth = array.from(
input.string("","",inline="00"),
input.string("","",inline="01"),
input.string("","",inline="02"),
input.string("","",inline="03"),
input.string("","",inline="04"),
input.string("","",inline="05"),
input.string("","",inline="06"),
input.string("","",inline="07"),
input.string("","",inline="08"),
input.string("","",inline="09"),
input.string("","",inline="10"),
input.string("","",inline="11"),
input.string("","",inline="12"),
input.string("","",inline="13"),
input.string("","",inline="14"),
input.string("","",inline="15"),
input.string("","",inline="16"),
input.string("","",inline="17"),
input.string("","",inline="18"),
input.string("","",inline="19")
)
//Table design
pos = input.string(position.top_right, title="Position",options =[position.top_right,position.top_center,
position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],group="Style",inline="tbl")
TblSize = input.string(size.auto,title="",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],group="Style",inline="tbl")
bullbackgr = input.color(#11132d,"Bg",group="Style",inline="tbl")
frame = input.color(color.rgb(255, 255, 255),"Frame",group="Style",inline="tbl")
textcol = input.color(color.white,"Text",group="Style",inline="col")
col_1 = input.color(color.new(#60e565, 80),title="Divended", group="Style",inline="col")
col_2 = input.color(color.new(#1848cc, 80),title="Summary", group="Style",inline="col")
col_3 = input.color(#0c3299,"Header", group="Style",inline="col")
col_4 = input.color(#1848cc,"", group="Style",inline="col")
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Functions {
//Estimation
Estimate(mat)=>
date = math.round(str.tonumber(str.format_time(time,"MM")))
for [i,row] in mat
max = row.max()
for j=date-1 to 11
if mat.get(i,j)!=0
mat.set(i,j,max)
//Sum the months and stocks
Sum(arr,ft)=>
newArray = array.new<float>()
for i=0 to (ft?arr.columns():arr.rows())-1
newArray.push(math.round((ft?arr.col(i).sum():arr.row(i).sum()),2))
newArray
//Stock dividend growth
Growth(growth)=>
growthArray = array.new<float>()
for [i,g] in growth
percentages = array.new<float>()
pays = g.gr
for j=1 to pays.size()-1
pres = pays.get(j)
prev = pays.get(j-1)
perc = (pres-prev)/prev
percentages.push(perc)
growthArray.push(percentages.avg())
growthArray
//Table header design
TableBG(col)=>
even = array.from(0,2,4,6,8,10,12)
odd = array.from(1,3,5,7,9,11)
if even.includes(col)
color.new(col_3,25)
else
col_4
//Switch text in Summary Table
TextSwitch(t1,t2)=>
varip txtchange = true
txtchange := not txtchange
txt = txtchange ? t1 : t2
//Custom month if user enteres custom months using "," as reference. Example "1,4,7,10"
method CustomMonth(matrix<float> m,i,cash)=>
user_input = customMonth.get(i)
if str.contains(user_input,",")
split = str.split(user_input,",")
for mon in split
m.set(i,math.round(str.tonumber(mon))-1,cash)
else
m.set(i,math.round(str.tonumber(user_input))-1,cash)
//Get stock data
Requests(ticker)=>
tickerid = str.replace(ticker,":",";",0)
payTime = request.security("ESD_FACTSET:"+tickerid+";DIVIDENDS","D",time,lookahead=barmerge.lookahead_on,currency=userCurrency)
payOut = request.security("ESD_FACTSET:"+tickerid+";DIVIDENDS","D",close,lookahead=barmerge.lookahead_on,currency=userCurrency)
[payTime,payOut]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ UDT's & Variables & Arrays {
// ~~ UDT {
type Growth
array<float> gr
//~~}
// ~~ Variables {
var refreshcount = 0
//Table
var tbl = table.new(pos, 15,30,bullbackgr,frame,2,frame,2)
//Request the data
[l00, t00] = Requests(s00)
[l01, t01] = Requests(s01)
[l02, t02] = Requests(s02)
[l03, t03] = Requests(s03)
[l04, t04] = Requests(s04)
[l05, t05] = Requests(s05)
[l06, t06] = Requests(s06)
[l07, t07] = Requests(s07)
[l08, t08] = Requests(s08)
[l09, t09] = Requests(s09)
[l10, t10] = Requests(s10)
[l11, t11] = Requests(s11)
[l12, t12] = Requests(s12)
[l13, t13] = Requests(s13)
[l14, t14] = Requests(s14)
[l15, t15] = Requests(s15)
[l16, t16] = Requests(s16)
[l17, t17] = Requests(s17)
[l18, t18] = Requests(s18)
[l19, t19] = Requests(s19)
//Alert
alert = false
alert_msg = ""
//~~}
// ~~ Arrays {
//Symbols array
symbols = array.from(
s00,
s01,
s02,
s03,
s04,
s05,
s06,
s07,
s08,
s09,
s10,
s11,
s12,
s13,
s14,
s15,
s16,
s17,
s18,
s19
)
// Paytime array
payTime = array.from(
l00,
l01,
l02,
l03,
l04,
l05,
l06,
l07,
l08,
l09,
l10,
l11,
l12,
l13,
l14,
l15,
l16,
l17,
l18,
l19
)
// Payout array
payOut = array.from(
t00,
t01,
t02,
t03,
t04,
t05,
t06,
t07,
t08,
t09,
t10,
t11,
t12,
t13,
t14,
t15,
t16,
t17,
t18,
t19
)
//Months
months = array.from(
"January",
"February",
"Mars",
"April",
"May",
"June",
"July",
"August",
"September",
"Oktober",
"November",
"December"
)
// Matrix to store the data
var data = matrix.new<float>(20,12,0)
var growth = array.new<Growth>()
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Main {
if barstate.isfirst
for i=0 to 19
growth.push(Growth.new(array.new<float>()))
if year!=year[1]
for [i,save] in growth
save.gr.push(data.row(i).sum())
if save.gr.size()>growthyears
save.gr.shift()
refreshcount+=1
if refreshcount>=2
refreshcount := 0
data := matrix.new<float>(20,12,0)
else
for [i,val] in payTime
if show.get(i)
amount = customPayout.get(i)==0?
payOut.get(i)*shares.get(i):
customPayout.get(i)
if customMonth.get(i)!=""
data.CustomMonth(i,amount)
else if time==val
date = math.round(str.tonumber(str.format_time(time,"MM")))
data.set(i,xday=="Ex-Date"?date-1:(date>=12?0:date),amount)
alert := true
alert_msg += str.split(symbols.get(i),":").get(1)
+ " " +
xday +
" with a payout of: " +
str.tostring(amount) +
"\n"
if estimate
Estimate(data)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plots & Outputs {
// ~~ Table {
if barstate.islast and timeframe.period=='D'
//Month Total
monthTotal = Sum(data,true)
//Stock Yearly Total
stockTotal = Sum(data,false)
//Full Calendar & Monthly
if tableDesign=="Full Calendar" or tableDesign=="Monthly"
//Table Display
//Months
for [i,m] in months
tbl.cell(i+1,0,m,text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace,bgcolor=TableBG(i))
//Month Total
tbl.cell(0,1,"Total",text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
for [i,mon] in monthTotal
tbl.cell(i+1,1,str.tostring(mon),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace,
bgcolor=color.from_gradient(mon,monthTotal.min(),monthTotal.max(),
color.new(col_1,90),color.new(col_1,20)))
if tableDesign=="Monthly"
tbl.cell(13,1,str.tostring(math.round(monthTotal.sum(),2)),
bgcolor=bullbackgr,text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
if tableDesign=="Full Calendar"
//Stock Total
tbl.cell(13,1,str.tostring(math.round(monthTotal.sum(),2)),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
for [i,st] in stockTotal
if show.get(i)
tbl.cell(13,i+2,str.tostring(st),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace,
bgcolor=color.from_gradient(st,stockTotal.min(),stockTotal.max(),
color.new(col_2,90),color.new(col_2,20)))
// Stocks
for [i,sy] in symbols
if show.get(i)
tbl.cell(0,i+2,str.split(sy,":").get(1),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
for j=0 to 11
tbl.cell(j+1,i+2,str.tostring(math.round(data.get(i,j),2)),
text_color=textcol,text_size=TblSize,text_font_family=font.family_monospace,
bgcolor=math.round(data.get(i,j),2)!=0?color.from_gradient(math.round(data.get(i,j),2),
data.min(),data.max(),
color.new(col_1,90),color.new(col_1,20)):bullbackgr)
tbl.cell(0,0,"💰")
tbl.cell(13,0,"💰")
//Growth
if showGrowth
growthArray = Growth(growth)
for [i,perc] in growthArray
if show.get(i)
tbl.cell(14,i+2,str.tostring(perc*100,format.percent),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace,bgcolor=bullbackgr)
//Income Table
if tableDesign=="Summary"
monMax = monthTotal.max()
monMin = monthTotal.min()
stoMax = stockTotal.max()
stoMin = stockTotal.min()
info = array.from(TextSwitch("Best month",months.get(monthTotal.indexof(monMax))),
TextSwitch("Worst month",months.get(monthTotal.indexof(monMin))),
TextSwitch("Highest paid stock",str.split(symbols.get(stockTotal.indexof(stoMax)),":").get(1)),
TextSwitch("Lowest paid stock",str.split(symbols.get(stockTotal.indexof(stoMin)),":").get(1)))
values = array.from(monMax,monMin,stoMax,stoMin)
for [i,desc] in info
tbl.cell(0,i,desc,bgcolor=bullbackgr,text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
tbl.cell(1,i,str.tostring(values.get(i)),bgcolor=bullbackgr,text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
summary = array.from("Yearly","Quarterly","Monthly","Daily")
income = stockTotal.sum()
sumIncome = array.from(income,income/4,income/12,income/365)
for [i,inc] in sumIncome
tbl.cell(2,i,summary.get(i),text_color=textcol,text_size=TblSize,text_font_family=font.family_monospace)
tbl.cell(3,i,str.tostring(math.round(inc,2)),text_color=textcol,text_size=TblSize,text_font_family=font.family_monospace)
//Error table
if timeframe.period!='D'
tbl.cell(0,0,"Error Message: Please go to the Daily Timeframe",
bgcolor=color.new(color.red,50),text_color=textcol,text_size=TblSize,
text_font_family=font.family_monospace)
//~~}
// ~~ Alerts {
if alert
alert(alert_msg,alert.freq_once_per_bar)
//~~}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Machine Learning using Neural Networks | Educational | https://www.tradingview.com/script/lxhedC8E-Machine-Learning-using-Neural-Networks-Educational/ | Alien_Algorithms | https://www.tradingview.com/u/Alien_Algorithms/ | 427 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
//@version=5
indicator("Neural Network Showcase | Alien_Algorithms", overlay=true, shorttitle="Neural Showcase | Alien_Algorithms")
lr = input.float(title='Learning Rate', defval=0.1, minval=0.00001)
epochs = input.int(title='Epochs', defval=60, minval=10, maxval=1000)
use_simple_backprop = input(defval=false, title='Simple Backpropagation')
plot_loss_curve = input(true, 'Plot Loss Curve', group='Statistics')
chart_scaling = input.int(title='Chart Scaling Factor', defval=1, minval=1, group = 'Statistics')
horizontal_offset = input.int(title='Chart Horizontal Offset', defval = 100, group='Statistics')
vertical_offset = input.int(title='Chart Vertical Offset (percentage)', defval = -2, group='Statistics')
vertical_offset_pct = 1 + (vertical_offset / 100)
// Begin logging the maximum price, to be used in normalization
var max_scale = 0.0
max_scale := high > max_scale ? high : max_scale
// Initialize weight matrices at random for better feature distribution
var w1 = matrix.new<float>(2, 2, 0.0)
var w2 = matrix.new<float>(1, 2, 0.0)
// Function to fill each element of a matrix with random values, while maintaining reproducibility with a seed.
// This is needed because matrix.new() can only set the same value for the entire matrix.
fillMatrixRandomly(matrix, rows, cols) =>
seed = 1337 // Any fixed number as a seed will do
for i = 0 to rows - 1
for j = 0 to cols - 1
// The seed is altered for each matrix element to ensure different values
// while still being repeatable on every run
matrix.set(matrix, i, j, math.random(0, 1, seed + i + j * rows))
// Fill w1 and w2 with random values
// It is important that the weights are not initialized with the same values, to induce asymmetry during gradient updates.
// This allows the network to utilize all the weights effectively
if barstate.isfirst
fillMatrixRandomly(w1, 2, 2)
fillMatrixRandomly(w2, 1, 2)
// Sigmoid activation function
sigmoid(x) =>
1 / (1 + math.exp(-x))
// Mean Squared Error Loss function
mse_loss(predicted, actual) =>
math.pow(predicted - actual, 2)
// Normalize the data between 0 and 1
normalize(data) =>
data / max_scale
// Revert the data back to the original form
standardize(data) =>
data * max_scale
// Feed forward through the neural network
// This process passes the input data through the network, and obtains an output
feedforward(input) =>
hidden_out = array.new_float(0)
// Push through the first layer
for i = 0 to 1
sum = 0.0
for j = 0 to 1
sum := sum + w1.get(i, j) * array.get(input, j)
array.push(hidden_out, sigmoid(sum))
// Push through the second layer
output = 0.0
for i = 0 to 1
output := output + w2.get(0, i) * array.get(hidden_out, i)
output := sigmoid(output)
[output, hidden_out]
// Backpropagation observes the difference in actual and predicted values (obtained from the feedforward), and adjusts the weights using a gradient to lower the error (loss).
backpropagation_simple(input, actual_output, predicted_output, hidden_out) =>
// Update weights of the second layer
for i = 0 to 1
w2.set(0, i, w2.get(0, i) - lr * 2 * (predicted_output - actual_output) * array.get(hidden_out, i))
// Update weights of the first layer
for i = 0 to 1
for j = 0 to 1
w1.set(i, j, w1.get(i, j) - lr * 2 * (predicted_output - actual_output) * w2.get(0, i) * array.get(input, j))
backpropagation_verbose(input, actual_output, predicted_output, hidden_out) =>
// Calculate the derivative of the loss with respect to the output (MSE loss)
float d_loss_d_output = 2 * (predicted_output - actual_output)
// Update weights of the second layer
for i = 0 to 1
float hidden_val = array.get(hidden_out, i)
float d_loss_d_w2 = d_loss_d_output * hidden_val
w2.set(0, i, w2.get(0, i) - lr * d_loss_d_w2)
// Update weights of the first layer
for i = 0 to 1
for j = 0 to 1
float input_val = array.get(input, j)
float w2_val = w2.get(0, i)
float hidden_val = array.get(hidden_out, i)
float sigmoid_derivative = hidden_val * (1 - hidden_val)
float d_loss_d_w1 = d_loss_d_output * w2_val * sigmoid_derivative * input_val
w1.set(i, j, w1.get(i, j) - lr * d_loss_d_w1)
// A wrapper function that trains the neural network with the set parameters (Learning Rate, Epochs)
train_nn(input, actual_output) =>
loss_curve = array.new<float>(0)
for epoch = 1 to epochs
// Predicting
[predicted_output, hidden_out] = feedforward(input)
loss = mse_loss(predicted_output, actual_output)
// Metrics
log.warning("~~~~ Epoch {0} ~~~~", epoch)
log.info("Loss: {0}", str.tostring(loss))
array.push(loss_curve, loss)
// Weight Adjustment (Training)
if use_simple_backprop
backpropagation_simple(input, actual_output, predicted_output, hidden_out)
else
backpropagation_verbose(input, actual_output, predicted_output, hidden_out)
loss_curve
// Define input and output variables that the network will use.
float[] input = array.new_float(0)
array.push(input, normalize(close[1]))
array.push(input, normalize(close[2]))
actual_output = normalize(close)
// Perform training only on the last confirmed bar to save resources
float predicted_output = na
if barstate.islastconfirmedhistory
// Training updates all the weights and returns a loss curve containing the loss for each epoch in an array, which can then be visualized.
loss_curve = train_nn(input, actual_output)
// Get neural network output
[predicted_output_normalized, _] = feedforward(input)
predicted_output := standardize(predicted_output_normalized)
log.error(str.tostring(w1))
log.error(str.tostring(w2))
// ~~~~~~~~~~~~~ Plot the neural network output ~~~~~~~~~~~~~
label.new(bar_index+40, predicted_output, text = 'Predicted Output', style = label.style_label_lower_left, color=color.purple, textcolor = color.white, tooltip = 'The price which the neural network predicted')
line.new(bar_index, predicted_output, bar_index+40, predicted_output, color=color.purple, width=4)
label.new(bar_index+40, standardize(actual_output), text = 'Actual Output',style = label.style_label_lower_left, color=color.green, textcolor = color.black, tooltip = 'The price which the neural network aims to predict')
line.new(bar_index, standardize(actual_output), bar_index+40, standardize(actual_output), color=color.green, width=4)
mid = math.abs(standardize(actual_output) - predicted_output) / 2
mid := predicted_output > standardize(actual_output) ? predicted_output - mid : predicted_output + mid
label.new(bar_index+10, mid, text = 'MSE Loss: '+str.tostring(array.get(loss_curve,epochs-1)), color=color.rgb(195, 195, 195), style=label.style_label_left, textcolor = color.black, tooltip = 'The rate of error between the prediction and actual value')
line.new(bar_index+10, predicted_output, bar_index+10, standardize(actual_output), color=color.rgb(177, 177, 177), style=line.style_dashed, width=1)
if plot_loss_curve
size = array.size(loss_curve)
float max_loss = array.max(loss_curve)
float min_loss = array.min(loss_curve)
float loss_range = max_loss - min_loss
float chart_range = (high - low) / chart_scaling
float scaling_factor = chart_range / loss_range
var points = array.new<chart.point>()
for i = 0 to size - 1
float normalized_loss = (array.get(loss_curve, i) - min_loss) / loss_range // Normalize to [0, 1]
float scaled_loss = normalized_loss * scaling_factor // Scale to chart range
float shifted_loss = scaled_loss + (close * vertical_offset_pct) // Shift to match chart values
point = chart.point.new(time+i+horizontal_offset, bar_index+i+horizontal_offset, shifted_loss)
points.push(point)
float first_loss = (array.get(loss_curve, 0) - min_loss) / loss_range * scaling_factor + (close * vertical_offset_pct)
float last_loss = (array.get(loss_curve, size-1) - min_loss) / loss_range * scaling_factor + (close * vertical_offset_pct)
label.new(bar_index+horizontal_offset+size, last_loss - 0.01 * scaling_factor, text = 'Loss Curve', style = label.style_label_upper_left, color=color.rgb(87, 87, 87), textcolor = color.rgb(255, 255, 255), tooltip='The MSE Loss (y-axis) plotted over the epoch iterations (x-axis)')
box.new(bar_index+horizontal_offset, first_loss, bar_index+horizontal_offset+size, last_loss - 0.01 * scaling_factor, bgcolor = color.rgb(120, 123, 134, 81),border_width = 3)
polyline.new(points, curved=true, line_color=color.rgb(194, 208, 0), line_width = 1)
|
Velocity and Acceleration Signals | https://www.tradingview.com/script/CUuh28js-Velocity-and-Acceleration-Signals/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 139 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo
//@version=5
indicator("Velocity and Acceleration Signals", overlay=false)
lookback = input.int(14, title="Lookback Period")
emaLength = input.int(20, title="EMA Length for Velocity")
// Calculate Velocity
velocitySum = 0.0
for i = 1 to lookback
velocitySum := velocitySum + (close - close[i]) / i
velocity = velocitySum / lookback
// Calculate Acceleration
accelerationSum = 0.0
for i = 1 to lookback
accelerationSum := accelerationSum + (velocity - velocity[i]) / i
acceleration = accelerationSum / lookback
// Smooth Velocity with EMA
smoothedVelocity = ta.ema(velocity, emaLength)
// Coloration
acccolor = acceleration > 0 ? color.lime : color.fuchsia
velcolor = smoothedVelocity > 0 ? color.green : color.red
barColoration = acceleration and smoothedVelocity > 0 ? color.lime : acceleration and smoothedVelocity < 0 ? color.fuchsia : color.gray
barcolor(barColoration)
// Plot Velocity and Acceleration
plot(smoothedVelocity, color=velcolor, title="Smoothed Velocity", style = plot.style_columns)
plot(acceleration, color=acccolor, title="Acceleration", style = plot.style_histogram, linewidth = 4)
hline(0, title="Zero Line", color=color.gray)
// Strong Up and Strong Down Conditions
upthreshold = input.float(0.01, "Up Threshold")
dnthreshold = input.float(-0.01, 'Down Threshold')
strongUp = ta.crossover(smoothedVelocity, upthreshold) and (acceleration[0] > 0)
strongDown = ta.crossunder(smoothedVelocity, dnthreshold) and (acceleration[0] < 0)
plotshape(strongUp, location=location.top, color=color.green, style=shape.triangleup, title="Up", size=size.small)
plotshape(strongDown, location=location.bottom, color=color.red, style=shape.triangledown, title="Down", size=size.small)
|
Machine Learning: Optimal RSI [YinYangAlgorithms] | https://www.tradingview.com/script/bLOzFkhi-Machine-Learning-Optimal-RSI-YinYangAlgorithms/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 272 | 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/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
indicator("Machine Learning: Optimal RSI [YinYangAlgorithms]", max_bars_back=500)
// ~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~ //
//Optimal RSI
showSignals = input.bool(true, "Show Crossing Signals", group="RSI Settings", inline="rsiToggles")
showTables = input.bool(true, "Show Tables", group="RSI Settings", inline="rsiToggles")
showNewSettings = input.bool(true, "Show New Settings", group="RSI Settings", inline="rsiToggles")
showBollingerBands = input.bool(true, "Show Bollinger Bands", group="RSI Settings", tooltip="Show RSI Bollinger Bands. These bands work like the TDI Indicator, except its length changes as it uses the current RSI Optimal Length.")
optimalType = input.string("All Crossings", "Optimal RSI Type", options=["All Crossings", "Extremity Crossings"], group="RSI Settings", tooltip="This is how we calculate our Optimal RSI. Do we use all RSI and RSI MA Crossings or just when it crosses within the Extremities.")
aiAdjust = input.string("Auto", "Adjust Optimal RSI Lookback and RSI Count", options=["Auto", "Manual"], group="RSI Settings", tooltip="Auto means the script will automatically adjust the Optimal RSI Lookback Length and RSI Count based on the current Time Frame and Bar Index's on chart. This will attempt to stop the script from 'Taking too long to Execute'.\nManual means you have full control of the Optimal RSI Lookback Length and RSI Count.")
optimalLength = input.int(200, "Optimal RSI Lookback Length", maxval=500, minval=10, group="RSI Settings", tooltip="How far back are we looking to see which RSI length is optimal? Please note the more bars the lower this needs to be. For instance with BTC/USDT you can use 500 here on 1D but only 200 for 15 Minutes; otherwise it will timeout.")
rsiCount = input.int(30, "RSI Count", group="RSI Settings", maxval=50, minval=5, tooltip="How many lengths are we checking? For instance, if our 'RSI Minimum Length' is 4 and this is 30, the valid RSI lengths we check is 4-34.")
rsiMinLength = input.int(4, "RSI Minimum Length", group="RSI Settings", minval=1, tooltip="What is the RSI length we start our scans at? We are capped with RSI Count otherwise it will cause the Indicator to timeout, so we don't want to waste any processing power on irrelevant lengths.")
maLength = input.int(14, "RSI MA Length", group="RSI Settings", minval=1, tooltip="What length are we using to calculate the optimal RSI cross' and likewise plot our RSI MA with?")
backupLength = input.int(14, "Extremity Crossings RSI Backup Length", minval=1, group="RSI Settings", tooltip="When there is no Optimal RSI (if using Extremity Crossings), which RSI should we use instead?")
//Machine Learning
useRationalQuadratics = input.bool(true, "Use Rational Quadratics", group="Machine Learning", tooltip="Rationalizing our Close may be beneficial for usage within ML calculations.")
onlyUseSimilarMA = input.bool(false, "Filter RSI and RSI MA", group="Machine Learning", tooltip="Should we filter the RSI's before usage in ML calculations? Essentially should we only use RSI data that are of the same type as our Optimal RSI? For instance if our Optimal RSI is Bullish (RSI > RSI MA), should we only use ML RSI's that are likewise bullish?")
useMachineLearning = input.string("Simple Average", "Machine Learning Type", options=["KNN Average", "KNN Exponential Average", "Simple Average", "None"], group="Machine Learning", tooltip="Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?")
distanceType = input.string("Both", "KNN Distance Type", options=["Both", "Max", "Min"], group="Machine Learning", tooltip="We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.")
mlLength = input.int(10, "Machine Learning Length", minval=1, group="Machine Learning", tooltip="How far back is our Machine Learning going to keep data for.")
knnLength = input.int(3, "k-Nearest Neighbour (KNN) Length", minval=1, group="Machine Learning", tooltip="How many k-Nearest Neighbours will we account for?")
fastLength = input.int(1, "Fast ML Data Length", minval=1, group="Machine Learning", tooltip="What is our Fast ML Length? This is used with our Slow Length to create our KNN Distance.")
slowLength = input.int(5, "Slow ML Data Length", minval=2, group="Machine Learning", tooltip="What is our Slow ML Length? This is used with our Fast Length to create our KNN Distance.")
// ~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~ //
distanceTypeMin = distanceType == "Min" or distanceType == "Both"
distanceTypeMax = distanceType == "Max" or distanceType == "Both"
adjustRatio = aiAdjust == "Auto"
// ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~ //
//Used to refactor INPUT Settings: Optimal RSI Lookback Length and RSI Count
//When there are bar indexs due to timeframe than having these values too high will cause the indicator to timeout
autoAdjust() =>
//Default settings (this should work on almost all Time Frames and Pairs (Premium or less Plans, not sure about > Premium))
newLength = 90
newCount = 20
//total lookback can't be >= 50,000,000
//how this is calculated is length * count * bar_index
//IE. newLength (90) * newCount (25) * 24,000 (1 HR BTC/USDT Binance Index's available) = 54,000,000 ... this will timeout
//The 50,000,000 lookback might also be based on Premium TradingView (40 second chart processing), so if you have a lower plan you may
//need to adjust this accordingly
//adjust based on bar_index, timeframe was an idea, but depending on what you're trading, the timeframe can still have too many indexs'
if barstate.isrealtime
//For realtime we no longer need to factor the Time Frame as we know how many bar_index's there are
if bar_index <= 20000
if bar_index <= 5000
newLength := 200
newCount := 30
else if bar_index <= 10000
newLength := 150
newCount := 30
else if bar_index <= 20000
newLength := 125
newCount := 25
else
newLength := 100
newCount := 20
else
//For historical bar, we factor in the Time Frame as we don't know how many bar index's will be on this chart yet
if bar_index <= 20000
_timeS = timeframe.period
_time = str.tonumber(_timeS)
if _time >= 240 and _time < 720
newLength := 125
newCount := 25
else if bar_index <= 10000 and _time >= 720 and _time < 1440
newLength := 150
newCount := 30
else if bar_index <= 5000 and (str.contains(_timeS, "D") or str.contains(_timeS, "W") or str.contains(_timeS, "M"))
newLength := 200
newCount := 30
[newLength, newCount]
//@jdehorty Kernel Function
//used to turn a source into a rational quadratic which performs better in ML calculations
rationalQuadratic(series float _src, simple int _lookback, simple float _relativeWeight, simple int startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight)
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
//Consistent and easy way to fill a table cell
f_fillCell(_table, _column, _row, _value, _color) =>
table.cell(_table, _column, _row, _value, bgcolor = color.new(_color, 75), text_color = _color, width = 20)
//Same as ta.sma but this way we can use a series length
pine_sma(x, series int y) =>
sum = 0.0
for i = 0 to y - 1
sum := sum + x[i] / y
sum
//Same as ta.rma but this way we can use a series length
pine_rma(src, series int length) =>
alpha = 1/length
sum = 0.0
sum := na(sum[1]) ? pine_sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])
//Same as ta.rsi but this way we can use a series length
pine_rsi(x, series int y) =>
u = math.max(x - x[1], 0) // upward ta.change
d = math.max(x[1] - x, 0) // downward ta.change
rs = pine_rma(u, y) / pine_rma(d, y)
res = 100 - 100 / (1 + rs)
res
//Calculate the optimal RSI length based on settings
getOptimalRSILength() =>
//Storage to know the RSI and RSI MA cross percents (how much profit or loss has occured since this cross)
crossPercents = array.new_float(rsiCount) //we use close not the rsi level
//Get our source
_src = useRationalQuadratics ? rationalQuadratic(close, 8, 8., 25) : close
//Calculate our Optimal RSI
for i = 0 to rsiCount - 1
//scan all bar indexs for each RSI type to evaluate its crosses and percent increases
len = i + rsiMinLength
crossPercent = 0.
crossType = 0 // 0 = none, -1 = under, 1 = over
crossClose = 0. //close // was 0.
crossCount = 0
inExtremity = false
for a = 0 to optimalLength - 1
//get current bars RSI and MA
currentRSI = pine_rsi(close[a], len)
currentMA = pine_sma(currentRSI, maLength)
//check for cross'
crossOver = ta.crossover(currentRSI, currentMA)
currentOver = optimalType == "All Crossings" or inExtremity ? crossOver :
currentRSI <= 40 and crossOver
crossUnder = ta.crossunder(currentRSI, currentMA)
currentUnder = optimalType == "All Crossings" or inExtremity ? crossUnder :
currentRSI >= 60 and crossUnder
//calculate cross percent and update data
if currentOver
if crossType != 0
crossPercent += crossClose / close[a]
crossCount += 1
crossClose := close[a]
crossType := 1
inExtremity := not inExtremity
else if currentUnder
if crossType != 0
crossPercent += close[a] / crossClose
crossCount += 1
crossClose := close[a]
crossType := -1
inExtremity := not inExtremity
//save the profit % of this RSI length
crossPercents.set(i, crossPercent / crossCount)
//See which RSI Length produced the highest profit
bestPercent = -100000.
bestIndex = 0
for p = 0 to rsiCount - 1
if crossPercents.get(p) > bestPercent
bestPercent := crossPercents.get(p)
bestIndex := p
//get the optimal Length
optimal = bestPercent != -100000 ? bestIndex + rsiMinLength : backupLength
//return the best RSI Length
[optimal, bestPercent]
//Get the exponential average of an array, where the exponential weight is focused on the first value of this array (current source)
getExponentialDataAverage(_data, _length) =>
avg = 0.
maxLen = math.min(_data.size(), _length)
if maxLen > 0
for i = 0 to maxLen - 1
curData = _data.get(i)
tempAvg = curData
if i > 0
for a = 0 to i
tempAvg += array.get(_data, a)
tempAvg := math.avg(_data.get(0), tempAvg / i)
avg += math.avg(_data.get(0), math.avg(curData, tempAvg))
avg / _length
else
avg
//Uses KNN to sort distances with our ML fast and slow data
//This is a modified version that sorts distances but rather than saving and outputting the distance average it outputs the mean of the valid distance and averages the total
knnAverage_fromDistance(_dataFast, _dataSlow, _minDist, _maxDist) =>
//failsafe we need at least 1 distance
maxDist = not _minDist ? true : _maxDist
//Calculate the distance between slow and fast moving ML Data
distances = array.new_float(0)
for i = 0 to _dataSlow.size() - 1
distance = _dataSlow.get(i) - _dataFast.get(i)
distances.push(distance)
//clone the array so it doesn't modify it
clonedDistances = distances.copy()
//slice the length from the array and calculate the max value from this slice
splicedDistances = clonedDistances.slice(0, math.min(knnLength, clonedDistances.size()))
maxDistanceAllowed = splicedDistances.max()
minDistanceAllowed = splicedDistances.min()
//scan all distances and add any that are less than max distance
validDistances = array.new_float(0)
for i = 0 to distances.size() - 1
if (not maxDist or distances.get(i) <= maxDistanceAllowed) and (not _minDist or distances.get(i) >= minDistanceAllowed)
distAvg = (_dataSlow.get(i) + _dataFast.get(i)) / 2
validDistances.push(distAvg)
// Get exponential or regular average
if useMachineLearning == "KNN Exponential Average"
getExponentialDataAverage(validDistances, 1)
else
validDistances.avg()
// ~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~ //
//Adjust length and counts
if adjustRatio
[newLength, newCount] = autoAdjust()
optimalLength := newLength
rsiCount := newCount
//Get our Optimal RSI Length
[rsiLength, bestPercent] = getOptimalRSILength()
//Calculate our Optimal RSI
float optimalRSI = pine_rsi(close, rsiLength)
float rsi = optimalRSI
//Calculate our temp RSI MA (this will change if our RSI does due to ML Calculations)
tempMA = ta.sma(rsi, maLength)
//Calculate if the RSI is bullish (RSI >= RSI MA) or bearish (RSI < RSI MA)
rsiBull = rsi >= tempMA
//Apply Machine Learning logic to our Optimal RSI if selected
if useMachineLearning != "None"
if useMachineLearning == "Simple Average"
// -- A simple machine Learning Average
//essentially just a simple Average of Optimal RSI data (potentially filtered to account for if its the same type (bullish or bearish))
rsiData = array.new_float(0)
for i = 0 to mlLength - 1
simpleTempMa = pine_sma(optimalRSI[i], maLength)
simpleTempBull = optimalRSI[i] > simpleTempMa
if not onlyUseSimilarMA or simpleTempBull == rsiBull
rsiData.push(optimalRSI[i])
rsi := rsiData.avg()
else
// -- A still simple but more complex approach to Machine Learning using KNN to sort validDistances
//Calculate our fast and slow MA's based on the current Optimal RSI
float rsiFast = ta.sma(optimalRSI, fastLength)
float rsiSlow = ta.sma(optimalRSI, slowLength)
//create storage data for ML lookbacks
rsiFastData = array.new_float(mlLength)
rsiSlowData = array.new_float(mlLength)
//populate our ML storage with lookbacks at our Fast and Slow Optimal RSIs
for i = 0 to mlLength - 1
rsiFastData.set(i, rsiFast[i])
rsiSlowData.set(i, rsiSlow[i])
//calculate our new Optimal RSI using KNN by using distances within KNN min/max and filtering by direction
rsi := knnAverage_fromDistance(rsiFastData, rsiSlowData, distanceTypeMin, distanceTypeMax)
//Calculate our RSI MA (we do this later incase the RSI changed through Machine Learning Calculations)
rsiMA = ta.sma(rsi, maLength)
//Calculate RSI and RSI MA crosses (Signals)
bullCross = ta.crossover(rsi, rsiMA)
bearCross = ta.crossunder(rsi, rsiMA)
//Bollinger Bands
upper_inner = 0.
lower_inner = 0.
upper_outer = 0.
lower_outer = 0.
if showBollingerBands
basis = ta.sma(rsi, optimalLength)
dev_inner = 1.6185 * ta.stdev(rsi, optimalLength)
dev_outer = 2.0 * ta.stdev(rsi, optimalLength)
upper_inner := basis + dev_inner
lower_inner := basis - dev_inner
upper_outer := basis + dev_outer
lower_outer := basis - dev_outer
// ~~~~~~~~~~~~ PLOTS ~~~~~~~~~~~~ //
//Bollinger Bands
bb_up_outer = plot(showBollingerBands ? upper_outer : na, "Upper Band", color = color.new(color.green, 40), linewidth = 1)
bb_up_inner = plot(showBollingerBands ? upper_inner : na, "Upper Band", color = color.new(color.green, 60), linewidth = 1)
fill(bb_up_outer, bb_up_inner, color=color.new(color.green, 95))
bb_down_outer = plot(showBollingerBands ? lower_outer : na, "Lower Band", color = color.new(color.red, 40), linewidth = 1)
bb_down_inner = plot(showBollingerBands ? lower_inner : na, "Lower Band", color = color.new(color.red, 60), linewidth = 1)
fill(bb_down_outer, bb_down_inner, color=color.new(color.red, 95))
//RSI Bands
h0 = hline(70, "Upper Band", color=#787B86)
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(30, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(126, 87, 194, 90), title="Background")
//RSI + RSI MA and gradient fills
rsiPlot = plot(rsi, "RSI", color=#7E57C2)
plot(rsiMA, "RSI MA", color=color.yellow)
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "RSI Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "RSI Oversold Gradient Fill")
//Crossing Signals
plot(showSignals and bullCross ? rsi : na, color=color.green, linewidth=3, style=plot.style_circles, title="RSI Bull Signal")
plot(showSignals and bearCross ? rsi : na, color=color.red, linewidth=3, style=plot.style_circles, title="RSI Bear Signal")
// ~~~~~~~~~~~~ TABLES ~~~~~~~~~~~~ //
var table perfTable = table.new(position.top_right, 4, 1, border_width = 5)
if showTables and barstate.islast
f_fillCell(perfTable, 0, 0, "Optimal RSI Length: " + str.tostring(rsiLength), color.green)
f_fillCell(perfTable, 1, 0, "Optimal Profit %: " + (bestPercent != -100000 ? str.tostring(math.round(bestPercent, 8)) : "None"), color.green)
if showNewSettings and adjustRatio
f_fillCell(perfTable, 2, 0, "New Lookback Length: " + str.tostring(optimalLength), color.green)
f_fillCell(perfTable, 3, 0, "New RSI Count: " + str.tostring(rsiCount), color.green)
// ~~~~~~~~~~~~ ALERTS ~~~~~~~~~~~~ //
alertcondition(bullCross, title="RSI Bull Signal", message="RSI Bull Signal")
alertcondition(bearCross, title="RSI Bear Signal", message="RSI Bear Signal")
// ~~~~~~~~~~~~ END ~~~~~~~~~~~~ // |
Volume and Price Z-Score [Multi-Asset] - By Leviathan | https://www.tradingview.com/script/CBnACnmq-Volume-and-Price-Z-Score-Multi-Asset-By-Leviathan/ | LeviathanCapital | https://www.tradingview.com/u/LeviathanCapital/ | 578 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeviathanCapital
//@version=5
indicator("Volume and Price Z-Score [Multi-Asset] - By Leviathan", max_labels_count = 500, max_lines_count = 500, max_boxes_count = 100)
g1 = 'Symbols'
g2 = 'General'
g3 = 'Columns/Circles'
g4 = 'Scatter Plot'
g10 = 'Heatmap'
g5 = 'Group 1'
g6 = 'Group 2'
g7 = 'Group 3'
g8 = 'Group 4'
g9 = 'Group 5'
tt1 = 'Select the group of symbols that should be displayed. The symbols can be adjusted in the last section of indicator settings'
tt2 = 'Select the color palette'
tt3 = 'Select how the data should be displayed'
tt4 = 'Mean is the moving average of price/volume (fundamental part of calculating the z-score). This input controls the length of the moving average'
tt5 = 'This input determines the length of the moving average for calculating the Average Z-Score. '
tt6 = 'Select the type of z-score you wish to display. Please read more about this in indicator description.'
tt7 = 'Select the timeframe used in calculations. Default is current chart timeframe.'
tt8 = 'Select the type of volume used for calculating volume z-score. Please read more about this in indicator description.'
tt9 = 'Select the type of moving average used for calculating the mean. SMA equally weights all prices in the period. Gives more weight to recent values, making it more sensitive to recent action.'
// General
ztype = input.string('Current Z-Score', 'Z-Score Type', options = ['Current Z-Score', 'Average Z-Score', 'Relative Z-Score'], tooltip = tt6)
disp = input.string('Scatter Plot', 'Display', ['Circles', 'Scatter Plot', 'Columns', 'Z-Price Heatmap', 'Z-Volume Heatmap', 'Z-Delta Heatmap', 'Delta Columns'], tooltip = tt3)
meantype = input.string('SMA', 'Mean Type', ['SMA', 'EMA'], tooltip = tt9)
zlen = input.int(20, 'Mean Length', tooltip = tt4)
azlen = input.int(14, 'Average Z-Score Length', tooltip = tt5)
voltype = input.string('VOLUME', 'Volume Type', ['VOLUME', 'OBV'], tooltip = tt8)
gn = input.string('Group 1', 'Asset Group', options = ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'], tooltip = tt1)
pl = input.string('Palette 1', 'Color Palette', ['Palette 1', 'Palette 2', 'Palette 3', 'Palette 4', 'Palette 5'], tooltip = tt2)
tf = input.timeframe('', 'Bar Timeframe', tooltip = tt7)
showtitle = input.bool(true, 'Show Title')
// Scatter
priceshape = input.string('Circle', 'Shape & Transparency', options = ['Circle', 'Square', 'Diamond'], group = g4, inline = 'sp')
trans = input.int(50, '', group = g4, inline = 'sp')
showquadr = input.bool(true, 'Square (σ) ', inline = 'quadrant', group = g4)
quadr = input.float(1, '', step = 0.1, inline = 'quadrant', group = g4)
quadrcol = input.color(color.gray, '', inline = 'quadrant', group = g4)
quadrbgcol = input.color(color.rgb(120, 123, 134, 100), '', inline = 'quadrant', group = g4)
showquadr1 = input.bool(true, 'Square (σ) ', inline = 'quadrant1', group = g4)
quadr1 = input.float(2, '', step = 0.1, inline = 'quadrant1', group = g4)
quadrcol1 = input.color(color.gray, '', inline = 'quadrant1', group = g4)
quadrbgcol1 = input.color(color.rgb(120, 123, 134, 100), '', inline = 'quadrant1', group = g4)
showquadr2 = input.bool(true, 'Square (σ) ', inline = 'quadrant2', group = g4)
quadr2 = input.float(3, '', step = 0.1, inline = 'quadrant2', group = g4)
quadrcol2 = input.color(color.gray, '', inline = 'quadrant2', group = g4)
quadrbgcol2 = input.color(color.rgb(120, 123, 134, 100), '', inline = 'quadrant2', group = g4)
gridcol = #787b861f
gridcol2 = #787b868f
lblplotscond = input.string('Outliers', 'Symbol names', options = ['Outliers', 'All', 'None'], group = g4, inline = 'lblcol')
lblplotscol = input.color(color.gray, '', inline = 'lblcol', group = g4)
outlierstd = input.float(1, ' SD(σ) >', group = g4, inline = 'lblcol')
helperlab = input.bool(true, 'Helper Labels', group = g4)
// Circles
zprice = input.bool(true, '', inline = 'p', group = g3)
zvol = input.bool(true, '', inline = 'v', group = g3)
priceshape2 = input.string('Circle', 'Z-Price ', options = ['Circle', 'Square', 'Diamond'], inline = 'p', group = g3)
volshape = input.string('Circle', 'Z-Volume', options = ['Circle', 'Square', 'Diamond'], inline = 'v', group = g3)
// Heatmap
hmpos = input.string('1', 'Heatmap Position', ['1', '2', '3', '4', '5'], group = g10)
hmcoltype = input.string('Two-Color', 'Color coding', ['Two-Color', 'Multi-Color'], group = g10)
colh1 = input.color(#b22222, 'Multi-Color (High->Low)', inline = 'hm', group = g10)
colh2 = input.color(#ffa07a, '', inline = 'hm', group = g10)
colh3 = input.color(#ffebeb, '', inline = 'hm', group = g10)
colc1 = input.color(#4682b4, '', inline = 'hm', group = g10)
colc2 = input.color(#add8e6, '', inline = 'hm', group = g10)
colc3 = input.color(#f0f8ff, '', inline = 'hm', group = g10)
colhh = input.color(#FF6161, 'Two-Color (High->Low)', inline = 'hm2', group = g10)
colcc = input.color(#1A237E, '', inline = 'hm2', group = g10)
// Function for switching object shape
switchshape(x) =>
switch x
'Circle' => label.style_circle
'Square' => label.style_square
'Diamond' => label.style_diamond
// User inputs - Group 1
sym1 = input.symbol('BTCUSDT.P', '' , group = g5), sym2 = input.symbol('ETHUSDT.P', '' , group = g5), sym3 = input.symbol('SOLUSDT.P', '' , group = g5), sym4 = input.symbol('OGNUSDT.P', '' , group = g5)
sym5 = input.symbol('LEVERUSDT.P', '' , group = g5), sym6 = input.symbol('LINKUSDT.P', '' , group = g5), sym7 = input.symbol('XRPUSDT.P', '' , group = g5), sym8 = input.symbol('TRBUSDT.P', '' , group = g5)
sym9 = input.symbol('WLDUSDT.P', '' , group = g5), sym10 = input.symbol('LPTUSDT.P', '' , group = g5), sym11 = input.symbol('BCHUSDT.P', '' , group = g5), sym12 = input.symbol('STORJUSDT.P', '' , group = g5)
sym13 = input.symbol('MATICUSDT.P', '' , group = g5), sym14 = input.symbol('DOGEUSDT.P', '' , group = g5), sym15 = input.symbol('BNBUSDT.P', '' , group = g5), sym16 = input.symbol('RUNEUSDT.P', '' , group = g5)
sym17 = input.symbol('ARBUSDT.P', '' , group = g5), sym18 = input.symbol('MKRUSDT.P', '' , group = g5), sym19 = input.symbol('LTCUSDT.P', '' , group = g5), sym20 = input.symbol('PEPEUSDT.P', '' , group = g5)
sym21 = input.symbol('SUIUSDT.P', '' , group = g5), sym22 = input.symbol('ADAUSDT.P', '' , group = g5), sym23 = input.symbol('OPUSDT.P', '' , group = g5), sym24 = input.symbol('APEUSDT.P', '' , group = g5)
sym25 = input.symbol('YGGUSDT.P', '' , group = g5), sym26 = input.symbol('IOTXUSDT.P', '' , group = g5), sym27 = input.symbol('DOTUSDT.P', '' , group = g5), sym28 = input.symbol('CRVUSDT.P', '' , group = g5)
sym29 = input.symbol('ETCUSDT.P', '' , group = g5), sym30 = input.symbol('GALAUSDT.P', '' , group = g5), sym31 = input.symbol('AVAXUSDT.P', '' , group = g5), sym32 = input.symbol('CFXUSDT.P', '' , group = g5)
sym33 = input.symbol('APTUSDT.P', '' , group = g5), sym34 = input.symbol('SHIBUSDT.P', '' , group = g5), sym35 = input.symbol('AMBUSDT.P', '' , group = g5), sym36 = input.symbol('FTMUSDT.P', '' , group = g5)
sym37 = input.symbol('FILUSDT.P', '' , group = g5), sym38 = input.symbol('ATOMUSDT.P', '' , group = g5), sym39 = input.symbol('COMPUSDT.P', '' , group = g5), sym40 = input.symbol('DYDXUSDT.P', '' , group = g5)
// User inputs - Group 2
sym41 = input.symbol('LQTYUSDT.P', '' , group = g6), sym42 = input.symbol('AXSUSDT.P', '' , group = g6), sym43 = input.symbol('GTCUSDT.P', '' , group = g6), sym44 = input.symbol('EOSUSDT.P', '' , group = g6)
sym45 = input.symbol('STMXUSDT.P', '' , group = g6), sym46 = input.symbol('STXUSDT.P', '' , group = g6), sym47 = input.symbol('FRONTUSDT.P', '' , group = g6), sym48 = input.symbol('LUNA2USDT.P', '' , group = g6)
sym49 = input.symbol('MASKUSDT.P', '' , group = g6), sym50 = input.symbol('BAKEUSDT.P', '' , group = g6), sym51 = input.symbol('TOMOUSDT.P', '' , group = g6), sym52 = input.symbol('BLZUSDT.P', '' , group = g6)
sym53 = input.symbol('PERPUSDT.P', '' , group = g6), sym54 = input.symbol('RNDRUSDT.P', '' , group = g6), sym55 = input.symbol('LDOUSDT.P', '' , group = g6), sym56 = input.symbol('TRXUSDT.P', '' , group = g6)
sym57 = input.symbol('1000FLOKIUSDT.P', '' , group = g6), sym58 = input.symbol('AAVEUSDT.P', '' , group = g6), sym59 = input.symbol('NEARUSDT.P', '' , group = g6), sym60 = input.symbol('HIFIUSDT.P', '' , group = g6)
sym61 = input.symbol('CYBERUSDT.P', '' , group = g6), sym62 = input.symbol('INJUSDT.P', '' , group = g6), sym63 = input.symbol('SANDUSDT.P', '' , group = g6), sym64 = input.symbol('UNFIUSDT.P', '' , group = g6)
sym65 = input.symbol('UNIUSDT.P', '' , group = g6), sym66 = input.symbol('ALGOUSDT.P', '' , group = g6), sym67 = input.symbol('XLMUSDT.P', '' , group = g6), sym68 = input.symbol('LITUSDT.P', '' , group = g6)
sym69 = input.symbol('MANAUSDT.P', '' , group = g6), sym70 = input.symbol('KNCUSDT.P', '' , group = g6), sym71 = input.symbol('FETUSDT.P', '' , group = g6), sym72 = input.symbol('XEMUSDT.P', '' , group = g6)
sym73 = input.symbol('SEIUSDT.P', '' , group = g6), sym74 = input.symbol('GMTUSDT.P', '' , group = g6), sym75 = input.symbol('CELOUSDT.P', '' , group = g6), sym76 = input.symbol('HBARUSDT.P', '' , group = g6)
sym77 = input.symbol('CHZUSDT.P', '' , group = g6), sym78 = input.symbol('CHRUSDT.P', '' , group = g6), sym79 = input.symbol('BLURUSDT.P', '' , group = g6), sym80 = input.symbol('RDNTUSDT.P', '' , group = g6)
// User inputs - Group 3
sym81 = input.symbol('QTUMUSDT.P', '' , group = g7), sym82 = input.symbol('WAVESUSDT.P', '' , group = g7), sym83 = input.symbol('1000XECUSDT.P', '' , group = g7), sym84 = input.symbol('MAVUSDT.P', '' , group = g7)
sym85 = input.symbol('FLMUSDT.P', '' , group = g7), sym86 = input.symbol('MAGICUSDT.P', '' , group = g7), sym87 = input.symbol('HIGHUSDT.P', '' , group = g7), sym88 = input.symbol('AGIXUSDT.P', '' , group = g7)
sym89 = input.symbol('NMRUSDT.P', '' , group = g7), sym90 = input.symbol('SNXUSDT.P', '' , group = g7), sym91 = input.symbol('IMXUSDT.P', '' , group = g7), sym92 = input.symbol('SPELLUSDT.P', '' , group = g7)
sym93 = input.symbol('BELUSDT.P', '' , group = g7), sym94 = input.symbol('JOEUSDT.P', '' , group = g7), sym95 = input.symbol('COMBOUSDT.P', '' , group = g7), sym96 = input.symbol('OMGUSDT.P', '' , group = g7)
sym97 = input.symbol('1000LUNCUSDT.P', '' , group = g7), sym98 = input.symbol('VETUSDT.P', '' , group = g7), sym99 = input.symbol('MTLUSDT.P', '' , group = g7), sym100 = input.symbol('LINAUSDT.P', '' , group = g7)
sym101 = input.symbol('TRUUSDT.P', '' , group = g7), sym102 = input.symbol('SXPUSDT.P', '' , group = g7), sym103 = input.symbol('C98USDT.P', '' , group = g7), sym104 = input.symbol('GMXUSDT.P', '' , group = g7)
sym105 = input.symbol('IDUSDT.P', '' , group = g7), sym106 = input.symbol('ENJUSDT.P', '' , group = g7), sym107 = input.symbol('ZILUSDT.P', '' , group = g7), sym108 = input.symbol('SUSHIUSDT.P', '' , group = g7)
sym109 = input.symbol('XMRUSDT.P', '' , group = g7), sym110 = input.symbol('KAVAUSDT.P', '' , group = g7), sym111 = input.symbol('FLOWUSDT.P', '' , group = g7), sym112 = input.symbol('ARKMUSDT.P', '' , group = g7)
sym113 = input.symbol('PENDLEUSDT.P', '' , group = g7), sym114 = input.symbol('GRTUSDT.P', '' , group = g7), sym115 = input.symbol('DARUSDT.P', '' , group = g7), sym116 = input.symbol('1INCHUSDT.P', '' , group = g7)
sym117 = input.symbol('EGLDUSDT.P', '' , group = g7), sym118 = input.symbol('AGLDUSDT.P', '' , group = g7), sym119 = input.symbol('HOOKUSDT.P', '' , group = g7), sym120 = input.symbol('WOOUSDT.P', '' , group = g7)
// User inputs - Group 4
sym121 = input.symbol('OCEANUSDT.P', '' , group = g8), sym122 = input.symbol('THETAUSDT.P', '' , group = g8), sym123 = input.symbol('IOSTUSDT.P', '' , group = g8), sym124 = input.symbol('NKNUSDT.P', '' , group = g8)
sym125 = input.symbol('YFIUSDT.P', '' , group = g8), sym126 = input.symbol('ENSUSDT.P', '' , group = g8), sym127 = input.symbol('ICPUSDT.P', '' , group = g8), sym128 = input.symbol('API3USDT.P', '' , group = g8)
sym129 = input.symbol('REEFUSDT.P', '' , group = g8), sym130 = input.symbol('EDUUSDT.P', '' , group = g8), sym131 = input.symbol('PHBUSDT.P', '' , group = g8), sym132 = input.symbol('PEOPLEUSDT.P', '' , group = g8)
sym133 = input.symbol('BANDUSDT.P', '' , group = g8), sym134 = input.symbol('STGUSDT.P', '' , group = g8), sym135 = input.symbol('MDTUSDT.P', '' , group = g8), sym136 = input.symbol('FXSUSDT.P', '' , group = g8)
sym137 = input.symbol('ROSEUSDT.P', '' , group = g8), sym138 = input.symbol('NEOUSDT.P', '' , group = g8), sym139 = input.symbol('OXTUSDT.P', '' , group = g8), sym140 = input.symbol('ARKUSDT.P', '' , group = g8)
sym141 = input.symbol('XTZUSDT.P', '' , group = g8), sym142 = input.symbol('SFPUSDT.P', '' , group = g8), sym143 = input.symbol('MINAUSDT.P', '' , group = g8), sym144 = input.symbol('CTSIUSDT.P', '' , group = g8)
sym145 = input.symbol('ALPHAUSDT.P', '' , group = g8), sym146 = input.symbol('JASMYUSDT.P', '' , group = g8), sym147 = input.symbol('ACHUSDT.P', '' , group = g8), sym148 = input.symbol('CELRUSDT.P', '' , group = g8)
sym149 = input.symbol('ANKRUSDT.P', '' , group = g8), sym150 = input.symbol('ONEUSDT.P', '' , group = g8), sym151 = input.symbol('GLMRUSDT.P', '' , group = g8), sym152 = input.symbol('BICOUSDT.P', '' , group = g8)
sym153 = input.symbol('GALUSDT.P', '' , group = g8), sym154 = input.symbol('ARPAUSDT.P', '' , group = g8), sym155 = input.symbol('XVSUSDT.P', '' , group = g8), sym156 = input.symbol('COTIUSDT.P', '' , group = g8)
sym157 = input.symbol('DASHUSDT.P', '' , group = g8), sym158 = input.symbol('HOTUSDT.P', '' , group = g8), sym159 = input.symbol('TUSDT.P', '' , group = g8), sym160 = input.symbol('ANTUSDT.P', '' , group = g8)
// User inputs - Group 5
sym161 = input.symbol('ATAUSDT.P', '' , group = g9), sym162 = input.symbol('ALICEUSDT.P', '' , group = g9), sym163 = input.symbol('ONTUSDT.P', '' , group = g9), sym164 = input.symbol('ZENUSDT.P', '' , group = g9)
sym165 = input.symbol('SSVUSDT.P', '' , group = g9), sym166 = input.symbol('DODOXUSDT.P', '' , group = g9), sym167 = input.symbol('KLAYUSDT.P', '' , group = g9), sym168 = input.symbol('DENTUSDT.P', '' , group = g9)
sym169 = input.symbol('ASTRUSDT.P', '' , group = g9), sym170 = input.symbol('DUSKUSDT.P', '' , group = g9), sym171 = input.symbol('RSRUSDT.P', '' , group = g9), sym172 = input.symbol('ZECUSDT.P', '' , group = g9)
sym173 = input.symbol('IOTAUSDT.P', '' , group = g9), sym174 = input.symbol('ARUSDT.P', '' , group = g9), sym175 = input.symbol('XVGUSDT.P', '' , group = g9), sym176 = input.symbol('RLCUSDT.P', '' , group = g9)
sym177 = input.symbol('LRCUSDT.P', '' , group = g9), sym178 = input.symbol('AUDIOUSDT.P', '' , group = g9), sym179 = input.symbol('KSMUSDT.P', '' , group = g9), sym180 = input.symbol('QNTUSDT.P', '' , group = g9)
sym181 = input.symbol('RENUSDT.P', '' , group = g9), sym182 = input.symbol('CVXUSDT.P', '' , group = g9), sym183 = input.symbol('UMAUSDT.P', '' , group = g9), sym184 = input.symbol('RADUSDT.P', '' , group = g9)
sym185 = input.symbol('ZRXUSDT.P', '' , group = g9), sym186 = input.symbol('HFTUSDT.P', '' , group = g9), sym187 = input.symbol('BATUSDT.P', '' , group = g9), sym188 = input.symbol('BALUSDT.P', '' , group = g9)
sym189 = input.symbol('KEYUSDT.P', '' , group = g9), sym190 = input.symbol('SKLUSDT.P', '' , group = g9), sym191 = input.symbol('RVNUSDT.P', '' , group = g9), sym192 = input.symbol('IDEXUSDT.P', '' , group = g9)
sym193 = input.symbol('BNXUSDT.P', '' , group = g9), sym194 = input.symbol('TLMUSDT.P', '' , group = g9), sym195 = input.symbol('DGBUSDT.P', '' , group = g9), sym196 = input.symbol('CTKUSDT.P', '' , group = g9)
sym197 = input.symbol('ICXUSDT.P', '' , group = g9), sym198 = input.symbol('BNTUSDT.P', '' , group = g9), sym199 = input.symbol('CKBUSDT.P', '' , group = g9), sym200 = input.symbol('DEFIUSDT.P', '' , group = g9)
// Assigning symbols to groups
S1 = gn=='Group 1' ? sym1 : gn=='Group 2' ? sym41 : gn=='Group 3' ? sym81 : gn=='Group 4' ? sym121 : sym161
S2 = gn=='Group 1' ? sym2 : gn=='Group 2' ? sym42 : gn=='Group 3' ? sym82 : gn=='Group 4' ? sym122 : sym162
S3 = gn=='Group 1' ? sym3 : gn=='Group 2' ? sym43 : gn=='Group 3' ? sym83 : gn=='Group 4' ? sym123 : sym163
S4 = gn=='Group 1' ? sym4 : gn=='Group 2' ? sym44 : gn=='Group 3' ? sym84 : gn=='Group 4' ? sym124 : sym164
S5 = gn=='Group 1' ? sym5 : gn=='Group 2' ? sym45 : gn=='Group 3' ? sym85 : gn=='Group 4' ? sym125 : sym165
S6 = gn=='Group 1' ? sym6 : gn=='Group 2' ? sym46 : gn=='Group 3' ? sym86 : gn=='Group 4' ? sym126 : sym166
S7 = gn=='Group 1' ? sym7 : gn=='Group 2' ? sym47 : gn=='Group 3' ? sym87 : gn=='Group 4' ? sym127 : sym167
S8 = gn=='Group 1' ? sym8 : gn=='Group 2' ? sym48 : gn=='Group 3' ? sym88 : gn=='Group 4' ? sym128 : sym168
S9 = gn=='Group 1' ? sym9 : gn=='Group 2' ? sym49 : gn=='Group 3' ? sym89 : gn=='Group 4' ? sym129 : sym169
S10 = gn=='Group 1' ? sym10 : gn=='Group 2' ? sym50 : gn=='Group 3' ? sym90 : gn=='Group 4' ? sym130 : sym170
S11 = gn=='Group 1' ? sym11 : gn=='Group 2' ? sym51 : gn=='Group 3' ? sym91 : gn=='Group 4' ? sym131 : sym171
S12 = gn=='Group 1' ? sym12 : gn=='Group 2' ? sym52 : gn=='Group 3' ? sym92 : gn=='Group 4' ? sym132 : sym172
S13 = gn=='Group 1' ? sym13 : gn=='Group 2' ? sym53 : gn=='Group 3' ? sym93 : gn=='Group 4' ? sym133 : sym173
S14 = gn=='Group 1' ? sym14 : gn=='Group 2' ? sym54 : gn=='Group 3' ? sym94 : gn=='Group 4' ? sym134 : sym174
S15 = gn=='Group 1' ? sym15 : gn=='Group 2' ? sym55 : gn=='Group 3' ? sym95 : gn=='Group 4' ? sym135 : sym175
S16 = gn=='Group 1' ? sym16 : gn=='Group 2' ? sym56 : gn=='Group 3' ? sym96 : gn=='Group 4' ? sym136 : sym176
S17 = gn=='Group 1' ? sym17 : gn=='Group 2' ? sym57 : gn=='Group 3' ? sym97 : gn=='Group 4' ? sym137 : sym177
S18 = gn=='Group 1' ? sym18 : gn=='Group 2' ? sym58 : gn=='Group 3' ? sym98 : gn=='Group 4' ? sym138 : sym178
S19 = gn=='Group 1' ? sym19 : gn=='Group 2' ? sym59 : gn=='Group 3' ? sym99 : gn=='Group 4' ? sym139 : sym179
S20 = gn=='Group 1' ? sym20 : gn=='Group 2' ? sym60 : gn=='Group 3' ? sym100 : gn=='Group 4' ? sym140 : sym180
S21 = gn=='Group 1' ? sym21 : gn=='Group 2' ? sym61 : gn=='Group 3' ? sym101 : gn=='Group 4' ? sym141 : sym181
S22 = gn=='Group 1' ? sym22 : gn=='Group 2' ? sym62 : gn=='Group 3' ? sym102 : gn=='Group 4' ? sym142 : sym182
S23 = gn=='Group 1' ? sym23 : gn=='Group 2' ? sym63 : gn=='Group 3' ? sym103 : gn=='Group 4' ? sym143 : sym183
S24 = gn=='Group 1' ? sym24 : gn=='Group 2' ? sym64 : gn=='Group 3' ? sym104 : gn=='Group 4' ? sym144 : sym184
S25 = gn=='Group 1' ? sym25 : gn=='Group 2' ? sym65 : gn=='Group 3' ? sym105 : gn=='Group 4' ? sym145 : sym185
S26 = gn=='Group 1' ? sym26 : gn=='Group 2' ? sym66 : gn=='Group 3' ? sym106 : gn=='Group 4' ? sym146 : sym186
S27 = gn=='Group 1' ? sym27 : gn=='Group 2' ? sym67 : gn=='Group 3' ? sym107 : gn=='Group 4' ? sym147 : sym187
S28 = gn=='Group 1' ? sym28 : gn=='Group 2' ? sym68 : gn=='Group 3' ? sym108 : gn=='Group 4' ? sym148 : sym188
S29 = gn=='Group 1' ? sym29 : gn=='Group 2' ? sym69 : gn=='Group 3' ? sym109 : gn=='Group 4' ? sym149 : sym189
S30 = gn=='Group 1' ? sym30 : gn=='Group 2' ? sym70 : gn=='Group 3' ? sym110 : gn=='Group 4' ? sym150 : sym190
S31 = gn=='Group 1' ? sym31 : gn=='Group 2' ? sym71 : gn=='Group 3' ? sym111 : gn=='Group 4' ? sym151 : sym191
S32 = gn=='Group 1' ? sym32 : gn=='Group 2' ? sym72 : gn=='Group 3' ? sym112 : gn=='Group 4' ? sym152 : sym192
S33 = gn=='Group 1' ? sym33 : gn=='Group 2' ? sym73 : gn=='Group 3' ? sym113 : gn=='Group 4' ? sym153 : sym193
S34 = gn=='Group 1' ? sym34 : gn=='Group 2' ? sym74 : gn=='Group 3' ? sym114 : gn=='Group 4' ? sym154 : sym194
S35 = gn=='Group 1' ? sym35 : gn=='Group 2' ? sym75 : gn=='Group 3' ? sym115 : gn=='Group 4' ? sym155 : sym195
S36 = gn=='Group 1' ? sym36 : gn=='Group 2' ? sym76 : gn=='Group 3' ? sym116 : gn=='Group 4' ? sym156 : sym196
S37 = gn=='Group 1' ? sym37 : gn=='Group 2' ? sym77 : gn=='Group 3' ? sym117 : gn=='Group 4' ? sym157 : sym197
S38 = gn=='Group 1' ? sym38 : gn=='Group 2' ? sym78 : gn=='Group 3' ? sym118 : gn=='Group 4' ? sym158 : sym198
S39 = gn=='Group 1' ? sym39 : gn=='Group 2' ? sym79 : gn=='Group 3' ? sym119 : gn=='Group 4' ? sym159 : sym199
S40 = gn=='Group 1' ? sym40 : gn=='Group 2' ? sym80 : gn=='Group 3' ? sym120 : gn=='Group 4' ? sym160 : sym200
// Assigning colors to palettes
C1 = pl=='Palette 1' ? #a0e4c0 : pl=='Palette 2' ? #8DD3C7 : pl=='Palette 3' ? #1F77B4 : pl=='Palette 4' ? #D32F2F : #007BFF
C2 = pl=='Palette 1' ? #7d8bae : pl=='Palette 2' ? #FFFFB3 : pl=='Palette 3' ? #FF7F0E : pl=='Palette 4' ? #1976D2 : #1C56AC
C3 = pl=='Palette 1' ? #e5857b : pl=='Palette 2' ? #BEBADA : pl=='Palette 3' ? #2CA02C : pl=='Palette 4' ? #388E3C : #0082CC
C4 = pl=='Palette 1' ? #f1b2b2 : pl=='Palette 2' ? #FB8072 : pl=='Palette 3' ? #D62728 : pl=='Palette 4' ? #FBC02D : #3D8DD9
C5 = pl=='Palette 1' ? #e8ccc7 : pl=='Palette 2' ? #80B1D3 : pl=='Palette 3' ? #9467BD : pl=='Palette 4' ? #8E24AA : #0066B2
C6 = pl=='Palette 1' ? #506488 : pl=='Palette 2' ? #FDB462 : pl=='Palette 3' ? #8C564B : pl=='Palette 4' ? #E64A19 : #3498DB
C7 = pl=='Palette 1' ? #849bb1 : pl=='Palette 2' ? #B3DE69 : pl=='Palette 3' ? #E377C2 : pl=='Palette 4' ? #0288D1 : #0099E5
C8 = pl=='Palette 1' ? #e89c8f : pl=='Palette 2' ? #FCCDD3 : pl=='Palette 3' ? #7F7F7F : pl=='Palette 4' ? #7B1FA2 : #57A8FF
C9 = pl=='Palette 1' ? #f3c3c3 : pl=='Palette 2' ? #D9D9D9 : pl=='Palette 3' ? #BCBD22 : pl=='Palette 4' ? #C2185B : #6BBBFF
C10 = pl=='Palette 1' ? #eddbd2 : pl=='Palette 2' ? #BC80BD : pl=='Palette 3' ? #17BECF : pl=='Palette 4' ? #7C4DFF : #4C8DBE
C11 = pl=='Palette 1' ? #5b7085 : pl=='Palette 2' ? #CCEDC5 : pl=='Palette 3' ? #9EDAE5 : pl=='Palette 4' ? #00796B : #7EBFFF
C12 = pl=='Palette 1' ? #8badb5 : pl=='Palette 2' ? #DEDAC4 : pl=='Palette 3' ? #FFBB78 : pl=='Palette 4' ? #D35400 : #53A0D1
C13 = pl=='Palette 1' ? #d17584 : pl=='Palette 2' ? #FED9A6 : pl=='Palette 3' ? #98DF8A : pl=='Palette 4' ? #CDDC39 : #80CAFF
C14 = pl=='Palette 1' ? #f4c8c5 : pl=='Palette 2' ? #FFED6F : pl=='Palette 3' ? #D6616B : pl=='Palette 4' ? #9E9E9E : #4694BF
C15 = pl=='Palette 1' ? #ddd8da : pl=='Palette 2' ? #98DF8A : pl=='Palette 3' ? #C5B0D5 : pl=='Palette 4' ? #607D8B : #8ED5FF
C16 = pl=='Palette 1' ? #667c91 : pl=='Palette 2' ? #9EDAE5 : pl=='Palette 3' ? #C49C94 : pl=='Palette 4' ? #8BC34A : #3E86AD
C17 = pl=='Palette 1' ? #92c0b8 : pl=='Palette 2' ? #D53E4F : pl=='Palette 3' ? #F7B6D2 : pl=='Palette 4' ? #795548 : #9CE0FF
C18 = pl=='Palette 1' ? #be6e8d : pl=='Palette 2' ? #F46D43 : pl=='Palette 3' ? #C7C7C7 : pl=='Palette 4' ? #5D4037 : #3A79A1
C19 = pl=='Palette 1' ? #f7dde0 : pl=='Palette 2' ? #FDA861 : pl=='Palette 3' ? #DBDB8D : pl=='Palette 4' ? #9C27B0 : #B2E9FF
C20 = pl=='Palette 1' ? #d4d9dd : pl=='Palette 2' ? #ABDDA4 : pl=='Palette 3' ? #9EDAE5 : pl=='Palette 4' ? #FFEB3B : #316595
C21 = pl=='Palette 1' ? #70878e : pl=='Palette 2' ? #80B1D3 : pl=='Palette 3' ? #AEC7E8 : pl=='Palette 4' ? #00BCD4 : #C4F1FF
C22 = pl=='Palette 1' ? #99d2bc : pl=='Palette 2' ? #FDB462 : pl=='Palette 3' ? #FF9896 : pl=='Palette 4' ? #03A9F4 : #295089
C23 = pl=='Palette 1' ? #aa688b : pl=='Palette 2' ? #B3DE69 : pl=='Palette 3' ? #C5B0D5 : pl=='Palette 4' ? #E91E63 : #D6FAFF
C24 = pl=='Palette 1' ? #fad2e3 : pl=='Palette 2' ? #FCCDD3 : pl=='Palette 3' ? #C49C94 : pl=='Palette 4' ? #FF5722 : #20477D
C25 = pl=='Palette 1' ? #ccd3d9 : pl=='Palette 2' ? #D9D9D9 : pl=='Palette 3' ? #F7B6D2 : pl=='Palette 4' ? #4CAF50 : #E6FFFF
C26 = pl=='Palette 1' ? #7c938a : pl=='Palette 2' ? #BC80BD : pl=='Palette 3' ? #7FCDBB : pl=='Palette 4' ? #3F51B5 : #1E66A8
C27 = pl=='Palette 1' ? #a0a2e4 : pl=='Palette 2' ? #CCEDC5 : pl=='Palette 3' ? #D9D9D9 : pl=='Palette 4' ? #FFC107 : #A1D7FF
C28 = pl=='Palette 1' ? #966398 : pl=='Palette 2' ? #DEDAC4 : pl=='Palette 3' ? #DB8D41 : pl=='Palette 4' ? #FF9800 : #2773A3
C29 = pl=='Palette 1' ? #fbe7ec : pl=='Palette 2' ? #FED9A6 : pl=='Palette 3' ? #1CAE78 : pl=='Palette 4' ? #673AB7 : #ACE3FF
C30 = pl=='Palette 1' ? #e3ecf0 : pl=='Palette 2' ? #FFED6F : pl=='Palette 3' ? #AD494A : pl=='Palette 4' ? #212121 : #2E7FAD
C31 = pl=='Palette 1' ? #b4e1d1 : pl=='Palette 2' ? #8CAFCB : pl=='Palette 3' ? #8C6D31 : pl=='Palette 4' ? #BDBDBD : #B6EEFF
C32 = pl=='Palette 1' ? #6a82a3 : pl=='Palette 2' ? #C994C7 : pl=='Palette 3' ? #E7969C : pl=='Palette 4' ? #76FF03 : #257C99
C33 = pl=='Palette 1' ? #f09f9b : pl=='Palette 2' ? #E5F5E0 : pl=='Palette 3' ? #7B4173 : pl=='Palette 4' ? #00E5FF : #BEDFFF
C34 = pl=='Palette 1' ? #f9c9ca : pl=='Palette 2' ? #67A9CF : pl=='Palette 3' ? #A55194 : pl=='Palette 4' ? #FF1744 : #21708E
C35 = pl=='Palette 1' ? #e5d6d2 : pl=='Palette 2' ? #E31A1C : pl=='Palette 3' ? #8C6D31 : pl=='Palette 4' ? #651FFF : #C6E9FF
C36 = pl=='Palette 1' ? #455a6f : pl=='Palette 2' ? #74C476 : pl=='Palette 3' ? #B5CF6B : pl=='Palette 4' ? #FF9100 : #1D6380
C37 = pl=='Palette 1' ? #7694a1 : pl=='Palette 2' ? #F768A1 : pl=='Palette 3' ? #CE6DBD : pl=='Palette 4' ? #8D6E63 : #D1F4FF
C38 = pl=='Palette 1' ? #df8980 : pl=='Palette 2' ? #7FCDBB : pl=='Palette 3' ? #BD9E39 : pl=='Palette 4' ? #4E342E : #186573
C39 = pl=='Palette 1' ? #f5bcbc : pl=='Palette 2' ? #9E9AC8 : pl=='Palette 3' ? #6B6ECF : pl=='Palette 4' ? #1B5E20 : #DBFEFF
C40 = pl=='Palette 1' ? #c9cfcd : pl=='Palette 2' ? #FEB24C : pl=='Palette 3' ? #D6616B : pl=='Palette 4' ? #01579B : #155C6B
debugtitle = input.bool(false, 'Fix Ticker Titling')
// Creating symbol and color arrays
syms = array.new_string()
cols = array.new_color()
// Pushing symbols into an array
array.push(syms, S1 ), array.push(syms, S2 ), array.push(syms, S3 ), array.push(syms, S4 ), array.push(syms, S5 )
array.push(syms, S6 ), array.push(syms, S7 ), array.push(syms, S8 ), array.push(syms, S9 ), array.push(syms, S10)
array.push(syms, S11), array.push(syms, S12), array.push(syms, S13), array.push(syms, S14), array.push(syms, S15)
array.push(syms, S16), array.push(syms, S17), array.push(syms, S18), array.push(syms, S19), array.push(syms, S20)
array.push(syms, S21), array.push(syms, S22), array.push(syms, S23), array.push(syms, S24), array.push(syms, S25)
array.push(syms, S26), array.push(syms, S27), array.push(syms, S28), array.push(syms, S29), array.push(syms, S30)
array.push(syms, S31), array.push(syms, S32), array.push(syms, S33), array.push(syms, S34), array.push(syms, S35)
array.push(syms, S36), array.push(syms, S37), array.push(syms, S38), array.push(syms, S39), array.push(syms, S40)
// Pushing colors into an array
array.push(cols, C1 ), array.push(cols, C2 ), array.push(cols, C3 ), array.push(cols, C4)
array.push(cols, C5 ), array.push(cols, C6 ), array.push(cols, C7 ), array.push(cols, C8)
array.push(cols, C9 ), array.push(cols, C10), array.push(cols, C11), array.push(cols, C12)
array.push(cols, C13), array.push(cols, C14), array.push(cols, C15), array.push(cols, C16)
array.push(cols, C17), array.push(cols, C18), array.push(cols, C19), array.push(cols, C20)
array.push(cols, C21), array.push(cols, C22), array.push(cols, C23), array.push(cols, C24)
array.push(cols, C25), array.push(cols, C26), array.push(cols, C27), array.push(cols, C28)
array.push(cols, C29), array.push(cols, C30), array.push(cols, C31), array.push(cols, C32)
array.push(cols, C33), array.push(cols, C34), array.push(cols, C35), array.push(cols, C36)
array.push(cols, C37), array.push(cols, C38), array.push(cols, C39), array.push(cols, C40)
// Function for calculating the Z-Score
f_zscore(src) =>
mean = meantype=='SMA' ? ta.sma(src, zlen) : ta.ema(src, zlen)
std_dev = ta.stdev(src, zlen)
z_score = (src - mean) / std_dev
// Function for encoding price + volume data (a trick to overcome max 40 security call limit)
encode_data(closeVal, volumeVal) =>
closeStr = na(closeVal) ? "na" : str.tostring(closeVal)
volumeStr = na(volumeVal) ? "na" : str.tostring(volumeVal)
encodedData = closeStr + "|" + volumeStr
encodedData
// Function for decoding price data
decode_close(encodedData) =>
data = str.split(encodedData, "|")
float closeVal = na
if array.size(data) > 0
for i = 0 to array.size(data)-1
if na(closeVal)
closeVal := str.tonumber(array.get(data, i))
else
closeVal := closeVal, str.tonumber(array.get(data, i))
else
closeVal := na
closeVal
// Function for decoding volume data
decode_volume(encodedData) =>
data = str.split(encodedData, "|")
float volumeVal = na
if array.size(data) > 1
val = str.tonumber(array.get(data, 1))
if not na(val)
volumeVal := val
volumeVal
// Function for fetching data
f_data(sym, t) =>
vol = voltype=='VOLUME' ? ta.sma(volume, 2) : ta.obv
combinedData = request.security(sym, timeframe.period, encode_data(close, vol))
dta = t == 0 ? decode_close(combinedData) : decode_volume(combinedData)
out = ztype=='Current Z-Score' or ztype=='Relative Z-Score' ? f_zscore(dta) : ta.sma(f_zscore(dta), azlen)
out > 4 ? 4 : out < -4 ? -4 : out
// Creating arrays for z-score values
Ps = array.new_float(40)
Vs = array.new_float(40)
// Fetching price and volume z-score data and pushing it into arrays
f_pushdata(index, p, v) =>
array.set(Ps, index, p)
array.set(Vs, index, v)
P1 = f_data(S1 , 0), V1 = f_data(S1 , 1), f_pushdata(0, P1 , V1 ), P2 = f_data(S2 , 0), V2 = f_data(S2 , 1), f_pushdata(1, P2 , V2 )
P3 = f_data(S3 , 0), V3 = f_data(S3 , 1), f_pushdata(2, P3 , V3 ), P4 = f_data(S4 , 0), V4 = f_data(S4 , 1), f_pushdata(3, P4 , V4 )
P5 = f_data(S5 , 0), V5 = f_data(S5 , 1), f_pushdata(4, P5 , V5 ), P6 = f_data(S6 , 0), V6 = f_data(S6 , 1), f_pushdata(5, P6 , V6 )
P7 = f_data(S7 , 0), V7 = f_data(S7 , 1), f_pushdata(6, P7 , V7 ), P8 = f_data(S8 , 0), V8 = f_data(S8 , 1), f_pushdata(7, P8 , V8 )
P9 = f_data(S9 , 0), V9 = f_data(S9 , 1), f_pushdata(8, P9 , V9 ), P10 = f_data(S10, 0), V10 = f_data(S10, 1), f_pushdata(9, P10, V10)
P11 = f_data(S11, 0), V11 = f_data(S11, 1), f_pushdata(10, P11, V11), P12 = f_data(S12, 0), V12 = f_data(S12, 1), f_pushdata(11, P12, V12)
P13 = f_data(S13, 0), V13 = f_data(S13, 1), f_pushdata(12, P13, V13), P14 = f_data(S14, 0), V14 = f_data(S14, 1), f_pushdata(13, P14, V14)
P15 = f_data(S15, 0), V15 = f_data(S15, 1), f_pushdata(14, P15, V15), P16 = f_data(S16, 0), V16 = f_data(S16, 1), f_pushdata(15, P16, V16)
P17 = f_data(S17, 0), V17 = f_data(S17, 1), f_pushdata(16, P17, V17), P18 = f_data(S18, 0), V18 = f_data(S18, 1), f_pushdata(17, P18, V18)
P19 = f_data(S19, 0), V19 = f_data(S19, 1), f_pushdata(18, P19, V19), P20 = f_data(S20, 0), V20 = f_data(S20, 1), f_pushdata(19, P20, V20)
P21 = f_data(S21, 0), V21 = f_data(S21, 1), f_pushdata(20, P21, V21), P22 = f_data(S22, 0), V22 = f_data(S22, 1), f_pushdata(21, P22, V22)
P23 = f_data(S23, 0), V23 = f_data(S23, 1), f_pushdata(22, P23, V23), P24 = f_data(S24, 0), V24 = f_data(S24, 1), f_pushdata(23, P24, V24)
P25 = f_data(S25, 0), V25 = f_data(S25, 1), f_pushdata(24, P25, V25), P26 = f_data(S26, 0), V26 = f_data(S26, 1), f_pushdata(25, P26, V26)
P27 = f_data(S27, 0), V27 = f_data(S27, 1), f_pushdata(26, P27, V27), P28 = f_data(S28, 0), V28 = f_data(S28, 1), f_pushdata(27, P28, V28)
P29 = f_data(S29, 0), V29 = f_data(S29, 1), f_pushdata(28, P29, V29), P30 = f_data(S30, 0), V30 = f_data(S30, 1), f_pushdata(29, P30, V30)
P31 = f_data(S31, 0), V31 = f_data(S31, 1), f_pushdata(30, P31, V31), P32 = f_data(S32, 0), V32 = f_data(S32, 1), f_pushdata(31, P32, V32)
P33 = f_data(S33, 0), V33 = f_data(S33, 1), f_pushdata(32, P33, V33), P34 = f_data(S34, 0), V34 = f_data(S34, 1), f_pushdata(33, P34, V34)
P35 = f_data(S35, 0), V35 = f_data(S35, 1), f_pushdata(34, P35, V35), P36 = f_data(S36, 0), V36 = f_data(S36, 1), f_pushdata(35, P36, V36)
P37 = f_data(S37, 0), V37 = f_data(S37, 1), f_pushdata(36, P37, V37), P38 = f_data(S38, 0), V38 = f_data(S38, 1), f_pushdata(37, P38, V38)
P39 = f_data(S39, 0), V39 = f_data(S39, 1), f_pushdata(38, P39, V39), P40 = f_data(S40, 0), V40 = f_data(S40, 1), f_pushdata(39, P40, V40)
// Relative/Second-Level Z-score
avgZscorePrice = array.avg(Ps)
avgZscoreVolume = array.avg(Vs)
stdDevPrice = array.stdev(Ps, false)
stdDevVolume = array.stdev(Vs, false)
relativeZscorePrice(P) =>
out = (P - avgZscorePrice) / stdDevPrice
out > 4 ? 4 : out < -4 ? -4 : out
relativeZscoreVolume(V) =>
out = (V - avgZscoreVolume) / stdDevVolume
out > 4 ? 4 : out < -4 ? -4 : out
// Modifying symbol names
ticker_names = array.new_string(40, na)
for i = 0 to 39
full_ticker = array.get(syms, i)
ticker_split = str.split(full_ticker, ":")
short_ticker = array.get(ticker_split, 1)
array.set(ticker_names, i, short_ticker)
// Creating an array with bar_index points
xs = array.new_int(0)
for i = 0 to 80
array.push(xs, bar_index[i])
// Function for transforming Z-Score values into bar_index points
f_magic(value) =>
index = 80 - int((value + 4) * 10)
array.get(xs, index)
// Initializing labels
var label[] pLabels = array.new_label(40, na)
var label[] vLabels = array.new_label(40, na)
var label[] nLabels = array.new_label(40, na)
var label[] sLabels = array.new_label(40, na)
var box[] pBoxes = array.new_box(40, na)
var box[] vBoxes = array.new_box(40, na)
// Functions to create or update labels and boxes
createOrUpdateLabel(arr, idx, x_val, y_val, lbl_style, lbl_color, lbl_text) =>
lbl = array.get(arr, idx)
if (na(lbl))
lbl := label.new(x_val, y_val, style = lbl_style, color = lbl_color, text = str.tostring(lbl_text), size = size.tiny, textcolor = lblplotscol)
array.set(arr, idx, lbl)
else
label.set_x(lbl, x = x_val)
createOrUpdateBox(arr, idx, x1_val, y1_val, x2_val, y2_val, bg_color) =>
bx = array.get(arr, idx)
if (na(bx))
bx := box.new(x1_val, y1_val, x2_val, y2_val, bgcolor = bg_color, border_color = chart.bg_color)
array.set(arr, idx, bx)
else
box.set_left(bx, x1_val)
box.set_right(bx, x2_val)
// Creating and updating labels and boxes
for i = 0 to 39
yValueP = ztype=='Relative Z-Score' ? relativeZscorePrice(array.get(Ps, i)) : array.get(Ps, i)
yValueV = ztype=='Relative Z-Score' ? relativeZscoreVolume(array.get(Vs, i)) : array.get(Vs, i)
xValue = 195 - i * 5
PlblColor = disp == 'Columns' ? color.new(array.get(cols, i), 30) : array.get(cols, i)
VlblColor = color.new(array.get(cols, i), trans)
txt = str.tostring(array.get(ticker_names, i))
txt1 = array.get(str.split(txt, 'USD'), 0)
if barstate.islast
if disp == 'Circles'
createOrUpdateLabel(pLabels, i, bar_index[xValue], yValueP, switchshape(priceshape), PlblColor, '')
createOrUpdateLabel(nLabels, i, bar_index[xValue], -4.3, label.style_label_up, color.rgb(120, 123, 134, 100), debugtitle ? txt : txt1)
createOrUpdateLabel(vLabels, i, bar_index[xValue], yValueV, switchshape(priceshape), VlblColor, '')
if disp == 'Columns'
createOrUpdateBox(pBoxes, i, bar_index[xValue], yValueP, bar_index[xValue] -2, 0, PlblColor)
createOrUpdateLabel(nLabels, i, bar_index[xValue], -4.3, label.style_label_up, color.rgb(54, 58, 69, 100), debugtitle ? txt : txt1)
createOrUpdateBox(vBoxes, i, bar_index[xValue] + 2, yValueV, bar_index[xValue], 0, VlblColor)
if disp == 'Delta Columns'
createOrUpdateBox(pBoxes, i, bar_index[xValue] - 2, yValueP - yValueV, bar_index[xValue] + 2, 0, PlblColor)
createOrUpdateLabel(nLabels, i, bar_index[xValue], -4.3, label.style_label_up, color.rgb(54, 58, 69, 100), debugtitle ? txt : txt1)
if disp == 'Scatter Plot'
cond = lblplotscond == 'Outliers' ? (yValueV > outlierstd or yValueV < -outlierstd) or (yValueP > outlierstd or yValueP < -outlierstd) : lblplotscond == 'All' ? true : false
createOrUpdateLabel(sLabels, i, f_magic(yValueP), yValueV, switchshape(priceshape), VlblColor, cond ? (debugtitle ? txt : txt1) : '')
mainsty = line.style_solid
quadsty = line.style_dotted
// Creating chart grid and lines
hlines = array.new_line()
vlines = array.new_line()
var s = disp == 'Scatter Plot' ? 80 : 200
var b = disp == 'Scatter Plot' ? 0 : 2
var line[] horzLines = na
if (na(horzLines)) and disp!='Z-Price Heatmap' and disp!='Z-Volume Heatmap' and disp!='Z-Delta Heatmap'
horzLines := array.new_line(9)
array.set(horzLines, 0, line.new(bar_index[s], 0, bar_index + b, 0, color = disp == 'Scatter Plot' ? gridcol : gridcol2))
array.set(horzLines, 1, line.new(bar_index[s], -4, bar_index + b, -4, color = disp == 'Scatter Plot' ? gridcol2 : gridcol))
array.set(horzLines, 2, line.new(bar_index[s], 1, bar_index + b, 1, color = gridcol))
array.set(horzLines, 3, line.new(bar_index[s], 2, bar_index + b, 2, color = gridcol))
array.set(horzLines, 4, line.new(bar_index[s], 3, bar_index + b, 3, color = gridcol))
array.set(horzLines, 5, line.new(bar_index[s], 4, bar_index + b, 4, color = gridcol))
array.set(horzLines, 6, line.new(bar_index[s], -1, bar_index + b, -1, color = gridcol))
array.set(horzLines, 7, line.new(bar_index[s], -2, bar_index + b, -2, color = gridcol))
array.set(horzLines, 8, line.new(bar_index[s], -3, bar_index + b, -3, color = gridcol))
if (barstate.islast) and disp!='Z-Price Heatmap' and disp!='Z-Volume Heatmap' and disp!='Z-Delta Heatmap'
for i = 0 to array.size(horzLines) - 1
line.set_x2(array.get(horzLines, i), bar_index + b)
line.set_x1(array.get(horzLines, i), bar_index[s])
var line[] vertLines = na
var label[] hlaLabels = na
if (na(vertLines)) and disp=='Scatter Plot'
vertLines := array.new_line(9)
hlaLabels := array.new_label(9)
array.set(vertLines, 0, line.new(bar_index[s], 4, bar_index[s], -4, color = color.rgb(120, 123, 134, 44)))
array.set(hlaLabels, 0, label.new(bar_index[s], -4.3, text = '-4', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 1, line.new(bar_index[s - 10], 4, bar_index[s - 10], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 1, label.new(bar_index[s - 10], -4.3, text = '-3', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 2, line.new(bar_index[s - 20], 4, bar_index[s - 20], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 2, label.new(bar_index[s - 20], -4.3, text = '-2', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 3, line.new(bar_index[s - 30], 4, bar_index[s - 30], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 3, label.new(bar_index[s - 30], -4.3, text = '-1', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 4, line.new(bar_index[s - 40], 4, bar_index[s - 40], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 4, label.new(bar_index[s - 40], -4.3, text = '0', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 5, line.new(bar_index[s - 50], 4, bar_index[s - 50], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 5, label.new(bar_index[s - 50], -4.3, text = '1', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 6, line.new(bar_index[s - 60], 4, bar_index[s - 60], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 6, label.new(bar_index[s - 60], -4.3, text = '2', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 7, line.new(bar_index[s - 70], 4, bar_index[s - 70], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 7, label.new(bar_index[s - 70], -4.3, text = '3', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
array.set(vertLines, 8, line.new(bar_index[s - 80], 4, bar_index[s - 80], -4, style = mainsty, color = gridcol))
array.set(hlaLabels, 8, label.new(bar_index[s - 80], -4.3, text = '4', textcolor = color.gray, style = label.style_label_up, color = na, size = size.tiny))
if (barstate.islast) and disp=='Scatter Plot'
for i = 0 to 8
line.set_x1(array.get(vertLines, i), bar_index[s - i * 10])
line.set_x2(array.get(vertLines, i), bar_index[s - i * 10])
label.set_x(array.get(hlaLabels, i), bar_index[s - i * 10])
if showquadr and disp == 'Scatter Plot'
q1 = box.new(f_magic(-quadr), quadr, f_magic(quadr), -quadr, quadrcol, border_style = quadsty, bgcolor = quadrbgcol, text = str.tostring(quadr) + 'σ', text_valign = text.align_top, text_size = size.normal, text_color = color.rgb(120, 123, 134, 40))
box.delete(q1[1])
if showquadr1 and disp == 'Scatter Plot'
q1 = box.new(f_magic(-quadr1), quadr1, f_magic(quadr1), -quadr1, quadrcol1, border_style = quadsty, bgcolor = quadrbgcol1, text = str.tostring(quadr1) + 'σ', text_valign = text.align_top, text_size = size.normal, text_color = color.rgb(120, 123, 134, 40))
box.delete(q1[1])
if showquadr2 and disp == 'Scatter Plot'
q1 = box.new(f_magic(-quadr2), quadr2, f_magic(quadr2), -quadr2, quadrcol2, border_style = quadsty, bgcolor = quadrbgcol2, text = str.tostring(quadr2) + 'σ', text_valign = text.align_top, text_size = size.normal, text_color = color.rgb(120, 123, 134, 40))
box.delete(q1[1])
// Grid labels
offset = 0.04
var label[] valueLabels = na
var label[] guideLabels = na
var label[] guideLabels2 = na
if (na(valueLabels)) and disp!='Z-Price Heatmap' and disp!='Z-Volume Heatmap' and disp!='Z-Delta Heatmap'
valueLabels := array.new_label(10)
array.set(valueLabels, 0, label.new(bar_index[s], 0 - offset, text = '0 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 1, label.new(bar_index[s], 1 - offset, text = '1 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 2, label.new(bar_index[s], 2 - offset, text = '2 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 3, label.new(bar_index[s], 3 - offset, text = '3 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 4, label.new(bar_index[s], 4 - offset, text = '4 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 5, label.new(bar_index[s], -1 - offset, text = '-1 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 6, label.new(bar_index[s], -2 - offset, text = '-2 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 7, label.new(bar_index[s], -3 - offset, text = '-3 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
array.set(valueLabels, 8, label.new(bar_index[s], -4 - offset, text = '-4 ', textcolor = color.gray, style = label.style_label_right, color = na, size = size.tiny))
if (barstate.islast) and disp!='Z-Price Heatmap' and disp!='Z-Volume Heatmap' and disp!='Z-Delta Heatmap'
for i = 0 to 9
label.set_x(array.get(valueLabels, i), bar_index[s])
if helperlab and (na(guideLabels)) and (na(guideLabels)) and disp=='Scatter Plot'
guideLabels := array.new_label(2)
guideLabels2 := array.new_label(2)
array.set(guideLabels, 0, label.new(bar_index[s +4], -4.5 - offset, text = 'Low Price - Low Volume', textcolor = color.gray, style = label.style_label_right, color = #787b8624, size = size.small))
array.set(guideLabels, 1, label.new(bar_index[s +4], 4.5 - offset, text = 'Low Price - High Volume', textcolor = color.gray, style = label.style_label_right, color = #787b8624, size = size.small))
array.set(guideLabels2, 0, label.new(bar_index + 4, -4.5 - offset, text = 'High Price - Low Volume', textcolor = color.gray, style = label.style_label_left, color = #787b8624, size = size.small))
array.set(guideLabels2, 1, label.new(bar_index + 4, 4.5 - offset, text = 'High Price - High Volume', textcolor = color.gray, style = label.style_label_left, color = #787b8624, size = size.small))
if helperlab and barstate.islast and disp=='Scatter Plot'
for i = 0 to 1
label.set_x(array.get(guideLabels, i), bar_index[s + 4])
for i = 0 to 1
label.set_x(array.get(guideLabels2, i), bar_index + 4)
// Creating the title
table1 = table.new(position.top_center, 5,5)
if showtitle
table.cell(table1, 0, 0, 'Price x Volume Z-Score: ' + str.tostring(disp), text_size = size.normal, text_color = color.gray)
table.cell(table1, 0, 1, '• Period: ' + str.tostring(zlen) + ' ' + '• Timeframe: ' + str.tostring(tf=='' ? (timeframe.period + (timeframe.isminutes ? 'm' : '')) : tf) + ' • Data: ' + str.tostring(ztype), text_size = size.tiny, text_color = color.gray)
// Creating heatmap grid
f_vertoffs(n) =>
hmpos=='1' ? n : hmpos=='2' ? -n : hmpos=='3' ? (-1*n - n) : hmpos=='4' ? (-2*n - n) : (-3*n - n)
h0 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(40) : na, display = display.none, linewidth = 0, editable = false)
h1 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(39) : na, display = display.none, linewidth = 0, editable = false)
h2 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(38) : na, display = display.none, linewidth = 0, editable = false)
h3 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(37) : na, display = display.none, linewidth = 0, editable = false)
h4 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(36) : na, display = display.none, linewidth = 0, editable = false)
h5 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(35) : na, display = display.none, linewidth = 0, editable = false)
h6 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(34) : na, display = display.none, linewidth = 0, editable = false)
h7 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(33) : na, display = display.none, linewidth = 0, editable = false)
h8 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(32) : na, display = display.none, linewidth = 0, editable = false)
h9 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(31) : na, display = display.none, linewidth = 0, editable = false)
h10 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(30) : na, display = display.none, linewidth = 0, editable = false)
h11 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(29) : na, display = display.none, linewidth = 0, editable = false)
h12 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(28) : na, display = display.none, linewidth = 0, editable = false)
h13 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(27) : na, display = display.none, linewidth = 0, editable = false)
h14 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(26) : na, display = display.none, linewidth = 0, editable = false)
h15 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(25) : na, display = display.none, linewidth = 0, editable = false)
h16 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(24) : na, display = display.none, linewidth = 0, editable = false)
h17 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(23) : na, display = display.none, linewidth = 0, editable = false)
h18 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(22) : na, display = display.none, linewidth = 0, editable = false)
h19 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(21) : na, display = display.none, linewidth = 0, editable = false)
h20 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(20) : na, display = display.none, linewidth = 0, editable = false)
h21 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(19) : na, display = display.none, linewidth = 0, editable = false)
h22 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(18) : na, display = display.none, linewidth = 0, editable = false)
h23 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(17) : na, display = display.none, linewidth = 0, editable = false)
h24 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(16) : na, display = display.none, linewidth = 0, editable = false)
h25 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(15) : na, display = display.none, linewidth = 0, editable = false)
h26 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(14) : na, display = display.none, linewidth = 0, editable = false)
h27 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(13) : na, display = display.none, linewidth = 0, editable = false)
h28 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(12) : na, display = display.none, linewidth = 0, editable = false)
h29 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(11) : na, display = display.none, linewidth = 0, editable = false)
h30 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(10) : na, display = display.none, linewidth = 0, editable = false)
h31 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(9 ) : na, display = display.none, linewidth = 0, editable = false)
h32 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(8 ) : na, display = display.none, linewidth = 0, editable = false)
h33 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(7 ) : na, display = display.none, linewidth = 0, editable = false)
h34 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(6 ) : na, display = display.none, linewidth = 0, editable = false)
h35 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(5 ) : na, display = display.none, linewidth = 0, editable = false)
h36 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(4 ) : na, display = display.none, linewidth = 0, editable = false)
h37 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(3 ) : na, display = display.none, linewidth = 0, editable = false)
h38 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(2 ) : na, display = display.none, linewidth = 0, editable = false)
h39 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(1 ) : na, display = display.none, linewidth = 0, editable = false)
h40 = hline(disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? f_vertoffs(0 ) : na, display = display.none, linewidth = 0, editable = false)
// Function for calculating heatmap color-coding
f_hmcol(P, V) =>
Px = disp=='Z-Price Heatmap' ? (ztype=='Relative Z-Score' ? relativeZscorePrice(P) : P) : disp=='Z-Volume Heatmap' ? (ztype=='Relative Z-Score' ? relativeZscoreVolume(V) : V) : (ztype=='Relative Z-Score' ? (relativeZscorePrice(P) - relativeZscoreVolume(V)) : (P - V))
hot = color.from_gradient(Px, 0, 2, colh3, colh2)
vhot = color.from_gradient(Px, 2, 4, colh2, colh1)
cold = color.from_gradient(Px, -2, 0, colc2, colc3)
vcold = color.from_gradient(Px, -4, -2, colc1, colc2)
out1 = Px == 0 ? colc3 : Px>0 and Px<2 ? hot : Px>2 ? vhot : Px<0 and Px>-2 ? cold : Px<-2 ? vcold : chart.bg_color
out2 = color.from_gradient(Px, -4, 4, colcc, colhh)
out = hmcoltype=='Two-Color' ? out2 : out1
// Filling the grid with color-coded colors
fill(h0, h1, f_hmcol(P1 , V1 ))
fill(h1, h2, f_hmcol(P2 , V2 ))
fill(h2, h3, f_hmcol(P3 , V3 ))
fill(h3, h4, f_hmcol(P4 , V4 ))
fill(h4, h5, f_hmcol(P5 , V5 ))
fill(h5, h6, f_hmcol(P6 , V6 ))
fill(h6, h7, f_hmcol(P7 , V7 ))
fill(h7, h8, f_hmcol(P8 , V8 ))
fill(h8, h9, f_hmcol(P9 , V9 ))
fill(h9, h10, f_hmcol(P10, V10))
fill(h10, h11, f_hmcol(P11, V11))
fill(h11, h12, f_hmcol(P12, V12))
fill(h12, h13, f_hmcol(P13, V13))
fill(h13, h14, f_hmcol(P14, V14))
fill(h14, h15, f_hmcol(P15, V15))
fill(h15, h16, f_hmcol(P16, V16))
fill(h16, h17, f_hmcol(P17, V17))
fill(h17, h18, f_hmcol(P18, V18))
fill(h18, h19, f_hmcol(P19, V19))
fill(h19, h20, f_hmcol(P20, V20))
fill(h20, h21, f_hmcol(P21, V21))
fill(h21, h22, f_hmcol(P22, V22))
fill(h22, h23, f_hmcol(P23, V23))
fill(h23, h24, f_hmcol(P24, V24))
fill(h24, h25, f_hmcol(P25, V25))
fill(h25, h26, f_hmcol(P26, V26))
fill(h26, h27, f_hmcol(P27, V27))
fill(h27, h28, f_hmcol(P28, V28))
fill(h28, h29, f_hmcol(P29, V29))
fill(h29, h30, f_hmcol(P30, V30))
fill(h30, h31, f_hmcol(P31, V31))
fill(h31, h32, f_hmcol(P32, V32))
fill(h32, h33, f_hmcol(P33, V33))
fill(h33, h34, f_hmcol(P34, V34))
fill(h34, h35, f_hmcol(P35, V35))
fill(h35, h36, f_hmcol(P36, V36))
fill(h36, h37, f_hmcol(P37, V37))
fill(h37, h38, f_hmcol(P38, V38))
fill(h38, h39, f_hmcol(P39, V39))
fill(h39, h40, f_hmcol(P40, V40))
// Creating heatmap symbol labels
var label[] tickerLabels = na
if disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap'
if (na(tickerLabels))
tickerLabels := array.new_label(40)
for i = 0 to 39
y_position = 39.5 - i
y_position := f_vertoffs(y_position)
txt = str.tostring(array.get(ticker_names, i))
txt1 = array.get(str.split(txt, 'USD'), 0)
array.set(tickerLabels, i, label.new(bar_index + 1, y_position - offset * 1, text = debugtitle ? txt : txt1, xloc = xloc.bar_index, style = label.style_label_left, color = color.rgb(255, 235, 59, 100), textcolor = color.gray, size = size.small, textalign = text.align_left))
else
for i = 0 to 39
lbl = array.get(tickerLabels, i)
label.set_x(lbl, bar_index + 1)
// Scaling anchor
scaleanchorup = disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? na : 5.3
scaleanchordown = disp=='Z-Price Heatmap' or disp=='Z-Volume Heatmap' or disp=='Z-Delta Heatmap' ? na : -5.3
plot(scaleanchorup, display = display.pane, color = na, editable = false)
plot(scaleanchordown, display = display.pane, color = na, editable = false)
|
RSI Radar Multi Time Frame | https://www.tradingview.com/script/8UtWhfo3-RSI-Radar-Multi-Time-Frame/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 348 | 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/
// © LonesomeTheBlue
get_rsi(rsiarr, rsih)=>
float rsix = na
if not na(rsiarr)
if array.size(rsiarr) > 0
rsix := array.get(rsiarr, array.size(rsiarr) - 1)
rsix := not na(rsix) ? rsix : rsih
get_time_string(T)=>
ret = T == "" ? timeframe.period : T
//@version=5
indicator("RSI Radar Multi Time Frame", overlay=true)
T1 = input.timeframe(defval = "")
T2 = input.timeframe(defval = "1")
T3 = input.timeframe(defval = "15")
T4 = input.timeframe(defval = "60")
T5 = input.timeframe(defval = "240")
T6 = input.timeframe(defval = "1D")
Rsicolor = input.color(defval = color.blue, title = "RSI line", inline = "rsi")
Rsiwidth = input.int(defval = 3, title = "", minval = 1, maxval = 10, inline = "rsi")
curved = input.bool(true, title = "Curved", inline = "rsi")
obcolor = input.color(defval = color.rgb(255, 0, 0, 65), title = "OB/OS Colors", inline = "colors")
oscolor = input.color(defval = color.rgb(0, 255, 0, 65), title = "", inline = "colors")
rsilabels = input.bool(true, title = "Labels")
circle = input.bool(true, title = "Circles")
var times = array.new_int(0)
if barstate.isnew or barstate.islastconfirmedhistory
array.push(times, time)
// we need to use bar index because for non 7/24 markets polyline shape may be corrupted
leftbarindex = array.indexof(times, chart.left_visible_bar_time)
rightbarindex = array.indexof(times, chart.right_visible_bar_time)
if rightbarindex == -1
rightbarindex := array.size(times) - 1
visibletime = rightbarindex - leftbarindex
timestep = math.round(visibletime / 100)
mid = (ta.highest(300) + ta.lowest(300)) / 2
diff = ta.highest(300) - ta.lowest(300)
len = diff / 3
mult = 1.1
xpoints = array.new_int(14)
ypoints = array.new_float(14)
array.set(xpoints, 0, leftbarindex + timestep * 46)
array.set(ypoints, 0, mid + len * mult)
array.set(xpoints, 1, leftbarindex + timestep * 54)
array.set(ypoints, 1, mid)
array.set(xpoints, 2, leftbarindex + timestep * 46)
array.set(ypoints, 2, mid - len * mult)
array.set(xpoints, 3, leftbarindex + timestep * 30)
array.set(ypoints, 3, mid - len * mult)
array.set(xpoints, 4, leftbarindex + timestep * 22)
array.set(ypoints, 4, mid)
array.set(xpoints, 5, leftbarindex + timestep * 30)
array.set(ypoints, 5, mid + len * mult)
midpx = leftbarindex + timestep * 38
midpy = mid
pointx = array.new_int(0)
pointy = array.new_float(0)
RsiArray = array.new_float(0)
osx = array.new_int(0)
osy = array.new_float(0)
min1arr = request.security_lower_tf(syminfo.tickerid, T1, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 = request.security(syminfo.tickerid, T1, ta.rsi(close, 14))
min1rsi = get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx + math.round(min1rsi * (array.get(xpoints, 1) - midpx) / 200))
array.push(pointy, midpy + min1rsi * (array.get(ypoints, 0) - midpy) / 100)
array.push(osx, midpx + math.round(30 * (array.get(xpoints, 1) - midpx) / 200))
array.push(osy, midpy + 30 * (array.get(ypoints, 0) - midpy) / 100)
array.push(RsiArray, min1rsi)
array.set(xpoints, 11, midpx + math.round(70 * (array.get(xpoints, 1) - midpx) / 200))
array.set(ypoints, 11, midpy + 70 * (array.get(ypoints, 0) - midpy) / 100)
min1arr := request.security_lower_tf(syminfo.tickerid, T2, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 := request.security(syminfo.tickerid, T2, ta.rsi(close, 14))
min1rsi := get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx + math.round(min1rsi * (array.get(xpoints, 1) - midpx) / 100))
array.push(pointy, midpy)
array.push(osx, midpx + math.round(30 * (array.get(xpoints, 1) - midpx) / 100))
array.push(osy, midpy)
array.push(RsiArray, min1rsi)
array.set(xpoints, 10, midpx + math.round(70 * (array.get(xpoints, 1) - midpx) / 100))
array.set(ypoints, 10, midpy)
min1arr := request.security_lower_tf(syminfo.tickerid, T3, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 := request.security(syminfo.tickerid, T3, ta.rsi(close, 14))
min1rsi := get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx + math.round(min1rsi * (array.get(xpoints, 2) - midpx) / 100))
array.push(pointy, midpy - min1rsi * (midpy - array.get(ypoints, 2)) / 100)
array.push(osx, midpx + math.round(30 * (array.get(xpoints, 2) - midpx) / 100))
array.push(osy, midpy - 30 * (midpy - array.get(ypoints, 2)) / 100)
array.push(RsiArray, min1rsi)
array.set(xpoints, 9, midpx + math.round(70 * (array.get(xpoints, 2) - midpx) / 100))
array.set(ypoints, 9, midpy - 70 * (midpy - array.get(ypoints, 2)) / 100)
min1arr := request.security_lower_tf(syminfo.tickerid, T4, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 := request.security(syminfo.tickerid, T4, ta.rsi(close, 14))
min1rsi := get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx - math.round(min1rsi * (midpx - array.get(xpoints, 3)) / 100))
array.push(pointy, midpy - min1rsi * (midpy - array.get(ypoints, 3)) / 100)
array.push(osx, midpx - math.round(30 * (midpx - array.get(xpoints, 3)) / 100))
array.push(osy, midpy - 30 * (midpy - array.get(ypoints, 3)) / 100)
array.push(RsiArray, min1rsi)
array.set(xpoints, 8, midpx - math.round(70 * (midpx - array.get(xpoints, 3)) / 100))
array.set(ypoints, 8, midpy - 70 * (midpy - array.get(ypoints, 3)) / 100)
min1arr := request.security_lower_tf(syminfo.tickerid, T5, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 := request.security(syminfo.tickerid, T5, ta.rsi(close, 14))
min1rsi := get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx - math.round(min1rsi * (midpx - array.get(xpoints, 4)) / 100))
array.push(pointy, midpy)
array.push(osx, midpx - math.round(30 * (midpx - array.get(xpoints, 4)) / 100))
array.push(osy, midpy)
array.push(RsiArray, min1rsi)
array.set(xpoints, 7, midpx - math.round(70 * (midpx - array.get(xpoints, 4)) / 100))
array.set(ypoints, 7, midpy)
min1arr := request.security_lower_tf(syminfo.tickerid, T6, ta.rsi(close, 14), ignore_invalid_timeframe = true)
min1rsi_2 := request.security(syminfo.tickerid, T6, ta.rsi(close, 14))
min1rsi := get_rsi(min1arr, min1rsi_2)
array.push(pointx, midpx - math.round(min1rsi * (midpx - array.get(xpoints, 5)) / 100))
array.push(pointy, midpy + min1rsi * (array.get(ypoints, 5) - midpy) / 100)
array.push(osx, midpx - math.round(30 * (midpx - array.get(xpoints, 5)) / 100))
array.push(osy, midpy + 30 * (array.get(ypoints, 5) - midpy) / 100)
array.push(RsiArray, min1rsi)
array.set(xpoints, 6, midpx - math.round(70 * (midpx - array.get(xpoints, 5)) / 100))
array.set(ypoints, 6, midpy + 70 * (array.get(ypoints, 5) - midpy) / 100)
array.set(xpoints, 12, array.get(xpoints, 6))
array.set(ypoints, 12, array.get(ypoints, 6))
array.set(xpoints, 13, array.get(xpoints, 5))
array.set(ypoints, 13, array.get(ypoints, 5))
get_text(T, rsival)=>
ret = "Res: " + get_time_string(T) + '\nRSI: ' + str.tostring(rsival, '#.##')
get_color(rsival)=>
backgr = rsival < 30 ? color.green : rsival > 70 ? color.red : color.black
txt = rsival < 30 ? color.black : rsival > 70 ? color.white : color.white
array.from(backgr, txt)
get_all_colors(rsiarray)=>
colors = matrix.new<color>()
for x = 0 to 5
matrix.add_row(colors, x, get_color(array.get(rsiarray, x)))
colors
if barstate.islast
mainpoints = array.new<chart.point>()
for x = 0 to 13
mainpoints.push(chart.point.from_index(array.get(xpoints, x), array.get(ypoints, x)))
points30 = array.new<chart.point>()
for x = 0 to 5
points30.push(chart.point.from_index(array.get(osx, x), array.get(osy, x)))
var polyline plnos = na
polyline.delete(plnos)
plnos := polyline.new(points30, curved = false, closed = true, fill_color = oscolor, line_style = line.style_dotted)
var polyline plnm = na
polyline.delete(plnm)
plnm := polyline.new(mainpoints, curved = false, closed = true, fill_color = obcolor)
colors = get_all_colors(RsiArray)
if rsilabels
labels = array.new_label(0)
for x = 1 to (array.size(labels) > 0 ? array.size(labels) : na)
label.delete(array.pop(labels))
var styles = array.from(label.style_label_lower_left, label.style_label_left, label.style_label_upper_left, label.style_label_upper_right, label.style_label_right, label.style_label_lower_right)
var TFs = array.from(T1, T2, T3, T4, T5, T6)
for x = 0 to 5
array.push(labels, label.new(array.get(xpoints, x), array.get(ypoints, x), text = get_text(array.get(TFs, x), array.get(RsiArray, x)), color = matrix.get(colors, x, 0) , textcolor = matrix.get(colors, x, 1), style = array.get(styles, x)))
var centerlines = array.new_line(0)
for x = 1 to (array.size(centerlines) > 0 ? array.size(centerlines) : na)
line.delete(array.pop(centerlines))
array.push(centerlines, line.new(x1 = array.get(xpoints, 0), y1 = array.get(ypoints, 0), x2 = array.get(xpoints, 3), y2 = array.get(ypoints, 3)))
array.push(centerlines, line.new(x1 = array.get(xpoints, 1), y1 = array.get(ypoints, 1), x2 = array.get(xpoints, 4), y2 = array.get(ypoints, 4)))
array.push(centerlines, line.new(x1 = array.get(xpoints, 2), y1 = array.get(ypoints, 2), x2 = array.get(xpoints, 5), y2 = array.get(ypoints, 5)))
points = array.new<chart.point>()
for x = 0 to 5
points.push(chart.point.from_index(array.get(pointx, x), array.get(pointy, x)))
var polyline pln = na
polyline.delete(pln)
pln := polyline.new(points, curved = curved, closed = true, line_color = Rsicolor, line_width = Rsiwidth)
if circle
var circles = array.new_label(0)
for x = 1 to (array.size(circles) > 0 ? array.size(circles) : na)
label.delete(array.pop(circles))
for x = 0 to 5
array.push(circles, label.new(array.get(pointx, x), array.get(pointy, x), style = label.style_circle, size = size.tiny, color = matrix.get(colors, x, 0)))
|
Smart Money Breakouts [ChartPrime] | https://www.tradingview.com/script/aM3PRWEM-Smart-Money-Breakouts-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 2,102 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime
//@version=5
indicator("Smart Money Breakouts [ChartPrime]", overlay=true, max_labels_count=500, max_lines_count=500)
color GREEN = color.rgb(2, 133, 69)
color TAIL = color.rgb(20, 141, 154)
color RED = color.rgb(246, 7, 7)
color _Green = color.rgb(2, 106, 89)
color OFF = color.new(color.red,100)
string DYNAMICSLG = "➞ Risk To Reward Settings 🔸"
string CORE = "➞ Core Settings 🔸"
var array<int> score = array.new_int(2,0)
//
var float UpdatedHigh = na
var float UpdatedLow = na
var bool ShortTrade = false
var bool TradeisON = false
var bool LongTrade = false
var int HighIndex = na
var bool phActive = false
var bool plActive = false
var int LowIndex = na
var bool HBreak = false
var line tpLine = na
var line SLLine = na
var label LAB = na
var float TP = 0.0
var float SL = 0.0
int Sync = bar_index
bool BUY = false
bool SELL = false
type Vol
array<float> Total
array<float> Green
array<float> Red
array<float> SCR
Volume = Vol.new(
array.new_float(),
array.new_float(),
array.new_float(),
array.new_float()
)
int period = input.int(20, 'Length',group = CORE,tooltip = "Swing Length")
bool CandleType = input.string(title = "Type ➞",
defval='Wicks',
options=['Wicks', 'Body'],
group = CORE,
tooltip = "Calculation Price : Wicks or Body of the candle")
== 'Wicks'
float RR1 = input.float(1.1,"RR Ratio",step = 0.1 , tooltip = "Risk to reward Ratio",group = CORE)
bool SLType = input.string('Close',
'SL Type', ['Close', 'High/Low'], group=CORE,tooltip = "Activate SL on candle close or high/low") == 'Close'
bool ShowSL = input.bool(false,"Show SL",group = CORE)
string Linestyle = input.string('Dashed',
'Line Style', ['Solid', 'Dashed', 'Dotted'], group=CORE,inline= "Line")
color Bull = input.color(GREEN,"",group=CORE,inline= "Line")
color Bear = input.color(RED,"",group=CORE,inline= "Line")
//----- { SL Calculation
// -- ATR
x2 = low - ta.rma(ta.tr(true), 14) * 1.5
xz = ta.rma(ta.tr(true), 14) * 1.5 + high
longDiffSL2 = math.abs(close - xz)
longDiffSL = math.abs(close - x2)
// }
StyleSwitch = switch Linestyle
'Dashed' => line.style_dashed ,
'Dotted' => line.style_dotted ,
=> line.style_solid
method volAdj(int len)=>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) [20] /2
Adj = volAdj(30)
VolCal(Index,Sync) =>
Bars = math.abs(Index - Sync)
for i = 0 to Bars -1
Volume.SCR.push(close[i])
for i = 0 to Volume.SCR.size() -1
if Volume.SCR.get(i) > open[i]
Volume.Green.push(volume[i])
if Volume.SCR.get(i) < open[i]
Volume.Red.push(volume[i])
Volume.Total.push(volume[i])
GreenRatio = math.round(Volume.Green.sum() / Volume.Total.sum()* 100,2)
RedRatio = math.round(Volume.Red.sum() / Volume.Total.sum()* 100,2)
Out = GreenRatio > 55 ? "🟢" : RedRatio > 55 ? "🔴" : "🟡"
Out
PH = ta.pivothigh(high, period, period)
PL = ta.pivotlow(low, period, period)
ScrHigh = CandleType ? high : close
ScrLow = CandleType ? low : close
if ta.change(fixnan(PH)) != 0
UpdatedHigh := PH
phActive := true
HighIndex := Sync - period
if ta.change(fixnan(PL)) != 0
UpdatedLow := PL
plActive := true
LowIndex := Sync - period
// LONG
if ScrHigh > UpdatedHigh and phActive
BUY := true
phActive := false
//Sell
if ScrLow < UpdatedLow and plActive
SELL := true
plActive := false
// lets Draw
if BUY and not TradeisON
sign = VolCal(HighIndex,Sync)
line.new(HighIndex,
UpdatedHigh,
Sync,
UpdatedHigh,
color=Bull,
style=StyleSwitch,
width=2)
label.new(math.floor(Sync - (Sync - HighIndex) / 2),
UpdatedHigh,
not HBreak ? 'CHoCH\n' + sign : 'BOS\n' + sign,
color=OFF,
textcolor=color.white,
size=size.tiny)
label.new(Sync,
low,
"",
yloc = yloc.belowbar,
color = color.lime,
size = size.small,
style = label.style_label_up)
HBreak := true
if SELL and not TradeisON
sign = VolCal(LowIndex,Sync)
line.new(LowIndex,
UpdatedLow,
Sync,
UpdatedLow,
color=Bear,
style=StyleSwitch,
width=2)
label.new(math.floor(Sync - (Sync - LowIndex) / 2),
UpdatedLow,
HBreak ? 'CHoCH\n' + sign : 'BOS\n' + sign,
color=OFF,
textcolor=color.white,
style=label.style_label_up,
size=size.tiny)
label.new(Sync,
low,
"",
yloc = yloc.abovebar,
color =RED,
size = size.small,
style = label.style_label_down)
HBreak := false
Long = BUY and not TradeisON
Short = SELL and not TradeisON
TradeFire = Long or Short
if Long and not TradeisON
LongTrade:= true
ShortTrade:= false
if Short and not TradeisON
LongTrade:= false
ShortTrade:= true
if true
if TradeFire and not TradeisON
TP := switch
Long => close + (RR1 * longDiffSL)
Short => close - (RR1 * longDiffSL2)
SL := switch
Long => close - longDiffSL
Short => close + longDiffSL2
TradeisON:= true
if true
line.new(bar_index,
Long ? high : low,
bar_index,
TP,
width=2,
color = TAIL,
style= line.style_dashed)
tpLine:= line.new(bar_index,
TP,
bar_index+2,
TP,
style= line.style_dashed,
color = TAIL
)
if ShowSL
SLLine:= line.new(bar_index,
SL,
bar_index+2,
SL,
style= line.style_dashed,
color = RED
)
LAB:=label.new(bar_index,
TP,
"Target",
color = TAIL,
style= label.style_label_left,
size=size.small,
textcolor = color.white
)
if TradeisON
line.set_x2(tpLine,bar_index)
label.set_x(LAB,bar_index+1)
if ShowSL
line.set_x2(SLLine,bar_index)
if LongTrade and TradeisON
if high >= TP
label.set_color(LAB,GREEN)
score.set(0,score.get(0)+1)
TradeisON:=false
if (SLType ? close : low) <= SL
score.set(1,score.get(1)+1)
label.set_color(LAB,color.new(RED,70))
label.set_tooltip(LAB,"Stoploss Hit : "+ str.tostring(math.round_to_mintick(SL)))
TradeisON:=false
else if ShortTrade and TradeisON
if low <= TP
label.set_color(LAB,GREEN)
score.set(0,score.get(0)+1)
TradeisON:=false
if (SLType ? close : high) >= SL
score.set(1,score.get(1)+1)
label.set_color(LAB,color.new(RED,70))
label.set_tooltip(LAB,"Stoploss Hit : "+ str.tostring(math.round_to_mintick(SL)))
TradeisON:=false
BearCon = TradeisON and ShortTrade
BullCon = TradeisON and LongTrade
barcolor(BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54) )
plotcandle(open, high, low, close, color = BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54),
wickcolor = color.rgb(103, 99, 99),bordercolor = BearCon ? RED : BullCon ? _Green : color.rgb(52, 52, 54))
bgcolor(BearCon ? color.rgb(136, 4, 15, 90) : BullCon ? color.rgb(8, 191, 158,90) : na )
// where is my table ?!
var tb = table.new(position.top_right, 3, 3,
bgcolor= color.new(color.gray,80))
if barstate.islast
table.cell(tb, 0, 0, "Winning Trades"
, text_color = #a3a3b1)
table.cell(tb, 1, 0, str.tostring(score.get(0))
, text_color = #08c09b)
table.cell(tb, 0, 1, "Losing Trades"
, text_color = #a3a3b1)
table.cell(tb, 1, 1, str.tostring(score.get(1))
, text_color = #cd0202)
alertcondition(Long,"BUY")
alertcondition(Short,"Sell") |
ICT HTF Candles [Source Code] (fadi) | https://www.tradingview.com/script/0KTDWTdN-ICT-HTF-Candles-Source-Code-fadi/ | fadizeidan | https://www.tradingview.com/u/fadizeidan/ | 134 | 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/
// © fadizeidan
// Last Published: 503
//@version=5
indicator("ICT HTF Candles (fadi)", overlay=true, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 5000)
type Candle
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
box body
line wick_up
line wick_down
type Trace
line o
line c
line h
line l
label o_l
label c_l
label h_l
label l_l
type Imbalance
box b
int idx
type Settings
bool htf_1_show
bool htf_2_show
bool htf_3_show
bool htf_4_show
bool htf_5_show
bool htf_6_show
string htf_1
string htf_2
string htf_3
string htf_4
string htf_5
string htf_6
int max_candles_1
int max_candles_2
int max_candles_3
int max_candles_4
int max_candles_5
int max_candles_6
color bull_body
color bull_border
color bull_wick
color bear_body
color bear_border
color bear_wick
int offset
int buffer
int htf_buffer
int width
bool trace_show
bool trace_1_show
bool trace_2_show
bool trace_3_show
bool trace_4_show
bool trace_5_show
bool trace_6_show
color trace_o_color
string trace_o_style
int trace_o_size
color trace_c_color
string trace_c_style
int trace_c_size
color trace_h_color
string trace_h_style
int trace_h_size
color trace_l_color
string trace_l_style
int trace_l_size
bool label_show
bool label_1_show
bool label_2_show
bool label_3_show
bool label_4_show
bool label_5_show
bool label_6_show
color label_color
string label_size
bool fvg_show
color fvg_color
bool vi_show
color vi_color
bool htf_label_show
color htf_label_color
string htf_label_size
Settings settings = Settings.new()
settings.htf_1_show := input.bool(true, "HTF 1", inline="htf1")
htf_1 = input.timeframe("5", "", inline="htf1")
settings.htf_1 := htf_1
settings.max_candles_1 := input.int(10, "", inline="htf1")
settings.htf_2_show := input.bool(true, "HTF 2", inline="htf2")
htf_2 = input.timeframe("15", "", inline="htf2")
settings.htf_2 := htf_2
settings.max_candles_2 := input.int(10, "", inline="htf2")
settings.htf_3_show := input.bool(true, "HTF 3", inline="htf3")
htf_3 = input.timeframe("60", "", inline="htf3")
settings.htf_3 := htf_3
settings.max_candles_3 := input.int(10, "", inline="htf3")
settings.htf_4_show := input.bool(true, "HTF 4", inline="htf4")
htf_4 = input.timeframe("240", "", inline="htf4")
settings.htf_4 := htf_4
settings.max_candles_4 := input.int(4, "", inline="htf4")
settings.htf_5_show := input.bool(true, "HTF 5", inline="htf5")
htf_5 = input.timeframe("1D", "", inline="htf5")
settings.htf_5 := htf_5
settings.max_candles_5 := input.int(2, "", inline="htf5")
settings.htf_6_show := input.bool(true, "HTF 6", inline="htf6")
htf_6 = input.timeframe("1W", "", inline="htf6")
settings.htf_6 := htf_6
settings.max_candles_6 := input.int(1, "", inline="htf6")
settings.bull_body := input.color(color.new(color.green, 10), "Body ", inline="body")
settings.bear_body := input.color(color.new(color.red, 10), "", inline="body")
settings.bull_border := input.color(color.new(color.black, 10), "Borders", inline="borders")
settings.bear_border := input.color(color.new(color.black, 10), "", inline="borders")
settings.bull_wick := input.color(color.new(color.black, 10), "Wick ", inline="wick")
settings.bear_wick := input.color(color.new(color.black, 10), "", inline="wick")
settings.offset := input.int(10, "padding from current candles", minval = 1)
settings.buffer := input.int(1, "space between candles", minval = 1, maxval = 4)
settings.htf_buffer := input.int(10, "space between Higher Timeframes", minval = 1, maxval = 10)
settings.width := input.int(1, "Candle Width", minval = 1, maxval = 4)*2
settings.htf_label_show := input.bool(true, "HTF Label ", inline="HTFlabel")
settings.htf_label_color := input.color(color.new(color.black, 10), "", inline='HTFlabel')
settings.htf_label_size := input.string(size.large, "", [size.tiny, size.small, size.normal, size.large, size.huge], inline="HTFlabel")
settings.fvg_show := input.bool(true, "Fair Value Gap ", group="Imbalance", inline="fvg")
settings.fvg_color := input.color(color.new(color.gray, 80), "", inline='fvg', group="Imbalance")
settings.vi_show := input.bool(true, "Volume Imbalance", group="Imbalance", inline="vi")
settings.vi_color := input.color(color.new(color.red, 50), "", inline='vi', group="Imbalance")
settings.trace_show := input.bool(true, "Trace lines", group="trace")
settings.trace_o_color := input.color(color.new(color.gray, 50), "Open ", inline='1', group="trace")
settings.trace_o_style := input.string('····', '', options = ['⎯⎯⎯', '----', '····'], inline='1', group="trace")
settings.trace_o_size := input.int(1, '', options = [1,2,3,4], inline='1', group="trace")
settings.trace_c_color := input.color(color.new(color.gray, 50), "Close ", inline='2', group="trace")
settings.trace_c_style := input.string('····', '', options = ['⎯⎯⎯', '----', '····'], inline='2', group="trace")
settings.trace_c_size := input.int(1, '', options = [1,2,3,4], inline='2', group="trace")
settings.trace_h_color := input.color(color.new(color.gray, 50), "High ", inline='3', group="trace")
settings.trace_h_style := input.string('····', '', options = ['⎯⎯⎯', '----', '····'], inline='3', group="trace")
settings.trace_h_size := input.int(1, '', options = [1,2,3,4], inline='3', group="trace")
settings.trace_l_color := input.color(color.new(color.gray, 50), "Low ", inline='4', group="trace")
settings.trace_l_style := input.string('····', '', options = ['⎯⎯⎯', '----', '····'], inline='4', group="trace")
settings.trace_l_size := input.int(1, '', options = [1,2,3,4], inline='4', group="trace")
settings.trace_1_show := input.bool(true, "HTF 1 ", group="trace", inline="traces")
settings.trace_2_show := input.bool(false, "HTF 2 ", group="trace", inline="traces")
settings.trace_3_show := input.bool(false, "HTF 3", group="trace", inline="traces")
settings.trace_4_show := input.bool(false, "HTF 4 ", group="trace", inline="traces2")
settings.trace_5_show := input.bool(false, "HTF 5 ", group="trace", inline="traces2")
settings.trace_6_show := input.bool(false, "HTF 6", group="trace", inline="traces2")
settings.label_show := input.bool(true, "Label ", inline="label")
settings.label_color := input.color(color.new(color.black, 10), "", inline='label')
settings.label_size := input.string(size.small, "", [size.tiny, size.small, size.normal, size.large, size.huge], inline="label")
settings.label_1_show := input.bool(true, "HTF 1 ", inline="labels")
settings.label_2_show := input.bool(false, "HTF 2 ", inline="labels")
settings.label_3_show := input.bool(false, "HTF 3", inline="labels")
settings.label_4_show := input.bool(false, "HTF 4 ", inline="labels2")
settings.label_5_show := input.bool(false, "HTF 5 ", inline="labels2")
settings.label_6_show := input.bool(false, "HTF 6", inline="labels2")
// Variables
var Candle[] candles_1 = array.new<Candle>(0)
var Candle[] candles_2 = array.new<Candle>(0)
var Candle[] candles_3 = array.new<Candle>(0)
var Candle[] candles_4 = array.new<Candle>(0)
var Candle[] candles_5 = array.new<Candle>(0)
var Candle[] candles_6 = array.new<Candle>(0)
var Imbalance[] imbalance_1 = array.new<Imbalance>(0)
var Imbalance[] imbalance_2 = array.new<Imbalance>(0)
var Imbalance[] imbalance_3 = array.new<Imbalance>(0)
var Imbalance[] imbalance_4 = array.new<Imbalance>(0)
var Imbalance[] imbalance_5 = array.new<Imbalance>(0)
var Imbalance[] imbalance_6 = array.new<Imbalance>(0)
var label[] htf_labels = array.new<label>(6)
var Trace[] traces = array.new<Trace>(6)
color color_transparent = #ffffff00
//+------------------------------------------------------------------------------------------------------------+//
//+--- Debugging ---+//
//+------------------------------------------------------------------------------------------------------------+//
var table infobox = table.new(position.top_right, 2, 10, border_width=1)
f_debug(_row, _value) =>
table.cell(infobox, 0, _row, str.tostring(_row+1), bgcolor=color.white, text_size=size.auto)
table.cell(infobox, 1, _row, str.tostring(_value), bgcolor=color.white, text_size=size.auto)
f_get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
Validtimeframe(tf) =>
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(tf)
n3 = n1 % n2
(n1 < n2 and math.round(n2/n1) == n2/n1)
f_get_htf_text(idx) =>
tf = ""
switch idx
1 =>
tf := settings.htf_1
2 =>
tf := settings.htf_2
3 =>
tf := settings.htf_3
4 =>
tf := settings.htf_4
5 =>
tf := settings.htf_5
6 =>
tf := settings.htf_6
formatted = tf
seconds = timeframe.in_seconds(tf)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted
f_show_trace(idx) =>
switch idx
1 =>
settings.trace_show and settings.trace_1_show
2 =>
settings.trace_show and settings.trace_2_show
3 =>
settings.trace_show and settings.trace_3_show
4 =>
settings.trace_show and settings.trace_4_show
5 =>
settings.trace_show and settings.trace_5_show
6 =>
settings.trace_show and settings.trace_6_show
f_show_labels(idx) =>
switch idx
1 =>
settings.label_show and settings.label_1_show
2 =>
settings.label_show and settings.label_2_show
3 =>
settings.label_show and settings.label_3_show
4 =>
settings.label_show and settings.label_4_show
5 =>
settings.label_show and settings.label_5_show
6 =>
settings.label_show and settings.label_6_show
f_get_candles_high(candles) =>
h = 0.0
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
Candle c = array.get(candles, i)
if c.h > h
h := c.h
h
f_compute_label_position(idx) =>
h = 0.0
h1 = f_get_candles_high(candles_1)
if h1 > h
h:= h1
h2 = f_get_candles_high(candles_2)
if h2 > h
h := h2
h3 = f_get_candles_high(candles_3)
if h3 > h
h := h3
h4 = f_get_candles_high(candles_4)
if h4 > h
h := h4
h5 = f_get_candles_high(candles_5)
if h5 > h
h := h5
h6 = f_get_candles_high(candles_6)
if h6 > h
h := h6
h
f_compute_htf_offset(idx) =>
o1 = settings.offset
o2 = settings.offset
o3 = settings.offset
o4 = settings.offset
o5 = settings.offset
o6 = settings.offset
if settings.htf_1_show and Validtimeframe(settings.htf_1)
o2 := o1 + (settings.max_candles_1 * (settings.width + settings.buffer)) + settings.htf_buffer
if settings.htf_2_show and Validtimeframe(settings.htf_2)
o3 := o2 + (settings.max_candles_2 * (settings.width + settings.buffer)) + settings.htf_buffer
if settings.htf_3_show and Validtimeframe(settings.htf_3)
o4 := o3 + (settings.max_candles_3 * (settings.width + settings.buffer)) + settings.htf_buffer
if settings.htf_4_show and Validtimeframe(settings.htf_4)
o5 := o4 + (settings.max_candles_4 * (settings.width + settings.buffer)) + settings.htf_buffer
if settings.htf_5_show and Validtimeframe(settings.htf_5)
o6 := o5 + (settings.max_candles_5 * (settings.width + settings.buffer)) + settings.htf_buffer
switch idx
1 =>
o1
2 =>
o2
3 =>
o3
4 =>
o4
5 =>
o5
6 =>
o6
f_reorder_candles(idx, candles) =>
computed_offset = f_compute_htf_offset(idx)
size = array.size(candles)
index = bar_index+settings.offset
if size > 0
for i = size-1 to 0
Candle candle = array.get(candles, i)
t_buffer = computed_offset + ((settings.width+settings.buffer)*(size-i))
box.set_left(candle.body, bar_index+ t_buffer)
box.set_right(candle.body, bar_index+settings.width + t_buffer)
line.set_x1(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x1(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
if settings.htf_label_show
var label l = array.get(htf_labels, idx-1)
top = f_compute_label_position(idx)
left = bar_index+computed_offset+(size*(settings.width+settings.buffer))/2 + (settings.width+settings.buffer)
if not na(l)
label.set_xy(l, left, top)
1
else
l := label.new(left, top, f_get_htf_text(idx), color=color_transparent, textcolor = settings.htf_label_color, style=label.style_label_down, size = settings.htf_label_size)
1
f_find_imbalances(candles, imbalance) =>
if array.size(imbalance) > 0
for i = array.size(imbalance)-1 to 0
Imbalance del = array.get(imbalance, i)
box.delete(del.b)
array.pop(imbalance)
if array.size(candles) > 3 and settings.fvg_show
for i = 1 to array.size(candles) -3
candle1 = array.get(candles, i)
candle2 = array.get(candles, i+2)
candle3 = array.get(candles, i+1)
if (candle1.l > candle2.h and math.min(candle1.o, candle1.c) > math.max(candle2.o, candle2.c))
Imbalance imb = Imbalance.new()
imb.b := box.new(box.get_left(candle2.body), candle2.h, box.get_right(candle1.body), candle1.l, bgcolor=settings.fvg_color, border_color = color_transparent)
array.push(imbalance, imb)
if (candle1.h < candle2.l and math.max(candle1.o, candle1.c) < math.min(candle2.o, candle2.c))
Imbalance imb = Imbalance.new()
imb.b := box.new(box.get_right(candle1.body), candle1.h, box.get_left(candle2.body), candle2.l, bgcolor=settings.fvg_color, border_color = color_transparent)
array.push(imbalance, imb)
box temp = box.copy(candle3.body)
box.delete(candle3.body)
candle3.body := temp
if array.size(candles) > 2 and settings.vi_show
for i = 1 to array.size(candles) -2
candle1 = array.get(candles, i)
candle2 = array.get(candles, i+1)
if (candle1.l < candle2.h and math.min(candle1.o, candle1.c) > math.max(candle2.o, candle2.c))
Imbalance imb = Imbalance.new()
imb.b := box.new(box.get_left(candle2.body), math.min(candle1.o, candle1.c), box.get_right(candle1.body), math.max(candle2.o, candle2.c), bgcolor=settings.vi_color, border_color = color_transparent)
array.push(imbalance, imb)
if (candle1.h > candle2.l and math.max(candle1.o, candle1.c) < math.min(candle2.o, candle2.c))
Imbalance imb = Imbalance.new()
imb.b := box.new(box.get_right(candle1.body), math.min(candle2.o, candle2.c), box.get_left(candle2.body), math.max(candle1.o, candle1.c), bgcolor=settings.vi_color, border_color = color_transparent)
array.push(imbalance, imb)
f_render_candles(htf, max, candles) =>
HTFBarTime = time(htf)
isNewHTFCandle = ta.change(HTFBarTime)
log.info("Render {0}: {1}", htf, isNewHTFCandle)
if isNewHTFCandle
Candle candle = Candle.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.o_idx := bar_index
candle.c_idx := bar_index
candle.h_idx := bar_index
candle.l_idx := bar_index
bull = candle.c > candle.o
index = bar_index
candle.body := box.new(index, math.max(candle.o, candle.c), index, math.min(candle.o, candle.c), bull ? settings.bull_border : settings.bear_border, 1, bgcolor = bull ? settings.bull_body : settings.bear_body)
candle.wick_up := line.new(index, candle.h, index, math.max(candle.o, candle.c), color=bull ? settings.bull_wick : settings.bear_wick)
candle.wick_down := line.new(index, math.min(candle.o, candle.c), index, candle.l, color=bull ? settings.bull_wick : settings.bear_wick)
array.unshift(candles, candle)
if array.size(candles) > max
Candle delCandle = array.pop(candles)
box.delete(delCandle.body)
line.delete(delCandle.wick_up)
line.delete(delCandle.wick_down)
f_update_last(idx, candles, imbalance) =>
if array.size(candles) > 0
Candle candle = array.get(candles, 0)
candle.h_idx := high > candle.h ? bar_index : candle.h_idx
candle.h := high > candle.h ? high : candle.h
candle.l_idx := low < candle.l ? bar_index : candle.l_idx
candle.l := low < candle.l ? low : candle.l
candle.c := close
candle.c_idx := bar_index
bull = candle.c > candle.o
box.set_top(candle.body, candle.o)
box.set_bottom(candle.body, candle.c)
box.set_bgcolor(candle.body, bull ? settings.bull_body : settings.bear_body)
box.set_border_color(candle.body, bull ? settings.bull_border : settings.bear_border)
line.set_y1(candle.wick_up, candle.h)
line.set_y2(candle.wick_up, math.max(candle.o, candle.c))
line.set_y1(candle.wick_down, candle.l)
line.set_y2(candle.wick_down, math.min(candle.o, candle.c))
if barstate.isrealtime or barstate.islast
f_reorder_candles(idx, candles)
if barstate.isrealtime or barstate.islast
if f_show_trace(idx)
var Trace trace = array.get(traces, idx-1)
if na(trace)
trace := Trace.new()
if na(trace.o)
trace.o := line.new(candle.o_idx, candle.o, box.get_left(candle.body), candle.o, color=settings.trace_o_color, style=f_get_line_style(settings.trace_o_style), width=settings.trace_o_size)
1
else
line.set_y1(trace.o, candle.o)
line.set_y2(trace.o, candle.o)
line.set_x2(trace.o, box.get_left(candle.body))
if na(trace.c)
trace.c := line.new(candle.c_idx, candle.c, box.get_left(candle.body), candle.c, color=settings.trace_c_color, style=f_get_line_style(settings.trace_c_style), width=settings.trace_c_size)
else
line.set_y1(trace.c, candle.c)
line.set_y2(trace.c, candle.c)
line.set_x2(trace.c, box.get_left(candle.body))
if na(trace.h)
trace.h := line.new(candle.h_idx, candle.h, line.get_x1(candle.wick_up), candle.h, color=settings.trace_h_color, style=f_get_line_style(settings.trace_h_style), width=settings.trace_h_size)
else
line.set_y1(trace.h, candle.h)
line.set_y2(trace.h, candle.h)
line.set_x2(trace.h, line.get_x1(candle.wick_up))
if na(trace.l)
trace.l := line.new(candle.l_idx, candle.l, line.get_x1(candle.wick_down), candle.l, color=settings.trace_l_color, style=f_get_line_style(settings.trace_l_style), width=settings.trace_l_size)
1
else
line.set_y1(trace.l, candle.l)
line.set_y2(trace.l, candle.l)
line.set_x2(trace.l, line.get_x1(candle.wick_down))
1
if f_show_labels(idx)
var Trace trace = array.get(traces, idx-1)
if na(trace)
trace := Trace.new()
if na(trace.o_l)
trace.o_l := label.new(box.get_right(candle.body), candle.o, str.tostring(candle.o), textalign = text.align_center, style=label.style_label_left, size=settings.label_size, color=color_transparent, textcolor=settings.label_color)
1
else
label.set_y(trace.o_l, candle.o)
label.set_x(trace.o_l, box.get_right(candle.body))
label.set_text(trace.o_l, str.tostring(candle.o))
1
if na(trace.c_l)
trace.c_l := label.new(box.get_right(candle.body), candle.c, str.tostring(candle.c), textalign = text.align_center, style=label.style_label_left, size=settings.label_size, color=color_transparent, textcolor=settings.label_color)
1
else
label.set_y(trace.c_l, candle.c)
label.set_x(trace.c_l, box.get_right(candle.body))
label.set_text(trace.c_l, str.tostring(candle.c))
1
if na(trace.h_l)
trace.h_l := label.new(box.get_right(candle.body), candle.h, str.tostring(candle.h), textalign = text.align_center, style=label.style_label_left, size=settings.label_size, color=color_transparent, textcolor=settings.label_color)
1
else
label.set_y(trace.h_l, candle.h)
label.set_x(trace.h_l, box.get_right(candle.body))
label.set_text(trace.h_l, str.tostring(candle.o))
1
if na(trace.l_l)
trace.l_l := label.new(box.get_right(candle.body), candle.l, str.tostring(candle.l), textalign = text.align_center, style=label.style_label_left, size=settings.label_size, color=color_transparent, textcolor=settings.label_color)
1
else
label.set_y(trace.l_l, candle.l)
label.set_x(trace.l_l, box.get_right(candle.body))
label.set_text(trace.l_l, str.tostring(candle.o))
1
f_find_imbalances(candles, imbalance)
log.info("{0}", Validtimeframe(settings.htf_5))
if settings.htf_1_show and Validtimeframe(settings.htf_1)
f_render_candles(settings.htf_1, settings.max_candles_1, candles_1)
if settings.htf_2_show and Validtimeframe(settings.htf_2)
f_render_candles(settings.htf_2, settings.max_candles_2, candles_2)
if settings.htf_3_show and Validtimeframe(settings.htf_3)
f_render_candles(settings.htf_3, settings.max_candles_3, candles_3)
if settings.htf_4_show and Validtimeframe(settings.htf_4)
f_render_candles(settings.htf_4, settings.max_candles_4, candles_4)
if settings.htf_5_show and Validtimeframe(settings.htf_5)
f_render_candles(settings.htf_5, settings.max_candles_5, candles_5)
if settings.htf_6_show and Validtimeframe(settings.htf_6)
f_render_candles(settings.htf_6, settings.max_candles_6, candles_6)
if settings.htf_1_show
f_update_last(1, candles_1, imbalance_1)
if settings.htf_2_show
f_update_last(2, candles_2, imbalance_2)
if settings.htf_3_show
f_update_last(3, candles_3, imbalance_3)
if settings.htf_4_show
f_update_last(4, candles_4, imbalance_4)
if settings.htf_5_show
f_update_last(5, candles_5, imbalance_5)
if settings.htf_6_show
f_update_last(6, candles_6, imbalance_6)
|
Volume Profile Plus | https://www.tradingview.com/script/Lh5drG70-Volume-Profile-Plus/ | algotraderdev | https://www.tradingview.com/u/algotraderdev/ | 196 | 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/
// © algotraderdev
//@version=5
indicator('VP+', overlay = true, max_bars_back = 1)
import algotraderdev/contrast/1
//#region Inputs & Constants
const string RANGE_GROUP = 'TIME RANGE'
const string VISIBLE_RANGE = 'Visible Range'
const string ANCHORED_RANGE = 'Anchored Range'
const string ALL_RANGE = 'All Range'
string RANGE_MODE = input.string(
VISIBLE_RANGE,
'Range Mode',
options = [VISIBLE_RANGE, ANCHORED_RANGE, ALL_RANGE],
tooltip = 'This setting determines the start time of the volume profile calculation.\n\n' +
'Visible Range (Default Mode): In this mode, the volume profile calculation begins at the time of the ' +
'left-most bar displayed in the current viewport. As the user scrolls through the viewport, the volume profile ' +
'updates automatically.\n\n' +
'Anchored Range: This mode allows the user to set the start time either by using the "Anchor Time" input box ' +
'below or by dragging the anchor line on the chart.\n\n' +
'All Range: In this mode, the volume profile calculation is based on all the historical bars available in the ' +
'chart.',
group = RANGE_GROUP)
int ANCHORED_TIME = input.time(
timestamp('2023-01-01T12:00:00'),
'Anchor Time',
tooltip = 'The start time of the volume profile calculation. This setting is only used when the "Range Mode" above ' +
'is set to "Anchored Range".',
group = RANGE_GROUP)
const string GRANULARITY_GROUP = 'GRANULARITY'
int NUM_ROWS = input.int(
300,
'Number of Rows',
minval = 100,
maxval = 2500,
step = 100,
tooltip = 'The number of rows to display in the volume profile histogram (Max 2500)',
group = GRANULARITY_GROUP,
display = display.none)
int MAX_LTF_BARS = input.int(
5000,
'Max Lower Timeframe Bars',
minval = 1000,
step = 1000,
tooltip = 'The max number of lower timeframe bars to use for the volume profile calculation.\n\n' +
'NOTE: The higher the number, the more time and memory the calculation needs. If you encounter a time limit ' +
'or memory limit error, please try lowering the number here.',
group = GRANULARITY_GROUP)
bool USE_SECOND_BASED_TIMEFRAMES = input.bool(
false,
'Use Second-Based Timeframes',
tooltip = 'Whether to use second-based timeframes (e.g. 1 second, 5 seconds) when the chart\'s current timeframe ' +
'is low (e.g. 5 minutes).\n\n' +
'NOTE: second-based timeframes are only supported if you\'re subscribed to the TradingView Premium Plan and ' +
'above.',
group = GRANULARITY_GROUP)
const string APPEARANCE_GROUP = 'APPEARANCE'
int HORIZONTAL_OFFSET = input.int(
20,
'Horizontal Offset',
step = 5,
tooltip = 'The distance, measured in the number of bars, between the last bar in the chart and the left of the ' +
'volume profile histogram.',
group = APPEARANCE_GROUP,
display = display.none)
int MAX_WIDTH = input.int(
80,
'Max Width',
maxval = 500,
minval = 10,
step = 10,
tooltip = 'The maximum width, measured in number of bars, for the volume profile histogram.',
group = APPEARANCE_GROUP,
display = display.none)
int HEIGHT_PERCENTAGE_PER_ROW = input.int(
40,
'Height % per Row',
minval = 1,
maxval = 100,
tooltip = 'The height of each volume profile histogram row, measured as the percentage of the price range ' +
'of each price bucket.',
group = APPEARANCE_GROUP,
display = display.none)
bool SHOW_DELTA = input.bool(
false,
'Show Volume Delta',
tooltip = 'Whether to show Volume Delta (the net difference between buying and selling volume).',
group = APPEARANCE_GROUP,
display = display.none)
const string COLOR_GROUP = 'COLOR'
color COLOR = input.color(#5d606b77, 'Default', group = COLOR_GROUP)
color BUY_COLOR = input.color(#00bcd480, 'Buy Volume', group = COLOR_GROUP)
color SELL_COLOR = input.color(#e91e6380, 'Sell Volume', group = COLOR_GROUP)
color POC_COLOR = input.color(color.yellow, 'POC (Point of Control)', group = COLOR_GROUP)
color VAH_COLOR = input.color(color.blue, 'VAH (Value Area High)', group = COLOR_GROUP)
color VAL_COLOR = input.color(color.blue, 'VAL (Value Area Low)', group = COLOR_GROUP)
const string KEY_PRICES_GROUP = 'POC & Value Area'
int VALUE_AREA_PERCENT = input.int(
70,
'Value Area Percent',
minval = 1,
maxval = 100,
tooltip = 'The percentage of the total trading volume that\'s considered as the value area.',
group = KEY_PRICES_GROUP,
display = display.none)
bool DISPLAY_VA = input.bool(
true,
'Display VAH/VAL',
group = KEY_PRICES_GROUP,
display = display.none)
bool DISPLAY_POC = input.bool(
true,
'Display POC',
group = KEY_PRICES_GROUP,
display = display.none)
bool EXTEND_LEFT = input.bool(
true,
'Extend Key Price Lines to the Left',
tooltip = 'Whether to extend the key price lines (POC, VAH, VAL) to the left of the chart.',
group = KEY_PRICES_GROUP)
int BASE_OFFSET = HORIZONTAL_OFFSET + MAX_WIDTH
int LABEL_OFFSET = BASE_OFFSET + 2
int START_TIME = switch RANGE_MODE
VISIBLE_RANGE => chart.left_visible_bar_time
ANCHORED_RANGE => ANCHORED_TIME
ALL_RANGE => 0
// If second-based timeframe is enabled, then set the minimal timeframe to 1 second.
// Otherwise, set it to 60 seconds (1 minute).
int MIN_TIMEFRAME_IN_SECONDS = USE_SECOND_BASED_TIMEFRAMES ? 1 : 60
//#endregion
//#region Utils
// @function Identifies the index of the max value in the array.
// @param a The array to find max index for.
// @returns The index of the max value in the array.
maxIndex(float[] a) =>
if a.size() == 0
na
float max = a.first()
int maxIndex = 0
for [i, v] in a
if v > max
max := v
maxIndex := i
maxIndex
//#endregion
//#region Candle
const int DIRECTION_NONE = 0
const int DIRECTION_BUY = 1
const int DIRECTION_SELL = -1
// @type The candle object holds the required information for each candle in the chart.
// @field high The `high` of the candle.
// @field low The `low` of the candle.
// @field volume The `volume` of the candle.
// @field direction Any of DIRECTION_NONE, DIRECTION_BUY, or DIRECTION_BUY.
type Candle
float high
float low
float volume
int direction
//#endregion
//#region Marker
// @type The Marker type is for highlighting a specific price point in the volume profile.
// @field poly The polyline for highlighting the price point. Note that we're using a `polyline` instead of `line`
// here since there seems to be bug in TradingView that prevents a `line` to be overlaid on top of a `polyline`.
// @field extendedLine A line at the price level that extends to the left of the screen.
// @field label Label for this marker.
type Marker
polyline poly
line extendedLine
label label
// @function Sets the properties of the marker.
// @param name The name of the marker. This is also displayed as part of the label text.
// @param left The bar index of the left x coordinate of the volume profile row.
// @param right The bar index of the right x coordinate of the volume profile row.
// @param price The price / y-coordinate of the marker.
// @param bg The background color of the marker.
// @param height The height of the volume profile row.
method set(Marker this, string name, int left, int right, float price, color bg, float height) =>
// Create a polyline to highlight the row.
if not na(this.poly)
this.poly.delete()
float bottom = price - height / 2
float top = bottom + height
chart.point[] points = array.from(
chart.point.from_index(left, bottom),
chart.point.from_index(left, top),
chart.point.from_index(right, top),
chart.point.from_index(right, bottom))
this.poly := polyline.new(points, line_color = bg, fill_color = bg)
// Create a dotted line and extend it to the left.
if not na(this.extendedLine)
this.extendedLine.delete()
if EXTEND_LEFT
this.extendedLine := line.new(
x1 = left,
y1 = price,
x2 = right,
y2 = price,
extend = extend.left,
style = line.style_dotted,
color = bg)
// Create a label to the right of the row.
if na(this.label)
this.label.delete()
string txt = str.format('{0}: {1}', name, math.round_to_mintick(price))
this.label := label.new(
x = bar_index + LABEL_OFFSET,
y = price,
text = txt,
style = label.style_label_left,
size = size.small,
color = bg,
textcolor = bg.contrast(0.6))
this
//#endregion
//#region VP
// @type The VP (Volume Profile) type is responsible for calculating and visualizing the distribution of
// volumes at various price points.
// @field candles The stored candles based on which the distribution will be calculated.
// @field minPrice The minimum price for all the stored candles.
// @field maxPrice The maximum price for all the stored candles.
// @field step The price difference between adjacent price buckets.
// @field poly The polyline that's used to draw the histogram of the volume profile.
// @field buyPoly The polyline that's used to draw the histogram of the buying volume.
// @field sellPoly The polyline that's used to draw the histogram of the selling volume.
// @field markers Markers that highlight POC, VAH, and VAL.
type VP
Candle[] candles
float minPrice
float maxPrice
float step
polyline poly
polyline buyPoly
polyline sellPoly
map<string, Marker> markers
// @function Initializes a new VP instance.
// @returns The initialized VP instance.
method init(VP this) =>
this.candles := array.new<Candle>()
this.markers := map.new<string, Marker>()
this
// @function Gets the bucket index for the given price.
// @param price The price to get index for.
// @returns The bucket index for the price.
method getBucketIndex(VP this, float price) =>
math.min(math.floor((price - this.minPrice) / this.step), NUM_ROWS - 1)
// @function Gets the bucketed price for the given index
// @param index The bucket index.
// @returns The average price for the bucket.
method getBucketedPrice(VP this, int index) =>
(index + 0.5) * this.step + this.minPrice
// @function Highlights a specific price / volume bucket.
// @param name The name of the label.
// @param index The index of the bucket to highlight.
// @param left The x coordinate of the left endpoint of the volume profile.
// @param bg The background highlight color.
// @param height The height of each row.
method mark(VP this, string name, float price, int left, color bg, float height) =>
int right = bar_index + BASE_OFFSET
Marker marker = this.markers.get(name)
if na(marker)
marker := Marker.new().set(name = name, left = left, right = right, price = price, bg = bg, height = height)
// @function Stores a candle for it to be analyzed later.
// Note that this method is expected to be called on every tick. The actual calculation of VP is deferred to only when
// the last bar in the chart is reached, as an optimization.
// @param candle The candle to store.
method store(VP this, Candle candle) =>
this.candles.push(candle)
this.minPrice := na(this.minPrice) ? candle.low : math.min(this.minPrice, candle.low)
this.maxPrice := na(this.maxPrice) ? candle.high : math.max(this.maxPrice, candle.high)
this.step := (this.maxPrice - this.minPrice) / NUM_ROWS
// @function Draws a histogram for the given coordinates.
// @param xs The x-coordinates for the left of the histogram rows.
// @param baseX The x-coordinate for the base of the histogram.
// @param step The step / delta between adjacent price points.
// @param height The height for each row.
// @param color The color for the histogram.
// @returns The drawn polyline.
method drawHistogram(VP this, int[] xs, int baseX, float step, float height, color color) =>
// Construct the polyline points.
chart.point[] points = array.new<chart.point>()
float gap = (step - height) / 2
for [i, x] in xs
float lo = i * step + gap + this.minPrice
float hi = lo + height
points.push(chart.point.from_index(index = baseX, price = lo))
points.push(chart.point.from_index(index = x, price = lo))
points.push(chart.point.from_index(index = x, price = hi))
points.push(chart.point.from_index(index = baseX, price = hi))
polyline.new(points, closed = true, line_color = color, fill_color = color)
// @function Calculates the distribution and visualizes it on the chart.
method update(VP this) =>
// Calculate the step size for each bucket.
float step = (this.maxPrice - this.minPrice) / NUM_ROWS
// Loop through the candles and populate the distribution array.
float[] dist = array.new_float(NUM_ROWS, 0)
float[] deltaDist = array.new_float(NUM_ROWS, 0)
for c in this.candles
// Calculate the start and end index of the buckets to fill the volume.
int start = this.getBucketIndex(c.low)
int end = this.getBucketIndex(c.high)
int buckets = end - start + 1
float vol = c.volume / buckets
for i = start to end
dist.set(i, dist.get(i) + vol)
deltaDist.set(i, deltaDist.get(i) + vol * c.direction)
float maxVol = dist.max()
// Calculate the x coordinate for each row.
int baseX = bar_index + BASE_OFFSET
int[] xs = array.new_int()
for vol in dist
int width = math.round(vol / maxVol * MAX_WIDTH)
int x = baseX - width
xs.push(x)
float height = HEIGHT_PERCENTAGE_PER_ROW / 100 * step
// Draw the histogram.
if not na(this.poly)
this.poly.delete()
this.poly := this.drawHistogram(xs, baseX, step, height, COLOR)
// Draw the delta histograms.
if SHOW_DELTA
int[] buyXs = array.new_int()
int[] sellXs = array.new_int()
for vol in deltaDist
int width = math.round(math.abs(vol) / maxVol * MAX_WIDTH)
int x = baseX - width
buyXs.push(vol > 0 ? x : baseX)
sellXs.push(vol < 0 ? x : baseX)
if not na(this.buyPoly)
this.buyPoly.delete()
this.buyPoly := this.drawHistogram(buyXs, baseX, step, height, BUY_COLOR)
if not na(this.sellPoly)
this.sellPoly.delete()
this.sellPoly := this.drawHistogram(sellXs, baseX, step, height, SELL_COLOR)
// Calculate the cumulative distribution.
float[] cumdist = dist.copy()
for i = 1 to cumdist.size() - 1
cumdist.set(i, cumdist.get(i - 1) + cumdist.get(i))
float totalVolume = cumdist.last()
// Highlight VAH and VAL.
if DISPLAY_VA
float valPercentile = (100 - VALUE_AREA_PERCENT) / 100 / 2
float vahPercentile = 1 - valPercentile
int valIndex = cumdist.binary_search_leftmost(totalVolume * valPercentile)
this.mark(
name = 'VAL',
price = this.getBucketedPrice(valIndex),
left = xs.get(valIndex),
bg = VAL_COLOR,
height = height)
int vahIndex = cumdist.binary_search_leftmost(totalVolume * vahPercentile)
this.mark(
name = 'VAH',
price = this.getBucketedPrice(vahIndex),
left = xs.get(vahIndex),
bg = VAH_COLOR,
height = height)
// Highlight POC.
if DISPLAY_POC
int pocIndex = maxIndex(dist)
this.mark(
name = 'POC',
price = this.getBucketedPrice(pocIndex),
left = xs.get(pocIndex),
bg = POC_COLOR,
height = height)
// Create another vertical polyline to mask the rightmost pixel of the volume profile, so that the minimum
// width for each price bucket can be 0 rather than 1.
chart.point maxPoint = chart.point.from_index(index = baseX, price = this.maxPrice)
chart.point minPoint = chart.point.from_index(index = baseX, price = this.minPrice)
polyline.new(array.from(maxPoint, minPoint), line_color = chart.bg_color)
//#endregion
//#region main
var VP vp = VP.new().init()
// @function Returns a lower timeframe string given the multiplier.
// @param multiplier The multiplier to use.
// @returns The timeframe string.
ltf(simple int multiplier) =>
timeframe.from_seconds(math.max(MIN_TIMEFRAME_IN_SECONDS, math.round(timeframe.in_seconds() / multiplier)))
simple string ltf1 = timeframe.period
simple string ltf2 = ltf(2)
simple string ltf4 = ltf(4)
simple string ltf8 = ltf(8)
simple string ltf16 = ltf(16)
simple string ltf32 = ltf(32)
// Checks a list of lower timeframes to see which one should be used for the volume profile calculation.
// NOTE: unfortunately we cannot use a for-loop to go through an array of timeframe strings since the timeframe
// parameter in `request.security_lower_tf` has to be an `simple string` whereas the type for items in array is
// always `series`, even if the array itself is marked as `const` or `simple`.
bool canProcess = time >= START_TIME and (last_bar_index - bar_index) < MAX_LTF_BARS
bool cp1 = canProcess
bool cp2 = request.security(syminfo.tickerid, ltf2, canProcess)
bool cp4 = request.security(syminfo.tickerid, ltf4, canProcess)
bool cp8 = request.security(syminfo.tickerid, ltf8, canProcess)
bool cp16 = request.security(syminfo.tickerid, ltf16, canProcess)
bool cp32 = request.security(syminfo.tickerid, ltf32, canProcess)
// A list of candidate candles in various timeframes.
int dir = switch
close > open => DIRECTION_BUY
close < open => DIRECTION_SELL
=> DIRECTION_NONE
Candle candle = Candle.new(high, low, volume, dir)
Candle[] c1 = array.from(candle)
Candle[] c2 = request.security_lower_tf(syminfo.tickerid, ltf2, candle, ignore_invalid_timeframe = true)
Candle[] c4 = request.security_lower_tf(syminfo.tickerid, ltf4, candle, ignore_invalid_timeframe = true)
Candle[] c8 = request.security_lower_tf(syminfo.tickerid, ltf8, candle, ignore_invalid_timeframe = true)
Candle[] c16 = request.security_lower_tf(syminfo.tickerid, ltf16, candle, ignore_invalid_timeframe = true)
Candle[] c32 = request.security_lower_tf(syminfo.tickerid, ltf32, candle, ignore_invalid_timeframe = true)
var string ltf = na
if na(ltf)
ltf := switch
cp32 => ltf32
cp16 => ltf16
cp8 => ltf8
cp4 => ltf4
cp2 => ltf2
cp1 => ltf1
Candle[] cs = switch ltf
ltf1 => c1
ltf2 => c2
ltf4 => c4
ltf8 => c8
ltf16 => c16
ltf32 => c32
if not na(cs)
for c in cs
vp.store(c)
if barstate.islast
vp.update()
//#endregion |
WHAlertCommand | https://www.tradingview.com/script/NVi8VlEH-WHAlertCommand/ | TheWickHunter | https://www.tradingview.com/u/TheWickHunter/ | 2 | 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/
// © WickHunter
//@version=5
// @description
library("WHAlertCommand", overlay = true)
export f_WH_Risk(string risk_Type_) =>
switch risk_Type_
"Very Low" => "VERY_LOW"
"Low" => str.upper(risk_Type_)
"Medium" => str.upper(risk_Type_)
"High" => str.upper(risk_Type_)
"Very High" => "VERY_HIGH"
export f_WH_Open_Position(string uuid_, bool enable_Buy_, bool enable_Sell, bool enable_All_Group_Members_, bool enable_Close_Opposite_Side_, bool enable_Risk_, string risk_Type_, string signal_Type_Buy_Or_Sell) =>
string WICK_HUNTER_START_COMMAND = "{"
string WICK_HUNTER_END_COMMAND = "}"
string WICK_HUNTER_OPEN = "\"cmd\":\"OPEN\""
string WICK_HUNTER_UUID = ",\"uuid\":\"" + uuid_ + "\""
string WICK_HUNTER_SYMBOL = ",\"symbol\":\"" + syminfo.ticker + "\""
string WICK_HUNTER_SIDE_BUY = ",\"side\":\"BUY\""
string WICK_HUNTER_SIDE_SELL = ",\"side\":\"SELL\""
string WICK_HUNTER_RISK = enable_Risk_ ? ",\"risk\":\"" + f_WH_Risk(risk_Type_ = risk_Type_) + "\"" : ""
string WICK_HUNTER_ALL_GROUP_MEMBERS = enable_All_Group_Members_ ? ",\"group\":true" : ""
string WICK_HUNTER_CLOSE_OPPOSITE_SIDE = enable_Close_Opposite_Side_ ? ",\"closePrevious\": true" : ""
string WICK_HUNTER_BUY = enable_Buy_ ? WICK_HUNTER_START_COMMAND + WICK_HUNTER_OPEN + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_BUY + WICK_HUNTER_RISK + WICK_HUNTER_ALL_GROUP_MEMBERS + WICK_HUNTER_CLOSE_OPPOSITE_SIDE + WICK_HUNTER_END_COMMAND : na
string WICK_HUNTER_SELL = enable_Sell ? WICK_HUNTER_START_COMMAND + WICK_HUNTER_OPEN + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_SELL + WICK_HUNTER_RISK + WICK_HUNTER_ALL_GROUP_MEMBERS + WICK_HUNTER_CLOSE_OPPOSITE_SIDE + WICK_HUNTER_END_COMMAND : na
if str.upper(signal_Type_Buy_Or_Sell) == "BUY"
WICK_HUNTER_BUY
else if str.upper(signal_Type_Buy_Or_Sell) == "SELL"
WICK_HUNTER_SELL
export f_WH_TP(string uuid_, float position_Size_Percent_, string side_) =>
string WICK_HUNTER_START_COMMAND = "{"
string WICK_HUNTER_END_COMMAND = "}"
string WICK_HUNTER_MARKET_TP = "\"cmd\":\"MARKET_TAKE_PROFIT\""
string WICK_HUNTER_UUID = ",\"uuid\":\"" + uuid_ + "\""
string WICK_HUNTER_SYMBOL = ",\"symbol\":\"" + syminfo.ticker + "\""
string WICK_HUNTER_SIDE_BUY = ",\"side\":\"BUY\""
string WICK_HUNTER_SIDE_SELL = ",\"side\":\"SELL\""
string WICK_HUNTER_PERCENT_POSITION_SIZE = ",\"percentageOfPositionSize\":" + str.tostring(position_Size_Percent_)
string WICK_HUNTER_TP_LONG = WICK_HUNTER_START_COMMAND + WICK_HUNTER_MARKET_TP + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_BUY + WICK_HUNTER_PERCENT_POSITION_SIZE + WICK_HUNTER_END_COMMAND
string WICK_HUNTER_TP_SHORT = WICK_HUNTER_START_COMMAND + WICK_HUNTER_MARKET_TP + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_SELL + WICK_HUNTER_PERCENT_POSITION_SIZE + WICK_HUNTER_END_COMMAND
if str.upper(side_) == "BUY"
WICK_HUNTER_TP_LONG
else if str.upper(side_) == "SELL"
WICK_HUNTER_TP_SHORT
export f_WH_MARKET_CLOSE(string uuid_, string side_) =>
string WICK_HUNTER_START_COMMAND = "{"
string WICK_HUNTER_END_COMMAND = "}"
string WICK_HUNTER_MARKET_TP = "\"cmd\":\"MARKET_CLOSE\""
string WICK_HUNTER_UUID = ",\"uuid\":\"" + uuid_ + "\""
string WICK_HUNTER_SYMBOL = ",\"symbol\":\"" + syminfo.ticker + "\""
string WICK_HUNTER_SIDE_BUY = ",\"side\":\"BUY\""
string WICK_HUNTER_SIDE_SELL = ",\"side\":\"SELL\""
string WICK_HUNTER_TP_LONG = WICK_HUNTER_START_COMMAND + WICK_HUNTER_MARKET_TP + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_BUY + WICK_HUNTER_END_COMMAND
string WICK_HUNTER_TP_SHORT = WICK_HUNTER_START_COMMAND + WICK_HUNTER_MARKET_TP + WICK_HUNTER_UUID + WICK_HUNTER_SYMBOL + WICK_HUNTER_SIDE_SELL + WICK_HUNTER_END_COMMAND
if str.upper(side_) == "BUY"
WICK_HUNTER_TP_LONG
else if str.upper(side_) == "SELL"
WICK_HUNTER_TP_SHORT |
PScolor | https://www.tradingview.com/script/uUKFd4jg/ | Pumpkin_Soup | https://www.tradingview.com/u/Pumpkin_Soup/ | 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/
// © Pumpkin_Soup
//@version=5
// @description TODO: add library description here
library("PScolor")
///https://materialui.co/colors/
//COLOR
//각 컬러는 0~9 / A1~A4 까지 있음
// (5기준 작으면 밝고, 크면 어두워짐)
// (A2 기준 형광)
//
//lv1col = RED
//lv2col = DEEP_ORANGE
//lv3col = ORANGE
//lv4col = AMBER
//lv5col = YELLOW
//lv6col = LIME
//lv7col = LIGHT_GREEN
//lv8col = GREEN
//lv9col = TEAL
//lv10col= CYAN
//lv11col= LIGHT_BLUE
//lv12col= BLUE
//lv13col= INDIGO
//lv14col= DEEP_PURPLE
//lv15col= PURPLE
//lv16col= PINK
//
//BROWN
//GRAY
//BLUE_GRAY
///////////////////////////
//lv16col = PINK
PINK0 = #FCE4EC, PINK1 = #F8BBD0, PINK2 = #F48FB1, PINK3 = #F06292, PINK4 = #EC407A, PINK5 = #E91E63, PINK6 = #D81B60, PINK7 = #C2185B, PINK8 = #AD1457, PINK9 = #880E4F
PINKA1 = #FF80AB, PINKA2 = #FF4081, PINKA3 = #F50057, PINKA4 = #C51162
lv16col0 = PINK0, lv16col1 = PINK1, lv16col2 = PINK2, lv16col3 = PINK3, lv16col4 = PINK4, lv16col5 = PINK5, lv16col6 = PINK6, lv16col7 = PINK7, lv16col8 = PINK8, lv16col9 = PINK9
lv16colA1 = PINKA1, lv16colA2 = PINKA2, lv16colA3 = PINKA3, lv16colA4 = PINKA4
///////////////////////////
//lv15col = PURPLE
PURPLE0 = #F3E5F5, PURPLE1 = #E1BEE7, PURPLE2 = #CE93D8, PURPLE3 = #BA68C8, PURPLE4 = #AB47BC, PURPLE5 = #9C27B0, PURPLE6 = #8E24AA, PURPLE7 = #7B1FA2, PURPLE8 = #6A1B9A, PURPLE9 = #4A148C
PURPLEA1 = #EA80FC, PURPLEA2 = #E040FB, PURPLEA3 = #D500F9, PURPLEA4 = #AA00FF
lv15col0 = PURPLE0, lv15col1 = PURPLE1, lv15col2 = PURPLE2, lv15col3 = PURPLE3, lv15col4 = PURPLE4, lv15col5 = PURPLE5, lv15col6 = PURPLE6, lv15col7 = PURPLE7, lv15col8 = PURPLE8, lv15col9 = PURPLE9
lv15colA1 = PURPLEA1, lv15colA2 = PURPLEA2, lv15colA3 = PURPLEA3, lv15colA4 = PURPLEA4
///////////////////////////
//DEEP_PURPLE
DEEP_PURPLE0 = #EDE7F6, DEEP_PURPLE1 = #D1C4E9, DEEP_PURPLE2 = #B39DDB, DEEP_PURPLE3 = #9575CD, DEEP_PURPLE4 = #7E57C2, DEEP_PURPLE5 = #673AB7, DEEP_PURPLE6 = #5E35B1, DEEP_PURPLE7 = #512DA8, DEEP_PURPLE8 = #4527A0, DEEP_PURPLE9 = #311B92
DEEP_PURPLEA1 = #8C9EFF, DEEP_PURPLEA2 = #536DFE, DEEP_PURPLEA3 = #3D5AFE, DEEP_PURPLEA4 = #304FFE
lv14col0 = DEEP_PURPLE0, lv14col1 = DEEP_PURPLE1, lv14col2 = DEEP_PURPLE2, lv14col3 = DEEP_PURPLE3, lv14col4 = DEEP_PURPLE4, lv14col5 = DEEP_PURPLE5, lv14col6 = DEEP_PURPLE6, lv14col7 = DEEP_PURPLE7, lv14col8 = DEEP_PURPLE8, lv14col9 = DEEP_PURPLE9
lv14colA1 = DEEP_PURPLEA1, lv14colA2 = DEEP_PURPLEA2, lv14colA3 = DEEP_PURPLEA3, lv14colA4 = DEEP_PURPLEA4
///////////////////////////
//lv13col = INDIGO
INDIGO0 = #E8EAF6, INDIGO1 = #C5CAE9, INDIGO2 = #9FA8DA, INDIGO3 = #7986CB, INDIGO4 = #5C6BC0, INDIGO5 = #3F51B5, INDIGO6 = #3949AB, INDIGO7 = #303F9F, INDIGO8 = #283593, INDIGO9 = #1A237E,
INDIGOA1 = #8C9EFF, INDIGOA2 = #536DFE, INDIGOA3 = #3D5AFE, INDIGOA4 = #304FFE
lv13col0 = INDIGO0, lv13col1 = INDIGO1, lv13col2 = INDIGO2, lv13col3 = INDIGO3, lv13col4 = INDIGO4, lv13col5 = INDIGO5, lv13col6 = INDIGO6, lv13col7 = INDIGO7, lv13col8 = INDIGO8, lv13col9 = INDIGO9
lv13colA1 = INDIGOA1, lv13colA2 = INDIGOA2, lv13colA3 = INDIGOA3, lv13colA4 = INDIGOA4
///////////////////////////
//lv12col = BLUE
BLUE0 = #E3F2FD, BLUE1 = #BBDEFB, BLUE2 = #90CAF9, BLUE3 = #64B5F6, BLUE4 = #42A5F5, BLUE5 = #2196F3, BLUE6 = #1E88E5, BLUE7 = #1976D2, BLUE8 = #1565C0, BLUE9 = #0D47A1
BLUEA1 = #82B1FF, BLUEA2 = #448AFF, BLUEA3 = #2979FF, BLUEA4 = #2962FF
lv12col0 = BLUE0, lv12col1 = BLUE1, lv12col2 = BLUE2, lv12col3 = BLUE3, lv12col4 = BLUE4, lv12col5 = BLUE5, lv12col6 = BLUE6, lv12col7 = BLUE7, lv12col8 = BLUE8, lv12col9 = BLUE9
lv12colA1 = BLUEA1, lv12colA2 = BLUEA2, lv12colA3 = BLUEA3, lv12colA4 = BLUEA4
///////////////////////////
//lv11col = LIGHT_BLUE
LIGHT_BLUE0 = #E1F5FE, LIGHT_BLUE1 = #B3E5FC, LIGHT_BLUE2 = #81D4FA, LIGHT_BLUE3 = #4FC3F7, LIGHT_BLUE4 = #29B6F6, LIGHT_BLUE5 = #03A9F4, LIGHT_BLUE6 = #039BE5, LIGHT_BLUE7 = #0288D1, LIGHT_BLUE8 = #0277BD, LIGHT_BLUE9 = #01579B
LIGHT_BLUEA1 = #80D8FF, LIGHT_BLUEA2 = #40C4FF, LIGHT_BLUEA3 = #00B0FF, LIGHT_BLUEA4 = #0091EA
lv11col0 = LIGHT_BLUE0, lv11col1 = LIGHT_BLUE1, lv11col2 = LIGHT_BLUE2, lv11col3 = LIGHT_BLUE3, lv11col4 = LIGHT_BLUE4, lv11col5 = LIGHT_BLUE5, lv11col6 = LIGHT_BLUE6, lv11col7 = LIGHT_BLUE7, lv11col8 = LIGHT_BLUE8, lv11col9 = LIGHT_BLUE9
lv11colA1 = LIGHT_BLUEA1, lv11colA2 = LIGHT_BLUEA2, lv11colA3 = LIGHT_BLUEA3, lv11colA4 = LIGHT_BLUEA4
///////////////////////////
//lv10col = CYAN
CYAN0 = #E0F7FA, CYAN1 = #B2EBF2, CYAN2 = #80DEEA, CYAN3 = #4DD0E1, CYAN4 = #26C6DA, CYAN5 = #00BCD4, CYAN6 = #00ACC1, CYAN7 = #0097A7, CYAN8 = #00838F, CYAN9 = #006064
CYANA1 = #84FFFF, CYANA2 = #18FFFF, CYANA3 = #00E5FF, CYANA4 = #00B8D4
lv10col0 = CYAN0, lv10col1 = CYAN1, lv10col2 = CYAN2, lv10col3 = CYAN3, lv10col4 = CYAN4, lv10col5 = CYAN5, lv10col6 = CYAN6, lv10col7 = CYAN7, lv10col8 = CYAN8, lv10col9 = CYAN9
lv10colA1 = CYANA1, lv10colA2 = CYANA2, lv10colA3 = CYANA3, lv10colA4 = CYANA4
///////////////////////////
//lv9col = TEAL
TEAL0 = #E0F2F1, TEAL1 = #B2DFDB, TEAL2 = #80CBC4, TEAL3 = #4DB6AC, TEAL4 = #26A69A, TEAL5 = #009688, TEAL6 = #00897B, TEAL7 = #00796B, TEAL8 = #00695C, TEAL9 = #004D40
TEALA1 = #A7FFEB, TEALA2 = #64FFDA, TEALA3 = #1DE9B6, TEALA4 = #00BFA5
lv9col0 = TEAL0, lv9col1 = TEAL1, lv9col2 = TEAL2, lv9col3 = TEAL3, lv9col4 = TEAL4, lv9col5 = TEAL5, lv9col6 = TEAL6, lv9col7 = TEAL7, lv9col8 = TEAL8, lv9col9 = TEAL9
lv9colA1 = TEALA1, lv9colA2 = TEALA2, lv9colA3 = TEALA3, lv9colA4 = TEALA4
///////////////////////////
//lv8col = GREEN
GREEN0 = #E8F5E9, GREEN1 = #C8E6C9, GREEN2 = #A5D6A7, GREEN3 = #81C784, GREEN4 = #66BB6A, GREEN5 = #4CAF50, GREEN6 = #43A047, GREEN7 = #388E3C, GREEN8 = #2E7D32, GREEN9 = #1B5E20
GREENA1 = #B9F6CA, GREENA2 = #69F0AE, GREENA3 = #00E676, GREENA4 = #00C853
lv8col0 = GREEN0, lv8col1 = GREEN1, lv8col2 = GREEN2, lv8col3 = GREEN3, lv8col4 = GREEN4, lv8col5 = GREEN5, lv8col6 = GREEN6, lv8col7 = GREEN7, lv8col8 = GREEN8, lv8col9 = GREEN9
lv8colA1 = GREENA1, lv8colA2 = GREENA2, lv8colA3 = GREENA3, lv8colA4 = GREENA4
///////////////////////////
//lv7col = LIGHT_GREEN
LIGHT_GREEN0 = #F1F8E9, LIGHT_GREEN1 = #DCEDC8, LIGHT_GREEN2 = #C5E1A5, LIGHT_GREEN3 = #AED581, LIGHT_GREEN4 = #9CCC65, LIGHT_GREEN5 = #8BC34A, LIGHT_GREEN6 = #7CB342, LIGHT_GREEN7 = #689F38, LIGHT_GREEN8 = #558B2F, LIGHT_GREEN9 = #33691E
LIGHT_GREENA1 = #CCFF90, LIGHT_GREENA2 = #B2FF59, LIGHT_GREENA3 = #76FF03, LIGHT_GREENA4 = #64DD17
lv7col0 = LIGHT_GREEN0, lv7col1 = LIGHT_GREEN1, lv7col2 = LIGHT_GREEN2, lv7col3 = LIGHT_GREEN3, lv7col4 = LIGHT_GREEN4, lv7col5 = LIGHT_GREEN5, lv7col6 = LIGHT_GREEN6, lv7col7 = LIGHT_GREEN7, lv7col8 = LIGHT_GREEN8, lv7col9 = LIGHT_GREEN9
lv7colA1 = LIGHT_GREENA1, lv7colA2 = LIGHT_GREENA2, lv7colA3 = LIGHT_GREENA3, lv7colA4 = LIGHT_GREENA4
///////////////////////////
//lv6col = LIME
LIME0 = #F9FBE7, LIME1 = #F0F4C3, LIME2 = #E6EE9C, LIME3 = #DCE775, LIME4 = #D4E157, LIME5 = #CDDC39, LIME6 = #C0CA33, LIME7 = #AFB42B, LIME8 = #9E9D24, LIME9 = #827717
LIMEA1 = #F4FF81, LIMEA2 = #EEFF41, LIMEA3 = #C6FF00, LIMEA4 = #AEEA00
lv6col0 = LIME0, lv6col1 = LIME1, lv6col2 = LIME2, lv6col3 = LIME3, lv6col4 = LIME4, lv6col5 = LIME5, lv6col6 = LIME6, lv6col7 = LIME7, lv6col8 = LIME8, lv6col9 = LIME9
lv6colA1 = LIMEA1, lv6colA2 = LIMEA2, lv6colA3 = LIMEA3, lv6colA4 = LIMEA4
///////////////////////////
//lv5col = YELLOW
YELLOW0 = #FFFDE7, YELLOW1 = #FFF9C4, YELLOW2 = #FFF59D, YELLOW3 = #FFF176, YELLOW4 = #FFEE58, YELLOW5 = #FFEB3B, YELLOW6 = #FDD835, YELLOW7 = #FBC02D, YELLOW8 = #F9A825, YELLOW9 = #F57F17
YELLOWA1 = #FFFF8D, YELLOWA2 = #FFFF00, YELLOWA3 = #FFEA00, YELLOWA4 = #FFD600
lv5col0 = YELLOW0, lv5col1 = YELLOW1, lv5col2 = YELLOW2, lv5col3 = YELLOW3, lv5col4 = YELLOW4, lv5col5 = YELLOW5, lv5col6 = YELLOW6, lv5col7 = YELLOW7, lv5col8 = YELLOW8, lv5col9 = YELLOW9
lv5colA1 = YELLOWA1, lv5colA2 = YELLOWA2, lv5colA3 = YELLOWA3, lv5colA4 = YELLOWA4
///////////////////////////
//lv4col = AMBER
AMBER0 = #FFF8E1, AMBER1 = #FFECB3, AMBER2 = #FFE082, AMBER3 = #FFD54F, AMBER4 = #FFCA28, AMBER5 = #FFC107, AMBER6 = #FFB300, AMBER7 = #FFA000, AMBER8 = #FF8F00, AMBER9 = #FF6F00
AMBERA1 = #FFE57F, AMBERA2 = #FFD740, AMBERA3 = #FFC400, AMBERA4 = #FFAB00
lv4col0 = AMBER0, lv4col1 = AMBER1, lv4col2 = AMBER2, lv4col3 = AMBER3, lv4col4 = AMBER4, lv4col5 = AMBER5, lv4col6 = AMBER6, lv4col7 = AMBER7, lv4col8 = AMBER8, lv4col9 = AMBER9
lv4colA1 = AMBERA1, lv4colA2 = AMBERA2, lv4colA3 = AMBERA3, lv4colA4 = AMBERA4
///////////////////////////
//lv3col = ORANGE
ORANGE0 = #FFF3E0, ORANGE1 = #FFE0B2, ORANGE2 = #FFCC80, ORANGE3 = #FFB74D, ORANGE4 = #FFA726, ORANGE5 = #FF9800, ORANGE6 = #FB8C00, ORANGE7 = #F57C00, ORANGE8 = #EF6C00, ORANGE9 = #E65100
ORANGEA1 = #FFD180, ORANGEA2 = #FFAB40, ORANGEA3 = #FF9100, ORANGEA4 = #FF6D00
lv3col0 = ORANGE0, lv3col1 = ORANGE1, lv3col2 = ORANGE2, lv3col3 = ORANGE3, lv3col4 = ORANGE4, lv3col5 = ORANGE5, lv3col6 = ORANGE6, lv3col7 = ORANGE7, lv3col8 = ORANGE8, lv3col9 = ORANGE9
lv3colA1 = ORANGEA1, lv3colA2 = ORANGEA2, lv3colA3 = ORANGEA3, lv3colA4 = ORANGEA4
///////////////////////////
//lv2col = DEEP_ORANGE
DEEP_ORANGE0 = #FBE9E7, DEEP_ORANGE1 = #FFCCBC, DEEP_ORANGE2 = #FFAB91, DEEP_ORANGE3 = #FF8A65, DEEP_ORANGE4 = #FF7043, DEEP_ORANGE5 = #FF5722, DEEP_ORANGE6 = #F4511E, DEEP_ORANGE7 = #E64A19, DEEP_ORANGE8 = #D84315, DEEP_ORANGE9 = #BF360C
DEEP_ORANGEA1 = #FF9E80, DEEP_ORANGEA2 = #FF6E40, DEEP_ORANGEA3 = #FF3D00, DEEP_ORANGEA4 = #DD2C00
lv2col0 = DEEP_ORANGE0, lv2col1 = DEEP_ORANGE1, lv2col2 = DEEP_ORANGE2, lv2col3 = DEEP_ORANGE3, lv2col4 = DEEP_ORANGE4, lv2col5 = DEEP_ORANGE5, lv2col6 = DEEP_ORANGE6, lv2col7 = DEEP_ORANGE7, lv2col8 = DEEP_ORANGE8, lv2col9 = DEEP_ORANGE9
lv2colA1 = DEEP_ORANGEA1, lv2colA2 = DEEP_ORANGEA2, lv2colA3 = DEEP_ORANGEA3, lv2colA4 = DEEP_ORANGEA4
///////////////////////////
//lv1col = RED
RED0 = #FFEBEE, RED1 = #FFCDD2, RED2 = #EF9A9A, RED3 = #E57373, RED4 = #EF5350, RED5 = #F44336, RED6 = #E53935, RED7 = #D32F2F, RED8 = #C62828, RED9 = #B71C1C
REDA1 = #FF8A80, REDA2 = #FF5252, REDA3 = #FF1744, REDA4 = #D50000
lv1col0 = RED0, lv1col1 = RED1, lv1col2 = RED2, lv1col3 = RED3, lv1col4 = RED4, lv1col5 = RED5, lv1col6 = RED6, lv1col7 = RED7, lv1col8 = RED8, lv1col9 = RED9
lv1colA1 = REDA1, lv1colA2 = REDA2, lv1colA3 = REDA3, lv1colA4 = REDA4
///////////////////////////
//BROWN
BROWN0 = #EFEBE9, BROWN1 = #D7CCC8, BROWN2 = #BCAAA4, BROWN3 = #A1887F, BROWN4 = #8D6E63, BROWN5 = #795548, BROWN6 = #6D4C41, BROWN7 = #5D4037, BROWN8 = #4E342E, BROWN9 = #3E2723
///////////////////////////
//GRAY
GRAY0 = #FAFAFA, GRAY1 = #F5F5F5, GRAY2 = #EEEEEE, GRAY3 = #E0E0E0, GRAY4 = #BDBDBD, GRAY5 = #9E9E9E, GRAY6 = #757575, GRAY7 = #616161, GRAY8 = #424242, GRAY9 = #212121
lv0col0 = GRAY0, lv0col1 = GRAY1, lv0col2 = GRAY2, lv0col3 = GRAY3, lv0col4 = GRAY4, lv0col5 = GRAY5, lv0col6 = GRAY6, lv0col7 = GRAY7, lv0col8 = GRAY8, lv0col9 = GRAY9
///////////////////////////
//BLUE_GRAY
BLUE_GRAY0 = #ECEFF1, BLUE_GRAY1 = #CFD8DC, BLUE_GRAY2 = #B0BEC5, BLUE_GRAY3 = #90A4AE, BLUE_GRAY4 = #78909C, BLUE_GRAY5 = #607D8B, BLUE_GRAY6 = #546E7A, BLUE_GRAY7 = #455A64, BLUE_GRAY8 = #37474F, BLUE_GRAY9 = #263238
///////////////////////////
//colormode = input(title='colormode (brightness(5):0~9 / fluorescence:10~13)', defval=5)
//trans = input(title='Transparency ', defval=20)
//
////////////////////////////////////////////////////////////
export lvcol(series int colormode, simple int Number,series float trans) =>
lv1col= colormode==0?lv1col0 : colormode==1?lv1col1 : colormode==2?lv1col2 : colormode==3?lv1col3 : colormode==4?lv1col4 : colormode==5?lv1col5 : colormode==6?lv1col6 : colormode==7?lv1col7 : colormode==8?lv1col8 : colormode==9?lv1col9 : colormode==10?lv1colA1 : colormode==11?lv1colA2 : colormode==12?lv1colA3 : colormode==13?lv1colA4 : na
lv2col= colormode==0?lv2col0 : colormode==1?lv2col1 : colormode==2?lv2col2 : colormode==3?lv2col3 : colormode==4?lv2col4 : colormode==5?lv2col5 : colormode==6?lv2col6 : colormode==7?lv2col7 : colormode==8?lv2col8 : colormode==9?lv2col9 : colormode==10?lv2colA1 : colormode==11?lv2colA2 : colormode==12?lv2colA3 : colormode==13?lv2colA4 : na
lv3col= colormode==0?lv3col0 : colormode==1?lv3col1 : colormode==2?lv3col2 : colormode==3?lv3col3 : colormode==4?lv3col4 : colormode==5?lv3col5 : colormode==6?lv3col6 : colormode==7?lv3col7 : colormode==8?lv3col8 : colormode==9?lv3col9 : colormode==10?lv3colA1 : colormode==11?lv3colA2 : colormode==12?lv3colA3 : colormode==13?lv3colA4 : na
lv4col= colormode==0?lv4col0 : colormode==1?lv4col1 : colormode==2?lv4col2 : colormode==3?lv4col3 : colormode==4?lv4col4 : colormode==5?lv4col5 : colormode==6?lv4col6 : colormode==7?lv4col7 : colormode==8?lv4col8 : colormode==9?lv4col9 : colormode==10?lv4colA1 : colormode==11?lv4colA2 : colormode==12?lv4colA3 : colormode==13?lv4colA4 : na
lv5col= colormode==0?lv5col0 : colormode==1?lv5col1 : colormode==2?lv5col2 : colormode==3?lv5col3 : colormode==4?lv5col4 : colormode==5?lv5col5 : colormode==6?lv5col6 : colormode==7?lv5col7 : colormode==8?lv5col8 : colormode==9?lv5col9 : colormode==10?lv5colA1 : colormode==11?lv5colA2 : colormode==12?lv5colA3 : colormode==13?lv5colA4 : na
lv6col= colormode==0?lv6col0 : colormode==1?lv6col1 : colormode==2?lv6col2 : colormode==3?lv6col3 : colormode==4?lv6col4 : colormode==5?lv6col5 : colormode==6?lv6col6 : colormode==7?lv6col7 : colormode==8?lv6col8 : colormode==9?lv6col9 : colormode==10?lv6colA1 : colormode==11?lv6colA2 : colormode==12?lv6colA3 : colormode==13?lv6colA4 : na
lv7col= colormode==0?lv7col0 : colormode==1?lv7col1 : colormode==2?lv7col2 : colormode==3?lv7col3 : colormode==4?lv7col4 : colormode==5?lv7col5 : colormode==6?lv7col6 : colormode==7?lv7col7 : colormode==8?lv7col8 : colormode==9?lv7col9 : colormode==10?lv7colA1 : colormode==11?lv7colA2 : colormode==12?lv7colA3 : colormode==13?lv7colA4 : na
lv8col= colormode==0?lv8col0 : colormode==1?lv8col1 : colormode==2?lv8col2 : colormode==3?lv8col3 : colormode==4?lv8col4 : colormode==5?lv8col5 : colormode==6?lv8col6 : colormode==7?lv8col7 : colormode==8?lv8col8 : colormode==9?lv8col9 : colormode==10?lv8colA1 : colormode==11?lv8colA2 : colormode==12?lv8colA3 : colormode==13?lv8colA4 : na
lv9col= colormode==0?lv9col0 : colormode==1?lv9col1 : colormode==2?lv9col2 : colormode==3?lv9col3 : colormode==4?lv9col4 : colormode==5?lv9col5 : colormode==6?lv9col6 : colormode==7?lv9col7 : colormode==8?lv9col8 : colormode==9?lv9col9 : colormode==10?lv9colA1 : colormode==11?lv9colA2 : colormode==12?lv9colA3 : colormode==13?lv9colA4 : na
lv10col= colormode==0?lv10col0 : colormode==1?lv10col1 : colormode==2?lv10col2 : colormode==3?lv10col3 : colormode==4?lv10col4 : colormode==5?lv10col5 : colormode==6?lv10col6 : colormode==7?lv10col7 : colormode==8?lv10col8 : colormode==9?lv10col9 : colormode==10?lv10colA1 : colormode==11?lv10colA2 : colormode==12?lv10colA3 : colormode==13?lv10colA4 : na
lv11col= colormode==0?lv11col0 : colormode==1?lv11col1 : colormode==2?lv11col2 : colormode==3?lv11col3 : colormode==4?lv11col4 : colormode==5?lv11col5 : colormode==6?lv11col6 : colormode==7?lv11col7 : colormode==8?lv11col8 : colormode==9?lv11col9 : colormode==10?lv11colA1 : colormode==11?lv11colA2 : colormode==12?lv11colA3 : colormode==13?lv11colA4 : na
lv12col= colormode==0?lv12col0 : colormode==1?lv12col1 : colormode==2?lv12col2 : colormode==3?lv12col3 : colormode==4?lv12col4 : colormode==5?lv12col5 : colormode==6?lv12col6 : colormode==7?lv12col7 : colormode==8?lv12col8 : colormode==9?lv12col9 : colormode==10?lv12colA1 : colormode==11?lv12colA2 : colormode==12?lv12colA3 : colormode==13?lv12colA4 : na
lv13col= colormode==0?lv13col0 : colormode==1?lv13col1 : colormode==2?lv13col2 : colormode==3?lv13col3 : colormode==4?lv13col4 : colormode==5?lv13col5 : colormode==6?lv13col6 : colormode==7?lv13col7 : colormode==8?lv13col8 : colormode==9?lv13col9 : colormode==10?lv13colA1 : colormode==11?lv13colA2 : colormode==12?lv13colA3 : colormode==13?lv13colA4 : na
lv14col= colormode==0?lv14col0 : colormode==1?lv14col1 : colormode==2?lv14col2 : colormode==3?lv14col3 : colormode==4?lv14col4 : colormode==5?lv14col5 : colormode==6?lv14col6 : colormode==7?lv14col7 : colormode==8?lv14col8 : colormode==9?lv14col9 : colormode==10?lv14colA1 : colormode==11?lv14colA2 : colormode==12?lv14colA3 : colormode==13?lv14colA4 : na
lv15col= colormode==0?lv15col0 : colormode==1?lv15col1 : colormode==2?lv15col2 : colormode==3?lv15col3 : colormode==4?lv15col4 : colormode==5?lv15col5 : colormode==6?lv15col6 : colormode==7?lv15col7 : colormode==8?lv15col8 : colormode==9?lv15col9 : colormode==10?lv15colA1 : colormode==11?lv15colA2 : colormode==12?lv15colA3 : colormode==13?lv15colA4 : na
lv16col= colormode==0?lv16col0 : colormode==1?lv16col1 : colormode==2?lv16col2 : colormode==3?lv16col3 : colormode==4?lv16col4 : colormode==5?lv16col5 : colormode==6?lv16col6 : colormode==7?lv16col7 : colormode==8?lv16col8 : colormode==9?lv16col9 : colormode==10?lv16colA1 : colormode==11?lv16colA2 : colormode==12?lv16colA3 : colormode==13?lv16colA4 : na
lv0col= colormode==0?lv0col0 : colormode==1?lv0col1 : colormode==2?lv0col2 : colormode==3?lv0col3 : colormode==4?lv0col4 : colormode==5?lv0col5 : colormode==6?lv0col6 : colormode==7?lv0col7 : colormode==8?lv0col8 : colormode==9?lv0col9 : na
switch Number
1 => color.new(lv1col,trans)
2 => color.new(lv2col,trans)
3 => color.new(lv3col,trans)
4 => color.new(lv4col,trans)
5 => color.new(lv5col,trans)
6 => color.new(lv6col,trans)
7 => color.new(lv7col,trans)
8 => color.new(lv8col,trans)
9 => color.new(lv9col,trans)
10 => color.new(lv10col,trans)
11 => color.new(lv11col,trans)
12 => color.new(lv12col,trans)
13 => color.new(lv13col,trans)
14 => color.new(lv14col,trans)
15 => color.new(lv15col,trans)
16 => color.new(lv16col,trans)
0 => color.new(lv10col,trans)
////////////////////////////////////////////////////////////
export lvcolA(series int colormode, simple int Number,series float trans) =>
lv1col= colormode==10?lv1colA1 : colormode==11?lv1colA2 : colormode==12?lv1colA3 : colormode==13?lv1colA4 : na
lv2col= colormode==10?lv2colA1 : colormode==11?lv2colA2 : colormode==12?lv2colA3 : colormode==13?lv2colA4 : na
lv3col= colormode==10?lv3colA1 : colormode==11?lv3colA2 : colormode==12?lv3colA3 : colormode==13?lv3colA4 : na
lv4col= colormode==10?lv4colA1 : colormode==11?lv4colA2 : colormode==12?lv4colA3 : colormode==13?lv4colA4 : na
lv5col= colormode==10?lv5colA1 : colormode==11?lv5colA2 : colormode==12?lv5colA3 : colormode==13?lv5colA4 : na
lv6col= colormode==10?lv6colA1 : colormode==11?lv6colA2 : colormode==12?lv6colA3 : colormode==13?lv6colA4 : na
lv7col= colormode==10?lv7colA1 : colormode==11?lv7colA2 : colormode==12?lv7colA3 : colormode==13?lv7colA4 : na
lv8col= colormode==10?lv8colA1 : colormode==11?lv8colA2 : colormode==12?lv8colA3 : colormode==13?lv8colA4 : na
lv9col= colormode==10?lv9colA1 : colormode==11?lv9colA2 : colormode==12?lv9colA3 : colormode==13?lv9colA4 : na
lv10col= colormode==10?lv10colA1 : colormode==11?lv10colA2 : colormode==12?lv10colA3 : colormode==13?lv10colA4 : na
lv11col= colormode==10?lv11colA1 : colormode==11?lv11colA2 : colormode==12?lv11colA3 : colormode==13?lv11colA4 : na
lv12col= colormode==10?lv12colA1 : colormode==11?lv12colA2 : colormode==12?lv12colA3 : colormode==13?lv12colA4 : na
lv13col= colormode==10?lv13colA1 : colormode==11?lv13colA2 : colormode==12?lv13colA3 : colormode==13?lv13colA4 : na
lv14col= colormode==10?lv14colA1 : colormode==11?lv14colA2 : colormode==12?lv14colA3 : colormode==13?lv14colA4 : na
lv15col= colormode==10?lv15colA1 : colormode==11?lv15colA2 : colormode==12?lv15colA3 : colormode==13?lv15colA4 : na
lv16col= colormode==10?lv16colA1 : colormode==11?lv16colA2 : colormode==12?lv16colA3 : colormode==13?lv16colA4 : na
switch Number
1 => color.new(lv1col,trans)
2 => color.new(lv2col,trans)
3 => color.new(lv3col,trans)
4 => color.new(lv4col,trans)
5 => color.new(lv5col,trans)
6 => color.new(lv6col,trans)
7 => color.new(lv7col,trans)
8 => color.new(lv8col,trans)
9 => color.new(lv9col,trans)
10 => color.new(lv10col,trans)
11 => color.new(lv11col,trans)
12 => color.new(lv12col,trans)
13 => color.new(lv13col,trans)
14 => color.new(lv14col,trans)
15 => color.new(lv15col,trans)
16 => color.new(lv16col,trans)
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
export lvcol2(series int colormode, simple string colorName,series float trans) =>
lv1col= colormode==0?lv1col0 : colormode==1?lv1col1 : colormode==2?lv1col2 : colormode==3?lv1col3 : colormode==4?lv1col4 : colormode==5?lv1col5 : colormode==6?lv1col6 : colormode==7?lv1col7 : colormode==8?lv1col8 : colormode==9?lv1col9 : colormode==10?lv1colA1 : colormode==11?lv1colA2 : colormode==12?lv1colA3 : colormode==13?lv1colA4 : na
lv2col= colormode==0?lv2col0 : colormode==1?lv2col1 : colormode==2?lv2col2 : colormode==3?lv2col3 : colormode==4?lv2col4 : colormode==5?lv2col5 : colormode==6?lv2col6 : colormode==7?lv2col7 : colormode==8?lv2col8 : colormode==9?lv2col9 : colormode==10?lv2colA1 : colormode==11?lv2colA2 : colormode==12?lv2colA3 : colormode==13?lv2colA4 : na
lv3col= colormode==0?lv3col0 : colormode==1?lv3col1 : colormode==2?lv3col2 : colormode==3?lv3col3 : colormode==4?lv3col4 : colormode==5?lv3col5 : colormode==6?lv3col6 : colormode==7?lv3col7 : colormode==8?lv3col8 : colormode==9?lv3col9 : colormode==10?lv3colA1 : colormode==11?lv3colA2 : colormode==12?lv3colA3 : colormode==13?lv3colA4 : na
lv4col= colormode==0?lv4col0 : colormode==1?lv4col1 : colormode==2?lv4col2 : colormode==3?lv4col3 : colormode==4?lv4col4 : colormode==5?lv4col5 : colormode==6?lv4col6 : colormode==7?lv4col7 : colormode==8?lv4col8 : colormode==9?lv4col9 : colormode==10?lv4colA1 : colormode==11?lv4colA2 : colormode==12?lv4colA3 : colormode==13?lv4colA4 : na
lv5col= colormode==0?lv5col0 : colormode==1?lv5col1 : colormode==2?lv5col2 : colormode==3?lv5col3 : colormode==4?lv5col4 : colormode==5?lv5col5 : colormode==6?lv5col6 : colormode==7?lv5col7 : colormode==8?lv5col8 : colormode==9?lv5col9 : colormode==10?lv5colA1 : colormode==11?lv5colA2 : colormode==12?lv5colA3 : colormode==13?lv5colA4 : na
lv6col= colormode==0?lv6col0 : colormode==1?lv6col1 : colormode==2?lv6col2 : colormode==3?lv6col3 : colormode==4?lv6col4 : colormode==5?lv6col5 : colormode==6?lv6col6 : colormode==7?lv6col7 : colormode==8?lv6col8 : colormode==9?lv6col9 : colormode==10?lv6colA1 : colormode==11?lv6colA2 : colormode==12?lv6colA3 : colormode==13?lv6colA4 : na
lv7col= colormode==0?lv7col0 : colormode==1?lv7col1 : colormode==2?lv7col2 : colormode==3?lv7col3 : colormode==4?lv7col4 : colormode==5?lv7col5 : colormode==6?lv7col6 : colormode==7?lv7col7 : colormode==8?lv7col8 : colormode==9?lv7col9 : colormode==10?lv7colA1 : colormode==11?lv7colA2 : colormode==12?lv7colA3 : colormode==13?lv7colA4 : na
lv8col= colormode==0?lv8col0 : colormode==1?lv8col1 : colormode==2?lv8col2 : colormode==3?lv8col3 : colormode==4?lv8col4 : colormode==5?lv8col5 : colormode==6?lv8col6 : colormode==7?lv8col7 : colormode==8?lv8col8 : colormode==9?lv8col9 : colormode==10?lv8colA1 : colormode==11?lv8colA2 : colormode==12?lv8colA3 : colormode==13?lv8colA4 : na
lv9col= colormode==0?lv9col0 : colormode==1?lv9col1 : colormode==2?lv9col2 : colormode==3?lv9col3 : colormode==4?lv9col4 : colormode==5?lv9col5 : colormode==6?lv9col6 : colormode==7?lv9col7 : colormode==8?lv9col8 : colormode==9?lv9col9 : colormode==10?lv9colA1 : colormode==11?lv9colA2 : colormode==12?lv9colA3 : colormode==13?lv9colA4 : na
lv10col= colormode==0?lv10col0 : colormode==1?lv10col1 : colormode==2?lv10col2 : colormode==3?lv10col3 : colormode==4?lv10col4 : colormode==5?lv10col5 : colormode==6?lv10col6 : colormode==7?lv10col7 : colormode==8?lv10col8 : colormode==9?lv10col9 : colormode==10?lv10colA1 : colormode==11?lv10colA2 : colormode==12?lv10colA3 : colormode==13?lv10colA4 : na
lv11col= colormode==0?lv11col0 : colormode==1?lv11col1 : colormode==2?lv11col2 : colormode==3?lv11col3 : colormode==4?lv11col4 : colormode==5?lv11col5 : colormode==6?lv11col6 : colormode==7?lv11col7 : colormode==8?lv11col8 : colormode==9?lv11col9 : colormode==10?lv11colA1 : colormode==11?lv11colA2 : colormode==12?lv11colA3 : colormode==13?lv11colA4 : na
lv12col= colormode==0?lv12col0 : colormode==1?lv12col1 : colormode==2?lv12col2 : colormode==3?lv12col3 : colormode==4?lv12col4 : colormode==5?lv12col5 : colormode==6?lv12col6 : colormode==7?lv12col7 : colormode==8?lv12col8 : colormode==9?lv12col9 : colormode==10?lv12colA1 : colormode==11?lv12colA2 : colormode==12?lv12colA3 : colormode==13?lv12colA4 : na
lv13col= colormode==0?lv13col0 : colormode==1?lv13col1 : colormode==2?lv13col2 : colormode==3?lv13col3 : colormode==4?lv13col4 : colormode==5?lv13col5 : colormode==6?lv13col6 : colormode==7?lv13col7 : colormode==8?lv13col8 : colormode==9?lv13col9 : colormode==10?lv13colA1 : colormode==11?lv13colA2 : colormode==12?lv13colA3 : colormode==13?lv13colA4 : na
lv14col= colormode==0?lv14col0 : colormode==1?lv14col1 : colormode==2?lv14col2 : colormode==3?lv14col3 : colormode==4?lv14col4 : colormode==5?lv14col5 : colormode==6?lv14col6 : colormode==7?lv14col7 : colormode==8?lv14col8 : colormode==9?lv14col9 : colormode==10?lv14colA1 : colormode==11?lv14colA2 : colormode==12?lv14colA3 : colormode==13?lv14colA4 : na
lv15col= colormode==0?lv15col0 : colormode==1?lv15col1 : colormode==2?lv15col2 : colormode==3?lv15col3 : colormode==4?lv15col4 : colormode==5?lv15col5 : colormode==6?lv15col6 : colormode==7?lv15col7 : colormode==8?lv15col8 : colormode==9?lv15col9 : colormode==10?lv15colA1 : colormode==11?lv15colA2 : colormode==12?lv15colA3 : colormode==13?lv15colA4 : na
lv16col= colormode==0?lv16col0 : colormode==1?lv16col1 : colormode==2?lv16col2 : colormode==3?lv16col3 : colormode==4?lv16col4 : colormode==5?lv16col5 : colormode==6?lv16col6 : colormode==7?lv16col7 : colormode==8?lv16col8 : colormode==9?lv16col9 : colormode==10?lv16colA1 : colormode==11?lv16colA2 : colormode==12?lv16colA3 : colormode==13?lv16colA4 : na
lv0col= colormode==0?lv0col0 : colormode==1?lv0col1 : colormode==2?lv0col2 : colormode==3?lv0col3 : colormode==4?lv0col4 : colormode==5?lv0col5 : colormode==6?lv0col6 : colormode==7?lv0col7 : colormode==8?lv0col8 : colormode==9?lv0col9 : na
switch colorName
'RED' => color.new(lv1col,trans)
'DEEP_ORANGE' => color.new(lv2col,trans)
'ORANGE' => color.new(lv3col,trans)
'AMBER' => color.new(lv4col,trans)
'YELLOW' => color.new(lv5col,trans)
'LIME' => color.new(lv6col,trans)
'LIGHT_GREEN' => color.new(lv7col,trans)
'GREEN' => color.new(lv8col,trans)
'TEAL' => color.new(lv9col,trans)
'CYAN' => color.new(lv10col,trans)
'LIGHT_BLUE' => color.new(lv11col,trans)
'BLUE' => color.new(lv12col,trans)
'INDIGO' => color.new(lv13col,trans)
'DEEP_PURPLE' => color.new(lv14col,trans)
'PURPLE' => color.new(lv15col,trans)
'PINK' => color.new(lv16col,trans)
'GRAY' => color.new(lv10col,trans)
////////////////////////////////////////////////////////////
export lvcol2A(series int colormode, simple string colorName,series float trans) =>
lv1col= colormode==10?lv1colA1 : colormode==11?lv1colA2 : colormode==12?lv1colA3 : colormode==13?lv1colA4 : na
lv2col= colormode==10?lv2colA1 : colormode==11?lv2colA2 : colormode==12?lv2colA3 : colormode==13?lv2colA4 : na
lv3col= colormode==10?lv3colA1 : colormode==11?lv3colA2 : colormode==12?lv3colA3 : colormode==13?lv3colA4 : na
lv4col= colormode==10?lv4colA1 : colormode==11?lv4colA2 : colormode==12?lv4colA3 : colormode==13?lv4colA4 : na
lv5col= colormode==10?lv5colA1 : colormode==11?lv5colA2 : colormode==12?lv5colA3 : colormode==13?lv5colA4 : na
lv6col= colormode==10?lv6colA1 : colormode==11?lv6colA2 : colormode==12?lv6colA3 : colormode==13?lv6colA4 : na
lv7col= colormode==10?lv7colA1 : colormode==11?lv7colA2 : colormode==12?lv7colA3 : colormode==13?lv7colA4 : na
lv8col= colormode==10?lv8colA1 : colormode==11?lv8colA2 : colormode==12?lv8colA3 : colormode==13?lv8colA4 : na
lv9col= colormode==10?lv9colA1 : colormode==11?lv9colA2 : colormode==12?lv9colA3 : colormode==13?lv9colA4 : na
lv10col= colormode==10?lv10colA1 : colormode==11?lv10colA2 : colormode==12?lv10colA3 : colormode==13?lv10colA4 : na
lv11col= colormode==10?lv11colA1 : colormode==11?lv11colA2 : colormode==12?lv11colA3 : colormode==13?lv11colA4 : na
lv12col= colormode==10?lv12colA1 : colormode==11?lv12colA2 : colormode==12?lv12colA3 : colormode==13?lv12colA4 : na
lv13col= colormode==10?lv13colA1 : colormode==11?lv13colA2 : colormode==12?lv13colA3 : colormode==13?lv13colA4 : na
lv14col= colormode==10?lv14colA1 : colormode==11?lv14colA2 : colormode==12?lv14colA3 : colormode==13?lv14colA4 : na
lv15col= colormode==10?lv15colA1 : colormode==11?lv15colA2 : colormode==12?lv15colA3 : colormode==13?lv15colA4 : na
lv16col= colormode==10?lv16colA1 : colormode==11?lv16colA2 : colormode==12?lv16colA3 : colormode==13?lv16colA4 : na
switch colorName
'RED' => color.new(lv1col,trans)
'DEEP_ORANGE' => color.new(lv2col,trans)
'ORANGE' => color.new(lv3col,trans)
'AMBER' => color.new(lv4col,trans)
'YELLOW' => color.new(lv5col,trans)
'LIME' => color.new(lv6col,trans)
'LIGHT_GREEN' => color.new(lv7col,trans)
'GREEN' => color.new(lv8col,trans)
'TEAL' => color.new(lv9col,trans)
'CYAN' => color.new(lv10col,trans)
'LIGHT_BLUE' => color.new(lv11col,trans)
'BLUE' => color.new(lv12col,trans)
'INDIGO' => color.new(lv13col,trans)
'DEEP_PURPLE' => color.new(lv14col,trans)
'PURPLE' => color.new(lv15col,trans)
'PINK' => color.new(lv16col,trans)
////////////////////////////////////////////////////////////
|
Subsets and Splits