Introduction to Tuple-like Returns
Pine Script™ allows for functions that return multiple results. This is particularly useful when you need to perform several related calculations within a single function and return all the results simultaneously.
Syntax for Multi-Result Functions
Defining the Function
A function that returns multiple results uses a tuple-like structure for its return value. Here’s an example of such a function:
calculateDifferences(x, y) => sum = x + y diff = x - y [sum, diff]
In this function, calculateDifferences
:
- Takes two parameters
x
andy
. - Calculates their sum (
sum
) and difference (diff
). - Returns both results as a list
[sum, diff]
.
Calling the Function
To utilize a function that returns multiple results, a special syntax is used to capture each result separately:
[total, difference] = calculateDifferences(open, close) plot(total) plot(difference)
- Here,
[total, difference]
captures the two results returned bycalculateDifferences
. total
receives the sum, anddifference
receives the difference ofopen
andclose
.- Both
total
anddifference
can then be used independently in the script.
Limitations of User-Defined Functions
While user-defined functions in Pine Script are quite versatile, they come with certain limitations. Specifically, they cannot use the following built-in functions:
barcolor()
fill()
hline()
indicator()
library()
plot()
plotbar()
plotcandle()
plotchar()
plotshape()
strategy()
These limitations ensure that functions remain focused on calculations and logic, leaving visual and strategy elements to be handled outside the function scope.
Conclusion and Key Takeaways
- Multiple Results: Functions in Pine Script can return multiple results, allowing for complex calculations within a single function call.
- Tuple-like Structure: The results are returned in a tuple-like structure and can be individually accessed when the function is called.
- Built-in Function Restrictions: Certain built-in functions are restricted within user-defined functions to maintain script integrity.