Home » Pinescript Syntax » Multi-Line Functions in Pine Script

Multi-Line Functions in Pine Script

Photo of author
Published on

Introduction to Multi-Line Functions

Pine Script™ supports multi-line functions for more complex operations that require multiple steps or calculations. These functions are defined over several lines, allowing for intricate logic and variable manipulations.

Syntax of Multi-Line Functions

The basic syntax for a multi-line function in Pine Script is:

<identifier>(<parameter_list>) =>

<identifier>(<list of parameters>) =>
    <variable declaration>
    <variable declaration or expression>
Components of Multi-Line Functions
  • Parameter List: Defined similarly to single-line functions, with each parameter optionally having a default value.
  • Local Block: The body of the function consisting of multiple statements, each on a separate line.
  • Indentation: Each statement within the function body must be indented (using 4 spaces or 1 tab) to denote its inclusion in the function’s scope.
  • End of Function Body: The first unindented statement signals the end of the function’s body.

Example: Creating a Geometric Average Function

Consider the function geom_average which calculates the geometric average of two values:

geom_average(x, y) =>
    squareX = x * x
    squareY = y * y
    math.sqrt(squareX + squareY)

In this function:

  • squareX and squareY are local variables holding the squares of x and y, respectively.
  • The function math.sqrt computes the square root of the sum squareX + squareY.
  • The result of math.sqrt(squareX + squareY) is the output of the geom_average function.

Understanding the Function’s Flow

  1. Variable Declaration: The variables squareX and squareY are declared and calculated within the function.
  2. Final Calculation: The last statement of the function (math.sqrt(squareX + squareY)) is the result returned when the function is called.
  3. Indentation: Note the importance of indentation for maintaining the function scope and clarity.

Conclusion and Key Takeaways

  • Multi-line functions in Pine Script allow for complex calculations and logical operations.
  • Proper indentation is crucial for defining the scope of the function’s body.
  • The last statement in the function determines the return value.

Leave a Comment