bar_index - PineScript Variable
bar_index
Section titled “bar_index”Overview
Section titled “Overview”bar_index is the zero-based position of the bar currently being processed. The first historical bar uses index 0, and each subsequent bar increments the value by one as data progresses toward realtime.
intQualifier
Section titled “Qualifier”series
Remarks
Section titled “Remarks”- Use historical references such as
bar_index[1]to compare neighbouring indices or to calculate spans between events. bar_indexincreases continuously across the loaded chart history. When new history loads (e.g., during scrolling), earlier bars receive negative indexes relative to the current dataset.- Because the variable changes on every bar, any logic that relies on specific index values may repaint when history is reloaded or chart depth changes.
Example
Section titled “Example”//@version=5indicator("Highlight first 200 bars", overlay=true)
limit = input.int(200, "Highlight bars", minval=1)isEarlyBar = bar_index < limit
bgcolor(isEarlyBar ? color.new(color.blue, 88) : na, title="Early history highlight")
if isEarlyBar and barstate.islastconfirmedhistory label.new(bar_index, high, text=str.tostring(bar_index), textcolor=color.white, bgcolor=color.new(color.blue, 70), style=label.style_label_down)