How to get the largest value from a Pine Script array?
How to get the largest value from a Pine Script array?
Section titled “How to get the largest value from a Pine Script array?”TL;DR
Populate a float array and callarray.max(myArray)to retrieve its highest stored value, then update your logic whenever that maximum changes.
At a Glance
Section titled “At a Glance”| Difficulty | Beginner |
| Time to implement | 5-10 min |
| Category | Arrays |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=5indicator("Array max demo", overlay=false)
var float[] swings = array.new_float()if barstate.isnew array.unshift(swings, high) if array.size(swings) > 10 array.pop(swings)
maxSwing = array.max(swings)plot(maxSwing, "Highest stored high")Why It Matters
Section titled “Why It Matters”Arrays let you capture custom sets of data—swing highs, indicator outputs, custom metrics—and array.max() turns that storage into actionable thresholds. Whether you want to monitor the strongest reading in a rolling window or trigger alerts when a new peak prints, the maximum is a critical reference point.
What You’ll Learn
Section titled “What You’ll Learn”- Create and maintain arrays that hold the data you care about.
- Query the maximum value with
array.max()and guard against empty arrays. - Compare incoming values against the maximum to detect new extremes.
- Visualise or publish the maximum so traders see it at a glance.
Quick Reference
Section titled “Quick Reference”| Call | Purpose |
|---|---|
array.new_float(size) | Creates a float array to store numeric values. |
array.unshift(id, value) | Pushes a value to the front of the array. |
array.pop(id) | Removes the oldest element to keep the array bounded. |
array.size(id) | Reports how many elements the array currently holds. |
array.max(id) | Returns the largest element of the array. |
Implementation Blueprint
Section titled “Implementation Blueprint”-
Persist the array across bars
Declare withvarso the array survives every script execution.var float[] samples = array.new_float() -
Insert and prune values
Decide how many elements you need and keep the array bounded to that size.array.unshift(samples, close)if array.size(samples) > 50array.pop(samples) -
Read and act on the maximum
Guard against empty arrays, then fetch the max and compare it with the latest reading.float maxValue = naif array.size(samples) > 0maxValue := array.max(samples)isNewHigh = close >= maxValue
Example Playbook
Section titled “Example Playbook”//@version=5indicator("Rolling range tracker", overlay=false, max_labels_count=500)
window = input.int(20, "Window size", minval=1)alertOnRecord = input.bool(true, "Alert on new max")
var float[] returns = array.new_float()
// Collect percentage returns and keep the window boundedret = math.abs(close / close[1] - 1.0)if barstate.isnew array.unshift(returns, ret) if array.size(returns) > window array.pop(returns)
float rollingMax = naif array.size(returns) > 0 rollingMax := array.max(returns)
plot(rollingMax, "Largest % move", color=color.new(color.orange, 0))plot(ret, "Current % move", color=color.new(color.blue, 0))
if alertOnRecord and not na(rollingMax) and ret >= rollingMax alert("New record intrabar move: " + str.tostring(ret * 100, format.percent))
if not na(rollingMax) label.new(bar_index, rollingMax, "Max: " + str.tostring(rollingMax * 100, format.percent), style=label.style_label_left, textcolor=color.white, bgcolor=color.new(color.orange, 70))- The array holds a rolling window of returns, so the maximum always reflects recent volatility.
- Plotting both the current value and the maximum makes new records obvious.
- Alerts trigger the first time a bar matches or exceeds the stored maximum.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”- Check
array.size()before callingarray.max()to avoid runtime errors on empty arrays. - Use
array.set(id, index, value)if you need to update elements in place before recomputing the maximum. array.max()runs in linear time; keep the array size reasonable if you call it every bar.- For both min and max tracking, compute
array.min()alongside the maximum and build a custom range indicator.
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”array.max() throws a runtime error
Section titled “array.max() throws a runtime error”It happens when the array is empty. Ensure you insert at least one element before reading the maximum, or guard with if array.size(arr) > 0.
The maximum never updates
Section titled “The maximum never updates”Remember that inserting values at the end with array.push() leaves older values in place. If you keep the array bounded, make sure you remove the oldest items so the maximum can change.
Can I know which index holds the maximum?
Section titled “Can I know which index holds the maximum?”Not directly. Store both the value and its index yourself (for example by scanning with a for loop and tracking the position whenever you see a new high).
Key Takeaways
Section titled “Key Takeaways”- Persist arrays with
varso they accumulate data between bars. - Guard
array.max()with a size check to avoid empty-array errors. - Use the maximum to detect new extremes, adjust stops, or flag regime shifts.
- Combine
array.max()with plotting and alerts for instant visibility when new records hit.
Keep Going
Section titled “Keep Going”- Open AI Editor to apply the pattern with guided assistance
- Browse Strategy Examples for ready-to-run templates
- Connect to Live Trading when you are ready to automate
Adapted from tradingcode.net, optimised for Algo Trade Analytics users.