ScriptingHow toHow to reuse a calculation with your own function

How to reuse a calculation with your own function

Declare the calculation once, then call it. An arrow body is enough for a single expression.

indicator("Two spreads", "spreads", false)

def spread(float a, float b) => a - b

plot(spread(high, low), title = "Bar range", color = color.blue)
plot(spread(close, open), title = "Body", color = color.orange)

Every parameter must state a data type. The type is the part you cannot leave out; the form type in front of it and the default value after it are both optional.

If the body needs more than one expression

Use a braced block and return.

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]), title = "Weighted", color = color.blue)

weight carries a default, so a caller may pass two arguments or three.

If you prefer a different keyword

def, func and no keyword at all declare the same thing. Pick one and keep to it across a script.

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

The failure to watch for

A function cannot draw. Every chart-output call must be made at the top level, and a function body is a scope of its own, so a plot inside one is rejected by name. Return the value and plot it at the top level — which is what both examples above do.

See Your own functions.

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