Arrays

Defining an array in Pine Script.

Defining an array in Pine Script.

Arrays are an essential feature in programming languages, allowing for the storage and organization of data in a single variable. Arrays can be used to store multiple values of any data type, making them a powerful tool for storing and manipulating data in programming. In Pine Script, arrays can help you develop advanced indicators and strategies that require complex math. In this article, I’ll show you a few ways to define new arrays in Pine Script.

The first way is to use an “array.new” family of functions. For example, to create an empty array with an integer type you can use the following code:

a1 = array.new_int(0)

The first argument of this function takes the size of the array you want to create so this code will create an empty array. There is also syntax for the same function:

a1 = array.new<int>(0)

This function has the second argument – “initial_value”. Using this value, you can fill your array with values if you’re creating a not empty array. For example, the following code will create an array of size five filled with close values:

a = array.new_int(5, int(close))

In Pine Script, you can create an array for ten different data types, so you have corresponding functions for all of them:

  • array.new_bool
  • array.new_box
  • array.new_color
  • array.new_float
  • array.new_int
  • array.new_label
  • array.new_line
  • array.new_linefill
  • array.new_string
  • array.new_table

If you already know a set of values you want to create your array from, you can use “array.from” function. Pine Script will look at the values you passed to this function and will create an array of the corresponding type.

a = array.from(4, 5, 1, 2, 5)
a = array.from("AAPL", "MSFT", "TSLA", "V", "UBER")

Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news