Skip to content
Algo Trade Analytics Docs
Pine library page — review pending. This page is preserved for compatibility but is not part of the reviewed search index. Check the official Pine Script v6 reference before relying on its explanation, signature, or example.

max_bars_back() - Pine Script Function

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.

max_bars_back(var, num) → void
NameTypeDescription
varseries int/float/bool/color/label/lineIdentifier of the series or object you will index dynamically.
numconst intMaximum number of historical bars Pine should retain for var.
  • Call max_bars_back() before the first place you index the target series with a variable offset.
  • Built-ins such as hl2 or ohlc4 are derived values; apply max_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.
//@version=6
indicator("Dynamic lookback pivot", overlay=false)
const int MAX_LOOKBACK = 800
max_bars_back(close, MAX_LOOKBACK)
lookback = input.int(150, "Bars back", minval=1, maxval=MAX_LOOKBACK - 1)
offset = math.min(lookback, bar_index)
pivotClose = na
if 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")