ScriptingHow toHow to return more than one value from a function

How to return more than one value from a function

Return a bracketed list. The arrow body accepts a tuple as well as a single expression.

indicator("Band around the average", "band", true)

def band(float centre, float width) => [centre - width, centre + width]

float average = talib.sma(close, 20)
[lower, upper] = band(average, talib.atr(14))

plot(average, title = "Average", color = color.gray)
plot(lower, title = "Lower", color = color.blue)
plot(upper, title = "Upper", color = color.blue)

Unpack the result in one statement, with the names in brackets on the left of =. The order is the order you returned them in.

The bracket trap

Square brackets index when they follow something and build a tuple when they stand on their own. band(average, atr)[1] would be an index into history, not the second value of the tuple. Unpack first, then index the name you unpacked.

Built-in functions do the same

Several talib functions return three values, and you unpack them the same way.

talib.macd(series float source, series int fastlen, series int slowlen, series int siglen) → [series float, series float, series float]

This edition does not name the three elements of any built-in tuple, so read the signature for how many values come back and no more than that.

Where the tuple goes

After the arrow. The tuple is one of the three body forms the grammar accepts — a braced block, a single expression after =>, or a tuple after => — so write it in place of the expression, not around the whole declaration.

See Your own functions and Referencing previous bars.

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