TimeframeComparisonLibrary "TimeframeComparison"
Timeframe comparison for higher and lower timeframe
█ OVERVIEW
This library is used to compare higher / lower timeframe by using timeframe.multiplier.
minMult()
timeframe multiplier in minutes
Returns: float value
Wskaźniki i strategie
arraysLibrary "arraymethods"
Supplementary array methods.
delete(arr, index)
remove int object from array of integers at specific index
Parameters:
arr : int array
index : index at which int object need to be removed
Returns: void
delete(arr, index)
remove float object from array of float at specific index
Parameters:
arr : float array
index : index at which float object need to be removed
Returns: float
delete(arr, index)
remove bool object from array of bool at specific index
Parameters:
arr : bool array
index : index at which bool object need to be removed
Returns: bool
delete(arr, index)
remove string object from array of string at specific index
Parameters:
arr : string array
index : index at which string object need to be removed
Returns: string
delete(arr, index)
remove color object from array of color at specific index
Parameters:
arr : color array
index : index at which color object need to be removed
Returns: color
delete(arr, index)
remove line object from array of lines at specific index and deletes the line
Parameters:
arr : line array
index : index at which line object need to be removed and deleted
Returns: void
delete(arr, index)
remove label object from array of labels at specific index and deletes the label
Parameters:
arr : label array
index : index at which label object need to be removed and deleted
Returns: void
delete(arr, index)
remove box object from array of boxes at specific index and deletes the box
Parameters:
arr : box array
index : index at which box object need to be removed and deleted
Returns: void
delete(arr, index)
remove table object from array of tables at specific index and deletes the table
Parameters:
arr : table array
index : index at which table object need to be removed and deleted
Returns: void
delete(arr, index)
remove linefill object from array of linefills at specific index and deletes the linefill
Parameters:
arr : linefill array
index : index at which linefill object need to be removed and deleted
Returns: void
popr(arr)
remove last int object from array
Parameters:
arr : int array
Returns: int
popr(arr)
remove last float object from array
Parameters:
arr : float array
Returns: float
popr(arr)
remove last bool object from array
Parameters:
arr : bool array
Returns: bool
popr(arr)
remove last string object from array
Parameters:
arr : string array
Returns: string
popr(arr)
remove last color object from array
Parameters:
arr : color array
Returns: color
popr(arr)
remove and delete last line object from array
Parameters:
arr : line array
Returns: void
popr(arr)
remove and delete last label object from array
Parameters:
arr : label array
Returns: void
popr(arr)
remove and delete last box object from array
Parameters:
arr : box array
Returns: void
popr(arr)
remove and delete last table object from array
Parameters:
arr : table array
Returns: void
popr(arr)
remove and delete last linefill object from array
Parameters:
arr : linefill array
Returns: void
shiftr(arr)
remove first int object from array
Parameters:
arr : int array
Returns: int
shiftr(arr)
remove first float object from array
Parameters:
arr : float array
Returns: float
shiftr(arr)
remove first bool object from array
Parameters:
arr : bool array
Returns: bool
shiftr(arr)
remove first string object from array
Parameters:
arr : string array
Returns: string
shiftr(arr)
remove first color object from array
Parameters:
arr : color array
Returns: color
shiftr(arr)
remove and delete first line object from array
Parameters:
arr : line array
Returns: void
shiftr(arr)
remove and delete first label object from array
Parameters:
arr : label array
Returns: void
shiftr(arr)
remove and delete first box object from array
Parameters:
arr : box array
Returns: void
shiftr(arr)
remove and delete first table object from array
Parameters:
arr : table array
Returns: void
shiftr(arr)
remove and delete first linefill object from array
Parameters:
arr : linefill array
Returns: void
push(arr, val, maxItems)
add int to the end of an array with max items cap. Objects are removed from start to maintain max items cap
Parameters:
arr : int array
val : int object to be pushed
maxItems : max number of items array can hold
Returns: int
push(arr, val, maxItems)
add float to the end of an array with max items cap. Objects are removed from start to maintain max items cap
Parameters:
arr : float array
val : float object to be pushed
maxItems : max number of items array can hold
Returns: float
push(arr, val, maxItems)
add bool to the end of an array with max items cap. Objects are removed from start to maintain max items cap
Parameters:
arr : bool array
val : bool object to be pushed
maxItems : max number of items array can hold
Returns: bool
push(arr, val, maxItems)
add string to the end of an array with max items cap. Objects are removed from start to maintain max items cap
Parameters:
arr : string array
val : string object to be pushed
maxItems : max number of items array can hold
Returns: string
push(arr, val, maxItems)
add color to the end of an array with max items cap. Objects are removed from start to maintain max items cap
Parameters:
arr : color array
val : color object to be pushed
maxItems : max number of items array can hold
Returns: color
push(arr, val, maxItems)
add line to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap
Parameters:
arr : line array
val : line object to be pushed
maxItems : max number of items array can hold
Returns: line
push(arr, val, maxItems)
add label to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap
Parameters:
arr : label array
val : label object to be pushed
maxItems : max number of items array can hold
Returns: label
push(arr, val, maxItems)
add box to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap
Parameters:
arr : box array
val : box object to be pushed
maxItems : max number of items array can hold
Returns: box
push(arr, val, maxItems)
add table to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap
Parameters:
arr : table array
val : table object to be pushed
maxItems : max number of items array can hold
Returns: table
push(arr, val, maxItems)
add linefill to the end of an array with max items cap. Objects are removed and deleted from start to maintain max items cap
Parameters:
arr : linefill array
val : linefill object to be pushed
maxItems : max number of items array can hold
Returns: linefill
unshift(arr, val, maxItems)
add int to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap
Parameters:
arr : int array
val : int object to be unshift
maxItems : max number of items array can hold
Returns: int
unshift(arr, val, maxItems)
add float to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap
Parameters:
arr : float array
val : float object to be unshift
maxItems : max number of items array can hold
Returns: float
unshift(arr, val, maxItems)
add bool to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap
Parameters:
arr : bool array
val : bool object to be unshift
maxItems : max number of items array can hold
Returns: bool
unshift(arr, val, maxItems)
add string to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap
Parameters:
arr : string array
val : string object to be unshift
maxItems : max number of items array can hold
Returns: string
unshift(arr, val, maxItems)
add color to the beginning of an array with max items cap. Objects are removed from end to maintain max items cap
Parameters:
arr : color array
val : color object to be unshift
maxItems : max number of items array can hold
Returns: color
unshift(arr, val, maxItems)
add line to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap
Parameters:
arr : line array
val : line object to be unshift
maxItems : max number of items array can hold
Returns: line
unshift(arr, val, maxItems)
add label to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap
Parameters:
arr : label array
val : label object to be unshift
maxItems : max number of items array can hold
Returns: label
unshift(arr, val, maxItems)
add box to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap
Parameters:
arr : box array
val : box object to be unshift
maxItems : max number of items array can hold
Returns: box
unshift(arr, val, maxItems)
add table to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap
Parameters:
arr : table array
val : table object to be unshift
maxItems : max number of items array can hold
Returns: table
unshift(arr, val, maxItems)
add linefill to the beginning of an array with max items cap. Objects are removed and deleted from end to maintain max items cap
Parameters:
arr : linefill array
val : linefill object to be unshift
maxItems : max number of items array can hold
Returns: linefill
flush(arr)
remove all int objects in an array
Parameters:
arr : int array
Returns: int
flush(arr)
remove all float objects in an array
Parameters:
arr : float array
Returns: float
flush(arr)
remove all bool objects in an array
Parameters:
arr : bool array
Returns: bool
flush(arr)
remove all string objects in an array
Parameters:
arr : string array
Returns: string
flush(arr)
remove all color objects in an array
Parameters:
arr : color array
Returns: color
flush(arr)
remove and delete all line objects in an array
Parameters:
arr : line array
Returns: line
flush(arr)
remove and delete all label objects in an array
Parameters:
arr : label array
Returns: label
flush(arr)
remove and delete all box objects in an array
Parameters:
arr : box array
Returns: box
flush(arr)
remove and delete all table objects in an array
Parameters:
arr : table array
Returns: table
flush(arr)
remove and delete all linefill objects in an array
Parameters:
arr : linefill array
Returns: linefill
ZigzagLibrary "Zigzag"
Zigzag related user defined types. Depends on DrawingTypes library for basic types
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Pivot object to string representation
Namespace types: Pivot
Parameters:
this (Pivot) : ZigzagTypes/Pivot
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Pivot
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts Array of Pivot objects to string representation
Namespace types: Pivot
Parameters:
this (Pivot ) : Pivot object array
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of Pivot object array
method tostring(this)
Converts ZigzagFlags object to string representation
Namespace types: ZigzagFlags
Parameters:
this (ZigzagFlags) : ZigzagFlags object
Returns: string representation of ZigzagFlags
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts ZigzagTypes/Zigzag object to string representation
Namespace types: Zigzag
Parameters:
this (Zigzag) : ZigzagTypes/Zigzagobject
sortKeys (bool) : If set to true, string output is sorted by keys.
sortOrder (int) : Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
includeKeys (string ) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of ZigzagTypes/Zigzag
method calculate(this, ohlc, indicators, indicatorNames)
Calculate zigzag based on input values and indicator values
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
ohlc (float ) : Array containing OHLC values. Can also have custom values for which zigzag to be calculated
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns: current Zigzag object
method calculate(this)
Calculate zigzag based on properties embedded within Zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: current Zigzag object
method nextlevel(this)
Calculate Next Level Zigzag based on the current calculated zigzag object
Namespace types: Zigzag
Parameters:
this (Zigzag) : Zigzag object
Returns: Next Level Zigzag object
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing ) : array
Returns: void
method drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
Returns: ZigzagDrawing object
method drawfresh(this, ohlc, indicators, indicatorNames)
draws fresh zigzag based on properties embedded in ZigzagDrawing object
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns: ZigzagDrawing object
method drawcontinuous(this, ohlc, indicators, indicatorNames)
draws zigzag based on the zigzagmatrix input
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing) : ZigzagDrawing object
ohlc (float ) : values on which the zigzag needs to be calculated and drawn. If not set will use regular OHLC
indicators (matrix) : Array of indicator values
indicatorNames (string ) : Array of indicator names for which values are present. Size of indicators array should be equal to that of indicatorNames
Returns:
method getPrices(pivots)
Namespace types: Pivot
Parameters:
pivots (Pivot )
method getBars(pivots)
Namespace types: Pivot
Parameters:
pivots (Pivot )
Indicator
Indicator is collection of indicator values applied on high, low and close
Fields:
indicatorHigh (series float) : Indicator Value applied on High
indicatorLow (series float) : Indicator Value applied on Low
PivotCandle
PivotCandle represents data of the candle which forms either pivot High or pivot low or both
Fields:
_high (series float) : High price of candle forming the pivot
_low (series float) : Low price of candle forming the pivot
length (series int) : Pivot length
pHighBar (series int) : represents number of bar back the pivot High occurred.
pLowBar (series int) : represents number of bar back the pivot Low occurred.
pHigh (series float) : Pivot High Price
pLow (series float) : Pivot Low Price
indicators (Indicator ) : Array of Indicators - allows to add multiple
Pivot
Pivot refers to zigzag pivot. Each pivot can contain various data
Fields:
point (chart.point) : pivot point coordinates
dir (series int) : direction of the pivot. Valid values are 1, -1, 2, -2
level (series int) : is used for multi level zigzags. For single level, it will always be 0
componentIndex (series int) : is the lower level zigzag array index for given pivot. Used only in multi level Zigzag Pivots
subComponents (series int) : is the number of sub waves per each zigzag wave. Only applicable for multi level zigzags
microComponents (series int) : is the number of base zigzag components in a zigzag wave
ratio (series float) : Price Ratio based on previous two pivots
sizeRatio (series float)
subPivots (Pivot )
indicatorNames (string ) : Names of the indicators applied on zigzag
indicatorValues (float ) : Values of the indicators applied on zigzag
indicatorRatios (float ) : Ratios of the indicators applied on zigzag based on previous 2 pivots
ZigzagFlags
Flags required for drawing zigzag. Only used internally in zigzag calculation. Should not set the values explicitly
Fields:
newPivot (series bool) : true if the calculation resulted in new pivot
doublePivot (series bool) : true if the calculation resulted in two pivots on same bar
updateLastPivot (series bool) : true if new pivot calculated replaces the old one.
Zigzag
Zigzag object which contains whole zigzag calculation parameters and pivots
Fields:
length (series int) : Zigzag length. Default value is 5
numberOfPivots (series int) : max number of pivots to hold in the calculation. Default value is 20
offset (series int) : Bar offset to be considered for calculation of zigzag. Default is 0 - which means calculation is done based on the latest bar.
level (series int) : Zigzag calculation level - used in multi level recursive zigzags
zigzagPivots (Pivot ) : array which holds the last n pivots calculated.
flags (ZigzagFlags) : ZigzagFlags object which is required for continuous drawing of zigzag lines.
ZigzagObject
Zigzag Drawing Object
Fields:
zigzagLine (series line) : Line joining two pivots
zigzagLabel (series label) : Label which can be used for drawing the values, ratios, directions etc.
ZigzagProperties
Object which holds properties of zigzag drawing. To be used along with ZigzagDrawing
Fields:
lineColor (series color) : Zigzag line color. Default is color.blue
lineWidth (series int) : Zigzag line width. Default is 1
lineStyle (series string) : Zigzag line style. Default is line.style_solid.
showLabel (series bool) : If set, the drawing will show labels on each pivot. Default is false
textColor (series color) : Text color of the labels. Only applicable if showLabel is set to true.
maxObjects (series int) : Max number of zigzag lines to display. Default is 300
xloc (series string) : Time/Bar reference to be used for zigzag drawing. Default is Time - xloc.bar_time.
ZigzagDrawing
Object which holds complete zigzag drawing objects and properties.
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
drawings (ZigzagObject ) : array which contains lines and labels of zigzag drawing.
ColorPalettesThis is my first public (and I hope not the last) library providing different color palettes used for data visualization. Each palette can contain either 3 to 9 colors or 3 to 11 colors.
So there you go. Happy New Year!
I want your new year to be as colorful, vibrant and rich as these color palettes.
Dedicated to @veryfid . RIP, dude.
---
Library "ColorPalettes"
A library of various color palettes for data visualization
Reds(n)
A function to generate the sequential `Reds` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Reds` palette.
Blues(n)
A function to generate the sequential `Blues` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Blues` palette.
Greens(n)
A function to generate the sequential `Greens` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Greens` palette.
Purples(n)
A function to generate the sequential `Purples` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Purples` palette.
Oranges(n)
A function to generate the sequential `Oranges` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Oranges` palette.
Greys(n)
A function to generate the sequential `Greys` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Greys` palette.
YlGn(n)
A function to generate the sequential `YlGn` (Yellow/Green) palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `YlGn` palette.
YlGnBu(n)
A function to generate the sequential `YlGnBu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `YlGnBu` palette.
GnBu(n)
A function to generate the sequential `GnBu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `GnBu` palette.
BuGn(n)
A function to generate the sequential `BuGn` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `BuGn` palette.
PuBuGn(n)
A function to generate the sequential `PuBuGn` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PuBuGn` palette.
PuBu(n)
A function to generate the sequential `PuBu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PuBu` palette.
BuPu(n)
A function to generate the sequential `BuPu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `BuPu` palette.
RdPu(n)
A function to generate the sequential `RdPu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `RdPu` palette.
PuRd(n)
A function to generate the sequential `PuRd` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PuRd` palette.
OrRd(n)
A function to generate the sequential `OrRd` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `OrRd` palette.
YlOrRd(n)
A function to generate the sequential `YlOrRd` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `YlOrRd` palette.
YlOrBr(n)
A function to generate the sequential `YlOrBr` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `YlOrBr` palette.
Inferno(n)
A function to generate the sequential `Inferno` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Inferno` palette.
Magma(n)
A function to generate the sequential `Magma` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Magma` palette.
Plasma(n)
A function to generate the sequential `Plasma` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Plasma` palette.
Viridis(n)
A function to generate the sequential `Viridis` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Viridis` palette.
Cividis(n)
A function to generate the sequential `Cividis` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Cividis` palette.
Spectral(n)
A function to generate the diverging `Spectral` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Spectral` palette.
Turbo(n)
A function to generate the diverging `Turbo` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `Turbo` palette.
BrBG(n)
A function to generate the diverging `BrBG` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `BrBG` palette.
PiYG(n)
A function to generate the diverging `PiYG` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PiYG` palette.
PRGn(n)
A function to generate the diverging `PRGn` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PRGn` palette.
PuOr(n)
A function to generate the diverging `PuOr` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `PuOr` palette.
RdBu(n)
A function to generate the diverging `RdBu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `RdBu` palette.
RdGy(n)
A function to generate the diverging `RdGy` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `RdGy` palette.
RdYlBu(n)
A function to generate the diverging `RdYlBu` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `RdYlBu` palette.
RdYlGn(n)
A function to generate the diverging `RdYlGn` palette of the specified size.
Parameters:
n (int) The size of the output palette to generate. Default is 9.
Returns: An array of colors from the `RdYlGn` palette.
chrono_utilsLibrary "chrono_utils"
Collection of objects and common functions that are related to datetime windows session days and time
ranges. The main purpose of this library is to handle time-related functionality and make it easy to reason about a
future bar and see if it is part of a predefined user session and/or inside a datetime window. All existing session
functions I found in the documentation e.g. "not na(time(timeframe, session, timezone))" are not suitable for
strategies, since the execution of the orders is delayed by one bar due to the execution happening at the bar close.
So a prediction for the next bar is necessary. Moreover, a history operator with a negative value is not allowed e.g.
`not na(time(timeframe, session, timezone) )` expression is not valid. Thus, I created this library to overcome
this small but very important limitation. In the meantime, I added useful functionality to handle session-based
behavior. An interesting utility that emerged from this development is data anomaly detection where a comparison
between the prediction and the actual value is happening. If those two values are different then a data inconsistency
happens between the prediction bar and the actual bar (probably due to a holiday or half session day etc..)
exTimezone(timezone)
exTimezone - Convert extended timezone to timezone string
Parameters:
timezone (simple string) : - The timezone or a special string
Returns: string representing the timezone
nameOfDay(day)
nameOfDay - Convert the day id into a short nameOfDay
Parameters:
day (int) : - The day id to convert
Returns: - The short name of the day
today()
today - Get the day id of this day
Returns: - The day id
nthDayAfter(day, n)
nthDayAfter - Get the day id of n days after the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days after the reference day
nextDayAfter(day)
nextDayAfter - Get the day id of next day after the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the next day after the reference day
nthDayBefore(day, n)
nthDayBefore - Get the day id of n days before the given day
Parameters:
day (int) : - The day id of the reference day
n (int) : - The number of days to go forward
Returns: - The day id of the day that is n days before the reference day
prevDayBefore(day)
prevDayBefore - Get the day id of previous day before the given day
Parameters:
day (int) : - The day id of the reference day
Returns: - The day id of the previous day before the reference day
tomorrow()
tomorrow - Get the day id of the next day
Returns: - The next day day id
normalize(num, min, max)
normalizeHour - Check if number is inthe range of
Parameters:
num (int)
min (int)
max (int)
Returns: - The normalized number
normalizeHour(hourInDay)
normalizeHour - Check if hour is valid and return a noralized hour range from
Parameters:
hourInDay (int)
Returns: - The normalized hour
normalizeMinute(minuteInHour)
normalizeMinute - Check if minute is valid and return a noralized minute from
Parameters:
minuteInHour (int)
Returns: - The normalized minute
monthInMilliseconds(mon)
monthInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Parameters:
mon (int) : - The month of reference to get the miliseconds
Returns: - The number of milliseconds of the month
barInMilliseconds()
barInMilliseconds - Calculate the miliseconds in one bar of the timeframe
Returns: - The number of milliseconds in one bar
method init(this, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, refTimezone, chTimezone, fromDateTime, toDateTime)
init - Initialize the time window object from boolean values of each session day
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object that will hold the from and to datetimes
refTimezone (simple string) : - The timezone of reference of the 'from' and 'to' dates
chTimezone (simple string) : - The target timezone to convert the 'from' and 'to' dates
fromDateTime (int) : - The starting datetime of the time window
toDateTime (int) : - The ending datetime of the time window
Returns: - The time window object
method init(this, sun, mon, tue, wed, thu, fri, sat)
init - Initialize the session days object from boolean values of each session day
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sun (bool) : - Is Sunday a trading day?
mon (bool) : - Is Monday a trading day?
tue (bool) : - Is Tuesday a trading day?
wed (bool) : - Is Wednesday a trading day?
thu (bool) : - Is Thursday a trading day?
fri (bool) : - Is Friday a trading day?
sat (bool) : - Is Saturday a trading day?
Returns: - The session days objectfrom_chart
method init(this, unixTime)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
unixTime (int) : - The unix time
Returns: - The session time object
method init(this, hourInDay, minuteInHour)
init - Initialize the object from the hour and minute of the session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
Returns: - The session time object
method init(this, hourInDay, minuteInHour, refTimezone)
init - Initialize the object from the hour and minute of the session time
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
hourInDay (int) : - The hour of the time
minuteInHour (int) : - The minute of the time
refTimezone (string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method init(this, startTime, endTime)
init - Initialize the object from the start and end session time in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTime (SessionTime) : - The time the session begins
endTime (SessionTime) : - The time the session ends
Returns: - The session time range object
method init(this, startTimeHour, startTimeMinute, endTimeHour, endTimeMinute, refTimezone)
init - Initialize the object from the start and end session time
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
startTimeHour (int) : - The time hour the session begins
startTimeMinute (int) : - The time minute the session begins
endTimeHour (int) : - The time hour the session ends
endTimeMinute (int) : - The time minute the session ends
refTimezone (string)
Returns: - The session time range object
method init(this, days, timeRanges)
init - Initialize the user session object from session days and time range
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
days (SessionDays) : - The session days object that defines the days the session is happening
timeRanges (SessionTimeRange ) : - The array of all the session time ranges during a session day
Returns: - The user session object
method to_string(this)
to_string - Formats the time window into a human-readable string
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The string of the time window
method to_string(this)
to_string - Formats the session days into a human-readable string with short day names
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The string of the session day short names
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_string(this)
to_string - Formats the session time into a human-readable string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_string(this)
to_string - Formats the user session into a human-readable string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - The string of the user session
method to_string(this)
to_string - Formats the bar into a human-readable string
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The string of the bar times
method to_string(this)
to_string - Formats the chart session into a human-readable string
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
Returns: - The string of the chart session
method get_size_in_secs(this)
get_size_in_secs - Count the seconds from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of seconds inside the time widow for the given timeframe
method get_size_in_secs(this)
get_size_in_secs - Calculate the seconds inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of seconds inside the session
method get_size_in_bars(this)
get_size_in_bars - Count the bars from start to end in the given timeframe
Namespace types: DateTimeWindow
Parameters:
this (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - The number of bars inside the time widow for the given timeframe
method get_size_in_bars(this)
get_size_in_bars - Calculate the bars inside the session
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The number of bars inside the session for the given timeframe
method from_chart(this)
from_chart - Initialize the session days object from the chart
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
Returns: - The user session object
method from_chart(this)
from_chart - Initialize the session time range object from the chart
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
Returns: - The session time range object
method from_chart(this)
from_chart - Initialize the session object from the chart
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that will hold the days and the time range shown in the chart
Returns: - The chart session object
method to_sess_string(this)
to_sess_string - Formats the session days into a session string with day ids
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object
Returns: - The string of the session day ids
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the session time into a session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - The string of the session time
method to_sess_string(this)
to_sess_string - Formats the user session into a session string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - The string of the user session
method to_sess_string(this)
to_sess_string - Formats the chart session into a session string
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
Returns: - The string of the chart session
method from_sess_string(this, sess)
from_sess_string - Initialize the session days object from the session string
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object that will hold the day selection
sess (string) : - The session string part that represents the days
Returns: - The session days object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
Returns: - The session time object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time object from the session string
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object that will hold the hour and minute of the time
sess (string) : - The session string part that represents the time HHmm
refTimezone (simple string) : - The timezone of reference of the 'hour' and 'minute'
Returns: - The session time object
method from_sess_string(this, sess)
from_sess_string - Initialize the session time range object from the session string in exchange timezone (syminfo.timezone)
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the session time range object from the session string
Namespace types: SessionTimeRange
Parameters:
this (SessionTimeRange) : - The session time range object that will hold the start and end time of the daily session
sess (string) : - The session string part that represents the time range HHmm-HHmm
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method from_sess_string(this, sess)
from_sess_string - Initialize the user session object from the session string in exchange timezone (syminfo.timezone)
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
sess (string) : - The session string that represents the user session HHmm-HHmm,HHmm-HHmm:ddddddd
Returns: - The session time range object
method from_sess_string(this, sess, refTimezone)
from_sess_string - Initialize the user session object from the session string
Namespace types: UserSession
Parameters:
this (UserSession) : - The user-defined session object that will hold the day and the time range selection
sess (string) : - The session string that represents the user session HHmm-HHmm,HHmm-HHmm:ddddddd
refTimezone (simple string) : - The timezone of reference of the time ranges
Returns: - The session time range object
method nth_day_after(this, day, n)
nth_day_after - The nth day after the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week after the given day
method nth_day_before(this, day, n)
nth_day_before - The nth day before the given day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
day (int) : - The day id of the reference day
n (int) : - The number of days after
Returns: - The day id of the nth session day of the week before the given day
method next_day(this)
next_day - The next day that is a session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the next session day of the week
method previous_day(this)
previous_day - The previous day that is session day (true) in the object
Namespace types: SessionDays
Parameters:
this (SessionDays) : - The session days object with the day selection
Returns: - The day id of the previous session day of the week
method get_sec_in_day(this)
get_sec_in_day - Count the seconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of seconds passed from the start of the day until that session time
method get_ms_in_day(this)
get_ms_in_day - Count the milliseconds since the start of the day this session time represents
Namespace types: SessionTime
Parameters:
this (SessionTime) : - The session time object with the hour and minute of the time of the day
Returns: - The number of milliseconds passed from the start of the day until that session time
method eq(this, other)
eq - Compare two bars
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
other (Bar) : - The bar object to compare with
Returns: - Whether this bar is equal to the other one
method get_open_time(this)
get_open_time - The open time object
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The open time object
method get_close_time(this)
get_close_time - The close time object
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The close time object
method get_time_range(this)
get_time_range - Get the time range of the bar
Namespace types: Bar
Parameters:
this (Bar) : - The bar object with the open and close times
Returns: - The time range that the bar is in
getBarNow()
getBarNow - Get the current bar object with time and time_close timestamps
Returns: - The current bar
getFixedBarNow()
getFixedBarNow - Get the current bar with fixed width defined by the timeframe. Note: There are case like SPX 15min timeframe where the last session bar is only 10min. This will return a bar of 15 minutes
Returns: - The current bar
method is_in_window(this, win)
is_in_window - Check if the given bar is between the start and end dates of the window
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes of the window
win (DateTimeWindow) : - The time window object with the from and to datetimes
Returns: - Whether the current bar is inside the datetime window
method is_in_timerange(this, rng)
is_in_timerange - Check if the given bar is inside the session time range
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes
rng (SessionTimeRange) : - The session time range object with the start and end time of the daily session
Returns: - Whether the bar is inside the session time range and if this part of the next trading day
method is_in_days(this, days)
is_in_days - Check if the given bar is inside the session days
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if its day is a trading day
days (SessionDays) : - The session days object with the day selection
Returns: - Whether the current bar day is inside the session
method is_in_session(this, sess)
is_in_session - Check if the given bar is inside the session as defined by the input params (what "not na(time(timeframe.period, this.to_sess_string()) )" should return if you could write it
Namespace types: Bar
Parameters:
this (Bar) : - The bar to check if it is between the from and to datetimes
sess (UserSession) : - The user-defined session object with the day and the time range selection
Returns: - Whether the current time is inside the session
method next_bar(this, offsetBars)
next_bar - Predicts the next bars open and close time based on the charts session
Namespace types: ChartSession
Parameters:
this (ChartSession) : - The chart session object that contains the days and the time range shown in the chart
offsetBars (simple int) : - The number of bars forward
Returns: - Whether the current time is inside the session
DateTimeWindow
DateTimeWindow - Object that represents a datetime window with a beginning and an end
Fields:
fromDateTime (series int) : - The beginning of the datetime window
toDateTime (series int) : - The end of the datetime window
SessionDays
SessionDays - Object that represent the trading days of the week
Fields:
days (map) : - The map that contains all days of the week and their session flag
SessionTime
SessionTime - Object that represents the time (hour and minutes)
Fields:
hourInDay (series int) : - The hour of the day that ranges from 0 to 24
minuteInHour (series int) : - The minute of the hour that ranges from 0 to 59
minuteInDay (series int) : - The minute of the day that ranges from 0 to 1440. They will be calculated based on hourInDay and minuteInHour when method is called
SessionTimeRange
SessionTimeRange - Object that represents a range that extends from the start to the end time
Fields:
startTime (SessionTime) : - The beginning of the time range
endTime (SessionTime) : - The end of the time range
isOvernight (series bool) : - Whether or not this is an overnight time range
UserSession
UserSession - Object that represents a user-defined session
Fields:
days (SessionDays) : - The map of the user-defined trading days
timeRanges (SessionTimeRange ) : - The array with all time ranges of the user-defined session during the trading days
Bar
Bar - Object that represents the bars' open and close times
Fields:
openUnixTime (series int) : - The open time of the bar
closeUnixTime (series int) : - The close time of the bar
chartDayOfWeek (series int)
ChartSession
ChartSession - Object that represents the default session that is shown in the chart
Fields:
days (SessionDays) : - A map with the trading days shown in the chart
timeRange (SessionTimeRange) : - The time range of the session during a trading day
isFinalized (series bool)
TTB_TableBuilderLibrary "TTB_TableBuilder"
A helper library to make it simpler to create tables in pinescript
DefaultDarkStyle()
method Size(this, width, height)
Change the size (width, height) of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
width (int)
height (int)
Returns: Cell
method Size(this, width, height)
Change the width of all cells in that row
Namespace types: Row
Parameters:
this (Row)
width (int)
height (int)
Returns: Row
method Width(this, width)
Change the width of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
width (int)
Returns: Cell
method Width(this, width)
Change the width of all cells in that row
Namespace types: Row
Parameters:
this (Row)
width (int)
Returns: Row
method Height(this, height)
Change the height of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
height (int)
Returns: Cell
method Height(this, height)
Change the height of all cells in that row
Namespace types: Row
Parameters:
this (Row)
height (int)
Returns: Row
method Text(this, text_)
Change the text of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
text_ (string)
Returns: Cell
method Text(this, c0, c1, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29)
Set text
Namespace types: Row
Parameters:
this (Row)
c0 (string) : ... c29
c1 (string)
c3 (string)
c4 (string)
c5 (string)
c6 (string)
c7 (string)
c8 (string)
c9 (string)
c10 (string)
c11 (string)
c12 (string)
c13 (string)
c14 (string)
c15 (string)
c16 (string)
c17 (string)
c18 (string)
c19 (string)
c20 (string)
c21 (string)
c22 (string)
c23 (string)
c24 (string)
c25 (string)
c26 (string)
c27 (string)
c28 (string)
c29 (string)
Returns: Row
method TextSize(this, text_size)
Change the text size of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
text_size (string)
Returns: Cell
method TextSize(this, text_size)
Set text size
Namespace types: Row
Parameters:
this (Row)
text_size (string)
Returns: Row
method TextColor(this, c)
Change the text color of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
c (color)
Returns: Cell
method TextColor(this, text_color)
Change the text color of all cells in that row
Namespace types: Row
Parameters:
this (Row)
text_color (color)
Returns: Row
method Bg(this, c)
Change the background color of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
c (color)
Returns: Cell
method Bg(this, bg)
Change the background color of all cells in that row
Namespace types: Row
Parameters:
this (Row)
bg (color)
Returns: Row
method Font(this, text_font_family)
Change the font family of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
text_font_family (string)
Returns: Cell
method Font(this, text_font_family)
Change the width of all cells in that row
Namespace types: Row
Parameters:
this (Row)
text_font_family (string)
Returns: Row
method AlignH(this, halign)
Change the horizontal align of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
halign (string)
Returns: Cell
method AlignH(this, halign)
Change the horizontal align of all cells in that row
Namespace types: Row
Parameters:
this (Row)
halign (string)
Returns: Cell
method AlignV(this, valign)
Change the vertical align of the table cell.
Namespace types: Cell
Parameters:
this (Cell)
valign (string)
Returns: Cell
method AlignV(this, valign)
Change the vertical of all cells in that row
Namespace types: Row
Parameters:
this (Row)
valign (string)
Returns: Cell
method C(this, column)
Get the cell corresponding to the column number
Namespace types: Row
Parameters:
this (Row)
column (int)
Returns: Cell
method C(this, column, row)
Namespace types: Table
Parameters:
this (Table)
column (int)
row (int)
method R(this, row)
Namespace types: Table
Parameters:
this (Table)
row (int)
method Style(this, style)
Namespace types: Table
Parameters:
this (Table)
style (TableStyle)
method Position(this, position)
Namespace types: Table
Parameters:
this (Table)
position (string)
new(position, columns, rows, style)
Parameters:
position (string)
columns (int)
rows (int)
style (TableStyle)
CellStyle
Fields:
text_color (series__color)
text_halign (series__string)
text_valign (series__string)
text_size (series__integer)
bgcolor (series__color)
tooltip (series__string)
text_font_family (series__string)
TableStyle
Fields:
bgcolor (series__color)
frame_color (series__color)
frame_width (series__integer)
border_color (series__color)
border_width (series__integer)
default_cell_style (|CellStyle|#OBJ)
Cell
Fields:
ref (series__table)
column (series__integer)
row (series__integer)
Row
Fields:
ref (series__table)
row (series__integer)
cells (array__|Cell|#OBJ)
Table
Fields:
body (series__table)
rows (array__|Row|#OBJ)
New_Concepts_in_Technical_Trading_SystemsLibrary "New_Concepts_in_Technical_Trading_Systems"
A library for trading with mathematical indicators as described by J. Welles Wilder Jr. in 1978
psar(highSeries, lowSeries, closeSeries, start, increment, max)
psar calculates the parabolic SAR for the given series. Uses defaults as described by Wilder
Parameters:
highSeries (float) : the series of high price values
lowSeries (float) : the series of low price values
closeSeries (float) : the series of close price values
start (float) : the initial acceleration factor
increment (float) : amount the acceleration factor is incremented each step
max (float) : the maximum acceleration factor
Returns: the value of the stop and reverse price
momentum(closeSeries)
momentum calculates the momentum value, representing an acceleration of the current trend direction. Also calculates the trend balancing point which is a pivot to the momentum increasing or decreasing.
Parameters:
closeSeries (float) : the series of close price values
Returns: the value of the momentum and the next trend balance point
AllTimeHighLowLibrary "AllTimeHighLow"
Provides functions calculating the all-time high/low of values.
hi(val)
Calculates the all-time high of a series.
Parameters:
val (float) : Series to use (`high` is used if no argument is supplied).
Returns: The all-time high for the series.
lo(val)
Calculates the all-time low of a series.
Parameters:
val (float) : Series to use (`low` is used if no argument is supplied).
Returns: The all-time low for the series.
VPQuantLibLibrary "VPQuantLib"
Misc of math, position size and consolidation detection functions that can be used accross various scripts.
isPercentAboveReference(current, percent, reference, or_equal)
Checks if the current value is bigger (or equal) with the provided percent value to the reference
Parameters:
current (float) : - what to check against the reference
percent (float) : - what is the percent to check for difference
reference (float) : - what to compare against
or_equal (bool) : - enables checking for bigger or equal
Returns: true if the current is percent bigger (or equal) to the reference
isPercentBelowReference(current, percent, reference, or_equal)
Checks if the current value is smaller (or equal) with the provided percent value to the reference
Parameters:
current (float) : - what to check against the reference
percent (float) : - what is the percent to check for difference
reference (float) : - what to compare against
or_equal (bool) : - enables checking for smaller or equal
Returns: true if the current is percent smaller (or equal) to the reference
isInRange(current, reference, min_percent, max_percent, below)
Checks if the current value is greater/smaller than the reference value within the provided percent range
Parameters:
current (float) : - what to check for being in range against the refenence
reference (float) : - what to compare against
min_percent (float) : - the min percent range border
max_percent (float) : - the max percent range border
below (bool) : - check if below or above the reference
@return true if the current is bigger/smaller than the reference withing the percent range provided
GetRiskBasedPositionSize(account_balance, equity_risk_perc, max_loss_per_share)
Calculates and returns the positins size based on risk of the equity
Parameters:
account_balance (float) : - total account balance
equity_risk_perc (int) : - percent of equity to risk in the trade
max_loss_per_share (float) : - maximum loss per share (in currency, not in %) that we're willing to loose (calc based on the entry_price-stop_loss_price)
@return number of shares to buy
CheckInRangeConsolidation(consolidation_period, allowed_consolidation_range, ref_high, ref_low, prev_bar_consolidaton, draw_consolidation_lines)
Checks if the current bar is in a consolidation range
Parameters:
consolidation_period (int) : - the number of bars to consider for consolidation range calculation
allowed_consolidation_range (int) : - the percentage range allowed for the current consolidation range to be considered valid
ref_high (float) : - the reference high value to use for consolidation range calculation
ref_low (float) : - the reference low value to use for consolidation range calculation
prev_bar_consolidaton (bool)
draw_consolidation_lines (bool) : - a boolean indicating if consolidation range lines should be drawn on the chart
@return a tuple of three values:
1. _curr_consolidation - a boolean indicating if the current bar is in consolidation range
2. _curr_consolidation_low - the current consolidation low value
3. _curr_consolidation_high - the current consolidation high value
FindBasicConsolidation(loopback_period, consolidation_length, ref_high, ref_low, draw_consolidation_lines)
Finds a basic consolidation areas, looking back 1000 bars to find the pivot of the trend and checks if the current bar is in consolidation area counting the
number of bars that have not broken the consolidation high/low levels
Parameters:
loopback_period (int) : - the number of bars to look back to determine the high/low watermark
consolidation_length (int) : - minimum number of bars required to establish a consolidation period
ref_high (float) : - user input for high (can be based on the bar or wicks)
ref_low (float) : - user input for high (can be based on the bar or wicks)
draw_consolidation_lines (bool) : - enable/disable drawing of the consolidation lines
Returns: _pivot_point - pivot point
TrendPivotsLibrary "TrendPivots"
This library provides functions to search for bullish and bearish divergences between pivots and indicators. Functions search for higher highs and lower lows, automating lines, labels and signals for technical analysis and strategies.
method maxBeforeLast(id)
Method function to get the maximum price before the last, stored in an array pivotPoint.
Namespace types: pivotPoint
Parameters:
id (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: pivotPoint
method minBeforeLast(id)
Method function to get the minimum price before the last, stored in an array pivotPoint.
Namespace types: pivotPoint
Parameters:
id (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: pivotPoint
method pivotLine(id, a, b, color)
Sets the coordinates of a given line using two pivotPoint variables.
Namespace types: series line
Parameters:
id (line) : (line) Existing line
a (pivotPoint) : (pivotPoint) First pivotPoint.
b (pivotPoint) : (pivotPoint) Second pivotPoint.
color (color) : (color) The desired color. Default is red.
Returns: void
bearishDivergence(pivotArray)
Look for bearish divergence in a pivotPoint array cointaining pivot highs.
Parameters:
pivotArray (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: bool True if bearish divergence was found.
bullishDivergence(pivotArray)
Look for bullish divergence in a pivotPoint array cointaining pivot lows.
Parameters:
pivotArray (pivotPoint ) : (array pivotPoint) The pivotPoint array to inspect.
Returns: bool True if bullish divergence was found.
uptrendPivot(leftBars, rightBars, indicator, reset, plotLabel, plotLine)
Detects higher highs, higher lows and bearish divergence in an uptrend. Creates a line when bearish divergence is found, and labels.
Parameters:
leftBars (int) : (int)
rightBars (int) : (int)
indicator (float) : (float) RSI, MACD or other value.
reset (bool) : (bool) A bool variable to reinitiates the pivot computation, such as time changes, crossovers, or another.
plotLabel (bool) : (bool) If true (default), plots labels to higher highs and for each pivot low. Default = true.
plotLine (bool) : (bool) If true (default), plots a line linking the lower lows with divergence. Default = true.
Returns:
downtrendPivot(leftBars, rightBars, indicator, reset, plotLabel, plotLine)
Detects lower lows, lower highs, and bullish divergence in a downtrend. Creates a line when bullish divergence is found, and labels.
Parameters:
leftBars (int) : (int)
rightBars (int) : (int)
indicator (float) : (float) RSI, MACD or other value.
reset (bool) : (bool) A bool variable to reinitiates the pivot computation, such as time changes, crossovers, or another.
plotLabel (bool) : (bool) If true (default), plots labels to lower lows, and for each pivot low.
plotLine (bool) : (bool) If true (default), plots a line linking the lower lows with divergence. Default = true.
Returns:
pivotPoint
The coordinates of a pivot point and corresponding indicator value.
Fields:
x (series int) : (int) Time.
y (series float) : (float) Price.
indicator (series float) : (float) Indicator value.
commonThe "Pineify/common" library presents a specialized toolkit crafted to empower traders and script developers with state-of-the-art time manipulation functions on the TradingView platform. It is instead a foundational utility aimed at enriching your script's ability to process and interpret time-based data with unparalleled precision.
Key Features
String Splitter:
The 'str_split_into_two' function is a universal string handler that separates any given input into two distinct strings based on a specified delimiter. This function is especially useful in parsing time strings or any scenario where a string needs to be divided into logical parts efficiently.
Example:
= str_split_into_two("a:b", ":")
// a = "a"
// b = "b"
Time Parser:
With 'time_to_hour_minute', users can effortlessly convert a time string into numerical hours and minutes. This function is pivotal for those who need to exact specific time series data or wish to schedule their trades down to the minute.
Example:
= time_to_hour_minute("02:30")
// time_hour = 2
// time_minute = 30
Unix Time Converter
The 'time_range_to_unix_time' function transcends traditional boundaries by converting a given time range into Unix timestamp format. This integration of date, time, and timezone, accounts for a comprehensive approach, allowing scripts to make timed decisions, perform historical analyses, and account for international markets across different time zones.
Example:
// Support 'hhmm-hhmm' and 'hh:mm-hh:mm'
= time_range_to_unix_time("09:30-12:00")
Summary:
Each function is meticulously designed to minimize complexity and maximize versatility. Whether you are a programmer seeking to streamline your code, or a trader requiring precise timing for your strategies, our library provides the logical framework that aligns with your needs.
The "Pineify/common" library is the bridge between high-level time concepts and actionable trading insights. It serves a multitude of purposes – from crafting elegant time-based triggers to dissecting complex string data. Embrace the power of precision with "Pineify/common" and elevate your TradingView scripting experience to new heights.
DiscordWebhooksLibrary🚀 Introduction
Welcome to the TradingView PineScript Library for Discord Webhook Integration! This library is designed for traders and developers who use TradingView for technical analysis and want to integrate their trading strategies with Discord notifications.
Key Features:
* Embed Creation: Easily create rich and informative embeds for your Discord messages, allowing you to send detailed trading alerts and summaries.
* Flexible Webhook Formatting: Customize your Discord messages with options for usernames, avatars, and text content, providing a personalized touch to your notifications.
* Simple Integration: Designed with simplicity in mind, this library can be integrated into your existing Pine Script trading strategies without extensive coding knowledge.
* Real-time Alerts: Utilize TradingView's alert system to send real-time trade signals and market updates to your Discord server.
Compatibility:
This library is compatible with TradingView's Pine Script version 5.
🍃 Code Snippets and Usage Examples
The following examples demonstrate how to use the Discord Webhook Integration Library in your TradingView Pine Scripts. These snippets cover various scenarios, showcasing the flexibility and utility of the library.
Example 1: Simple Alert with Markdown in Embed Description
embedDesc = "This is a **bold** and _italic_ alert message with a (replace_with_your_link)"
embedJson = createEmbedJSON("Simple Alert", embedDesc, 12345)
content = discordWebhookJSON("Alert from Captain Hook", "Captain Hook", na, embedJson)
Example 2: Multiple Embeds with Different Markdown Styles
embedDesc1 = "First alert with **bold** text"
embedDesc2 = "Second alert with _italic_ text"
embedDesc3 = "Third alert with ~~strikethrough~~"
embedJson1 = createEmbedJSON("Alert 1", embedDesc1, 654321)
embedJson2 = createEmbedJSON("Alert 2", embedDesc2, 123456)
embedJson3 = createEmbedJSON("Alert 3", embedDesc3, 111111)
embeds = embedJson1 + "," + embedJson2 + "," + embedJson3
content = discordWebhookJSON("Multiple Alerts", "Captain Hook", na, embeds)
Example 3: Complex Alert with Full Markdown Usage in Embed
embedDesc = "Alert: **Price Breakout!** " +
"*Symbol*: " + syminfo.ticker + " " +
"*Price*: $" + str.tostring(close) + " " +
" (replace_with_your_link)"
embedJson = createEmbedJSON("Complex Alert", embedDesc, 16711680) // Red color
content = discordWebhookJSON("Complex Alert", "Captain Hook", na, embedJson)
Example 4: Advanced Technical Analysis Alert
rsiValue = ta.rsi(close, 14)
= ta.macd(close, 12, 26, 9)
taMessage = "RSI: " + str.tostring(rsiValue) + " MACD: " + str.tostring(macdLine)
embedJson = createEmbedJSON("Technical Analysis Update", taMessage, 255) // Blue color
content = discordWebhookJSON("TA Alert", "Captain Hook", na, embedJson)
Example 5: Market Summary with Multiple Fields
counterTrend = "Your counter trend criterias"
counterTrendEmbed = createEmbedJSON(title = "Counter Trend", description = counterTrend, color = 15258703)
redFlags = "Your red flag criterias"
redFlagsEmbed = createEmbedJSON(title = "Red Flags", description = redFlags, color = 15229263)
embeds = counterTrendEmbed + "," + redFlagsEmbed
content = discordWebhookJSON(contentText = "Example of how a market analysis could look like", username = "Captain Hook", embeds = embeds)
🚨 Error Handling
Use Escape Characters Correctly: In message strings, remember to use for new lines instead of . This ensures that the newline character is correctly interpreted in the JSON format.
It can be helpful to plot the json on the last candle
if barstate.islast
label.new(bar_index, high, text=debugMessage, color=color.red, textcolor=color.white, yloc=yloc.abovebar)
🔥 FAQs
Q1: Can I send alerts for multiple conditions?
A: Yes, you can configure multiple conditions in your script. Use separate if statements for each condition and call the discordWebhookJSON function with the relevant message for each alert.
Q2: Why is my alert not triggering?
A: Ensure your alert conditions are correct and that you've properly set up the webhook in both your script and TradingView's alert configuration. Also, check for any syntax errors in your script.
Q3: How many alerts can I send to Discord?
A: While TradingView doesn't limit the number of alerts, Discord has rate limits for webhooks. Be mindful of these limits to avoid your webhook being temporarily blocked.
Q4: Can I customize the appearance of my Discord messages?
A: Yes, the createEmbedJSON function allows you to customize your messages with titles, descriptions, colors, and more. Experiment with different parameters to achieve the desired appearance.
Q5: Is it possible to include real-time data in alerts?
A: Yes, your script can include real-time price data, indicator values, or any other real-time data available in Pine Script.
Q6: How can I contribute to the library or suggest improvements?
A: You can provide feedback, suggest improvements, or contribute to the library's development through the community channels or contact points provided in the "Support and Community" section.
formatTimeframe()
discordWebhookJSON(contentText, username, avatar_url, embeds)
Constructs a JSON string for a Discord webhook message. This string includes optional fields for content, username, avatar URL, and embeds.
Parameters:
contentText (string) : (string, optional): The main text content of the webhook message. Default is 'na'.
username (string) : (string, optional): Overrides the default username of the webhook. Default is 'na'.
avatar_url (string) : (string, optional): Overrides the default avatar URL of the webhook. Default is 'na'.
embeds (string) : (string, optional): A string containing one or more embed JSON objects. This should be formatted correctly as a JSON array. Default is 'na'.
createEmbedJSON(title, description, color, authorName, authorUrl, authorIconUrl, fields)
Creates a JSON string for a single embed object for a Discord webhook.
Parameters:
title (string) : (string, optional): The title of the embed. Default is 'na' (not applicable).
description (string) : (string, optional): The description text of the embed. Supports basic formatting. Default is 'na'.
color (int) : (int, optional): The color code of the embed, typically in decimal format. Default is 'na'.
authorName (string) : (string, optional): The name of the author to display in the embed. Default is 'na'.
authorUrl (string) : (string, optional): The URL linked to the author's name. Default is 'na'.
authorIconUrl (string) : (string, optional): The URL of the icon to display next to the author's name. Default is 'na'.
fields (string) : (string, optional): A string containing one or more field JSON objects. This should be formatted correctly as a JSON array. Default is 'na'. Note: Use the 'createEmbedFieldJSON' function to generate these JSON field strings before adding them to the array.
createEmbedFieldJSON(name, value, inline)
Creates a JSON string representing a single field object within an embed for a Discord webhook message.
Parameters:
name (string) : (string): The name of the field, acting as a title for the field content.
value (string) : (string): The value of the field, containing the actual text or information you want to display within the field.
inline (bool) : (bool, optional): A boolean flag indicating whether the field should be displayed inline with other fields. If set to true, the field will be displayed on the same line as the next field
❤️ Please, support the work with like & comment! ❤️
Mad_FibonacciboxLibrary "Mad_Fibonaccibox"
This library is designed to create and manage multiple Fibonacci boxes, which are graphical representations based on the inputs.
-----------------
exports:
f_fib_calc(_Fibonacci_box, _itemnumber)
fibonacci calc.
@description This function block uses the levels and paramters set into the type_fibonacci_box(levels) and fills the corresponding array of prices.
Parameters:
_Fibonacci_box (type_Fibonacci_box )
_itemnumber (int)
Returns: returns a type_Fibonacci_box with the filled data
f_fib_draw(_Fibonacci_box, _itemnumber)
fibonacci draw.
@description This function block uses the levels, prices and paramters set into the type_fibonacci_box(levels) and draws the fib on the chart
Parameters:
_Fibonacci_box (type_Fibonacci_box )
_itemnumber (int)
Returns: returns lines labels and fills on the chart, no data returns
type_level
s for defining a lines and texts of a fibonacci box
Fields:
level (series float)
price (series float)
drawline (series bool)
linewidth (series int)
linetype (series string)
fiblinecolor (series color)
drawlabel (series string)
labeltext (series string)
textshift (series int)
fibtextcolor (series color)
fibtextsize (series string)
transp (series int)
type_fill
s for defining the fills of a fibonaccibox
Fields:
partner_A (series int)
partner_B (series int)
fill_color (series color)
transp (series int)
type_Fibonacci_box
s for defining a fibonacci box
Fields:
bottom_price (series float)
top_price (series float)
StartBar (series int)
StopBar (series int)
levels (type_level )
fills (type_fill )
ChartisLog (series bool)
fibreverse (series bool)
fibdrawreverse (series bool)
decimals_price (series int)
decimals_percent (series int)
drawlines (series bool)
drawlabels (series bool)
drawfills (series bool)
draw_biginfo (series bool)
biginfo_textshift (series int)
rangeinfo_location (series int)
rangeinfo_color (series color)
rangeinfo_textsize (series string)
line_array (line )
linefill_array (linefill )
label_array (label )
High Risk Trading TimeLibrary "HighRiskTradingTime"
Utilities for time range labeling
openTime()
timeMinInDay(t, timezone)
Convert given time to minutes of day
Parameters:
t (int) : Time
timezone (string) : Timezone of the input h:m
@return Minutes of day
All exported functions args should be typified
timeMinInDayManual(h, m)
Convert given hour and minute to minutes of day
Parameters:
h (int) : Hour in a day
m (int) : Minute in a day
isForexHighRiskTime()
Return if current time is High Risk for Forex
TimeFormattingLibraryLibrary "TimeFormattingLibrary"
Time formatting functions: formating functions to make timestrings more human readable friendly (for both fixed time and time-elapsed).
Also functions for last and first instance in month of day of week input.
Also a function for identifying bank holiday Mondays.
timeFormatFxn(showDayOfWeek, showDayOfMonth, showMonth, showYear, showHrMin, _time, _timezone)
converts time into readable format
Parameters:
showDayOfWeek (bool) : if you want to show day of week (i.e. Mon, Tues etc)
showDayOfMonth (bool) : if you want to show day number of month with superscript ordinals (i.e. 1ˢᵗ, 2ⁿᵈ, etc)
showMonth (bool) : if you want to show the month (i.e. Jan, Feb, etc)
showYear (bool) : if you want to show the year (i.e. 2023)
showHrMin (bool) : if you want to show time in 24hr clock format
_time (int) : is the unix time (i.e. time or time_close)
_timezone (string) : the user timezone input as string (e.g. "America/New_York", "UTC-5", "GMT+0530")
Returns: time date string
timeElapsedFxn(timespan)
converts timespan into readable format
Parameters:
timespan (int) : is the length of time in milliseconds to be converted into a human readable string
Returns: timespan string (whether it be a for showing 'time-elapsed' or for showing a 'countdown timer')
isFirstXdayofmonth(_dayofweek)
gives bool result for when first occurence in month of the day-of-week input
Parameters:
_dayofweek (int) : (can be integer 1-7 or can be dayofweek variable; i.e. dayofweek.wednesday)
isLastXdayofmonth(_dayofweek)
gives bool result for when last occurence in month of the day-of-week input
Parameters:
_dayofweek (int) : (can be integer 1-7 or can be dayofweek variable; i.e. dayofweek.wednesday)
wasBankHolidayMonday()
gives bool result for if yesterday was a bank holiday monday. Only for use with with request.security() function, see example code below
WeightedSumIndexLibrary "WeightedSumIndex"
WeightedSumIndex: Helper class to build indices.
Index value is a normalized weighted sum of all its input signals.
The value is from 0 to 100
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
init()
Initialize an Index
Returns: A new instance of Index object with no signals
method add(idx, signal)
Adds the specified signal to the index
Namespace types: Index
Parameters:
idx (Index) : The Index object
signal (Signal) : Signal object
method calc(idx)
Caclulates the Index value
Namespace types: Index
Parameters:
idx (Index) : The Index object
Returns: Normalized weighted sum of all signals with on=true
method update(idx)
Calculates the Index value by calling idx.calc() and stores its value in the Index object.
Namespace types: Index
Parameters:
idx (Index) : The Index object
Signal
Parameters of input signal
Fields:
on (series bool) : Switch the signal on/off
weight (series float)
value (series float) : Value of the signal: should be between min and max
min (series float)
max (series float)
Index
The Index type with its properties and stored values
Fields:
signals (Signal )
value (series float) : Value of the index, must be calculated using calc() method
GuageLibrary "Gauge"
The gauge library utilizes a gaugeParams object, encapsulating crucial parameters for gauge creation. Essential attributes include num (the measured value) , min (the minimum value equating to 100% on the gauge's minimum scale) , and max (the maximum value equating to 100% on the gauge's maximum scale) . The size attribute (defaulting to 10) splits the scale into increments, each representing 100% divided by the specified size.
The num value dynamically shifts within the gauge based on its percentage move from the mathematical average between min and max . When num is below the average, the minimum portion of the scale activates, displaying the appropriate percentage based on the distance from the average to the minimum. The same principle applies when num exceeds the average. The 100% scale is reached at either end when num equals min or max .
The library offers full customization, allowing users to configure color schemes, labels, and titles. The gauge can be displayed either vertically (default) or horizontally. The colors employ a gradient, adapting based on the number's movement. Overall, the gauge library provides a flexible and comprehensive tool for visualizing and interpreting numerical values within a specified range.
MarketHolidaysLibrary "MarketHolidays"
The MarketHolidays library compiles market holidays (including historical special market closures) into arrays, which can then be utilized in TradingView indicators and strategies to account for non-trading days. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
getHolidays(_country)
The getHolidays function aggregates holiday data from different time periods to create a single array with market holidays for a specified country.
Parameters:
_country (string) : The country code for which to retrieve market holidays. Accepts syminfo.country or pre-set country code in ISO 3166-1 alpha-2 format.
Returns: An array of timestamps of market holidays \ non-trading days for the given country.
holidays_2020to2025Library "holidays_2020to2025"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)
holidays_2015to2020Library "holidays_2015to2020"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)
holidays_2010to2015Library "holidays_2010to2015"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)
holidays_2005to2010Library "holidays_2005to2010"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)
holidays_2000to2005Library "holidays_2000to2005"
This dataset is part of my "MarketHolidays" library. The datasets were split into different libraries to overcome compiling limitations, streamline the process of removing specific time frames if not needed, and to enhance code execution speed. The timestamps are generated using a custom Python script that employs the 'pandas_market_calendars' library. To build your own set of arrays, you can find the script and instructions at github.com
holidays(_country)
Parameters:
_country (string)