PINE LIBRARY
Bar Index ⇄ Time

Library to convert a bar index to a timestamp and vice versa.
Utilizes runtime memory to store the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 values of every bar on the chart (and optional future bars), with the ability of storing additional custom values for every chart bar.
█ PREFACE
This library aims to tackle some problems that pine coders (from beginners to advanced) often come across, such as:
█ OVERVIEW
The core functionality provided is conversion between xloc.bar_index and xloc.bar_time values.
The main component of the library is the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object, created via the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function which basically stores the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 of every bar on the chart, and there are 3 more overloads to this function that allow collecting and storing additional data. Once a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object is created, use any of the exported methods:
█ USAGE
Step 1
Import the library. Replace <version> with the latest available version number for this library.
Pine Script®
Step 2
Create a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object to collect data on every bar. Do not declare as `var` or `varip`.
Pine Script®
Step 3
Call any method(s) on the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object. Do not modify its fields directly.
Pine Script®
█ EXAMPLES
• Collect Future Times
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚋𝚊𝚛𝚜𝙵𝚘𝚛𝚠𝚊𝚛𝚍 argument can additionally store time values for up to 500 bars into the future.

Pine Script®
• Collect Custom Data
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜 argument can additionally store custom user-specified values for every bar on the chart.

Pine Script®
• xloc.bar_index → xloc.bar_time
The 𝚝𝚒𝚖𝚎 value (or 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 value) can be retrieved for any bar index that is stored in memory by the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object.

Pine Script®
• xloc.bar_time → xloc.bar_index
Use 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡() to find the bar that a timestamp belongs to.
If the timestamp falls in between the close of one bar and the open of the next bar,
the 𝚜𝚗𝚊𝚙 parameter can be used to determine which bar to choose:

Pine Script®
• Get Price of Line at Timestamp
The pine script built-in function line.get_price() requires working with bar index values. To get the price of a line in terms of a timestamp, convert the timestamp into a bar index or offset.

Pine Script®
█ RUNTIME ERROR MESSAGES
This library's functions will generate a custom runtime error message in the following cases:
Any other runtime errors are due to incorrect usage of the library.
█ NOTES
• Function Descriptions
The library source code uses Markdown for the exported functions. Hover over a function/method call in the Pine Editor to display formatted, detailed information about the function/method.

Pine Script®
• Historical vs. Realtime Behavior
Under the hood, the data collector for this library is declared as `var`. Because of this, the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object will always reflect the latest available data on realtime updates. Any data that is recorded for historical bars will remain unchanged throughout the execution of a script.

Pine Script®
• Collecting Chart Data for Other Contexts
If your use case requires collecting chart data from another context, avoid directly retrieving the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object as this may exceed memory limits.

Pine Script®
• Memory Usage
The library's convenience and ease of use comes at the cost of increased usage of computational resources. For simple scripts, using this library will likely not cause any issues with exceeding memory limits. But for large and complex scripts, you can reduce memory issues by specifying a lower 𝚌𝚊𝚕𝚌_𝚋𝚊𝚛𝚜_𝚌𝚘𝚞𝚗𝚝 amount in the indicator() or strategy() declaration statement.

