lib_zigLibrary "lib_zig"
Object oriented implementation of ZigZag
method tostring(this, date_format)
Namespace types: Zigzag
Parameters:
this (Zigzag)
date_format (simple string)
method update(this)
Namespace types: Zigzag
Parameters:
this (Zigzag)
method draw(this, colors)
Namespace types: Zigzag
Parameters:
this (Zigzag)
colors (PivotColors type from robbatt/lib_pivot/19)
Zigzag
Fields:
max_pivots (series__integer)
hldata (|robbatt/lib_pivot/19;HLData|#OBJ)
pivots (array__|robbatt/lib_pivot/19;Pivot|#OBJ)
Framework
lib_pivotLibrary "lib_pivot"
Object oriented implementation of Pivot methods.
method tostring(this)
Converts HLData to a json string representation
Namespace types: HLData
Parameters:
this (HLData) : HLData
Returns: string representation of Pivot
method tostring(this, date_format)
Namespace types: Pivot
Parameters:
this (Pivot)
date_format (simple string)
method tostring(this, date_format)
Namespace types: Pivot
Parameters:
this (Pivot )
date_format (simple string)
method get_color(this, mode)
Namespace types: PivotColors
Parameters:
this (PivotColors)
mode (int)
method get_label_text(this)
Namespace types: Pivot
Parameters:
this (Pivot)
method direction(this)
Namespace types: Pivot
Parameters:
this (Pivot)
method same_direction_as(this, other)
Namespace types: Pivot
Parameters:
this (Pivot)
other (Pivot)
method exceeds(this, price)
Namespace types: Pivot
Parameters:
this (Pivot)
price (float)
method exceeds(this, other)
Namespace types: Pivot
Parameters:
this (Pivot)
other (Pivot)
method exceeded_by(this, price)
Namespace types: Pivot
Parameters:
this (Pivot)
price (float)
method exceeded_by(this, other)
Namespace types: Pivot
Parameters:
this (Pivot)
other (Pivot)
method retracement_ratio(this, lastPivot, sec_lastPivot)
Namespace types: Pivot
Parameters:
this (Pivot)
lastPivot (Pivot)
sec_lastPivot (Pivot)
ratio_target(sec_lastPivot, lastPivot, target_ratio)
Parameters:
sec_lastPivot (Pivot)
lastPivot (Pivot)
target_ratio (float)
method update(this, ref_highest, ref_lowest)
Namespace types: HLData
Parameters:
this (HLData)
ref_highest (float)
ref_lowest (float)
method update(this, bar_time, bar_idx, price, prev)
Namespace types: Pivot
Parameters:
this (Pivot)
bar_time (int)
bar_idx (int)
price (float)
prev (Pivot)
method create_next(this, bar_time, bar_idx, price)
Namespace types: Pivot
Parameters:
this (Pivot)
bar_time (int)
bar_idx (int)
price (float)
HLData
HLData wraps the data received from ta.highest, ta.highestbars, ta.lowest, ta.lowestbars, as well as the reference sources
Fields:
length (series int) : lookback length for pivot points
highest_offset (series int) : offset to highest value bar
lowest_offset (series int) : offset to lowest value bar
highest (series float) : highest value within lookback bars
lowest (series float) : lowest value within lookback bars
new_highest (series bool) : update() will set this true if the current candle forms a new highest high at the last (current) bar of set period (length)
new_lowest (series bool) : update() will set this true if the current candle forms a new lowest low at the last (current) bar of set period (length)
new_highest_fractal (series bool) : update() will set this true if the current candle forms a new fractal high at the center of set period (length)
new_lowest_fractal (series bool) : update() will set this true if the current candle forms a new fractal low at the center of set period (length)
PivotColors
Pivot colors for different modes
Fields:
hh (series color) : Color for Pivot mode 2 (HH)
lh (series color) : Color for Pivot mode 1 (LH)
hl (series color) : Color for Pivot mode -1 (HL)
ll (series color) : Color for Pivot mode -2 (LL)
Pivot
Pivot additional pivot data around basic Point
Fields:
point (Point type from robbatt/lib_plot_objects/5)
mode (series int) : can be -2/-1/1/2 for LL/HL/LH/HH
price_movement (series float) : The price difference between this and the previous pivot point in the opposite direction
retracement_ratio (series float) : The ratio between this price_movement and the previous
prev (Pivot)
lib_plot_objectsLibrary "lib_plot_objects"
library wrapping basic builtin object constructors, to be able to do calculations with points/lines/boxes/triangles/polygons via libraries and on securities. inspired by Trendoscope's ( and ) with added update mechanism to not have to recreate objects on every iteration for continously drawn items, automated xloc selection for coordinates, compatibility check for Points, added Triangle and Polygon types, object reflection via tostring to valid json (logging via webhook)
method assert_same_xloc(a, b, test)
checks two points for compatibility, i.e. having the same xloc
Namespace types: Point
Parameters:
a (Point)
b (Point)
test (Test type from robbatt/lib_unit/6)
method assert_same_xloc(a, b, test)
checks two lines for compatibility, i.e. having the same xloc
Namespace types: Line
Parameters:
a (Line)
b (Line)
test (Test type from robbatt/lib_unit/6)
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: 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 x(point, xloc)
automatically returns the correct x coordinate, based on the point's set xloc
Namespace types: Point
Parameters:
point (Point)
xloc (string)
method tostring(this, date_format)
converts object to json representation
Namespace types: Point
Parameters:
this (Point)
date_format (string)
method tostring(this, date_format)
converts object to json representation
Namespace types: Point
Parameters:
this (Point )
date_format (string)
method tostring(this)
converts object to json representation
Namespace types: LineArgs
Parameters:
this (LineArgs)
method tostring(this, date_format)
converts object to json representation
Namespace types: Line
Parameters:
this (Line)
date_format (string)
method tostring(this)
Namespace types: LabelArgs
Parameters:
this (LabelArgs)
method tostring(this, date_format)
Namespace types: Label
Parameters:
this (Label)
date_format (string)
method tostring(this, date_format)
Namespace types: LineFill
Parameters:
this (LineFill)
date_format (string)
method tostring(this)
Namespace types: BoxArgs
Parameters:
this (BoxArgs)
method tostring(this)
Namespace types: BoxTextArgs
Parameters:
this (BoxTextArgs)
method tostring(this, date_format)
Namespace types: Box
Parameters:
this (Box)
date_format (string)
method tostring(this, date_format)
Namespace types: Triangle
Parameters:
this (Triangle)
date_format (string)
method tostring(this, date_format)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
date_format (string)
method tostring(this, date_format)
Namespace types: Polygon
Parameters:
this (Polygon)
date_format (string)
method tostring(this, date_format)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
date_format (string)
method tostring(this, date_format)
Namespace types: Line
Parameters:
this (Line )
date_format (string)
method tostring(this, date_format)
Namespace types: Box
Parameters:
this (Box )
date_format (string)
method tostring(this, date_format)
Namespace types: Triangle
Parameters:
this (Triangle )
date_format (string)
method tostring(this, date_format)
Namespace types: Polygon
Parameters:
this (Polygon )
date_format (string)
method tostring(this, date_format)
Namespace types: PolygonFill
Parameters:
this (PolygonFill )
date_format (string)
method create_center(points)
Namespace types: Point
Parameters:
points (Point )
method create_center(this, other)
Namespace types: Point
Parameters:
this (Point)
other (Point)
method create_center(this)
Namespace types: Line
Parameters:
this (Line)
method create_line(this, other, args)
Namespace types: Point
Parameters:
this (Point)
other (Point)
args (LineArgs)
method create_triangle(this, b, c, args)
Namespace types: Point
Parameters:
this (Point)
b (Point)
c (Point)
args (LineArgs)
method create_triangle(this, c)
Namespace types: Line
Parameters:
this (Line)
c (Point)
method create_box(this, other, txt, args, text_args)
Namespace types: Point
Parameters:
this (Point)
other (Point)
txt (string)
args (BoxArgs)
text_args (BoxTextArgs)
method create_box(this, txt, args, text_args)
Namespace types: Line
Parameters:
this (Line)
txt (string)
args (BoxArgs)
text_args (BoxTextArgs)
method create_polygon(points, args)
Namespace types: Point
Parameters:
points (Point )
args (LineArgs)
method create_polygon(start, others, args)
Namespace types: Point
Parameters:
start (Point)
others (Point )
args (LineArgs)
method create_fill(this, other, fill_color)
Namespace types: Line
Parameters:
this (Line)
other (Line)
fill_color (color)
method create_fill(this, fill_color)
Namespace types: Triangle
Parameters:
this (Triangle)
fill_color (color)
method create_fill(this, fill_color)
Namespace types: Polygon
Parameters:
this (Polygon)
fill_color (color)
method create_label(this, txt, args, tooltip)
Namespace types: Point
Parameters:
this (Point)
txt (string)
args (LabelArgs)
tooltip (string)
method create_label(this, txt, args, tooltip)
Namespace types: Line
Parameters:
this (Line)
txt (string)
args (LabelArgs)
tooltip (string)
method create_label(this, txt, args, tooltip)
Namespace types: Box
Parameters:
this (Box)
txt (string)
args (LabelArgs)
tooltip (string)
method create_label(this, txt, args, tooltip)
Namespace types: Triangle
Parameters:
this (Triangle)
txt (string)
args (LabelArgs)
tooltip (string)
method create_label(this, txt, args, tooltip)
Namespace types: Polygon
Parameters:
this (Polygon)
txt (string)
args (LabelArgs)
tooltip (string)
method update(this, bar_time, bar_idx, price)
Namespace types: Point
Parameters:
this (Point)
bar_time (int)
bar_idx (int)
price (float)
method update(this, update)
Namespace types: Point
Parameters:
this (Point)
update (Point)
method update(this, point)
Namespace types: Label
Parameters:
this (Label)
point (Point)
method update(this, start, end)
Namespace types: Line
Parameters:
this (Line)
start (Point)
end (Point)
method update(this, left_top, right_bottom)
Namespace types: Box
Parameters:
this (Box)
left_top (Point)
right_bottom (Point)
method update(this, a, b, c)
Namespace types: Triangle
Parameters:
this (Triangle)
a (Point)
b (Point)
c (Point)
method update(this, points)
Namespace types: Polygon
Parameters:
this (Polygon)
points (Point )
method delete(this)
Namespace types: Line
Parameters:
this (Line)
method delete(this)
Namespace types: Label
Parameters:
this (Label)
method delete(this)
Namespace types: LineFill
Parameters:
this (LineFill)
method delete(this)
Namespace types: Box
Parameters:
this (Box)
method delete(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
method delete(this)
Namespace types: Triangle
Parameters:
this (Triangle)
method delete(this)
Namespace types: Polygon
Parameters:
this (Polygon)
method delete(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
method delete(this)
Namespace types: Line
Parameters:
this (Line )
method delete(this)
Namespace types: Label
Parameters:
this (Label )
method delete(this)
Namespace types: LineFill
Parameters:
this (LineFill )
method delete(this)
Namespace types: Box
Parameters:
this (Box )
method delete(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill )
method delete(this)
Namespace types: Polygon
Parameters:
this (Polygon )
method delete(this)
Namespace types: Triangle
Parameters:
this (Triangle )
method delete(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill )
method draw(this)
Namespace types: Label
Parameters:
this (Label)
method draw(this)
Namespace types: Line
Parameters:
this (Line)
method draw(this)
Namespace types: Box
Parameters:
this (Box)
method draw(this)
Namespace types: Triangle
Parameters:
this (Triangle)
method draw(this)
Namespace types: Polygon
Parameters:
this (Polygon)
method draw(this)
Namespace types: LineFill
Parameters:
this (LineFill)
method draw(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
method draw(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
Point
Fields:
bar_time (series int) : time based x coordinate
bar_idx (series int) : bar index based x coordinate
price (series float) : price based y coordinate
xloc (series string) : To select if x coordinate is represented by bar_idx or bar_time. Possible values: xloc.bar_index and xloc.bar_time. Default is xloc.bar_index.
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.
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 (Point) : The Label coordinates
txt (series string) : Label text. Default is empty string.
args (LabelArgs) : Wrapper for reusable arguments for label.new()
tooltip (series string) : Hover to see tooltip label.
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.
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 (Point) : starting point of the line
end (Point)
args (LineArgs) : Wrapper for reusable arguments for line.new()
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.
plot (series linefill) : The linefill object to be added and plotted via draw()
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.
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 (Point) : top-left corner of the box
right_bottom (Point) : bottom-right corner of the box
txt (series string) : The text to be displayed inside the box. Optional. The default is empty string.
args (BoxArgs) : Wrapper for reusable arguments for box.new()
text_args (BoxTextArgs)
plot (series box) : The box object to be added and plotted via draw()
Triangle
Fields:
a (Point) : first Corner
b (Point) : second Corner
c (Point) : third Corner
args (LineArgs) : Wrapper for reusable arguments for line.new()
plot_ab (series line) : The line object to be added and plotted via draw()
plot_ac (series line) : The line object to be added and plotted via draw()
plot_bc (series line) : The line object to be added and plotted via draw()
TriangleFill
Fields:
triangle (Triangle) : The Triangle object
fill_color (series color) : The color used to fill the space between the lines.
plot (series linefill) : The linefill object to be added and plotted via draw()
Polygon
Fields:
points (Point ) : array of points that make up the Polygon
center (Point) : Center point of the Polygon, can be used for a label and will be center for PolygonFill
args (LineArgs) : Wrapper for reusable arguments for line.new()
plot (line ) : An array of Lines that form Polygon Border
PolygonFill
Fields:
poly (Polygon) : the Polygon
fill_color (series color) : The color used to fill the space between the lines.
plot_segments (line ) : An array of helper lines to create linefills
plot_fills (linefill ) : An array of linefills that cover the Polygon surface
lib_drawing_compositesLibrary "lib_drawing_composites"
methods to draw and manage composite obejects. Based on Trendoscope's added Triangle and Polygon composite objects, fixed tostring method output to be actual json
method tostring(this, format_date, format, tz, pretty)
Converts lib_drawing_types/LineProperties object to a json string representation
Namespace types: D.Point
Parameters:
this (Point type from HeWhoMustNotBeNamed/DrawingTypes/2) : lib_drawing_types/LineProperties object
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool) : if true adds a line feed after every property and a space before properties (default: true)
Returns: string representation of lib_drawing_types/LineProperties
method tostring(this, pretty)
Converts lib_drawing_types/LabelProperties object to a json string representation
Namespace types: D.LineProperties
Parameters:
this (LineProperties type from HeWhoMustNotBeNamed/DrawingTypes/2) : lib_drawing_types/LabelProperties object
pretty (simple bool) : if true adds a line feed after every property and a space before properties (default: true)
Returns: string representation of lib_drawing_types/LabelProperties
method tostring(this, format_date, format, tz, pretty)
Converts lib_drawing_types/BoxProperties object to a json string representation
Namespace types: D.Line
Parameters:
this (Line type from HeWhoMustNotBeNamed/DrawingTypes/2) : lib_drawing_types/BoxProperties object
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool) : if true adds a line feed after every property and a space before properties (default: true)
Returns: string representation of lib_drawing_types/BoxProperties
method tostring(this, pretty)
Converts lib_drawing_types/BoxText object to a json string representation
Namespace types: D.LabelProperties
Parameters:
this (LabelProperties type from HeWhoMustNotBeNamed/DrawingTypes/2) : lib_drawing_types/BoxText object
pretty (simple bool) : if true adds a line feed after every property and a space before properties (default: true)
Returns: string representation of lib_drawing_types/BoxText
method tostring(this, format_date, format, tz, pretty)
Converts lib_drawing_types/TriangleProperties object to a json string representation
Namespace types: D.Label
Parameters:
this (Label type from HeWhoMustNotBeNamed/DrawingTypes/2) : lib_drawing_types/TriangleProperties object
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool) : if true adds a line feed after every property and a space before properties (default: true)
Returns: string representation of lib_drawing_types/TriangleProperties
method tostring(this, format_date, format, tz, pretty)
Namespace types: D.Linefill
Parameters:
this (Linefill type from HeWhoMustNotBeNamed/DrawingTypes/2)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method tostring(this, pretty)
Namespace types: D.BoxProperties
Parameters:
this (BoxProperties type from HeWhoMustNotBeNamed/DrawingTypes/2)
pretty (simple bool)
method tostring(this, pretty)
Namespace types: D.BoxText
Parameters:
this (BoxText type from HeWhoMustNotBeNamed/DrawingTypes/2)
pretty (simple bool)
method tostring(this, format_date, format, tz, pretty)
Namespace types: D.Box
Parameters:
this (Box type from HeWhoMustNotBeNamed/DrawingTypes/2)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method tostring(this, pretty)
Namespace types: DC.TriangleProperties
Parameters:
this (TriangleProperties type from robbatt/lib_drawing_composite_types/1)
pretty (simple bool)
method tostring(this, format_date, format, tz, pretty)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method tostring(this, format_date, format, tz, pretty)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method tostring(this, format_date, format, tz, pretty)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method tostring(this, format_date, format, tz, pretty)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
format_date (simple bool)
format (simple string)
tz (simple string)
pretty (simple bool)
method delete(this)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
method delete(this)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
method clear(this)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
method clear(this)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
method clear(this)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
method clear(this)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
method draw(this, is_polygon_section)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
is_polygon_section (bool)
method draw(this)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
method draw(this, is_polygon)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
is_polygon (bool)
method draw(this)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
method draw(this)
Namespace types: DC.Trianglefill
Parameters:
this (Trianglefill type from robbatt/lib_drawing_composite_types/1)
method draw(this)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
method draw(this)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
method draw(this)
Namespace types: DC.Polygonfill
Parameters:
this (Polygonfill type from robbatt/lib_drawing_composite_types/1)
method createCenter(this, other)
Namespace types: D.Point
Parameters:
this (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
other (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
method createCenter(this)
Namespace types: D.Point
Parameters:
this (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
method createCenter(this, other1, other2)
Namespace types: D.Point
Parameters:
this (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
other1 (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
other2 (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
method createLabel(this, labeltext, tooltip, properties)
Namespace types: D.Line
Parameters:
this (Line type from HeWhoMustNotBeNamed/DrawingTypes/2)
labeltext (string)
tooltip (string)
properties (LabelProperties type from HeWhoMustNotBeNamed/DrawingTypes/2)
method createLabel(this, labeltext, tooltip, properties)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
labeltext (string)
tooltip (string)
properties (LabelProperties type from HeWhoMustNotBeNamed/DrawingTypes/2)
method createTriangle(this, p2, p3, properties)
Namespace types: D.Point
Parameters:
this (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
p2 (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
p3 (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
properties (TriangleProperties type from robbatt/lib_drawing_composite_types/1)
method createTrianglefill(this, fill_color, transparency)
Namespace types: DC.Triangle
Parameters:
this (Triangle type from robbatt/lib_drawing_composite_types/1)
fill_color (color)
transparency (int)
method createPolygonfill(this, fill_color, transparency)
Namespace types: DC.Polygon
Parameters:
this (Polygon type from robbatt/lib_drawing_composite_types/1)
fill_color (color)
transparency (int)
method createPolygon(points, properties)
Namespace types: D.Point
Parameters:
points (Point type from HeWhoMustNotBeNamed/DrawingTypes/2)
properties (TriangleProperties type from robbatt/lib_drawing_composite_types/1)
lib_statemachineLibrary "lib_statemachine"
simple state machine that allows tracking a state an manipulating it with conditions
method step(this, before, after, condition)
will step the state of the state machine from one to the next in case of condition
Namespace types: StateMachine
Parameters:
this (StateMachine) : (StateMachine) the state machine to use
before (int) : (int) from state
after (int) : (int) to state
condition (bool) : (bool) if condition is true
Returns: true (bool) if the state of the statemachine changed
method step(this, after, condition)
will change the state of the state machine to the next in case of condition (not depending on previous state)
Namespace types: StateMachine
Parameters:
this (StateMachine) : (StateMachine) the state machine to use
after (int) : (int) to state
condition (bool) : (bool) if condition is true
Returns: true (bool) if the state of the statemachine changed
method changed(this, within_bars)
will return true if the state of the state machine was changed in this iteration
Namespace types: StateMachine
Parameters:
this (StateMachine) : (StateMachine) the state machine to use
within_bars (int)
Returns: true (bool) if the state of the statemachine changed
method reset(this, condition, min_occurrences)
will reset the state machine if a certain 'condition' appears 'min_occurrences' times
Namespace types: StateMachine
Parameters:
this (StateMachine) : (StateMachine) the state machine to use
condition (bool) : (bool) reset condition
min_occurrences (int) : (int) min times 'condition' must appear for the reset to happen
Returns: true (bool) if the state of the statemachine changed
StateMachine
Fields:
state (series__integer)
neutral (series__integer)
enabled (series__bool)
reset_counter (series__integer)
lib_colorLibrary "lib_color"
offset_mono(original, offset, transparency)
get offset color
Parameters:
original (simple color) : original color
offset (float) : offset for new color
transparency (float) : transparency for new color
Returns: offset color
lib_colorsLibrary "lib_colors"
offset_mono(original, offset, transparency)
get offset color
Parameters:
original (simple color) : original color
offset (float) : offset for new color
transparency (float) : transparency for new color
Returns: offset color
lib_arrayLibrary "lib_array"
several array functions for chained calls, batch conversion, incrementing and comparing arrays.
method sort(id, descending)
Namespace types: int
Parameters:
id (int ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method sort(id, descending)
Namespace types: float
Parameters:
id (float ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method sort(id, descending)
Namespace types: string
Parameters:
id (string ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method increment(id, by_value)
Namespace types: int
Parameters:
id (int ) : The array to increment (and return again)
by_value (int) : The value by which to increment (default: 1)
@return The array that was passed as parameter id
method increment(id, by_value)
Namespace types: float
Parameters:
id (float ) : The array to increment (and return again)
by_value (float) : The value by which to increment (default: 1.0)
@return The array that was passed as parameter id
method decrement(id, by_value)
Namespace types: int
Parameters:
id (int ) : The array to increment (and return again)
by_value (int) : The value by which to increment (default: 1)
@return The array that was passed as parameter id
method decrement(id, by_value)
Namespace types: float
Parameters:
id (float ) : The array to increment (and return again)
by_value (float) : The value by which to increment (default: 1.0)
@return The array that was passed as parameter id
method toint(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method toint(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tofloat(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method tofloat(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tostring(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tostring(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tobool(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tobool(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tobool(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method sum(id)
Namespace types: bool
Parameters:
id (bool ) : The array to convert
method enqueue(id, item, max, condition, lifo)
Namespace types: int
Parameters:
id (int ) : The array that is used as queue
item (int) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: float
Parameters:
id (float ) : The array that is used as queue
item (float) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: string
Parameters:
id (string ) : The array that is used as queue
item (string) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: line
Parameters:
id (line ) : The array that is used as queue
item (line) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: box
Parameters:
id (box ) : The array that is used as queue
item (box) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
Template Trailing Strategy (Backtester)💭 Overview
💢 What is the "Template Trailing Strategy” ❓
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingView’s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap “trading logic” by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.
NOTE: The “Template Trailing Strategy” does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a “Trading System”, because it gives its user full flexibility on that end (for better or worse).
💢 What is a “Signal Indicator” ❓
“Signal Indicator” (SI) is an indicator that can output a “signal” that follows a specific convention so that the “Template Trailing Strategy” can “understand” and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS “when” to enter or exit, and the TTS determines “how” to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a “long entry signal”. Once TTS receives the “long entry signal”, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a “Market” order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a “Stop” order type with a 1% Stop Distance, then when the price of the security rises by 1% after the “long entry signal” occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.
🤔 How to Guide
💢 How to connect a “signal” from a “Signal Indicator” ❓
The “Template Trailing Strategy” was designed to receive external signals from a “Signal Indicator”. In this way, a “new trading idea” can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, “Am I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?”
To make that possible by connecting an external signal indicator to TTS, you should:
Add in the same chart, the “Signal Indicator” of your choice (e.g. “Two MA Signal Indicator” , “Click Signal Indicator” , “Signal Adapter” , “Signal Composer” ) and the “Template Trailing Strategy”.
Go to the “Settings/Inputs” tab in the “🛠️ STRATEGY” group of the TTS and change the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" to “🔨External”
Go to the “🔨 STRATEGY – EXTERNAL” group settings of the TTS and change the “🔌𝐒𝐢𝐠𝐧𝐚𝐥 🛈➡” to the output signal of the “Signal Indicator” you want to connect. The selected combo box option should look like “:🔌Signal to TTS” where should correspond to the short title of your “Signal Indicator”
💢 How to create a Custom Trading logic ❓
The “Template Trailing Strategy” provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.
✍️ Develop your own Customized “Signal Indicator” 💥
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a “Signal Indicator”. To create a new script, press the “Pine Editor” button below the chart to open the “Pine Editor” and then press the “Open” button to open the drop-down menu with the templates. Select the “New Indicator” option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the “Pine Editor” with a warning on top stating that this is a read-only script. Press the “create a working copy”. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
startLongDeal = ,
startShortDeal = ,
endLongDeal = ,
endShortDeal = ,
cnlStartLongDeal = ,
cnlStartShortDeal = ,
cnlEndLongDeal = ,
cnlEndShortDeal = )
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the “…” part after “=”. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the “Add to chart” button. If all goes well, you will be able to connect your “signal” to the TTS as described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
🧩 Adapt and Combine existing non-signal indicators 💥
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the “indicator on indicator” feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the “Signal Adapter” script in the same chart as well. This script is a “Signal Indicator” that can be used as a proxy to define your custom logic in the CONDITIONS group of the “Settings/Inputs” tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a “signal” will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the “How to connect a “signal” from a “Signal Indicator”?” in the “🤔 How to Guide“ for more information.
If your logic is slightly more complicated, you can add a second “Signal Adapter” in your chart. Then you should add the “Signal Composer” in the same chart, go to the SIGNALS group of the “Settings/Inputs” tab, and connect the “signals” from the “Signal Adapters”. “Signal Composer” is also a SI so its composed “signal” can be connected to the TTS the same way it is described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of “Signal Adapters” and “Signal Composers” before connecting the final “signal” to the TTS.
💢 How to set up ⏰Alerts ❓
The “Template Trailing Strategy” provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the “🔔 ALERT MESSAGES” module of the TTS settings and check the “Enable…” checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. What’s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
❗ To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the “Message Box” that contains the message that came from the TTS.
💢 How to execute my orders in a broker ❓
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the “Template Trailing Strategy” first (see the “How to set up Alerts?” guide above). Then you should go to the “Create Alert/Notifications” tab check the “Webhook URL” and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.
📑 Definitions
This section tries to give some definitions in terms that appear in the “Settings/Inputs" tab of the “Template Trailing Strategy”
💢 What is Trailing ❓
Trailing is a technique where a price target follows another “barrier” price (usually high or low) by trying to keep a maximum distance from the “barrier” when it moves in only one direction (up or down). When the “barrier” moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.
💢 What is a Moonbag ❓
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.
💢 What is Distance ❓
Distance is the difference between two prices.
💢 What is Bias ❓
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.
💢 What is the Margin Distance of a price target ❓
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.
⚙️ Settings
In the “Settings/Inputs” tab of the “Template Trailing Strategy”, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon 🛈 where you can learn more if you mouse over it. The “Settings/Inputs” tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. “Distance Method”. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:
📆 FILTERS
In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.
🛠️ STRATEGY
This module contains the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" that defines if the “Template Trailing Strategy” will operate using the Internal or the External (“Signal Indicator”) conditions. Some general settings can be applied regardless of the mode.
🔨 STRATEGY – EXTERNAL
This sub-module makes the connection between the external signal of the “Signal Indicator” and the “Template Trailing Strategy”. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔨External”.
🔧 STRATEGY – INTERNAL
This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the “Two MA Signal Indicator” was used as a “signal” in external mode. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔧Internal”.
🎢 VOLATILITY
This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).
🔷 ENTRY
This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.
🎯 TAKE PROFIT
This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.
🛑 STOP LOSS
This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.
🟪 EXIT
This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.
💰 QUANTITY/RISK MANAGEMENT
This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
This module defines all the messages that can be emitted per event during the strategy execution.
😲 Caveats
💢 Does “Template Trailing Strategy” has a repainting behavior ❓
The answer is that the “Template Trailing Strategy” does not repaint as long as the “Signal Indicator” that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
⚠️There is an exception though, when the “Enable Trail⚠️💹” checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.
💢 Can “Template Trailing Strategy” satisfy all my trading strategies ❓
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
⚠️ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.
🤗 Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a “defect report” or asking questions that helped me to understand what improvements were necessary.
Enjoy!
Jason
Indicators Combination Framework v3 IND [DTU]Hello All,
This script is a framework to analyze and see the results by combine selected indicators for (long, short, longexit, shortexit) conditions.
I was designed this for beginners and users to facilitate to see effects of the technical indicators combinations on the chart WITH NO CODE
You can improve your strategies according the results of this system by connecting the framework to a strategy framework/template such as Pinecoder, Benson, daveatt or custom.
This is enhanced version of my previous indicator "Indicators & Conditions Test Framework "
Currently there are 93 indicators (23 newly added) connected over library. You can also import an External Indicator or add Custom indicator (In the source)
It is possible to change it from Indicator to strategy (simple one) by just remarking strategy parts in the source code and see real time profit of your combinations
Feel free to change or use it in your source
Special thanks goes to Pine wizards: Trading view (built-in Indicators), @Rodrigo, @midtownsk8rguy, @Lazybear, @Daveatt and others for their open source codes and contributions
SIMPLE USAGE
1. SETTING: Show Alerts= True (To see your entries and Exists)
2. Define your Indicators (ex: INDICATOR1: ema(close,14), INDICATOR2: ema(close,21), INDICATOR3: ema(close,200)
3. Define Your Combinations for long & Short Conditions
a. For Long: (INDICATOR1 crossover INDICATOR2) AND (INDICATOR3 < close)
b. For Short: (INDICATOR1 crossunder INDICATOR2) AND (INDICATOR3 > close)
4. Select Strategy/template (Import strategy to chart) that you export your signals from the list
5. Analyze the best profit by changing Indicators values
SOME INDICATORS DETAILS
Each Indicator includes:
- Factorization : Converting the selected indicator to Double, triple Quadruple such as EMA to DEMA, TEMA QEMA
- Log : Simple or log10 can be used for calculation on function entries
- Plot Type : You can overlay the indicator on the chart (such ema) or you can use stochastic/Percentrank approach to display in the variable hlines range
- Extended Parametes : You can use default parameters or you can use extended (P1,P2) parameters regarding to indicator type and your choice
- Color : You can define indicator color and line properties
- Smooth : you can enable swma smooth
- indicators : you can select one of the 93 function like ema(),rsi().. to define your indicator
- Source : you can select from already defined indicators (IND1-4), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...)
CONDITION DETAILS
- There are are 4 type of conditions, long entry, short entry, long exit, short exit.
- Each condition are built up from 4 combinations that joined with "AND" & "OR" operators
- You can see the results by enabling show alerts check box
- If you only wants to enter long entry and long exit, just fill these conditions
- If "close on opposite" checkbox selected on settings, long entry will be closed on short entry and vice versa
COMBINATIONS DETAILS
- There are 4 combinations that joined with "AND" & "OR" operators for each condition
- combinations are built up from compare 1st entry with 2nd one by using operator
- 1st and 2nd entries includes already defined indicators (IND1-5), External Indicator (EXT), Custom Indicator (CUST), and other sources (close, open...)
- Operators are comparison values such as >,<, crossover,...
- 2nd entry include "VALUE" parameter that will use to compare 1st indicator with value area
- If 2nd indicator selected different than "VALUE", value are will mean previous value of the selection. (ex: value area= 2, 2nd entry=close, means close )
- Selecting "NONE" for the 1st entry will disable calculation of current and following combinations
JOINS DETAILS
- Each combination will join wiht the following one with the JOIN (AND, OR) operator (if the following one is not equal "NONE")
CUSTOM INDICATOR
- Custom Indicator defines harcoded in the source code.
- You can call it with "CUST" in the Indicator definition source or combination entries source
- You can change or implement your custom indicator by updating the source code
EXTERNAL INDICATOR
- You can import an external indicator by selecting it from the ext source.
- External Indicator should be already imported to the chart and it have an plot function to output its signal
EXPORTING SIGNAL
- You can export your result to an already defined strategy template such as Pine coders, Benson, Daveatt Strategy templates
- Or you can define your custom export for other future strategy templates
ALERTS
- By enabling show alerts checkbox, you can see long entry exits on the bottom, and short entry exits aon the top of the chart
ADDITIONAL INFO
- You can see all off the inputs descriptions in the tooltips. (You can also see the previous version for details)
- Availability to set start, end dates
- Minimize repainting by using security function options (Secure, Semi Secure, Repaint)
- Availability of use timeframes
-
Version 3 INDICATORS LIST (More to be added):
▼▼▼ OVERLAY INDICATORS ▼▼▼
alma(src,len,offset=0.85,sigma=6).-------Arnaud Legoux Moving Average
ama(src,len,fast=14,slow=100).-----------Adjusted Moving Average
accdist().-------------------------------Accumulation/distribution index.
cma(src,len).----------------------------Corrective Moving average
dema(src,len).---------------------------Double EMA (Same as EMA with 2 factor)
ema(src,len).----------------------------Exponential Moving Average
gmma(src,len).---------------------------Geometric Mean Moving Average
highest(src,len).------------------------Highest value for a given number of bars back.
hl2ma(src,len).--------------------------higest lowest moving average
hma(src,len).----------------------------Hull Moving Average.
lagAdapt(src,len,perclen=5,fperc=50).----Ehlers Adaptive Laguerre filter
lagAdaptV(src,len,perclen=5,fperc=50).---Ehlers Adaptive Laguerre filter variation
laguerre(src,len).-----------------------Ehlers Laguerre filter
lesrcp(src,len).-------------------------lowest exponential esrcpanding moving line
lexp(src,len).---------------------------lowest exponential expanding moving line
linreg(src,len,loffset=1).---------------Linear regression
lowest(src,len).-------------------------Lovest value for a given number of bars back.
mcginley(src, len.-----------------------McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
percntl(src,len).------------------------percentile nearest rank. Calculates percentile using method of Nearest Rank.
percntli(src,len).-----------------------percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
previous(src,len).-----------------------Previous n (len) value of the source
pivothigh(src,BarsLeft=len,BarsRight=2).-Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
pivotlow(src,BarsLeft=len,BarsRight=2).--Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
rema(src,len).---------------------------Range EMA (REMA)
rma(src,len).----------------------------Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sar(start=len, inc=0.02, max=0.02).------Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)
sma(src,len).----------------------------Smoothed Moving Average
smma(src,len).---------------------------Smoothed Moving Average
super2(src,len).-------------------------Ehlers super smoother, 2 pole
super3(src,len).-------------------------Ehlers super smoother, 3 pole
supertrend(src,len,period=3).------------Supertrend indicator
swma(src,len).---------------------------Sine-Weighted Moving Average
tema(src,len).---------------------------Triple EMA (Same as EMA with 3 factor)
tma(src,len).----------------------------Triangular Moving Average
vida(src,len).---------------------------Variable Index Dynamic Average
vwma(src,len).---------------------------Volume Weigted Moving Average
volstop(src,len,atrfactor=2).------------Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
wma(src,len).----------------------------Weigted Moving Average
vwap(src_).------------------------------Volume Weighted Average Price (VWAP) is used to measure the average price weighted by volume
▼▼▼ NON OVERLAY INDICATORS ▼▼
adx(dilen=len, adxlen=14, adxtype=0).----adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
angle(src,len).--------------------------angle of the series (Use its Input as another indicator output)
aroon(len,dir=0).------------------------aroon indicator. Aroons major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
atr(src,len).----------------------------average true range. RMA of true range.
awesome(fast=len=5,slow=34,type=0).------Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
bbr(src,len,mult=1).---------------------bollinger %%
bbw(src,len,mult=2).---------------------Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci(src,len).----------------------------commodity channel index
cctbbo(src,len).-------------------------CCT Bollinger Band Oscilator
change(src,len).-------------------------A.K.A. Momentum. Difference between current value and previous, source - source . is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security
cmf(len=20).-----------------------------Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
cmo(src,len).----------------------------Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog(src,len).----------------------------The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
copcurve(src,len).-----------------------Coppock Curve. was originally developed by Edwin Sedge Coppock (Barrons Magazine, October 1962).
correl(src,len).-------------------------Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count(src,len).--------------------------green avg - red avg
cti(src,len).----------------------------Ehler s Correlation Trend Indicator by
dev(src,len).----------------------------ta.dev() Measure of difference between the series and its ta.sma
dpo(len).--------------------------------Detrended Price OScilator is used to remove trend from price.
efi(len).--------------------------------Elders Force Index (EFI) measures the power behind a price movement using price and volume.
eom(len=14,div=10000).-------------------Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
falling(src,len).------------------------ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
fisher(len).-----------------------------Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
histvol(len).----------------------------Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
kcr(src,len,mult=2).---------------------Keltner Channels Range
kcw(src,len,mult=2).---------------------ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
klinger(type=len).-----------------------Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
macd(src,len).---------------------------MACD (Moving Average Convergence/Divergence)
mfi(src,len).----------------------------Money Flow Index s a tool used for measuring buying and selling pressure
msi(len=10).-----------------------------Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
nvi().-----------------------------------Negative Volume Index
obv().-----------------------------------On Balance Volume
pvi().-----------------------------------Positive Volume Index
pvt().-----------------------------------Price Volume Trend
ranges(src,upper=len, lower=-5).---------ranges of the source. src=src, upper=len, v1:lower=upper . returns: -1 source=upper otherwise 0
rising(src,len).-------------------------ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc(src,len).----------------------------Rate of Change
rsi(src,len).----------------------------Relative strength Index
rvi(src,len).----------------------------The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
smi_osc(src,len,fast=5, slow=34).--------smi Oscillator
smi_sig(src,len,fast=5, slow=34).--------smi Signal
stc(src,len,fast=23,slow=50).------------Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from
stdev(src,len).--------------------------Standart deviation
trix(src,len) .--------------------------the rate of change of a triple exponentially smoothed moving average.
tsi(src,len).----------------------------The True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend.
ultimateOsc(len.-------------------------Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
variance(src,len).-----------------------ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
willprc(src,len).------------------------Williams %R
wad().-----------------------------------Williams Accumulation/Distribution.
wvad().----------------------------------Williams Variable Accumulation/Distribution.
HISTORY
v3.01
ADD: 23 new indicators added to indicators list from the library. Current Total number of Indicators are 93. (to be continued to adding)
ADD: 2 more Parameters (P1,P2) for indicator calculation added. Par:(Use Defaults) uses only indicator(Source, Length) with library's default parameters. Par:(Use Extra Parameters P1,P2) use indicator(Source,Length,p1,p2) with additional parameters if indicator needs.
ADD: log calculation (simple, log10) option added on indicator function entries
ADD: New Output Signals added for compatibility on exporting condition signals to different Strategy templates.
ADD: Alerts Added according to conditions results
UPD: Indicator source inputs now display with indicators descriptions
UPD: Most off the source code rearranged and some functions moved to the new library. Now system work like a little bit frontend/backend
UPD: Performance improvement made on factorization and other source code
UPD: Input GUI rearranged
UPD: Tooltips corrected
REM: Extended indicators removed
UPD: IND1-IND4 added to indicator data source. Now it is possible to create new indicators with the previously defined indicators value. ex: IND1=ema(close,14) and IND2=rsi(IND1,20) means IND2=rsi(ema(close,14),20)
UPD: Custom Indicator (CUST) added to indicator data source and Combination Indicator source.
UPD: Volume added to indicator data source and Combination Indicator source.
REM: Custom indicators removed and only one custom indicator left
REM: Plot Type "Org. Range (-1,1)" removed
UPD: angle, rising, falling type operators moved to indicator library
Indicators & Conditions Test Framework [DTU]Hello All,
This script is a framework to build strategies by combining indicators and conditions (long, short, exits). You are able to analyze your strategies in realtime by changing the input parameters related to indicators, conditions and their combinations.
OVERVIEW
With this Study/Strategy framework, you will be able to create strategy conditions, display them on the chart, and test them using existing indicators as well as external and custom indicators that you can add.
The main purpose of the Framework is to choose your indicators to be used in the conditions and test your strategy by producing your "Long, short, Exit long, Exit short" combinations.
Although may be, it can be a bit difficult and complicated at first start, but you can understand the logic on its use in a very short time.
Notes:
I removed external links off descriptive images and video to be comply with Trading view violation House Rules
Since I am new in the community and still trying to understand the pine script language I can make errors and violations on my script. Please Inform me on any issue that I made..
HOW TO
STEP 1: SETTINGS ______________________________________________________________________________________________________
SOURCE, TIMEFRAME, SECURITY
Select the Source, timeframe and Secure type that your indicators will use.
Here, the Secure entry consists of 3 parts and the f_security function is used to determine it.
a)Secure
This option is defined as reducing repaint in tradingview calculations as much as possible. The following function is used.
request.security(_symbol, _res, _src , lookahead=barmerge.lookahead_on)
b)Semi Secure
While this option can reduce repaint in tradingview calculations as much as possible, it is less secure. The following function is used.
request.security(_symbol, _res, _src )
c)Repaint
This option turns on the repaint feature. The following function is used.
request.security(_symbol, _res, _src ) : na
Ind Source:
You can the source that indicators will use their own calculations
Ext Source:
You can import external Indicator sources from here . It appears on condition/combination area as "EXT".
To export the External indicator plot it with a title. It will be visible in source dropdown input
PERIOD , ALERTS...
Period:
Determine your strategy testing period by selecting start and end date/time
(!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars.
The extra bar option may cause problems such as not appearing in the calculations or errors).
Plot Alerts:
Plot condition result as alerts arrows on the chart's bottom for "LONG" and the top for "SHORT" entries, exits
Close on opposite:
When selected, a long entry gets closed when a short entry opens and vice versa
Show Profit:
It appears if script is in strategy mode (not in study) this can display current or open profit for better reanalyzing your strategy entry exit points. (Currently under development)
PLOT TYPE OPERATIONS
This option has 4 entries
a) Mult
Sets the multiplier for the selected Plot Type (stochastic, Percentrank, Org Range (-1,1) ) except for "Original" in the range (-1,1).
EXAMPLE: When 1000 is selected, the indicator in the range of (-1,1) will appear in the range of (-1000, 1000) on the screen.
b) Shift
It determines the shift that will appear on the screen for the selected Plot Type (stochastic, Percentrank,Org Range (-1,1) ) in the range (-1,1) other than "Original".
EXAMPLE: When Shift:35000 and mult:1000 are selected, the indicator will appear in the range (34000, 36000) on the screen.
c) Smooth
This option (only for Stochastic & PercentRank) allows to smooth the indicator to be displayed.
Here, tradinview ta.swma function is used.
b) hline
Adjusts the horizontal lines to appear on the screen according to the mult factor for the range (-1,1)
The lines represent the values (-1, -05, 0, 05, 1)
STEP 2: INDICATORS ______________________________________________________________________________________________________
You need to choose indicators that you can use in strategy conditions.
Here, the indicators come from the dturkuler/lib_Indicators_DT open script library defined in the code
In addition, you can add the indicators that you will create in the area defined in the code to this list..
You can also import external indicators and test them with other variables on the system..
You can choose a maximum of 5 indicators that you can use in total. (can be increased in new versions)
Indicators are categorized in 3 main sections
Indicator Selection:
You can select your indicators from this area
a)Moving Averages
These are indicators such as EMA, SMA that you can show on the stock. They come from the library.
These indicators are fed from Settings/source. Only the length value can be used as a parameter.
In addition, line colors can be changed..
As of now, there are 28 indicators in the library in total and 5 indicators are left as future use for this field for now.
b)Other Indicators
These are different indicators from the stock value such as RSI, COG. They come from the library. These indicators are fed from Settings/source.
Only the length value can be used as a parameter. In addition, line colors can be changed.
As of now, there are 24 indicators in the library in total and 5 indicators are left as a future use for this field for now.
c)Custom Indicators
These indicators are the ones you can create by programming yourself in the source code..
The area at the bottom of the settings screen is reserved for the parameters of this type of indicators.
Indicator Length:
You can update your selected indicator length value from here. (Not: it doesn't work for custom indicators since they have their parameter on cust. Ind. input screen )
Indicator Plot Type:
Next to the indicators, there is an input selection field about how they will be displayed on the screen.
a)Original
The indicator is displayed on the screen with its current values. It is an ideal solution for displaying moving average indicators such as (EMA, SMA) over current stock.
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
For this reason, other options may be more suitable for these.
b)Stochastic
The indicator is displayed on the screen with stochastic calculation in the range of -1.1.
It uses the stochastic(50) calculation method to spread indicators such as (RSI, COB) over the range (-1,1).
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
c)PercentRank
The indicator is displayed on the screen with stochastic calculation in the range of -1.1. .
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen
((!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
d)Org Range (-1,1)
If your indicator is in the range of -1.1, your indicator will be displayed on the screen with its original calculation in the range of -1.1.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your fitness calculations. Instead, get the values from Data Window)
STEP 2 NOTES:
STEP 3: CONDITIONS ______________________________________________________________________________________________________
After choosing the indicators you will use in the conditions, you move on to the "CONDITIONS" section.
There are 4 conditions type here.
• LONG ENTRY CONDITION
• SHORT ENTRY CONDITION
• LONG CLOSE CONDITION
• SHORT CLOSE CONDITION
The use of each condition is the same.
There are 3 combinations you can use in each condition. (can be increased in new versions)
a)COMBINATIONS
There are 3 combinations you can use in each condition. (can be increased in new versions)
Each combination are build from 4 parts
1)1st Indicator
If set to "NONE" this combination will not be used on calculations. You can select
IND1-5: from indicators (See above),
EXT: value from externally imported indicator
Stock built-in values: close, open...
2)Operator
Selected Operator compares 1st Indicator with the 2nd one. You can select different operators such as
crossover, crossunder, cross,>,<,=....
3)2nd Indicator
This indicator will be compared with the 1st one via selected Operator. You can select
IND1-5: from indicators (See above),
VALUE: a float value defined in the combinations value parameter
EXT: value from externally imported indicator
Stock builtin values: close,open...
4)Value
When the 2nd indicator field is "VALUE", value area compares the entered value.
ex: 1st indicator="open", op=">", 2nd indicator="VALUE", value=3000.12 means is(close>3000.12)
In other conditions, it compares the previous values of the indicator.
ex: 1st indicator="open", op=">" 2nd indicator is "close" and value is 2 means is(open>close )
EXAMPLES:
indicator 1= "IND1", Operator=">", indicator 2= "IND2" => is(IND1>IND2)
indicator 1= "IND1", Operator=">", indicator 2= "VALUE", "0.1" => is(IND1>0.9)
indicator 1= "IND2", Operator="crossover", indicator 2= "IND1" => is(IND2 crossover IND1) : like a=ta.crossover(IND2, IND1)
indicator 1= "IND1", Operator="<", indicator 2= "close" => is(IND1>close)
indicator 1= "IND1", Operator="<", indicator 2= "EXT" => is(IND1>EXT) , EXT mean external imported indicator that define on settings section
indicator 1= "IND1", Operator="<", indicator 2= "IND1", Value="1" => is (IND1>IND1 )
b)JOIN COMBINATIONS
Each combination in Condition is compared with the next one via JOIN operator
The join operator can be selected as AND or OR.
Examples:
1st combination= is(IND1>0.9) true
2nd combination= is(IND2 crossover IND1) false
1st combination "AND" 2ndcombination" => false (is(IND1>0.9) AND is(IND2 crossover IND1))
1st combination "OR" 2nd combination" => true (is(IND1>0.9) OR is(IND2 crossover IND1))
STEP 3 NOTES:
When the 2nd indicator field is "VALUE", value area compares the entered value. In other conditions, it compares the previous values of the indicator.
In cases where "VALUE" is not selected, integer values must be entered in this field. (float should not be entered. ie 1, 2 should be entered)
!!!If the 1st indicator is "NONE" in the combination, that combination is cancelled.
Each combination returns true/false, allowing the selected value to be compared with another value
Example: EMA(21)>EMA(50) returns true under all conditions or (EMA(21) crossover EMA(50)) returns true when passed.
You can use , Value of 5 indicators (IND1-IND5) or (VALUE) that you have defined in combinations or import indicator (EXT) or stock values (close, open, high...) in your calculations.
combination Compares the 1st indicator with 2nd indicator via the operator.
STEP 4: CUSTOM INDICATORS ______________________________________________________________________________________________________
There is an area in the code for designing Custom Indicators.
Here you can design your own indicators and use them in the framework.
You can also create unlimited parameters for your indicators in the SETTINGS custom indicator field.
For now, only 3 Custom indicators have been defined.
Examples are entered in the code for custom indicators.
STEP 4 NOTES:
Including / updating custom to the code is explained in the source code
• LIMITATIONS:
!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars. More bar options may cause problems such as not appearing in the calculations or errors.
• RAMBLINGS:
• NOTES [ /i]
This Script can be used as an indicator if the last strategy parts in the code are commented out and converted to the initial strategy study.
It was originally prepared for my use with my own strategy framework and has export functions accordingly.
When integrated to my own strategy framework it brings many more features over strategy definition of trades.
• TODO [ /i]
TODO: Add tooltips to the settings screen
TODO: Add double triple, Quatr factor for all indicators (convert any indicator to factor2-4 facotr. ex: EMA to DEMA, TEMA, QEMA...)
TODO: Add factorized Fibo avg range indicator (good for trend definition and entry exit points)
TODO: Add bands to the indicator and conditions
TODO: Add debug window for exporting indicator's parameters
TODO: Add isRising(value) isFalling(value), is...(value) .... to combinations (they can be used as custom indicator also
TODO: Reassess condition entry screen for user friendly GUI
TODO: Increase # conditions from 3 to 4
TODO: Reassess strategy entries, exit and close (should be improved)
TODO: Add Alerts, Condiional alerts for indicator (study) part
TODO: Create export function v3 for Pinecoders Indicator framework
• THANKS:
For Pine script format docs RicardoSantos .
For Pine script coding standards Pinecoders .
For moving average script used on library s RodrigoKazuma .
[UTILS] Unit Testing FrameworkTL;DR
This script doesn't provide any buy/sell signals.
This script won't make you profitable implicitly.
This script is intended for utility function testing, library testing, custom assertions.
It is free and open-source.
Introduction
About the idea: is not exclusive, programmers tend to use this method a lot and for a long time.
The point is to ensure that parts of a software, "units" (i.e modules, functions, procedures, class methods etc), work as they should, meet they design and behave as intended. That's why we use the term "Unit testing".
In PineScript we don't have a lot of entities mentioned above yet. What we have are functions. For example, a function that sums numbers should return a number, a particular sum. Or a professor wrote a function that calculates something or whatever. He and you want to be sure that the function works as expected and further code changes (refactoring) won't break its behaviour. What the professor needs to do is to write unit tests for his function/library of functions. And what you need to do is to check if the professor wrote tests or not.
No tests = No code
- Total test-driven development
Ok, it is not so serious, but very important in software development. And I created a tool for that.
I tried to follow the APIs of testing tools/libs/frameworks I worked or work with: Jasmine (Javascript), Mocha/Chai (Javascript), Jest (Javascript), RSpec (Ruby), unittest (Python), pytest (Python) and others. Got something workable but it would be much easier to implement (and it would look much better) if PineScript had a higher-order functions feature.
API
_describe(suiteName: string)
A function to declare a test suite. Each suite with tests may have 2 statuses:
✔️ Passed
❌ Failed
A suite is considered to be failed if at least one of the specs in it has failed.
_it(specName: string, actual: any, expected: any)
A function to run a test. Each test may have 3 statuses:
✔️ Passed
❌ Failed
⛔ Skipped
Some examples:
_it("is a falsey value", 1 != 2, true)
_it("is not a number", na(something), true)
_it("should sum two integers", _sum(1, 2), 1)
_it("arrays are equal", _isEqual(array.from(1, 2), array.from(1, 2)), true)
Remember that both the 'actual' and 'expected' arguments must be of the same type.
And a group of _it() functions must be preceded by a _describe() declaration (see in the code).
_test(specName: string, actual: any, expected: any)
An alias for _it . Does the same thing.
_xit(specName: string, actual: any, expected: any)
A function to skip a particular test for a while. Doesn't make any comparisons, but the test will appear in the results as skipped.
This feature is unstable and may be removed in the future releases.
_xtest(specName: string, actual: any, expected: any)
An alias for _xit . Does the same thing.
_isEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function doesn't take into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) will be equal.
_isStrictEqual(id_1: array, id_2: array)
A function to compare two arrays for equality. Both arrays must be of the same type.
This function is a stricter version of _isEqual because it takes into account the order of elements in each array. So arrays like (1, 2, 3) and (3, 2, 1) won't be equal.
Usage
To use this script to test your library you need to do the following steps:
1) Copy all the code you see between line #5 and #282 (Unit Testing Framework Core)
2) Place the copied code at the very beginning of your script (but below study())
3) Start to write suites and tests where your code ends. That's it.
NOTE
The current version is 0.0.1 which means that a lot of things may be changed on the way to 1.0.0 - the first stable version.
Color Gradient Framework [PineCoders]█ OVERVIEW
This indicator shows how you can use the new color functions in Pine to generate color gradients. We provide functions that will help Pine coders generate gradients for multiple use cases using base colors for bull and bear states.
█ CONCEPTS
For coders interested in maximizing the use of color in their scripts, TradingView has added new color functions and new functionality to existing functions. For us coders, this translates in the ability to generate colors on the fly and use dynamic colors ("series color") in more places.
New functions allow us to:
• Generate colors dynamically from calculated RGBA components ("A" is the Alpha channel, known to Pine coders as the "transparency"). See color.rgb() .
• Extract RGBA components from existing colors. See color.r() , color.g() , color.b() and color.t() .
• Generate linear gradients between two colors. See color.from_gradient() .
Improvements to existing color/plotting functions allow more flexible use of color:
• plotcandle() now accepts a "series color" argument for its `wickcolor` and `bordercolor` parameters.
• plotarrow() now accepts a "series color" argument for its `colorup` and `colordown` parameters.
Gradients are not only useful to make script visuals prettier; they can be used to pack more information in your displays. Our gradient #4 goes overboard with the concept by using a different gradient for the source line, its fill, and the background.
█ OUR SCRIPT
The script presents four functions to generate gradients:
f_c_gradientRelative(_source, _min, _max, _c_bear, _c_bull)
f_c_gradientRelativePro(_source, _min, _max, _c_bearWeak, _c_bearStrong, _c_bullWeak, _c_bullStrong)
f_c_gradientAdvDec(_source, _center, _c_bear, _c_bull)
f_c_gradientAdvDecPro(_source, _center, _steps, _c_bearWeak, _c_bearStrong, _c_bullWeak, _c_bullStrong)
The relative gradient functions are useful to generate gradients on a source that oscillates between known upper/lower limits. They use the relative position of the source between the `_min` and `_max` levels to generate the color. A centerline is derived from the `_min` and `_max` levels. The source's position above/below that centerline determines if the bull/bear color is used, and the relative position of the source between the centerline and the max/min level determines the gradient of the bull/bear color.
The advance/decline gradient functions are useful to generate gradients on a source for which min/max levels are unknown. These functions use source advances and declines to determine a gradient level. The `f_c_gradientAdvDec()` version uses the historical maximum of advances/declines to determine how many correspond to the strongest bull/bear colors, making its gradients adaptive. The `f_c_gradientAdvDecPro()` version requires the explicit number of advances/declines that correspond to the strongest bull/bear colors. This is useful when coloring chart bars, for example, where too many gradient levels are difficult to distinguish. Using the Pro version of the function allows you to limit the number of gradient levels to 5, for example, so that transitions are fewer, but more obvious. The `_center` parameter of the advance/decline functions allows them to determine which of the bull/bear colors to use.
Note that the custom `f_colorNew(_color, _transp)` function we use in our script should soon no longer be necessary, as changes are under way to allow color.new() to accept series arguments.
Inputs
The script's inputs demonstrate one way you can allow users to choose base bull/bear colors. Because users can modify any of the colors, only two are technically needed: one for bull, one for bear, as we do for the configuration of the bull/bear colors for the background in the gradient #4 configuration. Providing a few presets from which users can choose can be useful for color-challenged script users, but that type of inputs has the disadvantage of not rendering optimally in all OS/Browser environments.
You can use the inputs to select one of eight gradient demonstrations to display.
█ THANKS
Thanks to the PineCoders team for validating the code and description of this publication.
Thanks also to the many TradingView devs from multiple teams who made these improvements to Pine colors possible.
Look first. Then leap.
String Manipulation Framework [PineCoders FAQ]█ OVERVIEW
This script provides string manipulation functions to help Pine coders.
█ FUNCTIONS PROVIDED
f_strLeft(_str, _n)
Function returning the leftmost `_n` characters in `_str`.
f_strRight(_str, _n)
Function returning the rightmost `_n` characters in `_str`.
f_strMid(_str, _from, _to)
Function returning the substring of `_str` from character position `_from` to `_to` inclusively.
f_strLeftOf(_str, _of)
Function returning the sub-string of `_str` to the left of the `_of` separating character.
f_strRightOf(_str, _of)
Function returning the sub-string of `_str` to the right of the `_of` separating character.
f_strCharPos(_str, _chr)
Function returning the position of the first occurrence of `_chr` in `_str`, where the first character position is 0. Returns -1 if the character is not found.
f_strReplace(_src, _pos, _str)
Function that replaces a character at position `_pos` in the `_src` string with the `_str` character or string.
f_tickFormat()
Function returning a format string usable with `tostring()` to round a value to the symbol's tick precision.
f_tostringPad(_val, _fmt)
Function returning a string representation of a numeric `_val` using a special `_fmt` string allowing all strings to be of the same width, to help align columns of values.
`f_tostringPad()`
Using the functions should be straightforward, but `f_tostringPad()` requires more explanations. Its purpose is to help coders produce columns of fixed-width string representations of numbers which can be used to produce columns of numbers that vertically align neatly in labels, something that comes in handy when, for example, you need to center columns, yet still produce numbers of various lengths that nonetheless align.
While the formatting string used with this function resembles the one used in tostring() , it has a few additional characteristics:
• The question mark (" ? ") is used to indicate that padding is needed.
• If negative numbers must be handled by the function, the first character of the formatting string must be a minus sign ("-"),
otherwise the unary minus sign of negative numbers will be stripped out.
• You will produce more predictable results by using "0" rather than "#" in the formatting string.
You can experiment with `f_tostringPad()` formatting strings by changing the one used in the script's inputs and see the results on the chart.
These are some valid examples of formatting strings that can be used with `f_tostringPad()`:
"???0": forces strings to be four units wide, in all-positive "int" format.
"-???0": forces strings to be four units wide, plus room for a unary minus sign in the first position, in "int" format.
"???0.0": forces strings to be four units wide to the left of the point, all-positive, with a decimal point and then a mantissa rounded to a single digit.
"-???0.0?": same as above, but adds a unary minus sign for negative values, and adds a space after the single-digit mantissa.
"?????????0.0": forces the left part of the float to occupy the space of 10 digits, with a decimal point and then a mantissa rounded to a single digit.
█ CHART
The information displayed by this indicator uses the values in the script's Inputs, so you can use them to play around.
The chart shows the following information:
• Column 0 : The numeric input values in a centered column, converted to strings using tostring() without a formatting argument.
• Column 1 : Shows the values formatted using `f_tostringPad()` with the formatting string from the inputs.
• Column 2 : Shows the values formatted using `f_tostringPad()` but with only the part of the formatting string left of the decimal point, if it contains one.
• Column 3 : Shows the values formatted using `f_tostringPad()` but with the part of the formatting string left of the decimal point,
to which is added the right part of the `f_tostringPad()` formatting string, to obtain the precision in ticks of the symbol the chart is on.
• Column 4 : Shows the result of using the other string manipulation functions in the script on the source string supplied in the inputs.
It also demonstrates how to split up a label in two distinct parts so that you can vertically align columns when the leftmost part contains strings with varying lengths.
You will see in our code how we construct this column in two steps.
█ LIMITATIONS
The Pine runtime is optimized for number crunching. Too many string manipulations will take a toll on the performance of your scripts, as can readily be seen with the running time of this script. To minimize the impact of using string manipulation functions in your scripts, consider limiting their calculation to the first or last bar of the dataset when possible. This can be achieved by using the var keyword when declaring variables containing the result of your string manipulations, or by enclosing blocks of code in if blocks using barstate.isfirst or barstate.islast .
█ NOTES
To understand the challenges we face when trying to align strings vertically, it is useful to know that:
• As is the case in many other places in the TadingView UI and other docs, the Pine runtime uses the MS Trebuchet font to display label text.
• Trebuchet uses proportionally-spaced letters (a "W" takes more horizontal space than an "I"), but fixed-space digits (a "1" takes the same horizontal space as a "3").
Digits all use a figure space width, and it is this property that allows us to align numbers vertically.
The fact that letters are proportionally spaced is the reason why we can't vertically align columns using a "legend" + ":" `+ value structure when the "legend" part varies in width.
• The unary minus sign is the width of a punctuation space . We use this property to pad the beginning of numbers
when you use a "-" as the first character of the `f_tostringPad()` formatting string.
Our script was written using the PineCoders Coding Conventions for Pine .
The description was formatted using the techniques explained in the How We Write and Format Script Descriptions PineCoders publication.
█ THANKS
Thanks to LonesomeTheBlue for the `f_strReplace()` function.
Look first. Then leap.
[fareid] Quick Backtest Framework█ OVERVIEW
This Framework allows Pine Coders to quickly code Study() based signal/strategy and validate its viability before proceed to code with more advance/complex customized rules for entry, exit, trailstop, risk management etc..
This is somewhat an upgraded version of my earlier personal template with different strategy used, cleaner code
and additional features.
█ USE CASES
- You have an idea for trade signal and need a quick way to verify its potential before writing lengthy/complicated code
- You found a study script for trading signal in public library and want to validate it profitability with minimum effort before including it in your trading playbook
█ FEATURES
- Alert: Ready to use alert function based on signals from your custom indicator.
- Visual Backtest: Auto-plot entry, stop-loss and take profit for simple strategy performance analysis
- Backtest Statistic: Provide basic key metrics based on backtest strategy
- BTE External Signal Protocol: Ready to use code that will supply required state to PineCoders Backtesting & Trading Engine if you wish to have more advance and sophisticated backtesting engine
Notes: All of the above features have On/Off toggle
█ Description & How To Use
This Framework consist of 5 Modules but you only need to edit the first 2 Modules:
Module1: Indicator
Module2: Framework Input Protocol
Module3: Alert
Module4: Backtest
Module5: Backtest & Trading Engine
Tips: The source-code includes collapsible block by module for easy navigating
Module1: Indicator:
-----------------------------------------------------------------------------------
Main Module. Place custom indicator input parameter/calculation/indicator plotting here
Sample Strategy: Double MACD Crossover
MACD Signal: 1st MACD Cross above signal line indicate Buy Signal
1st MACD Cross below signal line indicate Sell Signal
MACD Filter: 2nd MACD is above 0 line indicate Uptrend
2nd MACD is below 0 line indicate Downtrend
Module2: Framework Input Protocol:
-----------------------------------------------------------------------------------
Use this module to connect main indicator/signal calculated in Module1 to the rest of the framework's module
4 variables needed to be defined here:
1. Uptrend
2. Dntrend
3. BuySignal
4. SellSignal
i'm not sure how to place a code snippet here to show you example so in the source code i already put a comment in Module2 on which part u need to edit. I hope its pretty simple to use.
Module3: Alert Module Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the alert module is ready to use without any further modification.
Input:
Enable Alert --> Enable TV's alert and plot signal to chart
Alert Type --> Set to take Buy only, Sell only or Both alert
Module4: Backtest Module Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the backtest module is ready to use without any further modification.
Input:
Backtest Stat --> Enable Backtest Statistic Label
Backtest Visual --> Enable Backtest visual simulation
Backtest Type --> Set to take Buy only or Sell only or both
SL Type -->
ATR : Set SL in ATR times Multiplier below entry price
Fixed : Set SL in fixed point below entry point (in 'Dollar'). e.g. for Stocks -> 0.5 equals to 50cent while for EURUSD currency -> 0.005 equal to 50 pips
HiLo Bar: Set SL at highest/lowest wick of previous bar plus/minus Fixed point. e.g. EURUSD HiLo=3 and Fixed Point = 0.0005, buy trade will place SL 5 Pips below lowest of previous 3 bar
SL ATR Multi --> Set Lookback Period used for SL's ATR calculation
SL ATR Multi --> Set ATR Multiplier for SL
SL Fixed --> Set Fixed Level for SL
SL Bar --> Set Number of previous bar to check for SL placement
TP RR Ratio --> Set TP based on RR multiplier. e.g. 2 means TP level will be twice further from entry point compared to Entry-SL distance.
Notes: The point is for preliminary testing, so it only supports 1 trade at a time and no Trailing Stop
Module5: Backtest & Trading Engine Description:
-----------------------------------------------------------------------------------
As long as the variables in Module2 properly defined, the Pinecoders BTE module is ready to use without any further modification.
Input:
External Signal Protocol --> Set ESP State to send to "Backtesting & Trading Engine "
Signal With Filter --> Use this to send entry signal that already filtered by this study indicator (without stoploss level)
Signal Without Filter --> Use this to send raw entry signal that are NOT YET FILTERED by this study indicator (without stoploss level)
Signal and Stop With Filter --> Use this to send entry signal WITH StopLoss that already filtered by this study indicator (with stoploss level)
Signal and Stop Without Filter --> Use this to send raw entry signal WITH StopLoss that are NOT YET FILTERED by this study indicator (with stoploss level)
Notes: Backtesting & Trading Engine already have built-in Filter, Entries and Stop Level. e.g. Unselect all their filter state if only want to use custom filter and make sure send Signal with Filter (with or without SL level)
█ DISCLAIMER:
This framework main objective is to create my personal indicator template so that i just have to modify the indicator module for preliminary testing in future.
The sample strategy included are for educational purpose only. Use at your own risk
credit: LucF/PineCoders for a lot of his scripts that i use as a guide to complete this
Time Offset Calculation Framework - PineCoders FAQ█ OVERVIEW
Calculating time-based offsets is necessary when coders need to draw lines or labels into the future because using `xloc = xloc.bar_time` in `label.new()` or `line.new()` is then mandatory.
This script provides a function to help with those calculations:
f_timeFrom(_from, _qty, _units)
The function calculates a negative (into the past) or positive (into the future) offset from the current bar's starting or closing time, or from the current time of day.
The offset can be expressed in units of chart resolution, or in seconds, minutes, hours, days, months or years.
█ HOW TO USE THE FRAMEWORK
1. You will need to include the supplied `f_resInMinutes()` function in your script in order to use `f_timeFrom()`.
It is used to calculate offsets using chart units when `f_timeFrom(_, _, "chart")` is used.
2. Whether you use `f_timeFrom()` for labels or lines, remember to use `xloc = xloc.bar_time`, as the default is `xloc = xloc.bar_index`.
3. Use `f_timeFrom()` for the `x` argument in `label.new()`, or for `x1` or `x2` in `line.new()`.
It can of course also be used in the relevant `label.set_*()` or `line.set_*()` functions.
Examples
// Label 3 days into the future from current bar's time.
label.new(f_timeFrom("bar", 3, "days"), high, "time + 3 days", xloc.bar_time)
// Label 2 hours into the future from current time
label.new(f_timeFrom("now", 2, "hours"), high, "timenow + 3 hours", xloc.bar_time)
// Label at bar's time plus 4 units of the chart's resolution.
label.new(f_timeFrom("bar", 4, "chart"), high, "time + 3 chart units", xloc.bar_time)
The parameters are:
f_timeFrom(_from, _qty, _units) =>
// _from : starting time from where the offset is calculated: "bar" to start from the bar's starting time, "close" to start from the bar's closing time, "now" to start from the current time.
// _qty : the +/- qty of _units of offset required. A "series float" can be used but it will be cast to a "series int".
// _units : string containing one of the seven allowed time units: "chart" (chart's resolution), "seconds", "minutes", "hours", "days", "months", "years".
█ LIMITATIONS
While this function makes it easier for coders to calculate time offsets using a variety of methods, it does not solve the inherent problematic that offsets do not calculate accurately when bars are missing between the start and end times of the offset. There is currently no way to circumvent this challenge in Pine.
Missing bars will occur on holidays, during no-trade periods (including normal periods where markets are closed) and when there are irregularities in data feeds. Charts at seconds resolutions, for example, will often miss bars when there are no trades to update the feed. On hourly charts of non 24x7 markets, periods when the markets are closed will also cause irregularities, as will holidays on day charts.
Other irregularities can occur because of how the offsets are calculated. A calculation of a one second offset from the bar's time will end one bar further on daily charts, for example. `f_timeFrom()` is no panacea; it simply makes offsets easier to calculate, however imprecise they are.
█ HOW TO USE THIS SCRIPT
The script's Inputs allow you to specify an offset, its units and starting time, and control the frequency of bars where lines are drawn.
Use the Inputs to play around with the parameters; you will quickly notice the irregularities mentioned above and be able to judge the usefulness of time-based offsets on the type of chart you use.
Look first. Then leap.
[NLX-L2] Fisher Stochastic Center of Gravity (v4)- Fisher Stochastic Center of Gravity-
This is Fisher's Stochastic Center of Gravity converted to pine v4 by blackcat. A very powerful entry indicator!
The original was published by DasanC & EmpiricalFX and it's a very interesting take on FSCG.
All the credit for the indicator goes to the authors and inventor of FSCG, this is just a mod to be used with my NLX Modular Trading Framework .
- How to Use -
1. Add a Trend Indicator like Trend Index MTF to your chart
2. Add " Fisher Stochastic Center of Gravity" Indicator to your Chart and select the Trend Index MTF with Type L1 in the Settings as Source
2. Add the Backtest to your Chart and select the FSCG Signal with Type L2 as Source
- Alerts for Automated Trading -
See my signature below for more information. Contact me for the Alert module.
Alert Creation Framework - PineCoders FAQThis script provides a framework to add alerts to a script.
It uses a method and provides code that:
— Allows the indicator's users to select the plotting of markers representing the different conditions used to trigger alerts.
— Allows filtering of the markers on direction: both, longs only, shorts only.
— Uses a single alert for the indicator. It will trigger on any number of marker conditions selected by the user when the alert is configured. The user can thus create the combination that suits his needs.
— Includes the marker's number in the alert's message.
NOTES
— Alerts should usually be configured to trigger Once Per Bar Close to prevent false signals.
— See the Pine User Manual page on alerts .
— This code uses the Pine Script Coding Conventions .
Look first. Then leap.
MTF Selection Framework - PineCoders FAQOur MTF Selection Framework allows Pine coders to add multi-timeframe capabilities to their script with the following features:
► Timeframe selection
The higher timeframe can be selected using 3 different ways:
• By steps (60 min., 1D, 3D, 1W, 1M, 1Y).
• As a multiple of the current chart's resolution, which can be fractional, so 3.5 will work.
• Fixed.
► Non-repainting or Repainting mode can be selected.
► Smoothing of the HTF line
Can be turned on/off and a smoothing factor allows the user to select the degree of smoothing he requires.
The framework is used here to create a higher timeframe version of a simple RSI line, but it can be used to access HTF information for almost any signal.
Functions used
f_resInMinutes()
Converts the current timeframe.multiplier plus the TF into minutes of type float.
• In Pine, the timeframe.multiplier is an integer representing the resolution, but a value of 1 can mean one day or one minute. This function converts that information in a standard fractional float minutes format that can then be used by the other functions in the framework.
• If the chart's current resolution is 15 seconds, the function will return 0.25 . If the chart's resolution is one day, it will return 1440 .
f_tfResInMinutes(_resolution)
Returns resolution of _resolution period in minutes.
• This function does the same as f_resInMinutes() , but on the target resolution supplied as a parameter in the timeframe.period string format.
f_resNextStep(_res)
Given a current resolution in fractional float minutes, returns its corresponding stepped HTF in the timeframe.period string format.
• This allows the implementation of the step HTF selection mode.
f_multipleOfRes(_res, _mult)
Given a current resolution in fractional float minutes and a fractional multiplier, returns a multiple of the resolution as a string in "timeframe.period" format usable with "security()".
• A multiple like 3.5 is allowed.
• Note that with seconds resolutions, the result returned is constrained by the discrete seconds resolutions available on TV.
f_htfLabel(_txt, _y, _color)
Used to display a label showing either:
• A warning when the chart's resolution is not lower than the HTF.
• The HTF resolution currently used.
The y position used to position the label will require adaptation to the signal you are using. For use in "overlay = true" mode, a technique that works well is commented out in the code.
Look first. Then leap.
Pinescript v3 Compatibility Framework (v4 Migration Tool)Pinescript v3 Compatibility Framework (v4 Migration Tool)
This code makes most v3 scripts work in v4 with only a few minor changes below. Place the framework code before the first input statement.
You can totally delete all comments.
Pros:
- to port to v4 you only need to make a few simple changes, not affecting the core v3 code functionality
Cons:
- without #include - large redundant code block, but can be reduced as needed
- no proper syntax highlighting, intellisence for substitute constant names
Make the following changes in v3 script:
1. standard types can't be var names, color_transp can't be in a function, rename in v3 script:
color() => color.new()
bool => bool_
integer => integer_
float => float_
string => string_
2. init na requires explicit type declaration
float a = na
color col = na
3. persistent var init (optional):
s = na
s := nz(s , s) // or s := na(s ) ? 0 : s
// can be replaced with var s
var s = 0
s := s + 1
___________________________________________________________
Key features of Pinescript v4 (FYI):
1. optional explicit type declaration/conversion (you still can't cast series to int)
float s
2. persistent var modifier
var s
var float s
3. string series - persistent strings now can be used in cond and output to screen dynamically
4. label and line objects
- can be dynamically created, deleted, modified using get/set functions, moved before/after the current bar
- can be in if or a function unlike plot
- max limit: 50-55 label, and 50-55 line drawing objects in addition to already existing plots - both not affected by max plot outputs 64
- can only be used in the main chart
- can serve as the only output function - at least one is required: plot, barcolor, line, label etc.
- dynamic var values (including strings) can be output to screen as text using label.new and to_string
str = close >= open ? "up" : "down"
label.new(bar_index, high, text=str)
col = close >= open ? color.green : color.red
label.new(bar_index, na, "close = " + tostring(close), color=col, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar)
// create new objects, delete old ones
l = line.new(bar_index, high, bar_index , low , width=4)
line.delete(l )
// free object buffer by deleting old objects first, then create new ones
var l = na
line.delete(l)
l = line.new(bar_index, high, bar_index , low , width=4)
Dragon-Bot - Default ScriptDragon-Script is a framework to make it as easy as possible to test your own strategies and set alerts for external execution bots. This is the alerts version of the script.
The script has many features build in, like:
1) A ping/pong mechanism between longs and shorts
2) A stop-loss
3) Trailing Stops with several ways to calculate them.
4) 2 different ways to flip from long to short.
The script is divided into several parts.
The first part of the script is used to set all the variables. You should normally never change the first part except for the comments at the top.
The second part of the script is the part where you initialise all your indicators. Several indicators can be found on Tradingview and on other sites. Please keep in mind that all the variable names used in the indicator should be unique. (all the … = … parts)
The third part of the script, is the most important part of the script. Here you can create the entry and exit points.
Let’s look at the OPENLONG function to explain this part: The first variables are all the possible entries; These are longentry1 till longentry5. You can add many more if you like.
The variables are all initialised as being false. This way the script can set a value to true if an entry happens.
The if function is the actual logic: You could say “if this is true” then (the line below the if function) longentry1 := (becomes) true.
In this case we have said: “if this is true” then (the line below the if function) longentry1 := (becomes) true when the current close is larger than the close that is 1 back.
The last part is the makelong_funct. This part says that if any of the entries are true, the whole function is true.
The last part of the script is the actual execution. Here the alerts are plotted and the back test strategies are opened and closed.
We hope you guys like it and all feedback is welcome!
Dragon Bot - Default ScriptDragon Script is a framework to make it as easy as possible to test your own strategies and set alerts for external execution bots.
The script has many features build in, like:
1) A ping/pong mechanism between longs and shorts
2) A stop-loss
3) Trailing Stops with several ways to calculate them.
4) 2 different ways to flip from long to short.
The script is divided into several parts.
The first part of the script is used to set all the variables. You should normally never change the first part except for the comments at the top.
The second part of the script is the part where you initialise all your indicators. Several indicators can be found on Tradingview and on other sites. Please keep in mind that all the variable names used in the indicator should be unique. (all the … = … parts)
The third part of the script, is the most important part of the script. Here you can create the entry and exit points.
Let’s look at the OPENLONG function to explain this part: The first variables are all the possible entries; These are longentry1 till longentry5. You can add many more if you like.
The variables are all initialised as being false. This way the script can set a value to true if an entry happens.
The if function is the actual logic: You could say “if this is true” then (the line below the if function) longentry1 := (becomes) true.
In this case we have said: “if this is true” then (the line below the if function) longentry1 := (becomes) true when the current close is larger than the close that is 1 back.
The last part is the makelong_funct. This part says that if any of the entries are true, the whole function is true.
The last part of the script is the actual execution. Here the alerts are plotted and the back test strategies are opened and closed.
We hope you guys like it and all feedback is welcome!