Skip to main content
An array holds a list of values that can grow and shrink while the script runs. In this tutorial we keep the last N closes in one, calculate their average, highest and lowest, and count how many are above the average. Every step is a whole script: replace what is in the editor, and check it.
1

collect the closes

array.new<float>(0) creates an empty array of floats and array.push(window, close) adds a value at its end. A plain declaration creates a new array on every bar, so we declare it static to create it once and keep adding to it. We plot the length to watch it grow.
The line rises by one per bar. An array holds at most 10,000 elements, so a script that only pushes would stop there.
2

keep only the last N

array.shift(window) removes the first, oldest, element. Make the window length an input and trim whenever the array is longer.
The line rises to 10 and stays there: the array now holds the last 10 closes.
3

calculate from the array

array.avg, array.max and array.min work on the whole array. We move to the price bars with overlay=true and plot three lines.
The average sits between the highest and lowest close of the window, as a band that follows price.
4

loop over the array

for value in window visits each element in order, and does nothing on an empty array. We count the closes above the average and shade the background when at least 70 percent of them are.

Two mistakes to avoid

There is no array.size. The count of elements is array.length:
The compiler says: Namespace array has no function size. Did you mean slice()? An index outside the array stops the script. array.get(window, 0) on an empty array passes the check and stops the script when it runs with an “Index out of bounds” error, and so does an index past array.length(window) - 1. Test the length first. Reading window[0] is not an element either: [] on an array is the history operator, so use array.get.

What we built

An indicator that keeps the last N closes in a static array, trims it with array.shift, plots the average, highest and lowest of the window, and shades the background when most of the window sits above its average.

Next

Arrays

every array function and the rules for arrays of drawings and of your own types.

Values that persist across bars

static and intra.