Bar Index ⇄ TimeLibrary 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:
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 𝚟𝚊𝚛𝚒𝚊𝚋𝚕𝚎 ?
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.
█ 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:
𝚐𝚎𝚝𝙴𝚊𝚛𝚕𝚒𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊(), 𝚐𝚎𝚝𝙻𝚊𝚝𝚎𝚜𝚝𝚂𝚝𝚘𝚛𝚎𝚍𝙳𝚊𝚝𝚊()
Note: the library's strong suit is referencing data from very old bars in the past, which is especially useful for scripts that perform its necessary calculations only on the last bar.
█ USAGE
Step 1
Import the library. Replace with the latest available version number for this library.
//@version=6
indicator("Usage")
import n00btraders/ChartData/
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 variables = map.new()
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 ", 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 : -1
table.cell_set_text(table1, 0, i, "chartData.value(\"open\", " + str.tostring(5000 * i) + "): ")
table.cell_set_text(table2, 0, i, "open : ")
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,#} - Equivalent to {1} bars ago 𝚕𝚒𝚗𝚎.𝚐𝚎𝚝_𝚙𝚛𝚒𝚌𝚎(): {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
Note: there is no runtime error generated for an invalid 𝚝𝚒𝚖𝚎𝚜𝚝𝚊𝚖𝚙 or 𝚋𝚊𝚛𝙸𝚗𝚍𝚎𝚡 argument in any of the functions. Instead, the functions will assign 𝚗𝚊 to the returned values.
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 variables = map.new()
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} 𝚘𝚙𝚎𝚗 at update #1: {1,number,#.##} 𝚌𝚕𝚘𝚜𝚎 at update #1: {2,number,#.##} "
+ "𝚘𝚙𝚎𝚗 at update #{0}: {3,number,#.##} 𝚌𝚕𝚘𝚜𝚎 at update #{0}: {4,number,#.##} "
+ "𝚘𝚙𝚎𝚗 stored in memory: {5,number,#.##} 𝚌𝚕𝚘𝚜𝚎 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 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 variables = map.new()
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) : 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) : The `time` values of all chart (and future) bars.
timeCloseValues (array) : The `time_close` values of all chart (and future) bars.
variables (array) : 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) : 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) : 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:
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:
指標和策略
DevDashboardLibraryThis is a helper library designed to encapsulate the rendering logic for an information panel (dashboard) in Pine Script indicators.
Purpose
The main goal of this library is to streamline the main indicator code by offloading all the work of creating and populating a table into a separate, reusable function. This makes the main script cleaner, more readable, and easier to maintain.
How to Use
The library exports one main function: drawDashboard(). This function takes the ID of an existing table and a set of text and color data as input, then populates the table's cells to form a neat and informative dashboard.
Authorship
This library was created and modified by user Dev0880 for personal use in their projects.
TAUtilityLibLibrary "TAUtilityLib"
Technical Analysis Utility Library - Collection of functions for market analysis, smoothing, scaling, and structure detection
log_snapshot(label1, val1, label2, val2, label3, val3, label4, val4, label5, val5)
Creates formatted log snapshot with 5 labeled values
Parameters:
label1 (string)
val1 (float)
label2 (string)
val2 (float)
label3 (string)
val3 (float)
label4 (string)
val4 (float)
label5 (string)
val5 (float)
Returns: void (logs to console)
f_get_next_tf(tf, steps)
Gets next higher timeframe(s) from current
Parameters:
tf (string) : Current timeframe string
steps (string) : "1 TF Higher" for next TF, any other value for 2 TFs higher
Returns: Next timeframe string or na if at maximum
f_get_prev_tf(tf)
Gets previous lower timeframe from current
Parameters:
tf (string) : Current timeframe string
Returns: Previous timeframe string or na if at minimum
supersmoother(_src, _length)
Ehler's SuperSmoother - low-lag smoothing filter
Parameters:
_src (float) : Source series to smooth
_length (simple int) : Smoothing period
Returns: Smoothed series
butter_smooth(src, len)
Butterworth filter for ultra-smooth price filtering
Parameters:
src (float) : Source series
len (simple int) : Filter period
Returns: Butterworth smoothed series
f_dynamic_ema(source, dynamic_length)
Dynamic EMA with variable length
Parameters:
source (float) : Source series
dynamic_length (float) : Dynamic period (can vary bar to bar)
Returns: Dynamically adjusted EMA
dema(source, length)
Double Exponential Moving Average (DEMA)
Parameters:
source (float) : Source series
length (simple int) : Period for DEMA calculation
Returns: DEMA value
f_scale_percentile(primary_line, secondary_line, x)
Scales secondary line to match primary line using percentile ranges
Parameters:
primary_line (float) : Reference series for target scale
secondary_line (float) : Series to be scaled
x (int) : Lookback bars for percentile calculation
Returns: Scaled version of secondary_line
calculate_correlation_scaling(demamom_range, demamom_min, correlation_range, correlation_min)
Calculates scaling factors for correlation alignment
Parameters:
demamom_range (float) : Range of primary series
demamom_min (float) : Minimum of primary series
correlation_range (float) : Range of secondary series
correlation_min (float) : Minimum of secondary series
Returns: tuple for alignment
getBB(src, length, mult, chartlevel)
Calculates Bollinger Bands with chart level offset
Parameters:
src (float) : Source series
length (simple int) : MA period
mult (simple float) : Standard deviation multiplier
chartlevel (simple float) : Vertical offset for plotting
Returns: tuple
get_mrc(source, length, mult, mult2, gradsize)
Mean Reversion Channel with multiple bands and conditions
Parameters:
source (float) : Price source
length (simple int) : Channel period
mult (simple float) : First band multiplier
mult2 (simple float) : Second band multiplier
gradsize (simple float) : Gradient size for zone detection
Returns:
analyzeMarketStructure(highFractalBars, highFractalPrices, lowFractalBars, lowFractalPrices, trendDirection)
Analyzes market structure for ChoCH and BOS patterns
Parameters:
highFractalBars (array) : Array of high fractal bar indices
highFractalPrices (array) : Array of high fractal prices
lowFractalBars (array) : Array of low fractal bar indices
lowFractalPrices (array) : Array of low fractal prices
trendDirection (int) : Current trend (1=up, -1=down, 0=neutral)
Returns: - change signals and new trend direction
DevSignalLibraryDevSignalLibrary: A Stable Library for Market Structure Analysis
This is a modified and fully standalone version of a popular public library for calculating non-repainting structural points (Zig Zag).
Core Purpose
This library was created to ensure the long-term stability and independence of indicators from external scripts. It solves the problem where a primary indicator might stop working because the original library's author changes their username or deletes the script.
The library exports one main function, signalLib(), which is the core engine for identifying significant swing highs and lows on the chart.
Features and Modifications
Full Autonomy: The library's code can be imported into any of your indicators, making them completely self-contained.
Pine Script v6 Compatibility: The code has been fully refactored and adapted for the latest version of Pine Script, ensuring it functions correctly.
Preserved Logic: The fundamental calculation algorithm has been kept unchanged to preserve its effectiveness.
Credits and Original Source
This code is an adaptation of the public signalLib library, which was created by Yash Gode and published by user RezzoRedPriest.
This modification was made by user Dev0880 for the purpose of ensuring stability and compatibility in personal projects.
tvunitLibrary "tvunit"
method assert(this, description, passed, bar)
Adds a test result to the test suite.
Namespace types: TestSuite
Parameters:
this (TestSuite) : The (TestSuite) instance.
description (string) : A description of the test.
passed (bool) : Whether the test passed or result.
bar (int) : The bar index at which the test was run.
Returns: Whether the assertion passed or result.
method assertWindow(this, runTests, description, bars, passed, stopOnFirstFailure)
Adds a test result to the test suite.
Namespace types: TestSuite
Parameters:
this (TestSuite) : The (TestSuite) instance.
runTests (bool) : Whether to run the tests.
description (string) : A description of the test.
bars (int) : The number of bars to test.
passed (bool) : A series of boolean values indicating whether each bar passed.
stopOnFirstFailure (bool) : Whether to stop on the first test failure.
Returns: Whether the assertion ran or not
method totalTests(this)
Returns the total number of tests in the test suite.
Namespace types: TestSuite
Parameters:
this (TestSuite) : The (TestSuite) instance.
Returns: The total number of tests.
method totalTests(this)
Returns the total number of tests in the test suite.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSuite) instance.
Returns: The total number of tests.
method passedTests(this)
Returns the total number of passed tests in the test suite.
Namespace types: TestSuite
Parameters:
this (TestSuite) : The (TestSuite) instance.
Returns: The total number of passed tests.
method passedTests(this)
Returns the total number of passed tests in the test suite.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSuite) instance.
Returns: The total number of passed tests.
method failedTests(this)
Returns the total number of result tests in the test suite.
Namespace types: TestSuite
Parameters:
this (TestSuite) : The (TestSuite) instance.
Returns: The total number of result tests.
method failedTests(this)
Returns the total number of result tests in the test suite.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSuite) instance.
Returns: The total number of result tests.
newTestSession()
Creates a new test session instance.
Returns: A new (TestSession) instance.
method addNewTestSuite(this, name, description)
Creates a new test suite instance.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSession) instance.
name (string) : The name of the test suite.
description (string) : (optional) A description of the test suite.
Returns: A new (TestSuite) instance.
method add(this, suite)
Creates a new test suite instance.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSession) instance.
suite (TestSuite) : The (TestSuite) instance to add.
Returns: The (TestSession) instance.
method totalSuites(this)
Returns the total number of sessions in the test session.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSession) instance.
Returns: The total number of sessions.
method report(this, show, showOnlyFailedTest)
Generates a report of the test session summary that is suitable for logging.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSession) instance.
show (bool) : Optional: Whether to show the report or not. default: true
showOnlyFailedTest (bool) : Optional: Whether to show only result tests or not. default: false
Returns: A formatted string report of the test suite summary.
method reportGui(this, show, pages, pageSize)
Generates a report of the test suite summary for the GUI.
Namespace types: TestSession
Parameters:
this (TestSession) : The (TestSession) instance.
show (bool) : Optional: Whether to show the report or not. default: true
pages (int) : Optional: The number of pages to show (columns). default: 4
pageSize (int) : Optional: The number of results to show per page (rows), excluding the header. default: 5
approxEqual(a, b, tolerance)
Checks if two floating-point numbers are approximately equal within a specified tolerance.
Parameters:
a (float) : The first floating-point number.
b (float) : The second floating-point number.
tolerance (float) : The tolerance within which the two numbers are considered equal. Default is 1e-6.
Returns: True if the numbers are approximately equal, false otherwise. If both are na, returns true.
TestResult
Fields:
description (series string)
passed (series bool)
bar (series int)
TestSuite
Fields:
isEnabled (series bool)
name (series string)
description (series string)
tests (array)
TestSession
Fields:
suites (array)
Adaptive FoS LibraryThis library provides Adaptive Functions that I use in my scripts. For calculations, I use the max_bars_back function with a fixed length of 200 bars to prevent errors when a script tries to access data beyond its available history. This is a key difference from most other adaptive libraries — if you don’t need it, you don’t have to use it.
Some of the adaptive length functions are normalized. In addition to the adaptive length functions, this library includes various methods for calculating moving averages, normalized differences between fast and slow MA's, as well as several normalized oscillators.
FNGAdataDates_Part2FNGAdataDates_Part2 provides the second part of historical trading dates for a financial instrument (e.g., FNGA index or related asset), covering approximately mid-2021 to January 22, 2018, with 896 trading days. The dates are organized into 18 chunks (dates_19 to dates_36), with 50 dates per chunk for 19–35 and 46 dates for chunk 36 (excluding weekends and possibly holidays). This library complements FNGAdataDates_Part1 to complete the 1,846-date dataset and is designed to align with the FNGAopenPrices and FNGAclosePrices libraries for backtesting, analysis, or visualization in Pine Script.
FNGAdataDates_Part1FNGAdataDates_Part1 provides historical trading dates for a financial instrument (e.g., FNGA index or related asset) from May 23, 2025, to approximately mid-2021, covering 950 trading days. The dates are organized into 19 chunks (dates_0 to dates_18), each containing 50 timestamps representing trading days (excluding weekends and possibly holidays). This library is part one of a two-part set due to Pine Script token limits and must be used with FNGAdataDates_Part2 for the complete dataset (1,846 dates). It is designed to align with the FNGAopenPrices and FNGAclosePrices libraries for backtesting, technical analysis, or visualization in Pine Script.
WCWebLibLibrary "WCWebLib"
method buildWebhookJson(msg, constants)
Builds the final JSON payload from a webhookMessage type.
Namespace types: webhookMessage
Parameters:
msg (webhookMessage) : (webhookMessage) A prepared webhookMessage.
constants (CONSTANTS)
Returns: A JSON Payload.
method buildTakeProfitJson(msg)
Builds the takeProfit JSON message to be used in a webhook message.
Namespace types: takeProfitMessage
Parameters:
msg (takeProfitMessage)
method buildStopLossJson(msg, constants)
Builds the stopLoss JSON message to be used in a webhook message.
Namespace types: stopLossMessage
Parameters:
msg (stopLossMessage)
constants (CONSTANTS)
CONSTANTS
Constants for payload values.
Fields:
ACTION_BUY (series string)
ACTION_SELL (series string)
ACTION_EXIT (series string)
ACTION_CANCEL (series string)
ACTION_ADD (series string)
SENTIMENT_BULLISH (series string)
SENTIMENT_BEARISH (series string)
SENTIMENT_LONG (series string)
SENTIMENT_SHORT (series string)
SENTIMENT_FLAT (series string)
STOP_LOSS_TYPE_STOP (series string)
STOP_LOSS_TYPE_STOP_LIMIT (series string)
STOP_LOSS_TYPE_TRAILING_STOP (series string)
EXTENDEDHOURS (series bool)
ORDER_TYPE_LIMIT (series string)
ORDER_TYPE_MARKET (series string)
TIF_DAY (series string)
webhookMessage
Final webhook message.
Fields:
ticker (series string)
action (series string)
sentiment (series string)
price (series float)
quantity (series int)
takeProfit (series string)
stopLoss (series string)
extendedHours (series bool)
type (series string)
timeInForce (series string)
takeProfitMessage
Take profit message.
Fields:
limitPrice (series float)
percent (series float)
amount (series float)
stopLossMessage
Stop loss message.
Fields:
type (series string)
percent (series float)
amount (series float)
stopPrice (series float)
limitPrice (series float)
trailPrice (series float)
trailPercent (series float)
FNGAdataCloseClose prices for FNGA ETF (Dec 2018–May 2025)
The Close prices for FNGA ETF (December 2018 – May 2025) represent the final trading price recorded at the end of each regular U.S. market session (4:00 p.m. Eastern Time) over the entire lifespan of this leveraged exchange-traded note. Initially issued under the ticker FNGU and later rebranded as FNGA in March 2025 before its redemption in May 2025, the product was designed to provide 3x daily leveraged exposure to the MicroSectors FANG+™ Index, which tracks a concentrated group of large-cap technology and tech-enabled growth leaders such as Apple, Amazon, Meta (Facebook), Netflix, and Alphabet (Google).
Close prices are widely regarded as the most important reference point in market data because they establish the official end-of-day valuation of a security. For leveraged products like FNGA, the closing price is especially critical, since it directly determines the reset value for the following trading session. This daily compounding effect means that FNGA’s closing levels often diverged significantly from the long-term performance of its underlying index, creating both opportunities and risks for traders.
FNGAdataLow“Low prices for FNGA ETF (Dec 2018–May 2025)
The Low prices for FNGA ETF (December 2018 – May 2025) capture the lowest trading price reached during each regular U.S. market session over the entire lifespan of this leveraged exchange-traded note. Initially launched under the ticker FNGU, and later rebranded as FNGA in March 2025 before its eventual redemption, the fund was structured to deliver 3x daily leveraged exposure to the MicroSectors FANG+™ Index. This index concentrated on a small basket of leading technology and tech-enabled growth companies such as Meta (Facebook), Amazon, Apple, Netflix, and Alphabet (Google), along with a few other innovators.
The Low price is particularly important in the study of FNGA because it highlights the intraday downside extremes of a highly volatile, leveraged product. Since FNGA was designed to reset leverage daily, its lows often reflected moments of amplified market stress, when declines in the underlying FANG+™ stocks were multiplied through the 3x leverage structure.
FNGAdataHighHigh prices for FNGA ETF (Dec 2018–May 2025)
The High prices for FNGA ETF (December 2018 – May 2025) represent the maximum trading price reached during each regular U.S. market session over the entire trading lifespan of this leveraged exchange-traded note. Originally issued under the ticker FNGU, and later rebranded as FNGA in March 2025 before its redemption, the fund was designed to deliver 3x daily leveraged exposure to the MicroSectors FANG+™ Index. This index focused on a concentrated group of large-cap technology and technology-enabled companies such as Facebook (Meta), Amazon, Apple, Netflix, and Google (Alphabet), along with a few other growth leaders.
The High price data from December 2018 through May 2025 is crucial for understanding how FNGA behaved during intraday trading sessions. Because FNGA was a daily resetting 3x leveraged product, its intraday highs often displayed extreme sensitivity to movements in the underlying FANG+™ stocks, resulting in sharp upward spikes during bullish days and pronounced volatility during broader market rallies.
FNGAdataOpenOpen prices for FNGA ETF (Dec 2018–May 2025)
The FNGA ETF (originally launched under the FNGU ticker before being renamed in March 2025) tracked the MicroSectors FANG+™ Index with 3x daily leverage and was designed to give traders magnified exposure to a concentrated basket of large-cap technology and tech-enabled companies. The fund’s price history contains multiple phases due to ticker changes, corporate actions, and its eventual redemption in mid-2025.
When looking specifically at Open prices from December 2018 through May 2025, this dataset provides the daily opening values for FNGA across its entire lifecycle. The opening price is the first traded price at the start of each regular U.S. market session (9:30 a.m. Eastern Time). It is an important measure for traders and analysts because it reflects overnight sentiment, pre-market positioning, and often sets the tone for intraday volatility.
utilitiesLibrary for commonly used utilities, for visualizing rolling returns, correlations and sharpe
jsonbuilderLibrary "jsonbuilder"
JsonBuilder for easiest way to generate json string
JSONBuilder(pairs)
Create JSONBuilder instance
Parameters:
pairs (array) : Pairs list, not required for users
method addField(this, key, value, kind)
Add Json Object
Namespace types: _JSONBuilder
Parameters:
this (_JSONBuilder)
key (string) : Field key
value (string) : Field value
kind (series Kind) : Kind value
method execute(this)
Create json string
Namespace types: _JSONBuilder
Parameters:
this (_JSONBuilder)
method addArray(this, key, value)
Add Json Array
Namespace types: _JSONBuilder
Parameters:
this (_JSONBuilder)
key (string) : Field key
value (array<_JSONBuilder>) : Object value array
method addObject(this, key, value)
Add Json Object
Namespace types: _JSONBuilder
Parameters:
this (_JSONBuilder)
key (string) : Field key
value (_JSONBuilder) : Object value
_JSONBuilder
JSONBuilder type
Fields:
pairs (array) : Pairs data
TickerLibraryLibrary "TickerLibrary"
TODO: add library description here
update(session)
Parameters:
session (string)
DrIdrLibraryLibrary "DrIdrLibrary"
TODO: add library description here
update()
DR
Fields:
price (series float)
isValid (series bool)
city (series City)
l (series line)
Data
Fields:
pendingDRs (array)
activeDrs (array)
Pivot Points. High & Lows By Reversal PercentageLibrary "Pivot Points. High & Lows By Reversal Percentage" by Jal9000
This Pine Script library provides a robust function for identifying and tracking pivot points (reversal points) in price data, suitable for integration into custom trading indicators and strategies.
🛠️ Main Features:
- ✅ Identifies pivot highs and lows based on configurable price movement thresholds.
- ✅ Lightweight. No candle backtracing used. Much less computation heavy.
- ✅ Supports multiple calls (with different values) within a single script.
- ✅ Compatible with request.security for multi-timeframe analysis.
- ✅ Returns both confirmed and temporary pivots for flexible integration.
- ✅ Pinescript V5 and V6 compliant code.
Purpose:
The pivots library enables Pine Script developers to easily add pivot point detection to their scripts. It identifies significant price reversals by evaluating price movements against a minimum range threshold ( min_range_pct ) and confirming reversals based on a percentage ( reversal_pct ) of the prior trend’s magnitude. The library supports multiple simultaneous calls with different settings, making it ideal for multi-timeframe strategies.
How It Works:
The library’s f_calculatePivot function tracks price movements to detect pivot points:
Minimum Range Threshold : A potential pivot is considered if the price moves beyond the min_range_pct percentage of the current high (for a high pivot) or low (for a low pivot), ensuring sufficient movement.
Reversal Confirmation : A pivot is confirmed if the price reverses from the potential pivot by at least the reversal_pct percentage of the distance between the last confirmed pivot and the current potential pivot, measuring the retracement relative to the prior trend’s magnitude.
The function alternates between tracking highs (in an uptrend) and lows (in a downtrend), updating the trend when a pivot is confirmed.
State management uses an array of pivot_state objects, allowing independent calculations for different timeframes and min_range_pct values within the same script.
## Technical Reference
Functions:
f_calculatePivot(series float _high, series float _low, float _min_range_pct, float _reversal_pct) →
- Parameters:
_high : The high price series (e.g., high or math.max(open, close) ).
_low : The low price series (e.g., low or math.min(open, close) ).
_min_range_pct : The minimum percentage price movement to consider a potential pivot.
_reversal_pct : The percentage of the prior trend’s distance required to confirm a pivot.
- Returns:
A tuple containing:
isNewPivot : Boolean indicating if a new pivot was confirmed.
last_confirmed_pivot : The most recent confirmed pivot (type pivot ).
temp_pivot : The current temporary pivot (type pivot ).
Pivot type:
idx (series int) : Bar index of the pivot.
typ (series int) : Type of pivot ( PIVOT_HIGH or PIVOT_LOW ).
prc (series float) : Price of the pivot.
tme (series int) : Timestamp of the pivot.
Constants (internal):
TREND_LONG , TREND_SHORT : Trend direction indicators (1, -1).
PIVOT_HIGH , PIVOT_LOW : Pivot type indicators (1, -1).
✨ Example of Use:
//@version=5
indicator("Pivot Example", overlay=true)
import jal9000/pivots/1 as pivots
// Inputs
min_range_pct = input.float(20.0, 'Min Range %')
reversal_pct = input.float(30.0, 'Reversal %')
ignore_wick = input.bool(true, 'Ignore wick')
h = ignore_wick ? math.max(open, close) : high
l = ignore_wick ? math.min(open, close) : low
// Call the function with high, low, and input parameters
= pivots.f_calculatePivot(h, l, min_range_pct, reversal_pct)
// Variable to store previous confirmed pivot outside the function
var pivots.pivot prev_confirmed_pivot = na
// Draw the line if a new pivot is confirmed and previous pivot exists
if is_new_pivot
if not na(prev_confirmed_pivot) and not na(new_confirmed_pivot)
line.new(x1 = prev_confirmed_pivot.idx, y1 = prev_confirmed_pivot.prc, x2 = new_confirmed_pivot.idx, y2 = new_confirmed_pivot.prc, color = color.blue, width = 1)
prev_confirmed_pivot := new_confirmed_pivot
## Release Notes
v1
- Initial release of the pivots library with f_calculatePivot function for detecting pivot points and supporting multiple configurations and timeframes.
v2
- Code is Pinescript V6 ready. Remains identified as V5, but changing the version number is the only thing that is required to be v6.
SessionRangeLibraryLibrary "SessionRangeLibrary"
TODO: add library description here
update(session)
Parameters:
session (string)
Data
Fields:
drh (series float)
drl (series float)
idrh (series float)
idrl (series float)
mid (series float)
FibonacciRetracementHi all!
This library will help you draw Fibonacci retracement levels (zones). The code is from my indicator "Fibonacci retracement" (). You can see that description for more information about the behaviour and example of how to use this library. The code is almost the same with the addition of alerts. If the alert frequency is 'alert.freq_once_per_bar_close' alert messages will be concatenated and have a header saying how many messages it contains (if it's more than 1).
Hope this is of help!
Library "FibonacciRetracement"
ConcateAlerts(context)
Concatenates all alerts from the bar to one string (separated by new lines) and clears alert messages on the current bar.
Parameters:
context (Context)
AddAlert(context, message, unshiftInsteadOfPush)
Parameters:
context (Context)
message (string)
unshiftInsteadOfPush (bool)
Range(context, structure, settings)
Will return values if new levels/zones should be drawn.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement.
structure (Structure type from mickes/PriceAction/1) : The current 'Structure' from the 'MarketStructure' library.
settings (Settings) : The 'Settings' object for the 'Context'.
Returns: A tuple with the start and end pivot if new zones should be drawn, ' ' otherwise.
DrawAll(context, settings, start, end)
Draws lines and labels for the zone. It will also set the 'Price' value that will be used for absolute positions.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement.
settings (Settings) : The 'Settings' object for the 'Context'.
start (Pivot type from mickes/PriceAction/1)
end (Pivot type from mickes/PriceAction/1)
AlertActive(context, settings)
Will alert for all zones that are active. If multiple alert messages are added they will be concatenated (separated by a new line) with a header saying how many messages the alert contains.
Parameters:
context (Context) : The 'Context' for the Fibonacci retracement. This contains the zones that will be alerted if price (wick or close according to the settings) enters it.
settings (Settings) : The 'Settings' object for the 'Context'.
TrendlineSettings
Holds all the values for 'TrendlineSettings'.
Fields:
Enabled (series bool) : If the trendline should be visible or not.
Color (series color) : The color of the trendline.
Style (series string) : The style of the trendline (as a string).
GenericZonesSettings
Holds all the values for 'GenericZonesSettings', that will be applicable to all drawn objects.
Fields:
ExtendRight (series bool) : If all lines should extend to the right or not.
Style (series string) : The style of all drawn lines
Reverse (series bool) : If true, all lines will be reversed.
Prices (series bool) : If price levels should be shown or not.
Levels (series bool) : If levels should be shown or not.
LevelsValue (series string) : Either 'Value' or 'Percent'. Defined if value or percentage should be shown.
FontSize (series int) : The for size of the text in labels drawn.
LabelsPosition (series string) : Coul be 'Left', 'Rigth' or 'Adapt'. 'Adapt' will try to adapt the labels position to the prices.
ZoneSettings
Holds all the values for 'ZoneSettings'.
Fields:
Enabled (series bool) : If this zone is enabled or not.
Level (series float) : The level of the zone.
Color (series color) : The color that will be displayed.
Price (series float) : The price of the level. Will be set internally.
Settings
Holds all the values for 'Settings'.
Fields:
PivotLeftLength (series int) : The left length used to find pivots through the 'MarketStructure' library.
PivotRightLength (series int) : The right length used to find pivots through the 'MarketStructure' library.
Trendline (TrendlineSettings) : The settings for the 'Trendline' object.
GenericZonesSettings (GenericZonesSettings) : The setting applicable to all zones.
AlertFrequency (series string) : The frequency for the alerts. If 'alert.freq_once_per_bar_close', alert messages will be concatenated and have a header saying how many messages it contains (if it's more than 1).
AlertPrice (series string) : The price that has to enter a zone. Can be 'Close' (the closing price) or 'Wick' (the whole candle needs to be in the zone).
Zone1 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone2 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone3 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone4 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone5 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone6 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone7 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone8 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone9 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone10 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone11 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone12 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone13 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone14 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone15 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone16 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone17 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone18 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone19 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone20 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone21 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone22 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone23 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Zone24 (ZoneSettings) : The 'ZoneSettings' that represents this zone.
Context
Holds all the values for 'Context'.
Fields:
Lines (array) : All the drawn lines for the current 'Context'.
Labels (array) : All the drawn labels for the current 'Context'.
Boxes (array) : All the drawn boxes for the current 'Context'.
Alerts (array) : All the alert messages on the current tick.
Start (series int) : The start bar index of the current 'Context'.
PriceActionLibrary "PriceAction"
Hi all!
This library will help you to plot the market structure and liquidity. By now, the only part in the price action section is liquidity, but I plan to add more later on. The market structure will be split into two parts, 'Internal' and 'Swing' with separate pivot lengths. For these two trends it will show you:
• Break of structure (BOS)
• Change of character (CHoCH/CHoCH+) (mandatory)
• Equal high/low (EQH/EQL)
It's inspired by "Smart Money Concepts (SMC) " by LuxAlgo.
This library is now the same code as the code in my library 'MarketStructure', but it has evolved into a more price action oriented library than just a market structure library. This is more accurate and I will continue working on this library to keep it growing.
This code does not provide any examples, but you can look at my indicators 'Market structure' () and 'Order blocks' (), where I use the 'MarketStructure' library (which is the same code).
Market structure
Both of these market structures can be enabled/disabled by setting them to 'na'. The pivots lengths can be configured separately. The pivots found will be the 'base' of and will show you when price breaks it. When that happens a break of structure or a change of character will be created. The latest 5 pivots found within the current trends will be kept to take action on. They are cleared on a change of character, so nothing (break of structures or change of characters) can happen on pivots before a trend change. The internal market structure is shown with dashed lines and swing market structure is shown with solid lines.
Labels for a change of character can have either the text 'CHoCH' or 'CHoCH+'. A Change of Character plus is formed when price fails to form a higher high or a lower low before reversing. Note that a pivot that is created after the change of character might have a higher high or a lower low, thus not making the break a 'CHoCH+'. This is not changed after the pivot is found but is kept as is.
A break of structure is removed if an earlier pivot within the same trend is broken, i.e. another break of structure (with a longer distance) is created. Like in the images below, the first pivot (in the first image) is removed when an earlier pivot's higher price within the same trend is broken (the second image):
[image [https://www.tradingview.com/x/PRP6YtPA/
Equal high/lows have a configurable color setting and can be configured to be extended to the right. Equal high/lows are only possible if it's not been broken by price. A factor (percentage of width) of the Average True Length (of length 14) that the pivot must be within to to be considered an Equal high/low. Equal highs/lows can be of 2 pivots or more.
You are able to show the pivots that are used. "HH" (higher high), "HL" (higher low), "LH" (lower high), "LL" (lower low) and "H"/"L" (for pivots (high/low) when the trend has changed) are the labels used. There are also labels for break of structures ('BOS') and change of characters ('CHoCH' or 'CHoCH+'). The size of these texts is set in the 'FontSize' setting.
When programming I focused on simplicity and ease of read. I did not focus on performance, I will do so if it's a problem (haven't noticed it is one yet).
You can set alerts for when a change of character, break of structure or an equal high/low (new or an addition to a previously found) happens. The alerts that are fired are on 'once_per_bar_close' to avoid repainting. This has the drawback to alert you when the bar closes.
Price action
The indicator will create lines and zones for spotted liquidity. It will draw a line (with dotted style) at the price level that was liquidated, but it will also draw a zone from that level to the bar that broke the pivot high or low price. If that zone is large the liquidation is big and might be significant. This can be disabled in the settings. You can also change the confirmation candles (that does not close above or below the pivot level) needed after a liquidation and how many pivots back to look at.
The lines and boxes drawn will look like this if the color is orange:
Hope this is of help!
Will draw out the market structure for the disired pivot length.
Liqudity(liquidity)
Will draw liquidity.
Parameters:
liquidity (Liquidity) : The 'PriceAction.Liquidity' object.
Pivot(structure)
Sets the pivots in the structure.
Parameters:
structure (Structure)
PivotLabels(structure)
Draws labels for the pivots found.
Parameters:
structure (Structure)
EqualHighOrLow(structure)
Draws the boxes for equal highs/lows. Also creates labels for the pivots included.
Parameters:
structure (Structure)
BreakOfStructure(structure)
Will create lines when a break of strycture occures.
Parameters:
structure (Structure)
Returns: A boolean that represents if a break of structure was found or not.
ChangeOfCharacter(structure)
Will create lines when a change of character occures. This line will have a label with "CHoCH" or "CHoCH+".
Parameters:
structure (Structure)
Returns: A boolean that represents if a change of character was found or not.
VisualizeCurrent(structure)
Will create a box with a background for between the latest high and low pivots. This can be used as the current trading range (if the pivots broke strucure somehow).
Parameters:
structure (Structure)
StructureBreak
Holds drawings for a structure break.
Fields:
Line (series line) : The line object.
Label (series label) : The label object.
Pivot
Holds all the values for a found pivot.
Fields:
Price (series float) : The price of the pivot.
BarIndex (series int) : The bar_index where the pivot occured.
Type (series int) : The type of the pivot (-1 = low, 1 = high).
Time (series int) : The time where the pivot occured.
BreakOfStructureBroken (series bool) : Sets to true if a break of structure has happened.
LiquidityBroken (series bool) : Sets to true if a liquidity of the price level has happened.
ChangeOfCharacterBroken (series bool) : Sets to true if a change of character has happened.
Structure
Holds all the values for the market structure.
Fields:
LeftLength (series int) : Define the left length of the pivots used.
RightLength (series int) : Define the right length of the pivots used.
Type (series Type) : Set the type of the market structure. Two types can be used, 'internal' and 'swing' (0 = internal, 1 = swing).
Trend (series int) : This will be set internally and can be -1 = downtrend, 1 = uptrend.
EqualPivotsFactor (series float) : Set how the limits are for an equal pivot. This is a factor of the Average True Length (ATR) of length 14. If a low pivot is considered to be equal if it doesn't break the low pivot (is at a lower value) and is inside the previous low pivot + this limit.
ExtendEqualPivotsZones (series bool) : Set to true if you want the equal pivots zones to be extended.
ExtendEqualPivotsStyle (series string) : Set the style of equal pivot zones.
ExtendEqualPivotsColor (series color) : Set the color of equal pivot zones.
EqualHighs (array) : Holds the boxes for zones that contains equal highs.
EqualLows (array) : Holds the boxes for zones that contains equal lows.
BreakOfStructures (array) : Holds all the break of structures within the trend (before a change of character).
Pivots (array) : All the pivots in the current trend, added with the latest first, this is cleared when the trend changes.
FontSize (series int) : Holds the size of the font displayed.
AlertChangeOfCharacter (series bool) : Holds true or false if a change of character should be alerted or not.
AlertBreakOfStructure (series bool) : Holds true or false if a break of structure should be alerted or not.
AlerEqualPivots (series bool) : Holds true or false if equal highs/lows should be alerted or not.
Liquidity
Holds all the values for liquidity.
Fields:
LiquidityPivotsHigh (array) : All high pivots for liquidity.
LiquidityPivotsLow (array) : All low pivots for liquidity.
LiquidityConfirmationBars (series int) : The number of bars to confirm that a liquidity is valid.
LiquidityPivotsLookback (series int) : A number of pivots to look back for.
FontSize (series int) : Holds the size of the font displayed.
PriceAction
Holds all the values for the general price action and the market structures.
Fields:
Liquidity (Liquidity)
Swing (Structure) : Placeholder for all objects used for the swing market structure.
Internal (Structure) : Placeholder for all objects used for the internal market structure.
ATR by Session Library [1CG]Library "ATRxSession"
This library shows you how big the bars usually are during a trading session. It looks only at the times you choose (like New York or London hours), measures the “true range” of every bar in that session, then finds the average for that session. It keeps the last N sessions and gives you their overall average, so you can quickly see how much the market typically moves per bar during your chosen session.
Call getSessionAtr(timezone, session, sessionCount) from your script, and it will return a single number: the average per-bar volatility during the chosen session, based on the last N completed sessions. This makes it easy to plug session-specific volatility into your own indicators or strategies.
getSessionAtr(_timezone, _session, _sessionCount)
getSessionAtr - Computes a session-aware ATR over completed sessions.
Parameters:
_timezone (string) : (string) - Timezone string to evaluate session timing.
_session (string) : (string) - Session time range string (e.g., "0930-1600").
_sessionCount (int) : (int) - Number of past completed sessions to include in the rolling average.
Returns: (float) - The average ATR across the last N completed sessions, or na if not enough data.
GoldenCrossLibrary "GoldenCross"
get_signals(short_len, long_len)
Parameters:
short_len (int)
long_len (int)