lib_plot_objects_1Library "lib_plot_objects_1"
method extend_to(this, end_time, end_idx, end_price)
Namespace types: Line
Parameters:
this (Line)
end_time (int)
end_idx (int)
end_price (float)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: LineArgs
Parameters:
args (LineArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: PolyLineArgs
Parameters:
args (PolyLineArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: LabelArgs
Parameters:
args (LabelArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: BoxArgs
Parameters:
args (BoxArgs)
method or_default(args)
checks args oject for being na, if so, provide a default instead
Namespace types: BoxTextArgs
Parameters:
args (BoxTextArgs)
method direction(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_green(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_red(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_bullish(this)
Namespace types: Candle
Parameters:
this (Candle)
method is_bearish(this)
Namespace types: Candle
Parameters:
this (Candle)
method total_size(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_size(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_top(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_bottom(this)
Namespace types: Candle
Parameters:
this (Candle)
method wick_size_top(this)
Namespace types: Candle
Parameters:
this (Candle)
method wick_size_bottom(this)
Namespace types: Candle
Parameters:
this (Candle)
method body_total_ratio(this)
Namespace types: Candle
Parameters:
this (Candle)
method duration(this)
Namespace types: Candle
Parameters:
this (Candle)
create_candle(t, tc, idx, o, h, l, c, v)
Creates Candle with ohlc and index data
Parameters:
t (int) : bar time of this candle
tc (int) : bar close time of this candle
idx (int) : bar index of this candle
o (float) : open price of this candle
h (float) : highest price of this candle
l (float) : lowest price of this candle
c (float) : close price of this candle
v (float)
Returns: new Candle
create_point(x, price, xloc)
Creates a new chart.point based on xloc switch
Parameters:
x (int)
price (float)
xloc (string)
method calculate_center(indexA, priceA, indexB, priceB)
Creates center chart.point between two chart.points
Namespace types: series int, simple int, input int, const int
Parameters:
indexA (int) : coordinates of point A (using just index, because time will not work properly in session based instruments)
priceA (float) : coordinates of point A
indexB (int) : coordinates of point B (using just index, because time will not work properly in session based instruments)
priceB (float) : coordinates of point B
Returns: center coordinates
method calculate_center(this, other)
Creates center chart.point between an array of given chart.points
Namespace types: chart.point
Parameters:
this (chart.point)
other (chart.point)
Returns: center coordinates
method calculate_center(points)
Creates center chart.point between an array of given chart.points
Namespace types: array
Parameters:
points (array) : array of chart.points for calculation of the center
Returns: center chart.point
method calculate_center(this)
Namespace types: Line
Parameters:
this (Line)
method calculate_center(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
method create_center(this, other)
Creates center chart.point between two chart.points
Namespace types: chart.point
Parameters:
this (chart.point) : chart.point
other (chart.point) : chart.point
Returns: center chart.point
method create_center(points)
Creates center chart.point between an array of given chart.points
Namespace types: array
Parameters:
points (array) : array of chart.points for calculation of the center
Returns: center chart.point
method create_center(this)
Namespace types: Line
Parameters:
this (Line)
method create_center(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
create_label(x, y, xloc, txt, tooltip)
Creates a new Label object.
Parameters:
x (int)
y (float)
xloc (string)
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: chart.point
Parameters:
this (chart.point)
txt (string)
tooltip (string)
method create_label(txt, tooltip)
Creates a new Label object.
Namespace types: series string, simple string, input string, const string
Parameters:
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Line
Parameters:
this (Line)
txt (string)
tooltip (string)
method create_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Box
Parameters:
this (Box)
txt (string)
tooltip (string)
method create_center_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: Line
Parameters:
this (Line)
txt (string)
tooltip (string)
method create_center_label(this, txt, tooltip)
Creates a new Label object.
Namespace types: PolyLine
Parameters:
this (PolyLine)
txt (string)
tooltip (string)
method nz(this, default)
Namespace types: chart.point
Parameters:
this (chart.point)
default (chart.point)
method nz(this, default)
Namespace types: Candle
Parameters:
this (Candle)
default (Candle)
method nz(this, default)
Namespace types: LabelArgs
Parameters:
this (LabelArgs)
default (LabelArgs)
method nz(this, default)
Namespace types: Label
Parameters:
this (Label)
default (Label)
method nz(this, default)
Namespace types: LineArgs
Parameters:
this (LineArgs)
default (LineArgs)
method nz(this, default)
Namespace types: Line
Parameters:
this (Line)
default (Line)
method nz(this, default)
Namespace types: PolyLineArgs
Parameters:
this (PolyLineArgs)
default (PolyLineArgs)
method nz(this, default)
Namespace types: PolyLine
Parameters:
this (PolyLine)
default (PolyLine)
method nz(this, default)
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
default (CenterLabel)
method nz(this, default)
Namespace types: LineFill
Parameters:
this (LineFill)
default (LineFill)
method nz(this, default)
Namespace types: BoxArgs
Parameters:
this (BoxArgs)
default (BoxArgs)
method nz(this, default)
Namespace types: BoxTextArgs
Parameters:
this (BoxTextArgs)
default (BoxTextArgs)
method nz(this, default)
Namespace types: Box
Parameters:
this (Box)
default (Box)
create_line(start_time, start_idx, start_price, end_time, end_idx, end_price)
Parameters:
start_time (int)
start_idx (int)
start_price (float)
end_time (int)
end_idx (int)
end_price (float)
create_line(x1, y1, x2, y2, xloc)
Parameters:
x1 (int)
y1 (float)
x2 (int)
y2 (float)
xloc (string)
create_line()
create_box(left_time, left_idx, top, right_time, right_idx, bottom, txt)
Parameters:
left_time (int)
left_idx (int)
top (float)
right_time (int)
right_idx (int)
bottom (float)
txt (string)
create_box(left, top, right, bottom, xloc, txt)
Parameters:
left (int)
top (float)
right (int)
bottom (float)
xloc (string)
txt (string)
create_box(txt)
Parameters:
txt (string)
method create_fill(this, other, fill_color, flip)
Creates a new LineFill object.
@field this The first Line object
@field other The second Line object
@field fill_color The color used to fill the space between the lines.
@field flip Optional if true, a new support line is created, drawn over other but with flipped start and end point
Namespace types: Line
Parameters:
this (Line)
other (Line)
fill_color (color)
flip (bool)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Candle)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (chart.point)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Label)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (CenterLabel)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (Line)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (LineFill)
max (int)
method enqueue(id, item, max)
Namespace types: array
Parameters:
id (array)
item (PolyLine)
max (int)
method update(this, bar_time, bar_time_close, bar_idx, o, h, l, c, v)
Updates a Candle object with new data.
Namespace types: Candle
Parameters:
this (Candle)
bar_time (int)
bar_time_close (int)
bar_idx (int)
o (float)
h (float)
l (float)
c (float)
v (float)
method update(this, bar_time, bar_idx, price)
Updates a chart.point object with new data.
Namespace types: chart.point
Parameters:
this (chart.point)
bar_time (int)
bar_idx (int)
price (float)
Returns: true if changed, false otherwise
method update(this, x, price, xloc)
Updates a chart.point object with new data.
Namespace types: chart.point
Parameters:
this (chart.point)
x (int)
price (float)
xloc (string)
Returns: true if changed, false otherwise
method update(this, update)
Updates a chart.point object with new data from another chart.point.
Namespace types: chart.point
Parameters:
this (chart.point)
update (chart.point)
Returns: true if changed, false otherwise
method update(this, bar_time, bar_idx, price, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: Label
Parameters:
this (Label)
bar_time (int)
bar_idx (int)
price (float)
txt (string)
tooltip (string)
method update(this, point, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: Label
Parameters:
this (Label)
point (chart.point)
txt (string)
tooltip (string)
method update(this, points, txt, tooltip, condition)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
points (array)
txt (string)
tooltip (string)
condition (bool)
method update(this, txt, tooltip)
Updates a Label's chart.point object with new data from another chart.point, or sets it if the Label's chart.point is na. If txt parameter is not given, it's not updated.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
txt (string)
tooltip (string)
method update(this, start, end)
Updates this Line's chart.point objects with new data from other chart.points.
Namespace types: Line
Parameters:
this (Line)
start (chart.point)
end (chart.point)
method update(this, points)
Updates this PolyLine's chart.point objects with new data from other chart.points. As the plot polyline has no options to be updated, it will be deleted before being redrawn in draw()
Namespace types: PolyLine
Parameters:
this (PolyLine)
points (array)
method update(this, left_top, right_bottom)
Updates a Box's chart.point objects with new data from other chart.points.
Namespace types: Box
Parameters:
this (Box)
left_top (chart.point)
right_bottom (chart.point)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Line
Parameters:
this (Line)
method delete(this)
Removes an objects representation from the chart.
Namespace types: PolyLine
Parameters:
this (PolyLine)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Label
Parameters:
this (Label)
method delete(this)
Removes an objects representation from the chart.
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
method delete(this)
Removes an objects representation from the chart.
Namespace types: Box
Parameters:
this (Box)
method delete(this)
Removes an objects representation from the chart.
Namespace types: LineFill
Parameters:
this (LineFill)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method delete(this)
Removes the representations of an array of objects from the chart.
Namespace types: array
Parameters:
this (array)
method draw(this, a, b, args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: series line
Parameters:
this (line)
a (chart.point)
b (chart.point)
args (LineArgs)
extend_only (bool) : this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates and text).
Namespace types: Label
Parameters:
this (Label)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates and text).
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: Line
Parameters:
this (Line)
args (LineArgs)
extend_only (bool) : this will omit redrawing x1 of the line, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, args, force_overlay)
Adds/Updates the representations of an object to the chart.
Namespace types: PolyLine
Parameters:
this (PolyLine)
args (PolyLineArgs)
force_overlay (simple bool)
method draw(this, args, text_args, extend_only, force_overlay)
Adds/Updates the representations of an object to the chart (only point coordinates).
Namespace types: Box
Parameters:
this (Box)
args (BoxArgs)
text_args (BoxTextArgs)
extend_only (bool) : this will omit redrawing the left side of the box, thereby prevent adressing bar_indexes too far in the past which causes max_bars_back errors. (default: true, set to false if you want x1 updated on drawing)
force_overlay (simple bool)
method draw(this, flip_support_args, force_overlay)
Adds/Replaces the representations of the object on the chart.
Namespace types: LineFill
Parameters:
this (LineFill)
flip_support_args (LineArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
force_overlay (simple bool)
method draw(this, args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (PolyLineArgs)
force_overlay (simple bool)
method draw(this, args, extend_only, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (LineArgs)
extend_only (bool)
force_overlay (simple bool)
method draw(this, flip_support_args, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
flip_support_args (LineArgs)
force_overlay (simple bool)
method draw(this, args, txt_args, extend_only, force_overlay)
converts this object into a builtin plot object, drawing it on the chart, unless drawn once before, this will either use the passed or default config for all objects
Namespace types: array
Parameters:
this (array)
args (BoxArgs)
txt_args (BoxTextArgs)
extend_only (bool)
force_overlay (simple bool)
method hide(this)
Namespace types: series label
Parameters:
this (label)
method hide(this)
Namespace types: series line
Parameters:
this (line)
method hide(this)
Namespace types: series polyline, series polyline, series polyline, series polyline
Parameters:
this (polyline)
method hide(this)
Namespace types: series box
Parameters:
this (box)
method hide(this)
Namespace types: chart.point
Parameters:
this (chart.point)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Label
Parameters:
this (Label)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Line
Parameters:
this (Line)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: PolyLine
Parameters:
this (PolyLine)
method hide(this)
hides an object by setting it's coordinates na, to unhide just update coordinates and call draw() again
Namespace types: Box
Parameters:
this (Box)
method apply_style(this, args)
Namespace types: series line
Parameters:
this (line)
args (LineArgs)
method apply_style(this, args)
Namespace types: series label
Parameters:
this (label)
args (LabelArgs)
method apply_style(this, args, text_args)
Namespace types: series box
Parameters:
this (box)
args (BoxArgs)
text_args (BoxTextArgs)
method apply_style(this, args)
updates styles on this objects plot
Namespace types: Label
Parameters:
this (Label)
args (LabelArgs)
method apply_style(this, args)
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
args (LabelArgs)
method apply_style(this, args)
Namespace types: Line
Parameters:
this (Line)
args (LineArgs)
method apply_style(this, args, text_args)
updates styles on this objects plot
Namespace types: Box
Parameters:
this (Box)
args (BoxArgs)
text_args (BoxTextArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LabelArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LineArgs)
method apply_style(this, args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (LineArgs)
method apply_style(this, args, text_args)
updates styles on these objects' plots
Namespace types: array
Parameters:
this (array)
args (BoxArgs)
text_args (BoxTextArgs)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Label
Parameters:
this (Label)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Line
Parameters:
this (Line)
method deep_copy(this)
clones the whole object including points and plots
Namespace types: Box
Parameters:
this (Box)
method deep_copy(this, copy_references)
clones the whole object including points and plots
Namespace types: CenterLabel
Parameters:
this (CenterLabel)
copy_references (bool)
method deep_copy(this, copy_references)
clones the whole object including points and plots
Namespace types: LineFill
Parameters:
this (LineFill)
copy_references (bool)
Candle
Fields:
bar_time (series int)
bar_time_close (series int)
bar_idx (series int)
o (series float)
h (series float)
l (series float)
c (series float)
v (series float)
LabelArgs
Fields:
text_color (series color) : Text color.
bg_color (series color) : Color of the label border and arrow.
text_font_family (series string) : The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
xloc (series string) : See description of x argument. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
yloc (series string) : Possible values are yloc.price, yloc.abovebar, yloc.belowbar. If yloc=yloc.price, y argument specifies the price of the label position. If yloc=yloc.abovebar, label is located above bar. If yloc=yloc.belowbar, label is located below bar. Default is yloc.price.
style (series string) : Label style. Possible values: label.style_none, label.style_xcross, label.style_cross, label.style_triangleup, label.style_triangledown, label.style_flag, label.style_circle, label.style_arrowup, label.style_arrowdown, label.style_label_up, label.style_label_down, label.style_label_left, label.style_label_right, label.style_label_lower_left, label.style_label_lower_right, label.style_label_upper_left, label.style_label_upper_right, label.style_label_center, label.style_square, label.style_diamond, label.style_text_outline. Default is label.style_label_down.
size (series string) : Label size. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge. Default value is size.normal.
text_align (series string) : Label text alignment. Possible values: text.align_left, text.align_center, text.align_right. Default value is text.align_center.
Label
Fields:
point (chart.point) : The Label coordinates
txt (series string) : Label text. Default is empty string.
tooltip (series string) : Hover to see tooltip label.
hidden (series bool)
plot (series label) : The label object to be added and plotted via draw()
LineArgs
Fields:
line_color (series color) : Line color.
style (series string) : Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
width (series int) : Line width in pixels.
xloc (series string) : Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
extend (series string) : f extend=extend.none, draws segment starting at point (x1, y1) and ending at point (x2, y2). If extend is equal to extend.right or extend.left, draws a ray starting at point (x1, y1) or (x2, y2), respectively. If extend=extend.both, draws a straight line that goes through these points. Default value is extend.none.
Line
Fields:
start (chart.point) : starting point of the line
end (chart.point)
hidden (series bool)
plot (series line) : The line object to be added and plotted via draw()
LineFill
Fields:
a (Line) : The first Line object
b (Line) : The second Line object
fill_color (series color) : The color used to fill the space between the lines.
flip_support (Line) : An additional Line that holds a flipped b support line (linefills are always drawn between line starts and line ends)
plot (series linefill) : The linefill object to be added and plotted via draw()
PolyLineArgs
Fields:
line_color (series color) : The color of the line segments. Optional. The default is color.gray.
fill_color (series color) : The fill color of the polyline. Optional. The default is na.
style (series string) : The style of the polyline. Possible values: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Optional. The default is line.style_solid.
width (series int) : The width of the line segments, expressed in pixels. Optional. The default is 1.
xloc (series string) : Determines the field of the chart.point objects in the points array that the polyline will use for its x-coordinates. If xloc.bar_index, the polyline will use the index field from each point. If xloc.bar_time, it will use the time field. Optional. The default is xloc.bar_index.
PolyLine
Fields:
points (array) : point array data of the polyline
curved (series bool) : Line color. If true, the drawing will connect all points from the points array using curved line segments. Optional. The default is false.
closed (series bool) : Line color. If true, the drawing will also connect the first point to the last point from the points array, resulting in a closed polyline. Optional. The default is false.
hidden (series bool)
plot (series polyline) : The polyline object to be added and plotted via draw()
CenterLabel
Fields:
center_label (Label) : The generated, centered Label
source_line (Line)
source_polyline (PolyLine)
BoxArgs
Fields:
border_color (series color) : Color of the four borders. Optional. The default is color.blue.
border_width (series int) : Width of the four borders, in pixels. Optional. The default is 1 pixel.
border_style (series string) : Style of the four borders. Possible values: line.style_solid, line.style_dotted, line.style_dashed. Optional. The default value is line.style_solid.
bg_color (series color) : Background color of the box. Optional. The default is color.blue.
xloc (series string) : Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc = xloc.bar_index, the arguments must be a bar index. If xloc = xloc.bar_time, the arguments must be a UNIX time. Possible values: xloc.bar_index and xloc.bar_time. Optional. The default is xloc.bar_index.
extend (series string) : When extend.none is used, the horizontal borders start at the left border and end at the right border. With extend.left or extend.right, the horizontal borders are extended indefinitely to the left or right of the box, respectively. With extend.both, the horizontal borders are extended on both sides. Optional. The default value is extend.none.
BoxTextArgs
Fields:
text_color (series color) : The color of the text. Optional. The default is color.black.
text_size (series string) : The size of the text. An optional parameter, the default value is size.auto. Possible values: size.auto, size.tiny, size.small, size.normal, size.large, size.huge.
text_halign (series string) : The horizontal alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_left, text.align_center, text.align_right.
text_valign (series string) : The vertical alignment of the box's text. Optional. The default value is text.align_center. Possible values: text.align_top, text.align_center, text.align_bottom.
text_wrap (series string) : Defines whether the text is presented in a single line, extending past the width of the box if necessary, or wrapped so every line is no wider than the box itself (and clipped by the bottom border of the box if the height of the resulting wrapped text is higher than the height of the box). Optional. The default value is text.wrap_none. Possible values: text.wrap_none, text.wrap_auto.
text_font_family (series string) : The font family of the text. Optional. The default value is font.family_default. Possible values: font.family_default, font.family_monospace.
Box
Fields:
left_top (chart.point) : top-left corner of the box
right_bottom (chart.point) : bottom-right corner of the box
txt (series string) : The text to be displayed inside the box. Optional. The default is empty string.
hidden (series bool)
plot (series box) : The box object to be added and plotted via draw()
Display
crypto_sectors_requestLibrary "crypto_sectors_request"
TODO: add library description here
getGaming()
PivotLabelsLibrary "PivotLabels"
drawPivots(qtyLabels, leftLegs, rightLegs)
Displays a label for each of the last `qtyLabels` pivots.
Colors high pivots in green, low pivots in red, and breached pivots in gray.
Parameters:
qtyLabels (int) : (simple int) Quantity of last labels to display.
leftLegs (int) : (simple int) Left pivot legs.
rightLegs (int) : (simple int) Right pivot legs.
Returns: Nothing.
vidya_calculateLibrary "vidya_calculate"
:
Calculates the Variable Index Dynamic Average (VIDYA).
Computes the VIDYA, which adjusts the degree of smoothing based on the strength of price momentum (absolute value of CMO),
and then returns the 15-period(variable) Simple Moving Average (SMA) of that VIDYA.
VIDYA tends to follow prices more closely when price fluctuations are large, and is smoothed more when fluctuations are small.
CMO = Chande Momentum Oscillator.
vidya(src, vidyaLength, vidyaMomentum, vidyaTrendPeriod)
: Calculates the Variable Index Dynamic Average (VIDYA)
Parameters:
src (float) : : Source
vidyaLength (int) : : VIDYA Length
vidyaMomentum (int) : : VIDYA Momentum
vidyaTrendPeriod (int) : : VIDYA Trend Period (Display)
Returns: : the 15-period(variable) Simple Moving Average (SMA) of that VIDYA
DrawingLibrary "Drawing"
User Defined types and methods for basic drawing structure. Consolidated from the earlier libraries - DrawingTypes and DrawingMethods
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.
method init(this)
Namespace types: PolyLine
Parameters:
this (PolyLine)
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Point object to string representation
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Point
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LineProperties object to string representation
Namespace types: LineProperties
Parameters:
this (LineProperties) : DrawingTypes/LineProperties object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LineProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Line object to string representation
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Line
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/LabelProperties object to string representation
Namespace types: LabelProperties
Parameters:
this (LabelProperties) : DrawingTypes/LabelProperties object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/LabelProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Label object to string representation
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Label
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Linefill object to string representation
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Linefill
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxProperties object to string representation
Namespace types: BoxProperties
Parameters:
this (BoxProperties) : DrawingTypes/BoxProperties object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxProperties
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/BoxText object to string representation
Namespace types: BoxText
Parameters:
this (BoxText) : DrawingTypes/BoxText object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/BoxText
method tostring(this, sortKeys, sortOrder, includeKeys)
Converts DrawingTypes/Box object to string representation
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
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 (array) : Array of string containing selective keys. Optional parmaeter. If not provided, all the keys are considered
Returns: string representation of DrawingTypes/Box
method delete(this)
Deletes line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: Line object deleted
method delete(this)
Deletes label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: Label object deleted
method delete(this)
Deletes Linefill from DrawingTypes/Linefill object
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill object
Returns: Linefill object deleted
method delete(this)
Deletes box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: DrawingTypes/Box object deleted
method delete(this)
Deletes lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method delete(this)
Deletes labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method delete(this)
Deletes linefill from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill objects
method delete(this)
Deletes boxes from array of DrawingTypes/Box objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Box objects
Returns: Array of DrawingTypes/Box objects
method clear(this)
clear items from array of DrawingTypes/Line while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Label while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Linefill while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method clear(this)
clear items from array of DrawingTypes/Box while deleting underlying objects
Namespace types: array
Parameters:
this (array) : array
Returns: void
method draw(this)
Creates line from DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : DrawingTypes/Line object
Returns: line created from DrawingTypes/Line object
method draw(this)
Creates lines from array of DrawingTypes/Line objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Line objects
Returns: Array of DrawingTypes/Line objects
method draw(this)
Creates label from DrawingTypes/Label object
Namespace types: Label
Parameters:
this (Label) : DrawingTypes/Label object
Returns: label created from DrawingTypes/Label object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method draw(this)
Creates linefill object from DrawingTypes/Linefill
Namespace types: Linefill
Parameters:
this (Linefill) : DrawingTypes/Linefill objects
Returns: linefill object created
method draw(this)
Creates linefill objects from array of DrawingTypes/Linefill objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Linefill objects
Returns: Array of DrawingTypes/Linefill used for creating linefills
method draw(this)
Creates box from DrawingTypes/Box object
Namespace types: Box
Parameters:
this (Box) : DrawingTypes/Box object
Returns: box created from DrawingTypes/Box object
method draw(this)
Creates labels from array of DrawingTypes/Label objects
Namespace types: array
Parameters:
this (array) : Array of DrawingTypes/Label objects
Returns: Array of DrawingTypes/Label objects
method createLabel(this, lblText, tooltip, properties)
Creates DrawingTypes/Label object from DrawingTypes/Point
Namespace types: chart.point
Parameters:
this (chart.point) : DrawingTypes/Point object
lblText (string) : Label text
tooltip (string) : Tooltip text. Default is na
properties (LabelProperties) : DrawingTypes/LabelProperties object. Default is na - meaning default values are used.
Returns: DrawingTypes/Label object
method createLine(this, other, properties)
Creates DrawingTypes/Line object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (LineProperties) : DrawingTypes/LineProperties object. Default set to na - meaning default values are used.
Returns: DrawingTypes/Line object
method createLinefill(this, other, fillColor, transparency)
Creates DrawingTypes/Linefill object from DrawingTypes/Line object to other DrawingTypes/Line object
Namespace types: Line
Parameters:
this (Line) : First DrawingTypes/Line object
other (Line) : Other DrawingTypes/Line object
fillColor (color) : fill color of linefill. Default is color.blue
transparency (int) : fill transparency for linefill. Default is 80
Returns: Array of DrawingTypes/Linefill object
method createBox(this, other, properties, textProperties)
Creates DrawingTypes/Box object from one DrawingTypes/Point to other
Namespace types: chart.point
Parameters:
this (chart.point) : First DrawingTypes/Point object
other (chart.point) : Second DrawingTypes/Point object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
method createBox(this, properties, textProperties)
Creates DrawingTypes/Box object from DrawingTypes/Line as diagonal line
Namespace types: Line
Parameters:
this (Line) : Diagonal DrawingTypes/PoLineint object
properties (BoxProperties) : DrawingTypes/BoxProperties object. Default set to na - meaning default values are used.
textProperties (BoxText) : DrawingTypes/BoxText object. Default is na - meaning no text will be drawn
Returns: DrawingTypes/Box object
LineProperties
Properties of line object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
extend (series string) : Property which sets line to extend towards either right or left or both. Valid values are extend.right, extend.left, extend.both, extend.none. Default is extend.none
color (series color) : Line color
style (series string) : Line style, valid values are line.style_solid, line.style_dashed, line.style_dotted, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Default is line.style_solid
width (series int) : Line width. Default is 1
Line
Line object created from points
Fields:
start (chart.point) : Starting point of the line
end (chart.point) : Ending point of the line
properties (LineProperties) : LineProperties object which defines the style of line
object (series line) : Derived line object
LabelProperties
Properties of label object
Fields:
xloc (series string) : X Reference - can be either xloc.bar_index or xloc.bar_time. Default is xloc.bar_index
yloc (series string) : Y reference - can be yloc.price, yloc.abovebar, yloc.belowbar. Default is yloc.price
color (series color) : Label fill color
style (series string) : Label style as defined in Tradingview Documentation. Default is label.style_none
textcolor (series color) : text color. Default is color.black
size (series string) : Label text size. Default is size.normal. Other values are size.auto, size.tiny, size.small, size.normal, size.large, size.huge
textalign (series string) : Label text alignment. Default if text.align_center. Other allowed values - text.align_right, text.align_left, text.align_top, text.align_bottom
text_font_family (series string) : The font family of the text. Default value is font.family_default. Other available option is font.family_monospace
Label
Label object
Fields:
point (chart.point) : Point where label is drawn
lblText (series string) : label text
tooltip (series string) : Tooltip text. Default is na
properties (LabelProperties) : LabelProperties object
object (series label) : Pine label object
Linefill
Linefill object
Fields:
line1 (Line) : First line to create linefill
line2 (Line) : Second line to create linefill
fillColor (series color) : Fill color
transparency (series int) : Fill transparency range from 0 to 100
object (series linefill) : linefill object created from wrapper
BoxProperties
BoxProperties object
Fields:
border_color (series color) : Box border color. Default is color.blue
bgcolor (series color) : box background color
border_width (series int) : Box border width. Default is 1
border_style (series string) : Box border style. Default is line.style_solid
extend (series string) : Extend property of box. default is extend.none
xloc (series string) : defines if drawing needs to be done based on bar index or time. default is xloc.bar_index
BoxText
Box Text properties.
Fields:
boxText (series string) : Text to be printed on the box
text_size (series string) : Text size. Default is size.auto
text_color (series color) : Box text color. Default is color.yellow.
text_halign (series string) : horizontal align style - default is text.align_center
text_valign (series string) : vertical align style - default is text.align_center
text_wrap (series string) : text wrap style - default is text.wrap_auto
text_font_family (series string) : Text font. Default is
Box
Box object
Fields:
p1 (chart.point) : Diagonal point one
p2 (chart.point) : Diagonal point two
properties (BoxProperties) : Box properties
textProperties (BoxText) : Box text properties
object (series box) : Box object created
PolyLineProperties
Fields:
curved (series bool)
closed (series bool)
xloc (series string)
lineColor (series color)
fillColor (series color)
lineStyle (series string)
lineWidth (series int)
PolyLine
Fields:
points (array)
properties (PolyLineProperties)
object (series polyline)
dataTableUtilitiesLibrary "dataTableUtilities"
generate_dataTable(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, include_comments)
: Generates and shows a data table.
Parameters:
dataTable_map (map)
title (string) : (string): Title of the table
tableYpos (string) : (string): Vertical position of the table
tableXpos (string) : (string): Horizontal position of the table
textSize (string) : (string): Text size
includes_multiple_maps (bool)
include_comments (bool)
Returns: : None
generate_dataTable_multiple_columns(dataTable_map, title, tableYpos, tableXpos, textSize, includes_multiple_maps, total_columns)
: Generates and shows a data table.
Parameters:
dataTable_map (map)
title (string) : (string): Title of the table
tableYpos (string) : (string): Vertical position of the table
tableXpos (string) : (string): Horizontal position of the table
textSize (string) : (string): Text size
includes_multiple_maps (bool)
total_columns (int)
Returns: : None
real_time_candlesIntroduction
The Real-Time Candles Library provides comprehensive tools for creating, manipulating, and visualizing custom timeframe candles in Pine Script. Unlike standard indicators that only update at bar close, this library enables real-time visualization of price action and indicators within the current bar, offering traders unprecedented insight into market dynamics as they unfold.
This library addresses a fundamental limitation in traditional technical analysis: the inability to see how indicators evolve between bar closes. By implementing sophisticated real-time data processing techniques, traders can now observe indicator movements, divergences, and trend changes as they develop, potentially identifying trading opportunities much earlier than with conventional approaches.
Key Features
The library supports two primary candle generation approaches:
Chart-Time Candles: Generate real-time OHLC data for any variable (like RSI, MACD, etc.) while maintaining synchronization with chart bars.
Custom Timeframe (CTF) Candles: Create candles with custom time intervals or tick counts completely independent of the chart's native timeframe.
Both approaches support traditional candlestick and Heikin-Ashi visualization styles, with options for moving average overlays to smooth the data.
Configuration Requirements
For optimal performance with this library:
Set max_bars_back = 5000 in your script settings
When using CTF drawing functions, set max_lines_count = 500, max_boxes_count = 500, and max_labels_count = 500
These settings ensure that you will be able to draw correctly and will avoid any runtime errors.
Usage Examples
Basic Chart-Time Candle Visualization
// Create real-time candles for RSI
float rsi = ta.rsi(close, 14)
Candle rsi_candle = candle_series(rsi, CandleType.candlestick)
// Plot the candles using Pine's built-in function
plotcandle(rsi_candle.Open, rsi_candle.High, rsi_candle.Low, rsi_candle.Close,
"RSI Candles", rsi_candle.candle_color, rsi_candle.candle_color)
Multiple Access Patterns
The library provides three ways to access candle data, accommodating different programming styles:
// 1. Array-based access for collection operations
Candle candles = candle_array(source)
// 2. Object-oriented access for single entity manipulation
Candle candle = candle_series(source)
float value = candle.source(Source.HLC3)
// 3. Tuple-based access for functional programming styles
= candle_tuple(source)
Custom Timeframe Examples
// Create 20-second candles with EMA overlay
plot_ctf_candles(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 20,
timezone = -5,
tied_open = true,
ema_period = 9,
enable_ema = true
)
// Create tick-based candles (new candle every 15 ticks)
plot_ctf_tick_candles(
source = close,
candle_type = CandleType.heikin_ashi,
number_of_ticks = 15,
timezone = -5,
tied_open = true
)
Advanced Usage with Custom Visualization
// Get custom timeframe candles without automatic plotting
CandleCTF my_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 30
)
// Apply custom logic to the candles
float ema_values = my_candles.ctf_ema(14)
// Draw candles and EMA using time-based coordinates
my_candles.draw_ctf_candles_time()
ema_values.draw_ctf_line_time(line_color = #FF6D00)
Library Components
Data Types
Candle: Structure representing chart-time candles with OHLC, polarity, and visualization properties
CandleCTF: Extended candle structure with additional time metadata for custom timeframes
TickData: Structure for individual price updates with time deltas
Enumerations
CandleType: Specifies visualization style (candlestick or Heikin-Ashi)
Source: Defines price components for calculations (Open, High, Low, Close, HL2, etc.)
SampleType: Sets sampling method (Time-based or Tick-based)
Core Functions
get_tick(): Captures current price as a tick data point
candle_array(): Creates an array of candles from price updates
candle_series(): Provides a single candle based on latest data
candle_tuple(): Returns OHLC values as a tuple
ctf_candles_array(): Creates custom timeframe candles without rendering
Visualization Functions
source(): Extracts specific price components from candles
candle_ctf_to_float(): Converts candle data to float arrays
ctf_ema(): Calculates exponential moving averages for candle arrays
draw_ctf_candles_time(): Renders candles using time coordinates
draw_ctf_candles_index(): Renders candles using bar index coordinates
draw_ctf_line_time(): Renders lines using time coordinates
draw_ctf_line_index(): Renders lines using bar index coordinates
Technical Implementation Notes
This library leverages Pine Script's varip variables for state management, creating a sophisticated real-time data processing system. The implementation includes:
Efficient tick capturing: Samples price at every execution, maintaining temporal tracking with time deltas
Smart state management: Uses a hybrid approach with mutable updates at index 0 and historical preservation at index 1+
Temporal synchronization: Manages two time domains (chart time and custom timeframe)
The tooltip implementation provides crucial temporal context for custom timeframe visualizations, allowing users to understand exactly when each candle formed regardless of chart timeframe.
Limitations
Custom timeframe candles cannot be backtested due to Pine Script's limitations with historical tick data
Real-time visualization is only available during live chart updates
Maximum history is constrained by Pine Script's array size limits
Applications
Indicator visualization: See how RSI, MACD, or other indicators evolve in real-time
Volume analysis: Create custom volume profiles independent of chart timeframe
Scalping strategies: Identify short-term patterns with precisely defined time windows
Volatility measurement: Track price movement characteristics within bars
Custom signal generation: Create entry/exit signals based on custom timeframe patterns
Conclusion
The Real-Time Candles Library bridges the gap between traditional technical analysis (based on discrete OHLC bars) and the continuous nature of market movement. By making indicators more responsive to real-time price action, it gives traders a significant edge in timing and decision-making, particularly in fast-moving markets where waiting for bar close could mean missing important opportunities.
Whether you're building custom indicators, researching price patterns, or developing trading strategies, this library provides the foundation for sophisticated real-time analysis in Pine Script.
Implementation Details & Advanced Guide
Core Implementation Concepts
The Real-Time Candles Library implements a sophisticated event-driven architecture within Pine Script's constraints. At its heart, the library creates what's essentially a reactive programming framework handling continuous data streams.
Tick Processing System
The foundation of the library is the get_tick() function, which captures price updates as they occur:
export get_tick(series float source = close, series float na_replace = na)=>
varip float price = na
varip int series_index = -1
varip int old_time = 0
varip int new_time = na
varip float time_delta = 0
// ...
This function:
Samples the current price
Calculates time elapsed since last update
Maintains a sequential index to track updates
The resulting TickData structure serves as the fundamental building block for all candle generation.
State Management Architecture
The library employs a sophisticated state management system using varip variables, which persist across executions within the same bar. This creates a hybrid programming paradigm that's different from standard Pine Script's bar-by-bar model.
For chart-time candles, the core state transition logic is:
// Real-time update of current candle
candle_data := Candle.new(Open, High, Low, Close, polarity, series_index, candle_color)
candles.set(0, candle_data)
// When a new bar starts, preserve the previous candle
if clear_state
candles.insert(1, candle_data)
price.clear()
// Reset state for new candle
Open := Close
price.push(Open)
series_index += 1
This pattern of updating index 0 in real-time while inserting completed candles at index 1 creates an elegant solution for maintaining both current state and historical data.
Custom Timeframe Implementation
The custom timeframe system manages its own time boundaries independent of chart bars:
bool clear_state = switch settings.sample_type
SampleType.Ticks => cumulative_series_idx >= settings.number_of_ticks
SampleType.Time => cumulative_time_delta >= settings.number_of_seconds
This dual-clock system synchronizes two time domains:
Pine's execution clock (bar-by-bar processing)
The custom timeframe clock (tick or time-based)
The library carefully handles temporal discontinuities, ensuring candle formation remains accurate despite irregular tick arrival or market gaps.
Advanced Usage Techniques
1. Creating Custom Indicators with Real-Time Candles
To develop indicators that process real-time data within the current bar:
// Get real-time candles for your data
Candle rsi_candles = candle_array(ta.rsi(close, 14))
// Calculate indicator values based on candle properties
float signal = ta.ema(rsi_candles.first().source(Source.Close), 9)
// Detect patterns that occur within the bar
bool divergence = close > close and rsi_candles.first().Close < rsi_candles.get(1).Close
2. Working with Custom Timeframes and Plotting
For maximum flexibility when visualizing custom timeframe data:
// Create custom timeframe candles
CandleCTF volume_candles = ctf_candles_array(
source = volume,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 60
)
// Convert specific candle properties to float arrays
float volume_closes = volume_candles.candle_ctf_to_float(Source.Close)
// Calculate derived values
float volume_ema = volume_candles.ctf_ema(14)
// Create custom visualization
volume_candles.draw_ctf_candles_time()
volume_ema.draw_ctf_line_time(line_color = color.orange)
3. Creating Hybrid Timeframe Analysis
One powerful application is comparing indicators across multiple timeframes:
// Standard chart timeframe RSI
float chart_rsi = ta.rsi(close, 14)
// Custom 5-second timeframe RSI
CandleCTF ctf_candles = ctf_candles_array(
source = close,
candle_type = CandleType.candlestick,
sample_type = SampleType.Time,
number_of_seconds = 5
)
float fast_rsi_array = ctf_candles.candle_ctf_to_float(Source.Close)
float fast_rsi = fast_rsi_array.first()
// Generate signals based on divergence between timeframes
bool entry_signal = chart_rsi < 30 and fast_rsi > fast_rsi_array.get(1)
Final Notes
This library represents an advanced implementation of real-time data processing within Pine Script's constraints. By creating a reactive programming framework for handling continuous data streams, it enables sophisticated analysis typically only available in dedicated trading platforms.
The design principles employed—including state management, temporal processing, and object-oriented architecture—can serve as patterns for other advanced Pine Script development beyond this specific application.
------------------------
Library "real_time_candles"
A comprehensive library for creating real-time candles with customizable timeframes and sampling methods.
Supports both chart-time and custom-time candles with options for candlestick and Heikin-Ashi visualization.
Allows for tick-based or time-based sampling with moving average overlay capabilities.
get_tick(source, na_replace)
Captures the current price as a tick data point
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
na_replace (float) : Optional - Value to use when source is na
Returns: TickData structure containing price, time since last update, and sequential index
candle_array(source, candle_type, sync_start, bullish_color, bearish_color)
Creates an array of candles based on price updates
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
sync_start (simple bool) : Optional - Whether to synchronize with the start of a new bar
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of Candle objects ordered with most recent at index 0
candle_series(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides a single candle based on the latest price data
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: A single Candle object representing the current state
candle_tuple(source, candle_type, wait_for_sync, bullish_color, bearish_color)
Provides candle data as a tuple of OHLC values
Parameters:
source (float) : Optional - Price source to sample (defaults to close)
candle_type (simple CandleType) : Optional - Type of candle chart to create (candlestick or Heikin-Ashi)
wait_for_sync (simple bool) : Optional - Whether to wait for a new bar before starting
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Tuple representing current candle values
method source(self, source, na_replace)
Extracts a specific price component from a Candle
Namespace types: Candle
Parameters:
self (Candle)
source (series Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
na_replace (float) : Optional - Value to use when source value is na
Returns: The requested price value from the candle
method source(self, source)
Extracts a specific price component from a CandleCTF
Namespace types: CandleCTF
Parameters:
self (CandleCTF)
source (simple Source) : Type of price data to extract (Open, High, Low, Close, or composite values)
Returns: The requested price value from the candle as a varip
method candle_ctf_to_float(self, source)
Converts a specific price component from each CandleCTF to a float array
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
Returns: Array of float values extracted from the candles, ordered with most recent at index 0
method ctf_ema(self, ema_period)
Calculates an Exponential Moving Average for a CandleCTF array
Namespace types: array
Parameters:
self (array)
ema_period (simple float) : Period for the EMA calculation
Returns: Array of float values representing the EMA of the candle data, ordered with most recent at index 0
method draw_ctf_candles_time(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar time coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using time-based x-coordinates
method draw_ctf_candles_index(self, sample_type, number_of_ticks, number_of_seconds, timezone)
Renders custom timeframe candles using bar index coordinates
Namespace types: array
Parameters:
self (array)
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks), used for tooltips
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks), used for tooltips
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time), used for tooltips
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12), used for tooltips
Returns: void - Renders candles on the chart using index-based x-coordinates
method draw_ctf_line_time(self, source, line_size, line_color)
Renders a line representing a price component from the candles using time coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_time(self, line_size, line_color)
Renders a line from a varip float array using time coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using time-based x-coordinates
method draw_ctf_line_index(self, source, line_size, line_color)
Renders a line representing a price component from the candles using index coordinates
Namespace types: array
Parameters:
self (array)
source (simple Source) : Optional - Type of price data to extract (defaults to Close)
line_size (simple int) : Optional - Width of the line
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
method draw_ctf_line_index(self, line_size, line_color)
Renders a line from a varip float array using index coordinates
Namespace types: array
Parameters:
self (array)
line_size (simple int) : Optional - Width of the line, defaults to 2
line_color (simple color) : Optional - Color of the line
Returns: void - Renders a connected line on the chart using index-based x-coordinates
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots tick-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_tick_candles(source, candle_type, number_of_ticks, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots tick-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_ticks (simple int) : Number of ticks per candle
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, line_width, ema_color, use_time_indexing)
Plots time-based candles with moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
ema_period (simple float) : Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with EMA overlay
plot_ctf_time_candles(source, candle_type, number_of_seconds, timezone, tied_open, bullish_color, bearish_color, use_time_indexing)
Plots time-based candles without moving average
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to display
number_of_seconds (simple float) : Time duration per candle in seconds
timezone (simple int) : Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart without moving average
plot_ctf_candles(source, candle_type, sample_type, number_of_ticks, number_of_seconds, timezone, tied_open, ema_period, bullish_color, bearish_color, enable_ema, line_width, ema_color, use_time_indexing)
Unified function for plotting candles with comprehensive options
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Optional - Type of candle chart to display
sample_type (simple SampleType) : Optional - Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
timezone (simple int) : Optional - Timezone offset from UTC (-12 to +12)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
ema_period (simple float) : Optional - Period for the exponential moving average
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
enable_ema (bool) : Optional - Whether to display the EMA overlay
line_width (simple int) : Optional - Width of the moving average line, defaults to 2
ema_color (color) : Optional - Color of the moving average line
use_time_indexing (simple bool) : Optional - When true the function will plot with xloc.time, when false it will plot using xloc.bar_index
Returns: void - Creates visual candle chart with optional EMA overlay
ctf_candles_array(source, candle_type, sample_type, number_of_ticks, number_of_seconds, tied_open, bullish_color, bearish_color)
Creates an array of custom timeframe candles without rendering them
Parameters:
source (float) : Input price source to sample
candle_type (simple CandleType) : Type of candle chart to create (candlestick or Heikin-Ashi)
sample_type (simple SampleType) : Method for sampling data (Time or Ticks)
number_of_ticks (simple int) : Optional - Number of ticks per candle (used when sample_type is Ticks)
number_of_seconds (simple float) : Optional - Time duration per candle in seconds (used when sample_type is Time)
tied_open (simple bool) : Optional - Whether to tie open price to close of previous candle
bullish_color (color) : Optional - Color for bullish candles
bearish_color (color) : Optional - Color for bearish candles
Returns: Array of CandleCTF objects ordered with most recent at index 0
Candle
Structure representing a complete candle with price data and display properties
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
candle_color (series color) : Color to use when rendering the candle
ready (series bool) : Boolean indicating if candle data is valid and ready for use
TickData
Structure for storing individual price updates
Fields:
price (series float) : The price value at this tick
time_delta (series float) : Time elapsed since the previous tick in milliseconds
series_index (series int) : Sequential index identifying this tick
CandleCTF
Structure representing a custom timeframe candle with additional time metadata
Fields:
Open (series float) : Opening price of the candle
High (series float) : Highest price of the candle
Low (series float) : Lowest price of the candle
Close (series float) : Closing price of the candle
polarity (series bool) : Boolean indicating if candle is bullish (true) or bearish (false)
series_index (series int) : Sequential index identifying the candle in the series
open_time (series int) : Timestamp marking when the candle was opened (in Unix time)
time_delta (series float) : Duration of the candle in milliseconds
candle_color (series color) : Color to use when rendering the candle
TickerLibLibrary "TickerLib"
Ticker Library
exists(tickerId)
Test if a tickerId exists
Parameters:
tickerId (string)
Returns: (bool)
notExist(tickerId)
Test if a tickerId do not exists
Parameters:
tickerId (string)
Returns: (bool)
getExchange(tickerId)
Pass a tickerId return the exchange
Parameters:
tickerId (string)
Returns: (string) exchange
isPerp(tickerId)
Test if tickerId is a perps pair
Parameters:
tickerId (string)
Returns: (bool)
isNotPerp(tickerId)
Test if tickerId is not a perps pair
Parameters:
tickerId (string)
Returns: (bool)
getPair(tickerId)
Pass a tickerId return the pair without exchange
Parameters:
tickerId (string)
Returns: (string) the pair
getSpotPair(tickerId)
Pass a tickerId return the pair without exchange and perps
Parameters:
tickerId (string)
Returns: (string) the pair
Casa_TableLibrary "Casa_Table"
A powerful library for creating customizable tables from data arrays and matrices.
Features flexible formatting options including:
- Multiple function implementations for different levels of control
- Consistent column counts required across matrix rows
- Matching dimensions needed for color arrays/matrices
- Cell spanning capabilities across rows/columns
- Rich examples demonstrating proper data structure setup
The library makes it easy to transform your data into professional-looking
tables while maintaining full control over their visual appearance.
floatArrayToCellArray(floatArray)
Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function
Parameters:
floatArray (array) : (array) the float array to convert to a Cell array.
Returns: array The Cell array to return.
stringArrayToCellArray(stringArray)
Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function
Parameters:
stringArray (array) : (array) the array to convert to a Cell array.
Returns: array The Cell array to return.
floatMatrixToCellMatrix(floatMatrix)
Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
floatMatrix (matrix) : (matrix) the float matrix to convert to a string matrix.
Returns: matrix The Cell matrix to render.
stringMatrixToCellMatrix(stringMatrix)
Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
stringMatrix (matrix) : (matrix) the string matrix to convert to a Cell matrix.
Returns: matrix The Cell matrix to return.
fromMatrix(CellMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Takes a CellMatrix and renders it as a table.
Parameters:
CellMatrix (matrix) : (matrix) The Cells to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a float matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a string matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a Cell array as a table.
Parameters:
dataArray (array) : (array) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a string array as a table.
Parameters:
dataArray (array) : (array_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a float array as a table.
Parameters:
dataArray (array) : (array_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
debug(message, position)
Renders a debug message in a table at the desired location on screen.
Parameters:
message (string) : (string) The message to render.
position (string) : (string) Optional. The position of the debug message. Defaults to position.middle_right.
Cell
Type for each cell's content and appearance
Fields:
content (series string)
bgColor (series color)
textColor (series color)
align (series string)
colspan (series int)
rowspan (series int)
Casa_UtilsLibrary "Casa_Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float) : The number to be formatted
Returns: The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: "Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int) : The hour number
minuteNumber (int) : The minute number
Returns: The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple)
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: "Solid", "Dashed", "Dotted", "None/Hidden". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string) : Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: "Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string) : Plain english position string
Returns: The string expected by tradingview functions
getRsiAvgsExpression(rsiLength)
Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
Parameters:
rsiLength (simple int) : The length of the RSI requested.
Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown)
use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
Parameters:
rsiLevel (float) : The RSI level to find price at.
rsiLength (int) : The length of the RSI to calculate.
avgUp (float) : The average move up of RSI.
avgDown (float) : The average move down of RSI.
Returns: The price level where the provided RSI level would be met.
getSizeFromString(sizeString)
Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: "Auto", "Huge", "Large", "Normal", "Small", "Tiny". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
sizeString (string) : Plain english size string
Returns: The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int) : The number of items to find singular/plural for.
Returns: The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string) : The string to be padded
labelStyle (string) : The style of the label being padded for.
Returns: The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int) : The number of items to find singular/plural for.
singular (string) : The string to return if num is singular. Defaults to an empty string.
plural (string) : The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: The number of secondsof that timeframe
timeframeOfChart()
Convert a timeframe string to a consistent standard.
Returns: The standard format for the string, or the unchanged value if it is unknown.
timeframeToString(timeframe)
Convert a timeframe string to a consistent standard.
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
stringToTimeframe(strTimeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
strTimeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor)
Defines a label for the end of a price level line.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelStyle (string) : A plain english string as defined in getLabelStyleFromString.
labelSize (string) : The size of the label.
labelColor (color) : The color of the label.
textColor (color) : The color of the label text (defaults to #ffffff)
Returns: The label that was created.
setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor)
Updates the label position & text based on price changes.
Parameters:
label (label) : The label to update.
labelName (string) : The name of the price level to be placed on the label.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelTemplate (string) : The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
labelStyle (string)
labelColor (color)
textColor (color)
getPriceLabelLine(price, labelOffset, labelColor, lineWidth)
Defines a line that will stretch from the plot line to the label.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelColor (color)
lineWidth (int) : The width of the line. Defaults to 1.
setPriceLabelLine(line, price, labelOffset, lastTime, lineColor)
Updates the price label line based on price changes.
Parameters:
line (line) : The line to update.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
lastTime (int) : The last time that the line should stretch from. Defaults to time.
lineColor (color)
DrawIndicatorOnTheChartLibrary "DrawIndicatorOnTheChart"
this library is used to show an indicator (such RSI, CCI, MOM etc) on the main chart with indicator's horizontal lines in a window. Location of the window is calculated dynamically by last price movemements
drawIndicator(enabled, indicatorName, indicator1, indicator2, indicator3, indicatorcolors, period, indimax_, indimin_, levels, precision, xlocation, lnwidth)
draws the realted indicator on the chart
Parameters:
enabled (bool) : if it's enabled to show
indicatorName (string) : is the indicator name as string such "RSI", "CCI" etc
indicator1 (float) : is first indicator you want to show, such rsi(close, 14), mom(close, 10) etc
indicator2 (float) : is second indicator you want to show, such -DI of DMI
indicator3 (float) : is third indicator you want to show, such ADX of DMI
indicatorcolors (array)
period (int) : is the length of the window to show
indimax_ (float) : is the maximum value of the indicator, for example for RSI it's 100.0, if the indicator (such CCI, MOM etc) doesn't have maximum value then use "na"
indimin_ (float) : is the minimum value of the indicator, for example for RSI it's 0.0, if the indicator (such CCI, MOM etc)doesn't have maximum value then use "na"
levels (array) : is the levels of the array for the horizontal lines. for example if you want horizontal lines at 30.0, and 70.0 then use array.from(30.0, 70.0). if no horizontal lines then use array.from(na)
precision (int) : is the precision/nuber of decimals that is used to show indicator values, for example for RSI set it 2
xlocation (int) : is end location of the indicator window, for example if xlocation = 0 window is created on the index of the last bar/candle
lnwidth (int) : is the line width of the indicator lines
Returns: none
UtilityLibraryLibrary "UtilityLibrary"
A collection of custom utility functions used in my scripts.
milliseconds_per_bar()
Gets the number of milliseconds per bar.
Returns: (int) The number of milliseconds per bar.
realtime()
Checks if the current bar is the actual realtime bar.
Returns: (bool) `true` when the current bar is the actual realtime bar, `false` otherwise.
replay()
Checks if the current bar is the last replay bar.
Returns: (bool) `true` when the current bar is the last replay bar, `false` otherwise.
bar_elapsed()
Checks how much of the current bar has elapsed.
Returns: (float) Between 0 and 1.
even(number)
Checks if a number is even.
Parameters:
number (float) : (float) The number to evaluate.
Returns: (bool) `true` when the number is even, `false` when the number is odd.
sign(number)
Gets the sign of a float.
Parameters:
number (float) : (float) The number to evaluate.
Returns: (int) 1 or -1, unlike math.sign() which returns 0 if the number is 0.
atan2(y, x)
Derives an angle in radians from the XY coordinate.
Parameters:
y (float) : (float) Y coordinate.
x (float) : (float) X coordinate.
Returns: (float) Between -π and π.
clamp(number, min, max)
Ensures a value is between the `min` and `max` thresholds.
Parameters:
number (float) : (float) The number to clamp.
min (float) : (float) The minimum threshold (0 by default).
max (float) : (float) The maximum threshold (1 by default).
Returns: (float) Between `min` and `max`.
remove_gamma(value)
Removes gamma from normalized sRGB channel values.
Parameters:
value (float) : (float) The normalized channel value .
Returns: (float) Channel value with gamma removed.
add_gama(value)
Adds gamma into normalized linear RGB channel values.
Parameters:
value (float) : (float) The normalized channel value .
Returns: (float) Channel value with gamma added.
rgb_to_xyz(Color)
Extracts XYZ-D65 channels from sRGB colors.
Parameters:
Color (color) : (color) The sRGB color to process.
Returns: (float tuple)
xyz_to_rgb(x, y, z)
Converts XYZ-D65 channels to sRGB channels.
Parameters:
x (float) : (float) The X channel value.
y (float) : (float) The Y channel value.
z (float) : (float) The Z channel value.
Returns: (int tuple)
rgb_to_oklab(Color)
Extracts OKLAB-D65 channels from sRGB colors.
Parameters:
Color (color) : (color) The sRGB color to process.
Returns: (float tuple)
oklab_to_rgb(l, a, b)
Converts OKLAB-D65 channels to sRGB channels.
Parameters:
l (float) : (float) The L channel value.
a (float) : (float) The A channel value.
b (float) : (float) The B channel value.
Returns: (int tuple)
rgb_to_oklch(Color)
Extracts OKLCH channels from sRGB colors.
Parameters:
Color (color) : (color) The sRGB color to process.
Returns: (float tuple)
oklch_to_rgb(l, c, h)
Converts OKLCH channels to sRGB channels.
Parameters:
l (float) : (float) The L channel value.
c (float) : (float) The C channel value.
h (float) : (float) The H channel value.
Returns: (float tuple)
hues(l1, h1, l2, h2, dist)
Ensures the hue angles are set correctly for linearly interpolating OKLCH.
Parameters:
l1 (float) : (float) The first L channel value.
h1 (float) : (float) The first H channel value.
l2 (float) : (float) The second L channel value.
h2 (float) : (float) The second H channel value.
dist (string) : (string) The preferred angular distance to use. Options: `min` or `max` (`min` by default).
Returns: (float tuple)
lerp(a, b, t)
Linearly interpolates between two values.
Parameters:
a (float) : (float) The starting point (first value).
b (float) : (float) The ending point (second value).
t (float) : (float) The interpolation factor .
Returns: (float) Between `a` and `b`.
smoothstep(t, precise)
A non-linear (smooth) interpolation between 0 and 1.
Parameters:
t (float) : (float) The interpolation factor .
precise (bool) : (bool) Sets if the calc should be precise or efficient (`true` by default).
Returns: (float) Between 0 and 1.
ease(t, n, v, x1, y1, x2, y2)
A customizable non-linear interpolation between 0 and 1.
Parameters:
t (float) : (float) The interpolation factor .
n (float) : (float) The degree of ease (1 by default).
v (string) : (string) The easing variant type: `in-out`, `in`, or `out` (`in-out` by default).
x1 (float) : (float) Optional X coordinate of starting point (0 by default).
y1 (float) : (float) Optional Y coordinate of starting point (0 by default).
x2 (float) : (float) Optional X coordinate of ending point (1 by default).
y2 (float) : (float) Optional Y coordinate of ending point (1 by default).
Returns: (float) Between 0 and 1.
mix(color1, color2, blend, space, dist)
Linearly interpolates between two colors.
Parameters:
color1 (color) : (color) The first color.
color2 (color) : (color) The second color.
blend (float) : (float) The interpolation factor .
space (string) : (string) The color space to use for interpolating. Options: `rgb`, `oklab`, and `oklch` (`rgb` by default).
dist (string) : (string) The anglular distance to use for the hue change when the color space is set to `oklch`. Options: `min` and `max` (`min` by default).
Returns: (color) Blend of `color1` and `color2`.
PremiumDiscountLibraryLibrary "PremiumDiscountLibrary"
isInZone(currentTime, price, trend, tz)
Vérifie si le prix est en zone premium ou discount
Parameters:
currentTime (int) : L'heure actuelle (timestamp)
price (float) : Le prix actuel
trend (string) : La tendance ("bullish" ou "bearish")
tz (string) : Le fuseau horaire pour calculer les sessions (par défaut : "GMT+1")
Returns: true si le prix est dans la zone correcte, sinon false
Milvetti_TraderPost_LibraryLibrary "Milvetti_TraderPost_Library"
This library has methods that provide practical signal transmission for traderpost.Developed By Milvetti
cancelOrders(symbol)
This method generates a signal in JSON format that cancels all orders for the specified pair. (If you want to cancel stop loss and takeprofit orders together, use the “exitOrder” method.
Parameters:
symbol (string)
exitOrders(symbol)
This method generates a signal in JSON format that close all orders for the specified pair.
Parameters:
symbol (string)
createOrder(ticker, positionType, orderType, entryPrice, signalPrice, qtyType, qty, stopLoss, stopType, stopValue, takeProfit, profitType, profitValue, timeInForce)
This function is designed to send buy or sell orders to traderpost. It can create customized orders by flexibly specifying parameters such as order type, position type, entry price, quantity calculation method, stop-loss, and take-profit. The purpose of the function is to consolidate all necessary details for opening a position into a single structure and present it as a structured JSON output. This format can be sent to trading platforms via webhooks.
Parameters:
ticker (string) : The ticker symbol of the instrument. Default value is the current chart's ticker (syminfo.ticker).
positionType (string) : Determines the type of order (e.g., "long" or "buy" for buying and "short" or "sell" for selling).
orderType (string) : Defines the order type for execution. Options: "market", "limit", "stop". Default is "market"
entryPrice (float) : The price level for entry orders. Only applicable for limit or stop orders. Default is 0 (market orders ignore this).
signalPrice (float) : Optional. Only necessary when using relative take profit or stop losses, and the broker does not support fetching quotes to perform the calculation. Default is 0
qtyType (string) : Determines how the order quantity is calculated. Options: "fixed_quantity", "dollar_amount", "percent_of_equity", "percent_of_position".
qty (float) : Quantity value. Can represent units of shares/contracts or a dollar amount, depending on qtyType.
stopLoss (bool) : Enable or disable stop-loss functionality. Set to `true` to activate.
stopType (string) : Specifies the stop-loss calculation type. Options: percent, "amount", "stopPrice", "trailPercent", "trailAmount". Default is "stopPrice"
stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount, or a specific stop price. Default is "stopPrice"
takeProfit (bool) : Enable or disable take-profit functionality. Set to `true` to activate.
profitType (string) : Specifies the take-profit calculation type. Options: "percent", "amount", "limitPrice". Default is "limitPrice"
profitValue (float) : Take-profit value based on profitType. Can be a percentage, dollar amount, or a specific limit price. Default is 0
timeInForce (string) : The time in force for your order. Options: day, gtc, opg, cls, ioc and fok
Returns: Return result in Json format.
addTsl(symbol, stopType, stopValue, price)
This method adds trailing stop loss to the current position. “Price” is the trailing stop loss starting level. You can leave price blank if you want it to start immediately
Parameters:
symbol (string)
stopType (string) : Specifies the trailing stoploss calculation type. Options: "trailPercent", "trailAmount".
stopValue (float) : Stop-loss value based on stopType. Can be a percentage, dollar amount.
price (float) : The trailing stop loss starting level. You can leave price blank if you want it to start immediately. Default is current price.
BacktestLibraryLibrary "BacktestLibrary"
A library providing functions for equity calculation and performance metrics.
since(date, active)
: Calculates the number of candles since a specified date.
Parameters:
date (simple float) : (simple float): The starting date in timestamp format (e.g., input.time(timestamp()))
active (simple bool) : (simple bool): If true, counts the number of candles since the date; if false, returns 0.
Returns: (int): The number of candles since the specified date.
buy_and_hold(r, startDate)
: Calculates the Buy and Hold Equity from a specified date.
Parameters:
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float): Buy and Hold Equity of the asset from the specified date.
equity(sig, threshold, r, startDate, signals)
: Calculates the strategy's equity on a candle-by-candle basis.
Parameters:
sig (float) : (series float): Signal values; positive for long, negative for short.
threshold (simple float) : (simple float): Signal threshold for entering trades.
r (float) : (series float): Daily returns of the asset (e.g., 0.02 for 2% move).
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
signals (simple string) : (simple string): Type of signals to backtest ("Long & Short", "Long Only", "Short Only").
Returns: (float): Strategy equity on a candle-by-candle basis.
PerformanceMetrics(base, Lookback, startDate)
: Calculates performance metrics of a strategy from a specified date.
Parameters:
base (float) : (series float): Equity values of the strategy or Buy and Hold equity.
Lookback (int) : (series int): Number of periods since the start date; recommended to use the 'since' function.
startDate (simple float) : (simple float): Timestamp of the starting date for the equity calculation.
Returns: (float ): Array of performance metrics.
PerfMetricTable(buy_and_hold, strategy)
: Plots a table comparing performance metrics of Buy and Hold and Strategy equity.
Parameters:
buy_and_hold (array) : (float ): Metrics from the PerformanceMetrics() function for Buy and Hold.
strategy (array) : (float ): Metrics from the PerformanceMetrics() function for the strategy.
Returns: : Table displaying the performance metrics comparison.
hinton_map█ HINTON MAP
This library provides functions to create and display a Hinton Map visualization. A Hinton map uses squares to represent the magnitude and direction of values in a matrix. This library allows you to display multiple ticker/timeframe/indicator combinations on a single chart, using color/boxsize/bnordersize to represent the values used. The values must be from -1.0 to 1.0 in value. 3 different values can be input per square.
Example Usage:
The example below demonstrates how to create a Hinton Map for two symbols (AAPL and MSFT) across three timeframes (1 minute, 5 minutes, and 1 day).
var hintonData = hinton_map.initHintonData(2, 3)
tickers = array.from("AAPL", "MSFT")
timeframes = array.from("1", "5", "1D")
for i = 0 to array.size(tickers) - 1
for j = 0 to array.size(timeframes) - 1
ticker = array.get(tickers, i)
timeframe = array.get(timeframes, j)
= request.security(ticker, timeframe, [close, close , ta.rsi(close, 14)], lookahead = barmerge.lookahead_on)
percent_change = (close_current - close_previous) / close_previous * 100
rsi_deviation = rsi_current - 50
hintonData.unitMatrix.set(i, j, hinton_map.createHintonUnit(
fillValue = percent_change,
borderValue = rsi_deviation,
innerValue = percent_change * rsi_deviation,
boxText = dv.from_string(str.tostring(math.round(percent_change, 2)) + "%"),
tooltipText = dv.from_string(syminfo.ticker + ", " + timeframe + ": " + str.tostring(math.round(percent_change, 2)) + "%, RSI: " + str.tostring(math.round(rsi_current, 2)))
))
hinton_map.drawHintonMap(hintonData)
█ createHintonUnit
Creates a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
Default Value: 0.0
• borderValue
Value to determine the border color hue and width.
Type: float
Default Value: 0.0
• innerValue
Value to determine the inner box color hue.
Type: float
Default Value: 0.0
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
Default Value: na
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
Default Value: na
Returns: HintonUnit
█ initHintonData
Initializes Hinton map data structure.
• rows
Number of rows.
Type: int
• columns
Number of columns.
Type: int
Returns: HintonData
█ drawHintonMap
Draws a Hinton map.
• hintonData
Hinton map data.
Type: HintonData
• unitSize
Size of each unit in bars.
Type: int
Default Value: 10
• borderWidth
Base width of the inner box border.
Type: int
Default Value: 5
• plusHue
Hue value for positive values (0-360).
Type: float
Default Value: 180
• minusHue
Hue value for negative values (0-360).
Type: float
Default Value: -30
█ HintonUnit
Data for a Hinton unit.
• fillValue
Value to determine the fill color hue.
Type: float
• borderValue
Value to determine the border color hue and width.
Type: float
• innerValue
Value to determine the inner box color hue.
Type: float
• boxText
Text to display in the inner box.
Type: dv.DisplayValue
• tooltipText
Tooltip text for the inner box.
Type: dv.DisplayValue
█ HintonData
Structure to store Hinton map data.
• unitMatrix
Matrix of Hinton units.
Type: matrix
• lineMatrix
Matrix of lines.
Type: matrix
• labelMatrix
Matrix of labels.
Type: matrix
• boxMatrix
Matrix of boxes.
Type: matrix
• fillMatrix
Matrix of line fills.
Type: matrix
MarketStructureLibrary "MarketStructure"
Will draw out the market structure for the disired pivot length. The code is from my indicator "Marker structure" ().
Create(type, length, source, equalPivotsFactor, extendEqualPivotsZones, equalPivotsStyle, equalPivotsColor, alertFrequency)
Call on each bar. Will create a Structure object.
Parameters:
type (int) : the type of the Structure to create. 0 = internal, 1 = swing.
length (int) : The lenghts (left and right) for pivots to use.
source (string) : The source to be used for structural changes ('Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend)).
equalPivotsFactor (float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
extendEqualPivotsZones (bool) : Set to true if you want the equal pivots zones to be extended.
equalPivotsStyle (string) : Set the style of equal pivot zones.
equalPivotsColor (color) : Set the color of equal pivot zones.
alertFrequency (string)
Returns: The 'structure' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
Returns: The 'structure' object.
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
Returns: The 'structure' object.
EqualHighOrLow(structure)
Draws the boxsa for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
Returns: The 'structure' object.
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
ChangeOfCharacter(structure)
Will create lines when a change of character occures.
Parameters:
structure (Structure)
Returns: The 'structure' object.
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
Structure
Holds all the values for the market structure.
Fields:
Length (series int) : Define the left and right lengths of the pivots used.
Type (series int) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
Source (series string) : Set the source for structural chandeg. Can be 'Close', 'High/low (aggresive)' (low in an uptrend) or 'High/low (passive)' (high in an uptrend).
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
AlertFrequency (series string) : set the frequency for alerts.
OrderBlocksLibrary "OrderBlocks"
This is a library I created that creates order blocks. It's originated from my indicator "Order blocks" (). It will return a Zone object that can be used to draw an order block. If you want to see how that is done you can check out my indicar that uses the same logic.
Create(settings)
Creates an order block if one is found according to the settings parameter.
Parameters:
settings (Settings) : set all values in this parameter to define the settings for the order block creation.
Returns: a Zone object if an order block is found, na otherwise
Zone
Fields:
Time (series int)
TimeClose (series int)
High (series float)
Low (series float)
ReactionLimit (series float)
TouchedZone (Zone type from mickes/Touched/14)
Type (series int)
Zones
Fields:
Index (series int)
Maximum (series int)
Zones (array)
Remove (Zone)
Settings
Fields:
TakeOut (series bool)
ReactionFactor (series float)
Type (series string)
ConsecutiveRisingOrFalling (series bool)
FairValueGap (series bool)
MonthlyReturnsTableLibrary "MonthlyReturnsTable"
showMonthlyReturns(show)
显示月度和年度收益率表格
Parameters:
show (bool) : (bool) 是否显示表格
Returns: 返回一个数组,包含是否显示表格的状态和当前月度收益率
DRKMetricsLibrary "DRKMetrics"
TODO: add library description here
curve(disp_ind)
Call function to get a certain curve of your strategy.
Parameters:
disp_ind (string)
Returns: Returns type of curve plot.
cleaner(disp_ind, plot)
Call function to filter out your Strategy plots
Parameters:
disp_ind (string)
plot (float)
cobraTable(option, position)
Assign this function to a random variable to get the "Performance Table"
Parameters:
option (simple string)
position (simple string)
UtilityLibrary "Utility"
A utility library for various trading tools such as signal generation, custom indicators, and multi-condition crossovers.
multiCrossover(source1, source2, threshold1, threshold2)
multiCrossover
@description Detects multi-condition crossovers between two sources with threshold filters.
Parameters:
source1 (float) : The first data series to compare.
source2 (float) : The second data series to compare.
threshold1 (float) : A value that source1 must exceed to trigger the crossover.
threshold2 (float) : A value that source2 must exceed to trigger the crossunder.
Returns: A tuple: (crossUp, crossDown) where crossUp is a boolean for upward crossover, and crossDown is for downward crossover.
macdCustom(source, fastLength, slowLength, signalLength, macdThresh)
macdCustom
@description Calculates custom MACD signals based on thresholds.
Parameters:
source (float) : The price data or input series.
fastLength (simple int) : The length of the fast EMA.
slowLength (simple int) : The length of the slow EMA.
signalLength (simple int) : The signal line length.
macdThresh (float) : A threshold for the MACD line to confirm buy/sell signals.
Returns: A tuple: (macdBuySignal, macdSellSignal) where macdBuySignal is true when MACD crosses above, and macdSellSignal is true when MACD crosses below the signal line.
combinedMacdRsi(source, fastLength, slowLength, signalLength, rsiLength, macdThresh, rsiThresh)
combinedMacdRsi
@description Generates combined signals from MACD and RSI indicators.
Parameters:
source (float) : The price data or input series.
fastLength (simple int) : The length of the fast EMA for MACD.
slowLength (simple int) : The length of the slow EMA for MACD.
signalLength (simple int) : The signal line length for MACD.
rsiLength (simple int) : The length of the RSI calculation.
macdThresh (float) : The threshold for MACD signals.
rsiThresh (float) : The threshold for RSI signals.
Returns: A tuple: (buySignal, sellSignal) where buySignal is generated when MACD is positive and RSI is below the threshold, and sellSignal when MACD is negative and RSI is above the threshold.
movingAverageCrossover(source, shortLength, longLength)
movingAverageCrossover
@description Detects crossovers between short-term and long-term moving averages.
Parameters:
source (float) : The price data or input series.
shortLength (int) : The length of the short-term moving average.
longLength (int) : The length of the long-term moving average.
Returns: A tuple: (crossUp, crossDown) where crossUp is true when the short-term MA crosses above the long-term MA, and crossDown when the reverse occurs.
Autotable█ OVERVIEW
The library allows to automatically draw a table based on a string or float matrix (or both) controlling all of the parameters of the table (including merging cells) with parameter matrices (like, e.g. matrix of cell colors).
All things you would normally do with table.new() and table.cell() are now possible using respective parameters of library's main function, autotable() (as explained further below).
Headers can be supplied as arrays.
Merging of the cells is controlled with a special matrix of "L" and "U" values which instruct a cell to merged with the cell to the left or upwards (please see examples in the script and in this description).
█ USAGE EXAMPLES
The simplest and most straightforward:
mxF = matrix.new(3,3, 3.14)
mxF.autotable(bgcolor = color.rgb(249, 209, 29)) // displays float matrix as a table in the top right corner with defalult settings
mxS = matrix.new(3,3,"PI")
// displays string matrix as a table in the top right corner with defalult settings
mxS.autotable(Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// displays matrix displaying a string value over a float value in each cell
mxS.autotable(mxF, Ypos = "middle", Xpos = "center", bgcolor = color.gray, text_color = #86f62a)
Draws this:
Tables with headers:
if barstate.islast
mxF = matrix.new(3,3, 3.14)
mxS = matrix.new(3,3,"PI")
arColHeaders = array.from("Col1", "Col2", "Col3")
arRowHeaders = array.from("Row1", "Row2", "Row3")
// float matrix with col headers
mxF.autotable(
bgcolor = #fdfd6b
, arColHeaders = arColHeaders
)
// string matrix with row headers
mxS.autotable(arRowHeaders = arRowHeaders, Ypos = "bottom", Xpos = "right", bgcolor = #b4d400)
// string/float matrix with both row and column headers
mxS.autotable(mxF
, Ypos = "middle", Xpos = "center"
, arRowHeaders = arRowHeaders
, arColHeaders = arColHeaders
, cornerBgClr = #707070, cornerTitle = "Corner cell", cornerTxtClr = #ffdc13
, bgcolor = color.gray, text_color = #86f62a
)
Draws this:
█ FUNCTIONS
One main function is autotable() which has only one required argument mxValS, a string matrix.
Please see below the description of all of the function parameters:
The table:
tbl (table) (Optional) If supplied, this table will be deleted.
The data:
mxValS (matrix ) (Required) Cell text values
mxValF (matrix) (Optional) Numerical part of cell text values. Is concatenated to the mxValS values via `string_float_separator` string (default " ")
Table properties, have same effect as in table.new() :
defaultBgColor (color) (Optional) bgcolor to be used if mxBgColor is not supplied
Ypos (string) (Optional) "top", "bottom" or "center"
Xpos (string) (Optional) "left", "right", or "center"
frame_color (color) (Optional) frame_color like in table.new()
frame_width (int) (Optional) frame_width like in table.new()
border_color (color) (Optional) border_color like in table.new()
border_width (int) (Optional) border_width like in table.new()
force_overlay (simple bool) (Optional) If true draws table on main pane.
Cell parameters, have same effect as in table.cell() ):
mxBgColor (matrix) (Optional) like bgcolor argument in table.cell()
mxTextColor (matrix) (Optional) like text_color argument in table.cell()
mxTt (matrix) (Optional) like tooltip argument in table.cell()
mxWidth (matrix) (Optional) like width argument in table.cell()
mxHeight (matrix) (Optional) like height argument in table.cell()
mxHalign (matrix) (Optional) like text_halign argument in table.cell()
mxValign (matrix) (Optional) like text_valign argument in table.cell()
mxTextSize (matrix) (Optional) like text_size argument in table.cell()
mxFontFamily (matrix) (Optional) like text_font_family argument in table.cell()
Other table properties:
tableWidth (float) (Optional) Overrides table width if cell widths are non zero. E.g. if there are four columns and cell widths are 20 (either as set via cellW or via mxWidth) then if tableWidth is set to e.g. 50 then cell widths will be 50 * (20 / 80), where 80 is 20*4 = total width of all cells. Works simialar for widths set via mxWidth - determines max sum of widths across all cloumns of mxWidth and adjusts cell widths proportionally to it. If cell widths are 0 (i.e. auto-adjust) tableWidth has no effect.
tableHeight (float) (Optional) Overrides table height if cell heights are non zero. E.g. if there are four rows and cell heights are 20 (either as set via cellH or via mxHeight) then if tableHeigh is set to e.g. 50 then cell heights will be 50 * (20 / 80), where 80 is 20*4 = total height of all cells. Works simialar for heights set via mxHeight - determines max sum of heights across all cloumns of mxHeight and adjusts cell heights proportionally to it. If cell heights are 0 (i.e. auto-adjust) tableHeight has no effect.
defaultTxtColor (color) (Optional) text_color to be used if mxTextColor is not supplied
text_size (string) (Optional) text_size to be used if mxTextSize is not supplied
font_family (string) (Optional) cell text_font_family value to be used if a value in mxFontFamily is no supplied
cellW (float) (Optional) cell width to be used if a value in mxWidth is no supplied
cellH (float) (Optional) cell height to be used if a value in mxHeight is no supplied
halign (string) (Optional) cell text_halign value to be used if a value in mxHalign is no supplied
valign (string) (Optional) cell text_valign value to be used if a value in mxValign is no supplied
Headers parameters:
arColTitles (array) (Optional) Array of column titles. If not na a header row is added.
arRowTitles (array) (Optional) Array of row titles. If not na a header column is added.
cornerTitle (string) (Optional) If both row and column titles are supplied allows to set the value of the corner cell.
colTitlesBgColor (color) (Optional) bgcolor for header row
colTitlesTxtColor (color) (Optional) text_color for header row
rowTitlesBgColor (color) (Optional) bgcolor for header column
rowTitlesTxtColor (color) (Optional) text_color for header column
cornerBgClr (color) (Optional) bgcolor for the corner cell
cornerTxtClr (color) (Optional) text_color for the corner cell
Cell merge parameters:
mxMerge (matrix) (Optional) A matrix determining how cells will be merged. "L" - cell merges to the left, "U" - upwards.
mergeAllColTitles (bool) (Optional) Allows to print a table title instead of column headers, merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
mergeAllRowTitles (bool) (Optional) Allows to print one text value merging all header row cells and leaving just the value of the first cell. For more flexible options use matrix arguments leaving header/row arguments na.
Format:
string_float_separator (string) (Optional) A string used to separate string and float parts of cell values (mxValS and mxValF). Default is " "
format (string) (Optional) format string like in str.format() used to format numerical values
nz (string) (Optional) Determines how na numerical values are displayed.
The only other available function is autotable(string,... ) with a string parameter instead of string and float matrices which draws a one cell table.
█ SAMPLE USE
E.g., CSVParser library demo uses Autotable's for generating complex tables with merged cells.
█ CREDITS
The library was inspired by @kaigouthro's matrixautotable . A true master. Many thanks to him for his creative, beautiful and very helpful libraries.
display_valueOVERVIEW
This script is a tinny library for creating and displaying formatted values in TradingView scripts. It provides a structured way to present key information like titles, percentages, currency values, decimals, and integers with clear formatting. This allows you to coordinate your strings in advance and hold one item to use for calling your string to a label, box, table.. Made for day to day use of most typical use cases, more advanced techniques should be used for complicated scenarios.
Building Blocks
User Defined Types (UDTs)
The script defines a UDT called `DisplayValue` to encapsulate the components of a display value:
* title : The title or label of the value.
* format_string : The string used to format the value (e.g., "{0} - 1,number,percent}").
* value : The actual value to be displayed.
* format : An enum value specifying the desired format (percent, currency, etc.).
Enums
The `DisplayFormat` enum provides predefined constants for various formatting options, making the code more readable and less prone to errors.
Functions
* create() : This function creates a new `DisplayValue` instance. It takes the title, value, and desired format as arguments and generates the appropriate format string.
* to_string() : This function converts a `DisplayValue` instance into a formatted string ready for display on the chart.
How to Use
1. Import the library:
import kaigouthro/display_value/1as dv
2. Create a DisplayValue instance:
myValue = dv.create("My Percentage", 0.5, dv.DisplayFormat.percent)
3. Convert it to a string:
formattedString = dv.to_string(myValue)
4. Display the formatted string:
label.new(bar_index, high, formattedString)
Example
//@version=5
import kaigouthro/display_value/1 as dv
myValue = dv.create("Profit", 0.15, dv.DisplayFormat.percent)
formattedString = dv.to_string(myValue)
label.new(bar_index, high, formattedString)
This will display a label on the chart with the text "Profit - 15%".
### Notes
* The library handles the formatting details, making it easier to display values consistently in your scripts.
* The use of enums and UDTs improves code organization and readability.
--------
Library "display_value"
create(display_name, display_value, display_format)
Gets the appropriate format string based on the display format.
Parameters:
display_name (string) : (string) The name of the display value. Default is na.
display_value (float)
display_format (series DisplayFormat)
Returns: (DisplayValue) A new DisplayValue instance with the formatted value.
to_string(item)
Converts the display value to a string with the specified format.
Parameters:
item (DisplayValue) : (DisplayValue) The display value to convert to a string.
Returns: (string) The string representation of the display value.
DisplayValue
Structure representing a display value.
Fields:
title (series string) : (string) The title of the display value.
format_string (series string) : (string) The format string to use for display.
value (series float) : (float) The value to display.
format (series DisplayFormat) : (DisplayFormat) The format to use.
analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics