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

Understanding the array.new() Function in Pine Script

Photo of author
Published on

This article delves into the array.new<type>() function, a fundamental tool for creating and initializing arrays in Pine Script.

What is array.new<type>()?

The array.new<type>() function is used to create a new array object that can store elements of a specific type. This function is versatile, allowing for the creation of arrays containing various data types, including integers, floating-point numbers, strings, colors, and more.

Syntax

array.new<type>(size, initial_value) → array<type>
  • size (optional, series int): Specifies the initial size of the array. If omitted, the default size is 0.
  • initial_value (optional): Sets the initial value for all elements in the array. If omitted, the default is ‘na’ (not available).

Returns

The function returns the ID of the newly created array object, which can then be used with other array functions.

Remarks

  • Array indexes in Pine Script start from 0, following the convention of many programming languages.
  • For initializing an array with a predefined set of elements, consider using array.from instead.

Examples

Example 1: Creating an Array of Strings

//@version=5
indicator("array.new<string> Example")
greetingArray = array.new<string>(1, "Hello, World!")
label.new(bar_index, close, array.get(greetingArray, 0))
Example 1

Code Explanation

  1. //@version=5: Specifies the version of Pine Script being used. Version 5 is the latest version, offering the most up-to-date features and functionalities.
  2. indicator("array.new<string> Example"): Defines a new indicator with the title “array.new<string> Example”. This title appears on the chart where the indicator is applied.
  3. greetingArray = array.new<string>(1, "Hello, World!"): Initializes a new array named greetingArray that can store strings. This array is created with an initial size of 1, and its first (and only) element is set to the string “Hello, World!”.
  4. label.new(bar_index, close, array.get(greetingArray, 0)): Creates a new label on the chart at the current bar’s index (bar_index) and the closing price of the current bar (close). The label’s text is set to the first element of greetingArray, which is retrieved using array.get(greetingArray, 0). Since array indexing starts at 0, array.get(greetingArray, 0) returns “Hello, World!”.

Example 2: Creating an Array of Colors

//@version=5
indicator("array.new<color> Example")
colorArray = array.new<color>()
array.push(colorArray, color.red)
array.push(colorArray, color.green)
plot(close, color = array.get(colorArray, close > open ? 1 : 0))
Example 2

Code Explanation

  1. //@version=5: This line indicates that the script uses version 5 of Pine Script, ensuring compatibility with the latest features and syntax.
  2. indicator("array.new<color> Example"): Declares a new indicator titled “array.new<color> Example” for display purposes. This title appears on the chart to identify the indicator.
  3. colorArray = array.new<color>(): Initializes an empty array named colorArray designed to hold elements of the type color. This array will store the colors used for plotting.
  4. array.push(colorArray, color.red): Adds the color red to the end of the colorArray. Now, colorArray contains one element: color.red.
  5. array.push(colorArray, color.green): Adds the color green to colorArray, which already contains red. After this operation, colorArray has two elements: red and green, in that order.
  6. plot(close, color = array.get(colorArray, close > open ? 1 : 0)): Plots the closing price of the security. The color of the plot is determined dynamically by evaluating close > open ? 1 : 0. If the close is greater than the open (meaning the price went up during the period), 1 is returned, selecting green from colorArray (the second element, index 1). If not, 0 is returned, selecting red (the first element, index 0). This ternary operation effectively changes the plot color to green for upward movements and red for downward movements.

Example 3: Simple Moving Average with array.new<float>

//@version=5
indicator("array.new<float> Example")
movingLength = 5
var priceArray = array.new<float>(movingLength, close)
if array.size(priceArray) == movingLength
    array.remove(priceArray, 0)
    array.push(priceArray, close)
plot(array.sum(priceArray) / movingLength, "SMA")
Example 3

Code Explanation

  1. Initialization of an Array to Store Closing Prices: The script initializes a variable priceArray as an array to store floating-point numbers (float). It’s created with an initial size equal to movingLength (5), and each slot is initially filled with the current close price. This setup prepares priceArray to hold the last 5 closing prices for the moving average calculation.
  2. Updating the Array with Latest Closing Prices: Within the script’s main loop, it checks if priceArray has reached its capacity (movingLength). If so, it removes the oldest price (first element) and appends the latest closing price (close) to the end. This ensures priceArray always contains the most recent 5 closing prices.
  3. Calculating and Plotting the Simple Moving Average (SMA): The script calculates the SMA by summing all prices in priceArray and dividing by movingLength. It then plots this average on the chart. This moving average provides a smoothed representation of the price over the specified period (5 bars in this case), updating dynamically as new data comes in.

Example 4: Managing Lines with array.new<line>

//@version=5
indicator("array.new<line> Example")
// Draw last 15 lines
var lineArray = array.new<line>()
array.push(lineArray, line.new(bar_index - 1, close[1], bar_index, close))
if array.size(lineArray) > 15
    oldLine = array.shift(lineArray)
    line.delete(oldLine)
Example 4

Code Explanation

  1. Line Array Initialization and Line Creation: The script initializes lineArray, an array to store line objects, with the array.new<line>() function, starting empty. It then immediately adds a new line to this array using array.push(lineArray, line.new(bar_index - 1, close[1], bar_index, close)). This line connects the previous bar’s close (close[1]) to the current bar’s close (close), visually representing the price movement from one bar to the next.
  2. Maintaining the Array Size: The script ensures that lineArray does not exceed 15 elements. It checks the size of lineArray with array.size(lineArray) > 15 and, if the array has more than 15 lines, it removes the oldest line using array.shift(lineArray). This keeps the display focused on the most recent 15 lines, avoiding clutter on the chart.
  3. Deleting Old Lines from the Chart: Upon removing the oldest line from lineArray, the script also ensures that this line is deleted from the chart using line.delete(oldLine). This step is crucial for keeping the chart clean and focused on the recent price action, as it prevents lines from accumulating off-screen, which could potentially impact performance and readability.

Key Takeaways

  • The array.new<type>() function is essential for creating arrays in Pine Script, allowing for the management of collections of data.
  • It offers flexibility in initializing arrays with a specific size and initial value.
  • Arrays can store various types of data, including numbers, strings, colors, and graphical objects, facilitating complex data manipulation and graphical representation in indicators and strategies.
  • Remember that array indexes start at 0, and consider using array.from for initializing arrays with specific elements.

Leave a Comment