TradeOnReplayDOCSSearch the whole guidetradeonreplay.com

Guide / Scripts

Types and methods

A type groups related values into one object. A method is a function you call on a value with a dot.

//@version=5
indicator("Swing tracker", overlay = true)

type Swing
    float price
    int bar
    bool isHigh = true

method distance(Swing this, float from) =>
    math.abs(this.price - from)

var last = Swing.new(high, bar_index)
if ta.pivothigh(high, 5, 5) == high[5]
    last := Swing.new(high[5], bar_index - 5)

plot(last.distance(close), "Distance to last swing high")

Types

type Name is followed by an indented list of fields: [type] name [= default]. Name.new(a, b) or Name.new(price = 1.0) makes an object. A field left out takes its default, else na ("" for a string, false for a bool).

p.price reads a field. p.price := 2 and p.count += 1 change it.

Objects are shared, not copied, when assigned: b = a is the same object. a.copy() (or Name.copy(a)) is a new one with the same fields. An object can hold other objects, arrays, maps and so on.

Methods

method name(Type this, ...) => is called as x.name(...). Two methods can share a name for different types, and a method can be defined on float, string and so on, as in close.double(). A built-in method of the same name (a.size() on an array) still works on its own types.

  • Types and methods are defined at the top level, before they are used.
  • Parameters can have defaults and be passed by name.
  • Reading a field of an na object stops the script with an error on that line.
  • p[1] is the object the variable held on the previous bar. On the first bar there is none, so guard it: bar_index > 0 ? p[1].x : na.