Pine Script®
█ EXPORTED ENUMS
Snap
Behavior for determining the bar that a timestamp belongs to.
Fields:
LEFT: Snap to the leftmost bar.
RIGHT: Snap to the rightmost bar.
DEFAULT: Default `xloc.bar_time` behavior.
█ EXPORTED TYPES
Note: users of the library do not need to worry about directly accessing the fields of these types; all computations are done through method calls on an object of the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 type.
Variable
Represents a user-specified variable that can be tracked on every chart bar.
Fields:
name (series string): Unique identifier for the variable.
values (array<float>): The array of stored values (one value per chart bar).
ChartData
Represents data for all bars on a chart.
Fields:
bars (series int): Current number of bars on the chart.
timeValues (array<int>): The `time` values of all chart (and future) bars.
timeCloseValues (array<int>): The `time_close` values of all chart (and future) bars.
variables (array<Variable>): Additional custom values to track on all chart bars.
█ EXPORTED FUNCTIONS
collectChartData()
Collects and tracks the `time` and `time_close` value of every bar on the chart.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars.
Parameters:
barsForward (simple int): Number of future bars to collect data for.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
variables (simple map<string, float>): Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward, variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
barsForward (simple int): Number of future bars to collect data for.
variables (simple map<string, float>): Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
█ EXPORTED METHODS
method timestampToBarIndex(chartData, timestamp, snap)
Converts a UNIX timestamp to a bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
timestamp (series int): A UNIX time.
snap (series Snap): A `Snap` enum value.
Returns: A bar index, or `na` if unable to find the appropriate bar index.
method getNumberOfBarsBack(chartData, timestamp)
Converts a UNIX timestamp to a history-referencing length (i.e., number of bars back).
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
timestamp (series int): A UNIX time.
Returns: A bar offset, or `na` if unable to find a valid number of bars back.
method timeAtBarIndex(chartData, barIndex)
Retrieves the `time` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (int): The bar index.
Returns: The `time` value, or `na` if there is no `time` stored for the bar index.
method time(chartData, length)
Retrieves the `time` value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
length (series int): Number of bars back.
Returns: The `time` value `length` bars ago, or `na` if there is no `time` stored for that bar.
method timeCloseAtBarIndex(chartData, barIndex)
Retrieves the `time_close` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (series int): The bar index.
Returns: The `time_close` value, or `na` if there is no `time_close` stored for the bar index.
method timeClose(chartData, length)
Retrieves the `time_close` value of the bar that is `length` bars back from the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
length (series int): Number of bars back.
Returns: The `time_close` value `length` bars ago, or `na` if there is none stored.
method valueAtBarIndex(chartData, name, barIndex)
Retrieves the value of a custom variable for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
name (series string): The variable name.
barIndex (series int): The bar index.
Returns: The value of the variable, or `na` if that variable is not stored for the bar index.
method value(chartData, name, length)
Retrieves a variable value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
name (series string): The variable name.
length (series int): Number of bars back.
Returns: The value `length` bars ago, or `na` if that variable is not stored for the bar index.
method getAllVariablesAtBarIndex(chartData, barIndex)
Retrieves all custom variables for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (series int): The bar index.
Returns: Map of all custom variables that are stored for the specified bar index.
method getEarliestStoredData(chartData)
Gets all values from the earliest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
Returns: A tuple: [barIndex, time, timeClose, variables]
method getLatestStoredData(chartData, futureData)
Gets all values from the latest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
futureData (series bool): Whether to include the future data that is stored in memory.
Returns: A tuple: [barIndex, time, timeClose, variables]
Utilizes runtime memory to store the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 values of every bar on the chart (and optional future bars), with the ability of storing additional custom values for every chart bar.
█ PREFACE
This library aims to tackle some problems that pine coders (from beginners to advanced) often come across, such as:
This library can solve the above problems (and many more) with the addition of a few lines of code, rather than requiring the coder to refactor their script to accommodate the limitations.
- I'm trying to draw an object with a 𝚋𝚊𝚛_𝚒𝚗𝚍𝚎𝚡 that is more than 10,000 bars into the past, but this causes my script to fail. How can I convert the 𝚋𝚊𝚛_𝚒𝚗𝚍𝚎𝚡 to a UNIX time so that I can draw visuals using xloc.bar_time?
- I have a diagonal line drawing and I want to get the "y" value at a specific time, but line.get_price() only accepts a bar index value. How can I convert the timestamp into a bar index value so that I can still use this function?
- I want to get a previous 𝚘𝚙𝚎𝚗 value that occurred at a specific timestamp. How can I convert the timestamp into a historical offset so that I can use 𝚘𝚙𝚎𝚗[𝚘𝚏𝚏𝚜𝚎𝚝]?
- I want to reference a very old value for a variable. How can I access a previous value that is older than the maximum historical buffer size of 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎[5000]?
█ OVERVIEW
The core functionality provided is conversion between xloc.bar_index and xloc.bar_time values.
The main component of the library is the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object, created via the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function which basically stores the 𝚝𝚒𝚖𝚎 and 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 of every bar on the chart, and there are 3 more overloads to this function that allow collecting and storing additional data. Once a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object is created, use any of the exported methods:
- Methods to convert a UNIX timestamp into a bar index or bar offset:
𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚐𝚎𝚝𝙽𝚞𝚖𝚋𝚎𝚛𝙾𝚏𝙱𝚊𝚛𝚜𝙱𝚊𝚌𝚔() - Methods to retrieve the stored data for a bar index:
𝚝𝚒𝚖𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚝𝚒𝚖𝚎𝙲𝚕𝚘𝚜𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚟𝚊𝚕𝚞𝚎𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡(), 𝚐𝚎𝚝𝙰𝚕𝚕𝚅𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜𝙰𝚝𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡() - Methods to retrieve the stored data at a number of bars back (i.e., historical offset):
𝚝𝚒𝚖𝚎(), 𝚝𝚒𝚖𝚎𝙲𝚕𝚘𝚜𝚎(), 𝚟𝚊𝚕𝚞𝚎() - Methods to retrieve all the data points from the earliest bar (or latest bar) stored in memory, which can be useful for debugging purposes:
𝚐𝚎𝚝𝙴𝚊𝚛𝚕𝚒𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊(), 𝚐𝚎𝚝𝙻𝚊𝚝𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊()
█ USAGE
Step 1
Import the library. Replace <version> with the latest available version number for this library.
//@version=6
indicator("Usage")
import n00btraders/ChartData/<version>
Step 2
Create a 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object to collect data on every bar. Do not declare as `var` or `varip`.
chartData = ChartData.collectChartData() // call on every bar to accumulate the necessary data
Step 3
Call any method(s) on the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object. Do not modify its fields directly.
if barstate.islast
int firstBarTime = chartData.timeAtBarIndex(0)
int lastBarTime = chartData.time(0)
log.info("First `time`: " + str.format_time(firstBarTime) + ", Last `time`: " + str.format_time(lastBarTime))
█ EXAMPLES
• Collect Future Times
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚋𝚊𝚛𝚜𝙵𝚘𝚛𝚠𝚊𝚛𝚍 argument can additionally store time values for up to 500 bars into the future.
//@version=6
indicator("Example `collectChartData(barsForward)`")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData(barsForward = 500)
var rectangle = box.new(na, na, na, na, xloc = xloc.bar_time, force_overlay = true)
if barstate.islast
int futureTime = chartData.timeAtBarIndex(bar_index + 100)
int lastBarTime = time
box.set_lefttop(rectangle, lastBarTime, open)
box.set_rightbottom(rectangle, futureTime, close)
box.set_text(rectangle, "Extending box 100 bars to the right. Time: " + str.format_time(futureTime))
• Collect Custom Data
The overloaded 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() functions that accept a 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜 argument can additionally store custom user-specified values for every bar on the chart.
//@version=6
indicator("Example `collectChartData(variables)`")
import n00btraders/ChartData/1
var map<string, float> variables = map.new<string, float>()
variables.put("open", open)
variables.put("close", close)
variables.put("open-close midpoint", (open + close) / 2)
variables.put("boolean", open > close ? 1 : 0)
chartData = ChartData.collectChartData(variables = variables)
var fgColor = chart.fg_color
var table1 = table.new(position.top_right, 2, 9, color(na), fgColor, 1, fgColor, 1, true)
var table2 = table.new(position.bottom_right, 2, 9, color(na), fgColor, 1, fgColor, 1, true)
if barstate.isfirst
table.cell(table1, 0, 0, "ChartData.value()", text_color = fgColor)
table.cell(table2, 0, 0, "open[offset]", text_color = fgColor)
table.merge_cells(table1, 0, 0, 1, 0)
table.merge_cells(table2, 0, 0, 1, 0)
for i = 1 to 8
table.cell(table1, 0, i, text_color = fgColor, text_halign = text.align_left, text_font_family = font.family_monospace)
table.cell(table2, 0, i, text_color = fgColor, text_halign = text.align_left, text_font_family = font.family_monospace)
table.cell(table1, 1, i, text_color = fgColor)
table.cell(table2, 1, i, text_color = fgColor)
if barstate.islast
for i = 1 to 8
float open1 = chartData.value("open", 5000 * i)
float open2 = i < 3 ? open[5000 * i] : -1
table.cell_set_text(table1, 0, i, "chartData.value(\"open\", " + str.tostring(5000 * i) + "): ")
table.cell_set_text(table2, 0, i, "open[" + str.tostring(5000 * i) + "]: ")
table.cell_set_text(table1, 1, i, str.tostring(open1))
table.cell_set_text(table2, 1, i, open2 >= 0 ? str.tostring(open2) : "Error")
• xloc.bar_index → xloc.bar_time
The 𝚝𝚒𝚖𝚎 value (or 𝚝𝚒𝚖𝚎_𝚌𝚕𝚘𝚜𝚎 value) can be retrieved for any bar index that is stored in memory by the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object.
//@version=6
indicator("Example `timeAtBarIndex()`")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData()
if barstate.islast
int start = bar_index - 15000
int end = bar_index - 100
// line.new(start, close, end, close) // !ERROR - `start` value is too far from current bar index
start := chartData.timeAtBarIndex(start)
end := chartData.timeAtBarIndex(end)
line.new(start, close, end, close, xloc.bar_time, width = 10)
• xloc.bar_time → xloc.bar_index
Use 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡() to find the bar that a timestamp belongs to.
If the timestamp falls in between the close of one bar and the open of the next bar,
the 𝚜𝚗𝚊𝚙 parameter can be used to determine which bar to choose:
𝚂𝚗𝚊𝚙.𝙻𝙴𝙵𝚃 - prefer to choose the leftmost bar (typically used for closing times)
𝚂𝚗𝚊𝚙.𝚁𝙸𝙶𝙷𝚃 - prefer to choose the rightmost bar (typically used for opening times)
𝚂𝚗𝚊𝚙.𝙳𝙴𝙵𝙰𝚄𝙻𝚃 (or 𝚗𝚊) - copies the same behavior as xloc.bar_time uses for drawing objects
//@version=6
indicator("Example `timestampToBarIndex()`")
import n00btraders/ChartData/1
startTimeInput = input.time(timestamp("01 Aug 2025 08:30 -0500"), "Session Start Time")
endTimeInput = input.time(timestamp("01 Aug 2025 15:15 -0500"), "Session End Time")
chartData = ChartData.collectChartData()
if barstate.islastconfirmedhistory
int startBarIndex = chartData.timestampToBarIndex(startTimeInput, ChartData.Snap.RIGHT)
int endBarIndex = chartData.timestampToBarIndex(endTimeInput, ChartData.Snap.LEFT)
line1 = line.new(startBarIndex, 0, startBarIndex, 1, extend = extend.both, color = color.new(color.green, 60), force_overlay = true)
line2 = line.new(endBarIndex, 0, endBarIndex, 1, extend = extend.both, color = color.new(color.green, 60), force_overlay = true)
linefill.new(line1, line2, color.new(color.green, 90))
// using Snap.DEFAULT to show that it is equivalent to drawing lines using `xloc.bar_time` (i.e., it aligns to the same bars)
startBarIndex := chartData.timestampToBarIndex(startTimeInput)
endBarIndex := chartData.timestampToBarIndex(endTimeInput)
line.new(startBarIndex, 0, startBarIndex, 1, extend = extend.both, color = color.yellow, width = 3)
line.new(endBarIndex, 0, endBarIndex, 1, extend = extend.both, color = color.yellow, width = 3)
line.new(startTimeInput, 0, startTimeInput, 1, xloc.bar_time, extend.both, color.new(color.blue, 85), width = 11)
line.new(endTimeInput, 0, endTimeInput, 1, xloc.bar_time, extend.both, color.new(color.blue, 85), width = 11)
• Get Price of Line at Timestamp
The pine script built-in function line.get_price() requires working with bar index values. To get the price of a line in terms of a timestamp, convert the timestamp into a bar index or offset.
//@version=6
indicator("Example `line.get_price()` at timestamp")
import n00btraders/ChartData/1
lineStartInput = input.time(timestamp("01 Aug 2025 08:30 -0500"), "Line Start")
chartData = ChartData.collectChartData()
var diagonal = line.new(na, na, na, na, force_overlay = true)
if time <= lineStartInput
line.set_xy1(diagonal, bar_index, open)
if barstate.islastconfirmedhistory
line.set_xy2(diagonal, bar_index, close)
if barstate.islast
int timeOneWeekAgo = timenow - (7 * timeframe.in_seconds("1D") * 1000)
// Note: could also use `timetampToBarIndex(timeOneWeekAgo, Snap.DEFAULT)` and pass the value directly to `line.get_price()`
int barsOneWeekAgo = chartData.getNumberOfBarsBack(timeOneWeekAgo)
float price = line.get_price(diagonal, bar_index - barsOneWeekAgo)
string formatString = "Time 1 week ago: {0,number,#}\n - Equivalent to {1} bars ago\n\n𝚕𝚒𝚗𝚎.𝚐𝚎𝚝_𝚙𝚛𝚒𝚌𝚎(): {2,number,#.##}"
string labelText = str.format(formatString, timeOneWeekAgo, barsOneWeekAgo, price)
label.new(timeOneWeekAgo, price, labelText, xloc.bar_time, style = label.style_label_lower_right, size = 16, textalign = text.align_left, force_overlay = true)
█ RUNTIME ERROR MESSAGES
This library's functions will generate a custom runtime error message in the following cases:
- 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() is not called consecutively, or is called more than once on a single bar
- Invalid 𝚋𝚊𝚛𝚜𝙵𝚘𝚛𝚠𝚊𝚛𝚍 argument in the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function
- Invalid 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎𝚜 argument in the 𝚌𝚘𝚕𝚕𝚎𝚌𝚝𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊() function
- Invalid 𝚕𝚎𝚗𝚐𝚝𝚑 argument in any of the functions that accept a number of bars back
Any other runtime errors are due to incorrect usage of the library.
█ NOTES
• Function Descriptions
The library source code uses Markdown for the exported functions. Hover over a function/method call in the Pine Editor to display formatted, detailed information about the function/method.
//@version=6
indicator("Demo Function Tooltip")
import n00btraders/ChartData/1
chartData = ChartData.collectChartData()
int barIndex = chartData.timestampToBarIndex(timenow)
log.info(str.tostring(barIndex))
• Historical vs. Realtime Behavior
Under the hood, the data collector for this library is declared as `var`. Because of this, the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object will always reflect the latest available data on realtime updates. Any data that is recorded for historical bars will remain unchanged throughout the execution of a script.
//@version=6
indicator("Demo Realtime Behavior")
import n00btraders/ChartData/1
var map<string, float> variables = map.new<string, float>()
variables.put("open", open)
variables.put("close", close)
chartData = ChartData.collectChartData(variables)
if barstate.isrealtime
varip float initialOpen = open
varip float initialClose = close
varip int updateCount = 0
updateCount += 1
float latestOpen = open
float latestClose = close
float recordedOpen = chartData.valueAtBarIndex("open", bar_index)
float recordedClose = chartData.valueAtBarIndex("close", bar_index)
string formatString = "# of updates: {0}\n\n𝚘𝚙𝚎𝚗 at update #1: {1,number,#.##}\n𝚌𝚕𝚘𝚜𝚎 at update #1: {2,number,#.##}\n\n"
+ "𝚘𝚙𝚎𝚗 at update #{0}: {3,number,#.##}\n𝚌𝚕𝚘𝚜𝚎 at update #{0}: {4,number,#.##}\n\n"
+ "𝚘𝚙𝚎𝚗 stored in memory: {5,number,#.##}\n𝚌𝚕𝚘𝚜𝚎 stored in memory: {6,number,#.##}"
string labelText = str.format(formatString, updateCount, initialOpen, initialClose, latestOpen, latestClose, recordedOpen, recordedClose)
label.new(bar_index, close, labelText, style = label.style_label_left, force_overlay = true)
• Collecting Chart Data for Other Contexts
If your use case requires collecting chart data from another context, avoid directly retrieving the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 object as this may exceed memory limits.
//@version=6
indicator("Demo Return Calculated Results")
import n00btraders/ChartData/1
timeInput = input.time(timestamp("01 Sep 2025 08:30 -0500"), "Time")
var int oneMinuteBarsAgo = na
// !ERROR - Memory Limits Exceeded
// chartDataArray = request.security_lower_tf(syminfo.tickerid, "1", ChartData.collectChartData())
// oneMinuteBarsAgo := chartDataArray.last().getNumberOfBarsBack(timeInput)
// function that returns calculated results (a single integer value instead of an entire `ChartData` object)
getNumberOfBarsBack() =>
chartData = ChartData.collectChartData()
chartData.getNumberOfBarsBack(timeInput)
calculatedResultsArray = request.security_lower_tf(syminfo.tickerid, "1", getNumberOfBarsBack())
oneMinuteBarsAgo := calculatedResultsArray.size() > 0 ? calculatedResultsArray.last() : na
if barstate.islast
string labelText = str.format("The selected timestamp occurs [{0}] 1-minute bars ago", oneMinuteBarsAgo)
label.new(bar_index, hl2, labelText, style = label.style_label_left, size = 16, force_overlay = true)
• Memory Usage
The library's convenience and ease of use comes at the cost of increased usage of computational resources. For simple scripts, using this library will likely not cause any issues with exceeding memory limits. But for large and complex scripts, you can reduce memory issues by specifying a lower 𝚌𝚊𝚕𝚌_𝚋𝚊𝚛𝚜_𝚌𝚘𝚞𝚗𝚝 amount in the indicator() or strategy() declaration statement.
//@version=6
// !ERROR - Memory Limits Exceeded using the default number of bars available (~20,000 bars for Premium plans)
//indicator("Demo `calc_bars_count` parameter")
// Reduce number of bars using `calc_bars_count` parameter
indicator("Demo `calc_bars_count` parameter", calc_bars_count = 15000)
import n00btraders/ChartData/1
map<string, float> variables = map.new<string, float>()
variables.put("open", open)
variables.put("close", close)
variables.put("weekofyear", weekofyear)
variables.put("dayofmonth", dayofmonth)
variables.put("hour", hour)
variables.put("minute", minute)
variables.put("second", second)
// simulate large memory usage
chartData0 = ChartData.collectChartData(variables)
chartData1 = ChartData.collectChartData(variables)
chartData2 = ChartData.collectChartData(variables)
chartData3 = ChartData.collectChartData(variables)
chartData4 = ChartData.collectChartData(variables)
chartData5 = ChartData.collectChartData(variables)
chartData6 = ChartData.collectChartData(variables)
chartData7 = ChartData.collectChartData(variables)
chartData8 = ChartData.collectChartData(variables)
chartData9 = ChartData.collectChartData(variables)
log.info(str.tostring(chartData0.time(0)))
log.info(str.tostring(chartData1.time(0)))
log.info(str.tostring(chartData2.time(0)))
log.info(str.tostring(chartData3.time(0)))
log.info(str.tostring(chartData4.time(0)))
log.info(str.tostring(chartData5.time(0)))
log.info(str.tostring(chartData6.time(0)))
log.info(str.tostring(chartData7.time(0)))
log.info(str.tostring(chartData8.time(0)))
log.info(str.tostring(chartData9.time(0)))
if barstate.islast
result = table.new(position.middle_right, 1, 1, force_overlay = true)
table.cell(result, 0, 0, "Script Execution Successful ✅", text_size = 40)
█ EXPORTED ENUMS
Snap
Behavior for determining the bar that a timestamp belongs to.
Fields:
LEFT: Snap to the leftmost bar.
RIGHT: Snap to the rightmost bar.
DEFAULT: Default `xloc.bar_time` behavior.
Note: this enum is used for the 𝚜𝚗𝚊𝚙 parameter of 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙𝚃𝚘𝙱𝚊𝚛𝙸𝚗𝚍𝚎𝚡().
█ EXPORTED TYPES
Note: users of the library do not need to worry about directly accessing the fields of these types; all computations are done through method calls on an object of the 𝙲𝚑𝚊𝚛𝚝𝙳𝚊𝚝𝚊 type.
Variable
Represents a user-specified variable that can be tracked on every chart bar.
Fields:
name (series string): Unique identifier for the variable.
values (array<float>): The array of stored values (one value per chart bar).
ChartData
Represents data for all bars on a chart.
Fields:
bars (series int): Current number of bars on the chart.
timeValues (array<int>): The `time` values of all chart (and future) bars.
timeCloseValues (array<int>): The `time_close` values of all chart (and future) bars.
variables (array<Variable>): Additional custom values to track on all chart bars.
█ EXPORTED FUNCTIONS
collectChartData()
Collects and tracks the `time` and `time_close` value of every bar on the chart.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars.
Parameters:
barsForward (simple int): Number of future bars to collect data for.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
variables (simple map<string, float>): Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
collectChartData(barsForward, variables)
Collects and tracks the `time` and `time_close` value of every bar on the chart as well as a specified number of future bars. Additionally, tracks a custom set of variables for every chart bar.
Parameters:
barsForward (simple int): Number of future bars to collect data for.
variables (simple map<string, float>): Custom values to collect on every chart bar.
Returns: `ChartData` object to convert between `xloc.bar_index` and `xloc.bar_time`.
█ EXPORTED METHODS
method timestampToBarIndex(chartData, timestamp, snap)
Converts a UNIX timestamp to a bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
timestamp (series int): A UNIX time.
snap (series Snap): A `Snap` enum value.
Returns: A bar index, or `na` if unable to find the appropriate bar index.
method getNumberOfBarsBack(chartData, timestamp)
Converts a UNIX timestamp to a history-referencing length (i.e., number of bars back).
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
timestamp (series int): A UNIX time.
Returns: A bar offset, or `na` if unable to find a valid number of bars back.
method timeAtBarIndex(chartData, barIndex)
Retrieves the `time` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (int): The bar index.
Returns: The `time` value, or `na` if there is no `time` stored for the bar index.
method time(chartData, length)
Retrieves the `time` value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
length (series int): Number of bars back.
Returns: The `time` value `length` bars ago, or `na` if there is no `time` stored for that bar.
method timeCloseAtBarIndex(chartData, barIndex)
Retrieves the `time_close` value for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (series int): The bar index.
Returns: The `time_close` value, or `na` if there is no `time_close` stored for the bar index.
method timeClose(chartData, length)
Retrieves the `time_close` value of the bar that is `length` bars back from the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
length (series int): Number of bars back.
Returns: The `time_close` value `length` bars ago, or `na` if there is none stored.
method valueAtBarIndex(chartData, name, barIndex)
Retrieves the value of a custom variable for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
name (series string): The variable name.
barIndex (series int): The bar index.
Returns: The value of the variable, or `na` if that variable is not stored for the bar index.
method value(chartData, name, length)
Retrieves a variable value of the bar that is `length` bars back relative to the latest bar.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
name (series string): The variable name.
length (series int): Number of bars back.
Returns: The value `length` bars ago, or `na` if that variable is not stored for the bar index.
method getAllVariablesAtBarIndex(chartData, barIndex)
Retrieves all custom variables for the specified bar index.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
barIndex (series int): The bar index.
Returns: Map of all custom variables that are stored for the specified bar index.
method getEarliestStoredData(chartData)
Gets all values from the earliest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
Returns: A tuple: [barIndex, time, timeClose, variables]
method getLatestStoredData(chartData, futureData)
Gets all values from the latest bar data that is currently stored in memory.
Namespace types: ChartData
Parameters:
chartData (series ChartData): The `ChartData` object.
futureData (series bool): Whether to include the future data that is stored in memory.
Returns: A tuple: [barIndex, time, timeClose, variables]
Библиотека Pine
В истинном духе TradingView автор опубликовал этот код Pine как библиотеку с открытым исходным кодом, чтобы другие программисты Pine из нашего сообщества могли им воспользоваться. Вы можете использовать эту библиотеку в приватных или других публикациях с открытым исходным кодом, но повторное использование этого кода в публикации регулируется Правилами поведения.
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.
Библиотека Pine
В истинном духе TradingView автор опубликовал этот код Pine как библиотеку с открытым исходным кодом, чтобы другие программисты Pine из нашего сообщества могли им воспользоваться. Вы можете использовать эту библиотеку в приватных или других публикациях с открытым исходным кодом, но повторное использование этого кода в публикации регулируется Правилами поведения.
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.