In this tutorial, we’ll dive deep into how to use the array.size()
function effectively, exploring its syntax, arguments, and practical examples.
Syntax
The syntax for the array.size()
function is straightforward:
array.size(id) → series int
Arguments
id
(any array type): This is the array object whose size you want to determine.
Example
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.
//@version=5 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
- Initialize an Empty Floating Point Array:
myArray = array.new_float(0)
: Creates a new, empty array of floating points.
- Populate the Array:
- The loop
for idx = 0 to 9
iterates 10 times, pushing the close price of the last 10 bars intomyArray
usingarray.push(myArray, close[idx])
.
- The loop
- Create a Slice of the Array:
mySlice = array.slice(myArray, 0, 5)
: Generates a new array (mySlice
) containing elements frommyArray
from index 0 to 4 (5 elements in total).
- Modify the Slice and Reflect on the Original Array:
array.push(mySlice, open)
: Adds the current open price tomySlice
. Since slices are references to the original array, this operation also affectsmyArray
.
- Plotting the Sizes:
- The
plot
function is used twice to display the size of bothmyArray
andmySlice
on the chart, illustrating how operations on the slice impact the original array.
- The
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.