Home » Array Functions » Understanding the array.size() Function in Pine Script

Understanding the array.size() Function in Pine Script

Photo of author
Published on

In this tutorial, we’ll dive deep into how to use the array.size() function effectively, exploring its syntax, arguments, and practical examples.


The syntax for the array.size() function is straightforward:

array.size(id) → series int


  • id (any array type): This is the array object whose size you want to determine.


To illustrate the use of array.size(), let’s modify the provided example to make it unique, while ensuring we cover all aspects of the function.

indicator("Array Size Demonstration")
myArray = array.new_float(0)
for idx = 0 to 9
    array.push(myArray, close[idx])

// Modifications in the slice affect the original array
mySlice = array.slice(myArray, 0, 5)
array.push(mySlice, open)

// The size changes in both slice and original array are demonstrated
plot(array.size(myArray), "Size of Original Array")
plot(array.size(mySlice), "Size of Slice")

Walkthrough of the Example

  1. Initialize an Empty Floating Point Array:
    • myArray = array.new_float(0): Creates a new, empty array of floating points.
  2. Populate the Array:
    • The loop for idx = 0 to 9 iterates 10 times, pushing the close price of the last 10 bars into myArray using array.push(myArray, close[idx]).
  3. Create a Slice of the Array:
    • mySlice = array.slice(myArray, 0, 5): Generates a new array (mySlice) containing elements from myArray from index 0 to 4 (5 elements in total).
  4. Modify the Slice and Reflect on the Original Array:
    • array.push(mySlice, open): Adds the current open price to mySlice. Since slices are references to the original array, this operation also affects myArray.
  5. Plotting the Sizes:
    • The plot function is used twice to display the size of both myArray and mySlice on the chart, illustrating how operations on the slice impact the original array.

Key Features and Takeaways

  • Function Usability and Syntax: The array.size() function is essential for managing array lengths dynamically, especially in loops or when arrays are modified during script execution.
  • Argument Type Flexibility: The function accepts any array type, making it versatile for different data structures.
  • Practical Application: In trading scripts, understanding the size of an array can help in scenarios like calculating moving averages, managing data sets, or when slices of arrays are utilized for calculations.
  • Impact of Array Operations: Operations on slices of arrays can affect the original arrays, highlighting the importance of understanding reference behavior in Pine Script.

In conclusion, the array.size() function is a fundamental component of array management in Pine Script, offering a simple yet powerful way to work with dynamic data structures in trading algorithms. 

Leave a Comment