ScriptingWriting LipiYour own functions

Your own functions

Write a function when the same calculation appears more than once, or when a line has grown too long to read.

Three ways to open a declaration

A declaration may begin with def, or with func, or with neither. All three declare the same thing. This is a house-style decision, not a choice between features.

Every parameter states its type

The type is the part you cannot leave out. A parameter is written as an optional form type, then a data type, then a name, then an optional default.

def weighted(float a, float b, float weight = 2.0) {
    return (a * weight + b) / (weight + 1)
}

Here weight carries a default, so a caller may pass two arguments or three. a and b do not, so they must be supplied.

return takes an expression.

Two body forms

A body is either a braced block, as above, or a single expression after =>.

func midpoint(float a, float b) => (a + b) / 2
average(float a, float b, float c) => (a + b + c) / 3

The second line shows both shortcuts at once: no declaration keyword, and an arrow body.

Returning more than one value

The arrow form also accepts a tuple, written as a bracketed list. A tuple can be assigned in a single statement.

bounds(float a, float b) => [a - b, a + b]
[lower, upper] = bounds(close, 2.0)

Square brackets mean two different things in Lipi, and position is what separates them. Written after something, they index history. Written on their own, they build a tuple.

A function cannot draw

Chart output functions have to be called at the top level of a script. A function body is a scope of its own, so an output call placed inside one is rejected by name. Return the value and plot it at the top level.

A complete script

indicator("Weighted close", "wclose", true)
def weighted(float a, float b, float weight = 2.0) {
    return (a * weight + b) / (weight + 1)
}
plot(weighted(close, close[1]))
Ready to put this into practice?
Try GoCharting Premium
Unlock advanced orderflow, market profile, options desk, and real-time data — everything you just read about, live in your charts.
Upgrade