forex_factory_decodingLibrary "forex_factory_decoding"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for formatting and saving Forex Factory News events.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
MMM(M)
Converts a month from a numerical integer format to a MMM format (i.e. 'Jan').
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Month in MMM format (i.e. 'Jan').
array2string(S, FWD)
Converts a string array to a simple string, concatenating its elements.
Parameters:
S (string ) : String array, or string array slice, to turn into a simple string.
FWD (bool) : Boolean defaulted to True. If True the array will be concatenated from head to tail, reversed order if False.
Returns: Returns the simple string equivalent of the provided string array.
month2number(M)
Converts a month string in 'MMM' format to its integer equivalent.
Parameters:
M (string) : Month string, in 'MMM' format.
Returns: Returns the integer equivalent of the provided Month string in 'MMM' format.
shiftFWD_Days(D)
Shifts forward the current Date by N days.
Parameters:
D (int) : Number of days to forward-shift, default is 7.
Returns: Returns the forward-shifted date in 'MMM %D' format (i.e. Jan 8, Sep 12).
ff_dow(D)
Converts a numbered day of the week string in format to 'DDD' format (i.e. "1" = Sun).
Parameters:
D (string) : Numbered day of the week from 1 to 7, starting on Sunday.
Returns: Returns the day of the week in 'DDD' format (i.e. "Fri").
ff_currency(C)
Converts a numbered currency string in format to 'CCC' format (i.e. "1" = AUD).
Parameters:
C (string) : Numbered currency, where "1" = "AUD", "2" = "CAD", "3" = "CHF", "4" = "CNY", "5" = "EUR", "6" = "GBP", "7" = "JPY", "8" = "NZD", "9" = "USD".
Returns: Returns the currency in 'CCC' format (i.e. "USD").
ff_t(T)
Converts a time of the day in 'hhmm' format into an intger.
Parameters:
T (string) : Time of the day string in 'hhmm' format.
Returns: Returns the time of the day integer in 'hhmm' format, or -1 if all day.
ff_tod(T)
Converts a time of the day from an integer 'hhmm' format into 'hh:mm' format.
Parameters:
T (int)
Returns: Returns the N Forex Factory News array with time of the day string in 'hh:mm' format, or 'All Day'.
ff_impact(I)
Converts a number from 1 to 4 to a relative color based on Forex Factory Impact types.
Parameters:
I (string) : Impact number string from 1 to 4, where "1" = Holiday, "2" = Low Impact, "3" = Medium Impact, "4" = High Impact.
Returns: Returns the color associated to the impact number based on Forex Factory Impact types.
ff_tmst(D, T)
Parameters:
D (string)
T (string)
decode(ID)
Decodes TOODEGREES_FOREX_FACTORY_SLOT_n Symbols' Pine Seeds data into Forex Factory News Events.
Parameters:
ID (int) : Identifier of the Forex Factory News Event, in "DCHHMMI%T" format (D = day of the week from 1 to 7, C = currency from 1 to 9, HHMM = hour:minute in 24h, I = impact from 1 to 4, %T = event title ID) .
Returns: Returns the Forex Factory News Event.
method pullNews(N, n)
Decodes the Forex Factory News Event and adds it to the Forex Factory News array.
Namespace types: ffUtil.News
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
n (float) : imported data from custom feed.
Returns: void
method readNews(N, S)
Pulls the individual Forex Factory News Event from the custom data feed format (joint News string), decodes them and adds them to the Forex Factory News array.
Namespace types: ffUtil.News
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
S (string) : joint string of the imported data from custom feed.
Returns: void
marketClosed(N, S, S1, S2, S3, S4, S5, S6, S7, S8, S9)
If the current ticker's market is closed, Pine Seeds data will be pushed twice upon new day. This function saves the data pushed from the missing day.
Parameters:
N (News type from toodegrees/forex_factory_utility/1) : Forex Factory News array.
S (string ) : String array containing the Pine Seeds daya from the missing day.
S1 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_1.
S2 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_2.
S3 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_3.
S4 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_4.
S5 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_5.
S6 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_6.
S7 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_7.
S8 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_8.
S9 (string) : Data coming from TOODEGREES_FOREX_FACTORY_SLOT_9.
Returns: Updated string array containing the Pine Seeds daya from the missing day.
Indikatoren und Strategien
forex_factory_events_id_BLibrary "forex_factory_events_id_B"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; database with the second 500 Forex Factory News Event types.
ff_titleB(ID)
Converts a number to Forex Factory News title (second 500).
Parameters:
ID (string) : Identifier of the Forex Factory News Event. Please see the library for more information.
Returns: Returns the title of the Forex Factory News Event.
forex_factory_events_id_ALibrary "forex_factory_events_id_A"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; database with the first 500 Forex Factory News Event types.
ff_titleA(ID)
Converts a number to Forex Factory News title (first 500).
Parameters:
ID (string) : Identifier of the Forex Factory News Event. Please see the library for more information.
Returns: Returns the title of the Forex Factory News Event.
forex_factory_utilityLibrary "forex_factory_utility"
Supporting Utility Library for the Live Economic Calendar by toodegrees Indicator; responsible for data handling, and plotting news event data.
isLeapYear()
Finds if it's currently a leap year or not.
Returns: Returns True if the current year is a leap year.
daysMonth(M)
Provides the days in a given month of the year, adjusted during leap years.
Parameters:
M (int) : Month in numerical integer format (i.e. Jan=1).
Returns: Days in the provided month.
size(S, N)
Converts a size string into the corresponding Pine Script v5 format, or N times smaller/bigger.
Parameters:
S (string) : Size string: "Tiny", "Small", "Normal", "Large", or "Huge".
N (int) : Size variation, can be positive (larger than S), or negative (smaller than S).
Returns: Size string in Pine Script v5 format.
lineStyle(S)
Converts a line style string into the corresponding Pine Script v5 format.
Parameters:
S (string) : Line style string: "Dashed", "Dotted" or "Solid".
Returns: Line style string in Pine Script v5 format.
lineTrnsp(S)
Converts a transparency style string into the corresponding integer value.
Parameters:
S (string) : Line style string: "Light", "Medium" or "Heavy".
Returns: Transparency integer.
boxLoc(X, Y)
Converts position strings of X and Y into a table position in Pine Script v5 format.
Parameters:
X (string) : X-axis string: "Left", "Center", or "Right".
Y (string) : Y-axis string: "Top", "Middle", or "Bottom".
Returns: Table location string in Pine Script v5 format.
method bubbleSort_NewsTOD(N)
Performs bubble sort on a Forex Factory News array of all news from the same date, ordering them in ascending order based on the time of the day.
Namespace types: News
Parameters:
N (News ) : Forex Factory News array.
Returns: void
bubbleSort_News(N)
Performs bubble sort on a Forex Factory News array, ordering them in ascending order based on the time of the day, and date.
Parameters:
N (News ) : Forex Factory News array.
Returns: Sorted Forex Factory News array.
weekNews(N, C, I)
Creates a Forex Factory News array containing the current week's Forex Factory News.
Parameters:
N (News ) : Forex Factory News array containing this week's unfiltered Forex Factory News.
C (string ) : Currency filter array (string array).
I (color ) : Impact filter array (color array).
Returns: Forex Factory News array containing the current week's Forex Factory News.
todayNews(W, D, M)
Creates a Forex Factory News array containing the current day's Forex Factory News.
Parameters:
W (News ) : Forex Factory News array containing this week's Forex Factory News.
D (News ) : Forex Factory News array for the current day's Forex Factory News.
M (bool) : Boolean that marks whether the current chart has a Day candle-switch at Midnight New York Time.
Returns: Forex Factory News array containing the current day's Forex Factory News.
impFilter(X, L, M, H)
Creates a filter array from the User's desired Forex Facory News to be shown based on Impact.
Parameters:
X (bool) : Boolean - if True Holidays listed on Forex Factory will be shown.
L (bool) : Boolean - if True Low Impact listed on Forex Factory News will be shown.
M (bool) : Boolean - if True Medium Impact listed on Forex Factory News will be shown.
H (bool) : Boolean - if True High Impact listed on Forex Factory News will be shown.
Returns: Color array with the colors corresponding to the Forex Factory News to be shown.
curFilter(A, C1, C2, C3, C4, C5, C6, C7, C8, C9)
Creates a filter array from the User's desired Forex Facory News to be shown based on Currency.
Parameters:
A (bool) : Boolean - if True News related to the current Chart's symbol listed on Forex Factory will be shown.
C1 (bool) : Boolean - if True News related to the Australian Dollar listed on Forex Factory will be shown.
C2 (bool) : Boolean - if True News related to the Canadian Dollar listed on Forex Factory will be shown.
C3 (bool) : Boolean - if True News related to the Swiss Franc listed on Forex Factory will be shown.
C4 (bool) : Boolean - if True News related to the Chinese Yuan listed on Forex Factory will be shown.
C5 (bool) : Boolean - if True News related to the Euro listed on Forex Factory will be shown.
C6 (bool) : Boolean - if True News related to the British Pound listed on Forex Factory will be shown.
C7 (bool) : Boolean - if True News related to the Japanese Yen listed on Forex Factory will be shown.
C8 (bool) : Boolean - if True News related to the New Zealand Dollar listed on Forex Factory will be shown.
C9 (bool) : Boolean - if True News related to the US Dollar listed on Forex Factory will be shown.
Returns: String array with the currencies corresponding to the Forex Factory News to be shown.
FF_OnChartLine(N, T, S)
Plots vertical lines where a Forex Factory News event will occur, or has already occurred.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
T (int) : Transparency integer value (0-100) for the lines.
S (string) : Line style in Pine Script v5 format.
Returns: void
method updateStringMatrix(M, P, V)
Namespace types: matrix
Parameters:
M (matrix)
P (int)
V (string)
FF_OnChartLabel(N, Y, S)
Plots labels where a Forex Factory News has already occurred based on its/their impact.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
Y (string) : String that gives direction on where to plot the label (options= "Above", "Below", "Auto").
S (string) : Label size in Pine Script v5 format.
Returns: void
historical(T, D, W, X)
Deletes Forex Factory News drawings which are ourside a specific Time window.
Parameters:
T (int) : Number of days input used for Forex Factory News drawings' history.
D (bool) : Boolean that when true will only display Forex Factory News drawings of the current day.
W (bool) : Boolean that when true will only display Forex Factory News drawings of the current week.
X (string) : String that gives direction on what lines to plot based on Time (options= "Past", "Future", "Both").
Returns: void
newTable(P)
Creates a new Table object with parameters tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
Returns: Empty Forex Factory News Table.
resetTable(P, S, headTextC, headBgC)
Resets a Table object with parameters and headers tailored to the Forex Factory News Table.
Parameters:
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
Returns: Empty Forex Factory News Table.
logNews(N, TBL, R, S, rowTextC, rowBgC)
Adds an event to the Forex Factory News Table.
Parameters:
N (News) : News-type object.
TBL (table) : Forex Factory News Table object to add the News to.
R (int) : Row to add the event to in the Forex Factory News Table.
S (string) : Size string for the event's text, in Pine Script v5 format.
rowTextC (color)
rowBgC (color)
Returns: void
FF_Table(N, P, S, headTextC, headBgC, rowTextC, rowBgC)
Creates the Forex Factory News Table.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
P (string) : Position string for the Table, in Pine Script v5 format.
S (string) : Size string for the Table's text, in Pine Script v5 format.
headTextC (color)
headBgC (color)
rowTextC (color)
rowBgC (color)
Returns: Forex Factory News Table.
timeline(N, T, F, D)
Shades Forex Factory News events in the Forex Factory News Table after they occur.
Parameters:
N (News ) : News-type array containing all the Forex Factory News.
T (table) : Forex Facory News table object.
F (color) : Color used as shading once the Forex Factory News has occurred.
D (bool) : Daily Forex Factory News flag.
Returns: Forex Factory News Table.
News
Custom News type which contains informatino about a Forex Factory News Event.
Fields:
dow (series string) : Day of the week, in DDD format (i.e. 'Mon').
dat (series string) : Date, in MMM D format (i.e. 'Jan 1').
_t (series int)
tod (series string) : Time of the day, in hh:mm 24-Hour format (i.e 17:10).
cur (series string) : Currency, in CCC format (i.e. "USD").
imp (series color) : Impact, the respective impact color for Forex Factory News Events.
ttl (series string) : Title, encoded in a custom number mapping (see the toodegrees/toodegrees_forex_factory library to learn more).
tmst (series int)
ln (series line)
chartpatternsLibrary "chartpatterns"
Library having complete chart pattern implementation
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method findPattern(this, properties, patterns)
Find patterns based on the currect zigzag object and store them in the patterns array
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Zigzag object containing pivots
properties (PatternProperties) : PatternProperties object
patterns (Pattern ) : Array of Pattern objects
Returns: Current Pattern object
PatternProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool)
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
allowedPatterns (bool ) : array of bool encoding the allowed pattern types.
themeColors (color ) : color array of themes to be used.
Pattern
Object containing Individual Pattern data
Fields:
pivots (Pivot type from Trendoscope/ZigzagLite/2) : array of Zigzag Pivot points
trendLine1 (Line type from Trendoscope/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (PatternProperties) : PatternProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (label ) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
LineWrapperLibrary "LineWrapper"
Wrapper Type for Line. Useful when you want to store the line details without drawing them. Can also be used in scnearios where you collect lines to be drawn and draw together towards the end.
method draw(this)
draws line as per the wrapper object contents
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: current Line object
method draw(this)
draws lines as per the wrapper object array
Namespace types: Line
Parameters:
this (Line ) : (series array) Array of Line object.
Returns: current Array of Line objects
method update(this)
updates or redraws line as per the wrapper object contents
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: current Line object
method update(this)
updates or redraws lines as per the wrapper object array
Namespace types: Line
Parameters:
this (Line ) : (series array) Array of Line object.
Returns: current Array of Line objects
method delete(this)
Deletes the underlying line drawing object
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
Returns: Current Line object
method get_price(this, bar)
get line price based on bar
Namespace types: Line
Parameters:
this (Line) : (series Line) Line object.
bar (int) : (series/int) bar at which line price need to be calculated
Returns: line price at given bar.
Line
Line Wrapper object
Fields:
p1 (chart.point)
p2 (chart.point)
xloc (series string) : (series string) See description of x1 argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
extend (series string) : (series string) If extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none.
color (series color) : (series color) Line color.
style (series string) : (series string) Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
width (series int) : (series int) Line width in pixels.
obj (series line) : line object
lib_fvgLibrary "lib_fvg"
further expansion of my object oriented library toolkit. This lib detects Fair Value Gaps and returns them as objects.
Drawing them is a separate step so the lib can be used with securities. It also allows for usage of current/close price to detect fill/invalidation of a gap and to adjust the fill level dynamically. FVGs can be detected while forming and extended indefinitely while they're unfilled.
method draw(this)
Namespace types: FVG
Parameters:
this (FVG)
method draw(fvgs)
Namespace types: FVG
Parameters:
fvgs (FVG )
is_fvg(mode, precondition, filter_insignificant, filter_insignificant_atr_factor, live)
Parameters:
mode (int) : switch for detection 1 for bullish FVGs, -1 for bearish FVGs
precondition (bool) : allows for other confluences to block/enable detection
filter_insignificant (bool) : allows to ignore small gaps
filter_insignificant_atr_factor (float) : allows to adjust how small (compared to a 50 period ATR)
live (bool) : allows to detect FVGs while the third bar is forming -> will cause repainting
Returns: a tuple of (bar_index of gap bar, gap top, gap bottom)
create_fvg(mode, idx, top, btm, filled_at_pc, config)
Parameters:
mode (int) : switch for detection 1 for bullish FVGs, -1 for bearish FVGs
idx (int) : the bar_index of the FVG gap bar
top (float) : the top level of the FVG
btm (float) : the bottom level of the FVG
filled_at_pc (float) : the ratio (0-1) that the fill source needs to retrace into the gap to consider it filled/invalidated/ready for removal
config (FVGConfig) : the plot configuration/styles for the FVG
Returns: a new FVG object if there was a new FVG, else na
detect_fvg(mode, filled_at_pc, precondition, filter_insignificant, filter_insignificant_atr_factor, live, config)
Parameters:
mode (int) : switch for detection 1 for bullish FVGs, -1 for bearish FVGs
filled_at_pc (float)
precondition (bool) : allows for other confluences to block/enable detection
filter_insignificant (bool) : allows to ignore small gaps
filter_insignificant_atr_factor (float) : allows to adjust how small (compared to a 50 period ATR)
live (bool) : allows to detect FVGs while the third bar is forming -> will cause repainting
config (FVGConfig)
Returns: a new FVG object if there was a new FVG, else na
method update(this, fill_src)
Namespace types: FVG
Parameters:
this (FVG)
fill_src (float) : allows for usage of different fill source series, e.g. high for bearish FVGs, low vor bullish FVGs or close for both
method update(all, fill_src)
Namespace types: FVG
Parameters:
all (FVG )
fill_src (float)
method remove_filled(unfilled_fvgs)
Namespace types: FVG
Parameters:
unfilled_fvgs (FVG )
method delete(this)
Namespace types: FVG
Parameters:
this (FVG)
method delete_filled_fvgs_buffered(filled_fvgs, max_keep)
Namespace types: FVG
Parameters:
filled_fvgs (FVG )
max_keep (int) : the number of filled, latest FVGs to retain on the chart.
FVGConfig
Fields:
box_args (|robbatt/lib_plot_objects/36;BoxArgs|#OBJ)
line_args (|robbatt/lib_plot_objects/36;LineArgs|#OBJ)
box_show (series__bool)
line_show (series__bool)
keep_filled (series__bool)
extend (series__bool)
FVG
Fields:
config (|FVGConfig|#OBJ)
startbar (series__integer)
mode (series__integer)
top (series__float)
btm (series__float)
center (series__float)
size (series__float)
fill_size (series__float)
fill_lvl_target (series__float)
fill_lvl_current (series__float)
fillbar (series__integer)
filled (series__bool)
_fvg_box (|robbatt/lib_plot_objects/36;Box|#OBJ)
_fill_line (|robbatt/lib_plot_objects/36;Line|#OBJ)
ZigzagLiteLibrary "ZigzagLite"
Lighter version of the Zigzag Library. Without indicators and sub-component divisions
method getPrices(pivots)
Gets the array of prices from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot prices
method getBars(pivots)
Gets the array of bars from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot bar indices
method getPoints(pivots)
Gets the array of chart.point from array of Pivots
Namespace types: Pivot
Parameters:
pivots (Pivot ) : array array of Pivot objects
Returns: array array of pivot points
method getPoints(this)
Namespace types: Zigzag
Parameters:
this (Zigzag)
method calculate(this, ohlc, ltfHighTime, ltfLowTime)
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
ltfHighTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
ltfLowTime (int) : Used for multi timeframe zigzags when called within request.security. Default value is current timeframe open time.
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)
Namespace types: Zigzag
Parameters:
this (Zigzag)
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawing
Parameters:
this (ZigzagDrawing ) : array
Returns: void
method clear(this)
Clears zigzag drawings array
Namespace types: ZigzagDrawingPL
Parameters:
this (ZigzagDrawingPL ) : 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 drawplain(this)
draws fresh zigzag based on properties embedded in ZigzagDrawingPL object without trying to calculate
Namespace types: ZigzagDrawingPL
Parameters:
this (ZigzagDrawingPL) : ZigzagDrawingPL object
Returns: ZigzagDrawingPL object
method drawfresh(this, ohlc)
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
Returns: ZigzagDrawing object
method drawcontinuous(this, ohlc)
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
Returns:
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
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
ratio (series float) : Price Ratio based on previous two pivots
sizeRatio (series float)
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.
curved (series bool) : Boolean field to print curved zigzag - used only with polyline implementation
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.
ZigzagDrawingPL
Object which holds complete zigzag drawing objects and properties - polyline version
Fields:
zigzag (Zigzag) : Zigzag object which holds the calculations.
properties (ZigzagProperties) : ZigzagProperties object which is used for setting the display styles of zigzag
zigzagLabels (label )
zigzagLine (series polyline) : polyline object of zigzag lines
ForecastingThis Forecasting library has a couple of Novel and traditional approaches to forecasting stock prices.
Traditionally, it provides a basic ARIMA forecaster using simple autoregression, as well as a linear regression and quadratic regression channel forecaster.
Novel approaches to forecasting include:
1) A Moving Average based Forecaster (modelled after ARIMA), it is capable of forecasting based on a user selected SMA.
2) Z-Score Forecast: Forecasting based on Z-Score (example displayed in chart).
Library "Forecasting"
ARIMA_Modeller(src)
: Creates a generic autoregressive ARIMA model
Parameters:
src (float)
Returns: : arima_result, arima_ucl, arima_lcl, arima_cor, arima_r2, arima_err, y1, y2, y3, y0
machine_learning_regression(output, x1, x2, x3, x4, x5, show_statistics)
: Creates an automatic regression based forecast model (can be used for other regression operations) from a list of possible independent variables.
Parameters:
output (float)
x1 (float)
x2 (float)
x3 (float)
x4 (float)
x5 (float)
show_statistics (bool)
Returns: : result, upper bound levels, lower bound levels, optional statitics table that displays the model parameters and statistics
time_series_linear_forecast(src, forecast_length, standard_deviation_extension_1, standard_deviation_extension_2)
: Creates a simple linear regression time series channel
Parameters:
src (float)
forecast_length (int)
standard_deviation_extension_1 (float)
standard_deviation_extension_2 (float)
Returns: : Linreg Channel
quadratic_time_series_forecast(src, forecast_length)
: Creates a simple quadratic regression time series channel
Parameters:
src (float)
forecast_length (int)
Returns: : Quadratic Regression Channel
moving_average_forecaster(source, train_time, ma_length, forecast_length, forecast_result, upper_bound_result, lower_bound_result)
: Creates an ARIMA style moving average forecaster
Parameters:
source (float)
train_time (int)
ma_length (int)
forecast_length (int)
forecast_result (float )
upper_bound_result (float )
lower_bound_result (float )
Returns: : forecast_result, upper_bound_result, lower_bound_result, moving_average, ucl, lcl
zscore_forecast(z_length, z_source, show_alerts, forecast_length, show_forecast_table)
: Creates a Z-Score Forecast and is capable of plotting the immediate forecast via a Polyline
Parameters:
z_length (int)
z_source (float)
show_alerts (bool)
forecast_length (int)
show_forecast_table (bool)
Returns: : The export is void, it will export the Polyline forecast and the Z-forecast table if you enable it.
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
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