max_bars_back() - Pine Script Function
max_bars_back()
Section titled “max_bars_back()”Overview
Section titled “Overview”max_bars_back() tells Pine how many historical bars to retain for a specific series or object. Use it when a history reference such as series[dynamicIndex] depends on runtime data that Pine cannot predict at compile time. Without an explicit buffer size the script may throw a runtime error once it asks for more history than is available.
The num argument must be a compile-time constant. Choose a value that comfortably exceeds the largest dynamic offset you expect, but avoid inflating it unnecessarily because large buffers increase memory usage.
Syntax
Section titled “Syntax”max_bars_back(var, num) → voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
var | series int/float/bool/color/label/line | Identifier of the series or object you will index dynamically. |
num | const int | Maximum number of historical bars Pine should retain for var. |
Remarks
Section titled “Remarks”- Call
max_bars_back()before the first place you index the target series with a variable offset. - Built-ins such as
hl2orohlc4are derived values; applymax_bars_back()to their components (high,low, etc.) instead. - Prefer the function to the global
indicator(..., max_bars_back=...)parameter when only a single series requires manual buffering; it keeps memory usage in check.
Example
Section titled “Example”//@version=5indicator("Dynamic lookback pivot", overlay=false)
const int MAX_LOOKBACK = 800max_bars_back(close, MAX_LOOKBACK)
lookback = input.int(150, "Bars back", minval=1, maxval=MAX_LOOKBACK - 1)offset = math.min(lookback, bar_index)
pivotClose = naif bar_index >= offset pivotClose := close[offset]
plot(close, "Close", color=color.gray)plot(pivotClose, "Close at bars-back offset", color=color.orange)
bgcolor(bar_index < offset ? color.new(color.red, 90) : na, title="Insufficient history warning")