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:
Arrays
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
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.
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.
BecakFloatingPanelsLibrary "BecakFloatingPanels"
Library for creating floating indicator panels with MACD, RSI, and Stochastic indicators
calculateMacd(source, fastLength, slowLength, signalLength)
Calculate MACD components
Parameters:
source (float) : Price source for calculation
fastLength (simple int) : Fast EMA period
slowLength (simple int) : Slow EMA period
signalLength (simple int) : Signal line period
Returns: MacdData MACD calculation results
calculateRsi(source, length)
Calculate RSI
Parameters:
source (float) : Price source for calculation
length (simple int) : RSI period
Returns: float RSI value
calculateStochastic(source, high, low, kLength, kSmoothing, dSmoothing)
Calculate Stochastic components
Parameters:
source (float) : Price source for calculation
high (float) : High prices
low (float) : Low prices
kLength (int) : %K period
kSmoothing (int) : %K smoothing period
dSmoothing (int) : %D smoothing period
Returns: StochData Stochastic calculation results
calculateStochSignals(stochK, stochD, overboughtLevel, oversoldLevel)
Calculate Stochastic signals
Parameters:
stochK (float) : Stochastic %K series
stochD (float) : Stochastic %D series
overboughtLevel (float) : Overbought threshold
oversoldLevel (float) : Oversold threshold
Returns: StochSignals Signal flags
calculateChartMetrics(high, low, lookbackLength)
Calculate chart range and positioning metrics
Parameters:
high (float) : High prices
low (float) : Low prices
lookbackLength (int) : Lookback period
Returns: ChartMetrics Chart positioning data
calculateMacdRange(macdLine, signalLine, histogram, safeLookback)
Calculate MACD range for normalization
Parameters:
macdLine (float) : MACD line series
signalLine (float) : Signal line series
histogram (float) : Histogram series
safeLookback (int) : Lookback period
Returns: MacdRange MACD range metrics
initVisualArrays()
Initialize visual arrays
Returns: VisualArrays Container with initialized arrays
clearVisuals(visuals)
Clear all visual elements
Parameters:
visuals (VisualArrays) : VisualArrays container
Returns: void
calculatePanelPositions(chartMetrics, oscPlacement, panelHeight, panelSpacing, centerOffset)
Calculate panel positions based on placement option
Parameters:
chartMetrics (ChartMetrics) : Chart metrics object
oscPlacement (string) : Panel placement option
panelHeight (float) : Panel height percentage
panelSpacing (float) : Panel spacing percentage
centerOffset (float) : Center offset percentage
Returns: PanelPositions Panel boundary coordinates
createPanelBackgrounds(visuals, positions, panelLeft, panelRight, showBackground, transparency)
Create panel backgrounds
Parameters:
visuals (VisualArrays) : VisualArrays container
positions (PanelPositions) : PanelPositions object
panelLeft (int) : Left boundary
panelRight (int) : Right boundary
showBackground (bool) : Show background flag
transparency (int) : Background transparency
Returns: void
drawReferenceLines(visuals, positions, chartMetrics, macdRange, dataLeft, dataRight, panelHeight, rsiOverbought, rsiOversold, stochOverbought, stochOversold)
Draw reference lines for all panels
Parameters:
visuals (VisualArrays) : VisualArrays container
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
macdRange (MacdRange) : MacdRange object
dataLeft (int) : Left data boundary
dataRight (int) : Right data boundary
panelHeight (float) : Panel height percentage
rsiOverbought (int) : RSI overbought level
rsiOversold (int) : RSI oversold level
stochOverbought (int) : Stochastic overbought level
stochOversold (int) : Stochastic oversold level
Returns: void
drawMacdIndicator(visuals, macdLine, signalLine, histogram, macdRange, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight)
Draw MACD indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
macdLine (float) : MACD line series
signalLine (float) : Signal line series
histogram (float) : Histogram series
macdRange (MacdRange) : MacdRange object
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
Returns: void
drawRsiIndicator(visuals, rsiValue, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight)
Draw RSI indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
rsiValue (float) : RSI value
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
Returns: void
drawStochasticIndicator(visuals, stochK, stochD, positions, chartMetrics, barIndex, nextBarIndex, barIndexOffset, panelHeight, stochOverbought, stochOversold)
Draw Stochastic indicator
Parameters:
visuals (VisualArrays) : VisualArrays container
stochK (float) : Stochastic %K series
stochD (float) : Stochastic %D series
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
barIndex (int) : Current bar index
nextBarIndex (int) : Next bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
stochOverbought (int) : Overbought level
stochOversold (int) : Oversold level
Returns: void
addStochasticSignals(visuals, buySignal, sellSignal, positions, chartMetrics, currentBarIndex, barIndexOffset, panelHeight, signalIndex)
Add Stochastic buy/sell signals
Parameters:
visuals (VisualArrays) : VisualArrays container
buySignal (bool) : Buy signal series
sellSignal (bool) : Sell signal series
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
currentBarIndex (int) : Current bar index
barIndexOffset (int) : Horizontal offset
panelHeight (float) : Panel height percentage
signalIndex (int) : Signal index for lookback
Returns: void
setPanelLabels(macdLabel, rsiLabel, stochLabel, positions, chartMetrics, labelOffset, panelHeight, barIndexOffset)
Set panel title labels
Parameters:
macdLabel (label) : MACD label reference
rsiLabel (label) : RSI label reference
stochLabel (label) : Stochastic label reference
positions (PanelPositions) : PanelPositions object
chartMetrics (ChartMetrics) : ChartMetrics object
labelOffset (int) : Label horizontal offset
panelHeight (float) : Panel height percentage
barIndexOffset (int) : Horizontal offset
Returns: void
showDebugInfo(chartMetrics, debugMode)
Display debug information
Parameters:
chartMetrics (ChartMetrics) : ChartMetrics object
debugMode (bool) : Debug mode flag
Returns: void
ChartMetrics
Chart metrics container
Fields:
visibleHigh (series float) : Highest visible price
visibleLow (series float) : Lowest visible price
chartRange (series float) : Price range of chart
chartCenter (series float) : Center point of chart
MacdData
MACD calculation results
Fields:
macdLine (series float) : Main MACD line
signalLine (series float) : Signal line
histogram (series float) : MACD histogram
MacdRange
MACD range metrics for normalization
Fields:
highest (series float) : Highest MACD value
lowest (series float) : Lowest MACD value
BRange (series float) : Total range
StochData
Stochastic calculation results
Fields:
k_smooth (series float) : Smoothed %K line
d (series float) : %D line
StochSignals
Stochastic signals
Fields:
buySignal (series bool) : Buy signal flag
sellSignal (series bool) : Sell signal flag
PanelPositions
Panel positioning data
Fields:
macdTop (series float) : MACD panel top
macdBottom (series float) : MACD panel bottom
rsiTop (series float) : RSI panel top
rsiBottom (series float) : RSI panel bottom
stochTop (series float) : Stochastic panel top
stochBottom (series float) : Stochastic panel bottom
VisualArrays
Visual elements arrays container
Fields:
macdLines (array) : Array of MACD lines
macdHist (array) : Array of MACD histogram boxes
rsiLines (array) : Array of RSI lines
stochLines (array) : Array of Stochastic lines
stochAreas (array) : Array of Stochastic areas
stochSignals (array) : Array of Stochastic signals
panelBackgrounds (array) : Array of panel backgrounds
MarketStructureLibMarketStructure Library
This library extends the "MarketStructure" library by mickes () under the Mozilla Public License 2.0, credited to mickes. It provides functions for detecting and visualizing market structure, including Break of Structure (BOS), Change of Character (CHoCH), Equal High/Low (EQH/EQL), and liquidity zones, with enhancements for improved accuracy and customization.
Functionality
Market Structure Detection: Identifies internal (orderflow) and swing market structures using pivot points, with support for BOS, CHoCH, and EQH/EQL.
Volatility Filter: Only confirms pivots when the ATR exceeds a user-defined threshold, reducing false signals in low-volatility markets.
Trend Strength Metric: Calculates a trend strength score based on pivot frequency and volatility, stored in the Structure type for use in scripts.
Customizable Visualizations: Allows users to configure line styles and colors for BOS and CHoCH, and label sizes for pivots, BOS, CHoCH, and liquidity.
Liquidity Zones: Visualizes liquidity levels with confirmation bars and lookback periods.
Methodology
Pivot Detection: Uses ta.pivothigh and ta.pivotlow with a volatility filter (ATR multiplier) to confirm significant pivots.
Trend Strength: Computes a score as pivotCount / LeftLength * (currentATR / ATR), reflecting trend reliability based on pivot frequency and market volatility.
BOS/CHoCH Logic: Detects BOS when price breaks a pivot in the trend direction, and CHoCH when price reverses against the trend, with labels for "MSF" or "MSF+" based on pivot patterns.
EQH/EQL Zones: Creates boxes around equal highs/lows within an ATR-based threshold, with optional extension.
Visualization: Draws lines and labels for BOS, CHoCH, and liquidity, with user-defined styles, colors, and sizes.
Usage
Integration: Import into Pine Script indicators (e.g., import Fenomentn/MarketStructure/1) to analyze market structure.
Configuration: Set pivot lengths, volatility threshold, label sizes, and visualization styles via script inputs.
Alerts: Enable alerts for BOS, CHoCH, and EQH/EQL events, triggered on bar close to avoid repainting.
Best Practices: Use on forex or crypto charts (1m to 12h timeframes) for optimal results. Adjust the volatility threshold for different market conditions.
Originality
This library builds on mickes’ framework by adding:
A volatility-based pivot filter to enhance signal accuracy.
A trend strength metric for assessing trend reliability.
Dynamic label sizing and customizable visualization styles for better usability. No additional open-source code was reused beyond mickes’ library, credited under MPL 2.0.
Developed by Fenomentn. Published under Mozilla Public License 2.0.
Primes_4These libraries (Primes_1 -> Primes_4) contain arrays of reduced Prime Numbers to minimize the amount of tokens, allowing more information to be exported.
Values, for example:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
are reduced to:
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
With the restoreValues() function found in this library, the reduced values can be restored back to its original state.
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
is restored back to:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
The libraries contain all Prime Numbers from 2 to 1.340.011
------------------------------------------------------------
Library "Primes_4"
Prime Numbers 1.096.031 - 1.340.011
primes_a()
Prime numbers 1.096.031 - 1.205.999
primes_b()
Prime numbers 1.206.013 - 1.317.989
primes_c()
Prime numbers 1.318.003 - 1.340.011
method restoreValues(iArray, iShow, iFrom, iTo)
restoreValues : Restores reduced prime number values in an array to their original state, for example `7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21` is restored to `7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021`
Namespace types: array
Parameters:
iArray (array)
iShow (bool)
iFrom (int)
iTo (int)
Returns: Initial array with restored prime number values
Primes_3These libraries (Primes_1 -> Primes_4) contain arrays of reduced Prime Numbers to minimize the amount of tokens, allowing more information to be exported.
Values, for example:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
are reduced to:
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
With the restoreValues() function found in the Primes_4 library, the reduced values can be restored back to its original state.
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
is restored back to:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
The libraries contain all Prime Numbers from 2 to 1.340.011
------------------------------------------------------------
Library "Primes_3"
Prime Numbers 713.021 - 1.095.989
primes_a()
Prime numbers 713.021 - 820.997
primes_b()
Prime numbers 821.003 - 928.979
primes_c()
Prime numbers 929.003 - 1.038.953
primes_d()
Prime numbers 1.039.001 - 1.095.989
Primes_2These libraries (Primes_1 -> Primes_4) contain arrays of reduced Prime Numbers to minimize the amount of tokens, allowing more information to be exported.
Values, for example:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
are reduced to:
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
With the restoreValues() function found in the Primes_4 library, the reduced values can be restored back to its original state.
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
is restored back to:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
The libraries contain all Prime Numbers from 2 to 1.340.011
------------------------------------------------------------
Library "Primes_2"
Prime Numbers 340.007 - 712.981
primes_a()
Prime numbers 340.007 - 441.971
primes_b()
Prime numbers 442.003 - 545.959
primes_c()
Prime numbers 546.001 - 650.987
primes_d()
Prime numbers 651.017 - 712.981
Primes_1These libraries (Primes_1 -> Primes_4) contain arrays of reduced Prime Numbers to minimize the amount of tokens, allowing more information to be exported.
Values, for example:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
are reduced to:
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
With the restoreValues() function found in the Primes_4 library, the reduced values can be restored back to its original state.
7001, 13, 19, 27, 39, 43, 57, 69, 79, 7103, 9, 21
is restored back to:
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7021
The libraries contain all Prime Numbers from 2 to 1.340.011
------------------------------------------------------------
Library "Primes_1"
Prime Numbers 2 - 339.991
primes_a()
Prime numbers 2 - 81.689
primes_b()
Prime numbers 81.701 - 175.897
primes_c()
Prime numbers 175.909 - 273.997
primes_d()
Prime numbers 274.007 - 339.991
AuthLibLibrary "AuthLib"
DrawingData
Fields:
kzone1Boxes (array)
kzone2Boxes (array)
kzone3Boxes (array)
kzone4Boxes (array)
kzone5Boxes (array)
kzone6Boxes (array)
kzone1Labels (array)
kzone2Labels (array)
kzone3Labels (array)
kzone4Labels (array)
kzone5Labels (array)
kzone6Labels (array)
kzone1TrendLines (array)
kzone2TrendLines (array)
kzone3TrendLines (array)
kzone4TrendLines (array)
kzone5TrendLines (array)
kzone6TrendLines (array)
kzone1PriceLabels (array)
kzone2PriceLabels (array)
kzone3PriceLabels (array)
kzone4PriceLabels (array)
kzone5PriceLabels (array)
kzone6PriceLabels (array)
lib_listaAtivos_PosseidonLibrary "lib_listaAtivos_Posseidon"
TODO: add library description here
ativos(loteSelected)
TODO: add function description here
Parameters:
loteSelected (simple int)
Returns: TODO: add what function returns
TrailingStopLibraryLibrary "TrailingStopLibrary"
专业移动止盈库 - 为Pine Script策略提供完整的追踪止盈功能。支持做多做空双向交易,基于风险回报比智能激活,提供收盘价和高低价两种判断模式。包含完整的状态管理、调试信息和易用的API接口。适用于股票、外汇、加密货币等各种市场的风险管理。
@version 1.0
@author runto2006
new_config(enabled, activation_ratio, pullback_percent, price_type)
创建移动止盈配置对象
Parameters:
enabled (bool) : (bool) 是否启用移动止盈,默认true
activation_ratio (float) : (float) 激活盈亏比,默认4.0,表示盈利4倍止损距离时激活
pullback_percent (float) : (float) 回撤百分比,默认1.0,表示回撤1%时触发止盈
price_type (string) : (string) 价格类型,默认"close"。"close"=收盘价模式,"hl"=高低价模式
Returns: Config 配置对象
new_state()
创建移动止盈状态对象
Returns: State 初始化的状态对象
reset(state)
重置移动止盈状态
Parameters:
state (State) : (State) 要重置的状态对象
Returns: void
calc_activation_target(entry_price, stop_price, activation_ratio, is_long)
计算激活目标价格
Parameters:
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
activation_ratio (float) : (float) 激活盈亏比
is_long (bool) : (bool) 是否为多头持仓
Returns: float 激活目标价格,如果输入无效则返回na
get_check_price(price_type, is_long, for_activation)
获取用于判断的价格
Parameters:
price_type (string) : (string) 价格类型:"close"或"hl"
is_long (bool) : (bool) 是否为多头持仓
for_activation (bool) : (bool) 是否用于激活判断,影响高低价的选择方向
Returns: float 当前判断价格
check_activation(config, state, entry_price, stop_price, is_long, has_position)
检查是否应该激活移动止盈
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
is_long (bool) : (bool) 是否为多头持仓
has_position (bool) : (bool) 是否有持仓
Returns: bool 是否成功激活
update_tracking(config, state, is_long)
更新移动止盈的追踪价格
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
is_long (bool) : (bool) 是否为多头持仓
Returns: void
check_trigger(config, state, entry_price, is_long)
检查是否触发移动止盈
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: bool 是否触发止盈
process(config, state, entry_price, stop_price, is_long, has_position)
一体化处理移动止盈逻辑
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
stop_price (float) : (float) 止损价格
is_long (bool) : (bool) 是否为多头持仓
has_position (bool) : (bool) 是否有持仓
Returns: bool 是否触发止盈
get_trigger_price(config, state, is_long)
获取当前触发价格
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
is_long (bool) : (bool) 是否为多头持仓
Returns: float 触发价格,未激活时返回na
get_pullback_percent(config, state, entry_price, is_long)
计算当前回撤百分比
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: float 当前回撤百分比,未激活时返回na
get_status_info(config, state, entry_price, is_long)
获取状态信息字符串(用于调试)
Parameters:
config (Config) : (Config) 移动止盈配置
state (State) : (State) 移动止盈状态
entry_price (float) : (float) 入场价格
is_long (bool) : (bool) 是否为多头持仓
Returns: string 详细的状态信息
Config
移动止盈配置对象
Fields:
enabled (series bool) : (bool) 是否启用移动止盈功能
activation_ratio (series float) : (float) 激活盈亏比 - 盈利达到止损距离的多少倍时激活追踪
pullback_percent (series float) : (float) 回撤百分比 - 从最优价格回撤多少百分比时触发止盈
price_type (series string) : (string) 价格判断类型 - "close"使用收盘价,"hl"使用高低价
State
移动止盈状态对象
Fields:
activated (series bool) : (bool) 是否已激活追踪止盈
highest_price (series float) : (float) 激活后记录的最高价格
lowest_price (series float) : (float) 激活后记录的最低价格
activation_target (series float) : (float) 激活目标价格
SIC_TICKER_DATAThe SIC Ticker Data is an advanced and efficient library for ticker-to-industry classification and sector analysis. Built with enterprise-grade performance optimizations, this library provides instant access to SIC codes, industry classifications, and peer company data for comprehensive market analysis.
Perfect for: Sector rotation strategies, peer analysis, portfolio diversification, market screening, and financial research tools.
The simple idea behind this library is to pull any data related to SIC number of any US stock market ticker provided by SEC in order to see the industry and also see the exact competitors of the ticker.
The library stores 3 types of data: SIC number, Ticker, and Industry name. What makes it very useful is that you can pull any one of this data using the other. For example, if you would like to know which tickers are inside a certain SIC, or what's the SIC number of a specific ticker, or even which tickers are inside a certain industry, you can use this library to pull this data. The idea for data inside this library is to be accessible in any direction possible as long as they're related to each other.
We've also published a simple indicator that uses this library in order to demonstrate the inner workings of this library.
The library stores thousands of tickers and their relevant SIC code and industry for your use and is constantly updated with new data when available. This is a large library but it is optimized to run as fast as possible. The previous unpublished versions would take over 40 seconds to load any data but the final public version here loads the data in less than 5 seconds.
🔍 Primary Lookup Functions
createDataStore()
Initialize the library with all pre-loaded data.
store = data.createDataStore()
getSicByTicker(store, ticker)
Get SIC code for any ticker symbol.
sic = data.getSicByTicker(store, "AAPL") // Returns: "3571"
getIndustryByTicker(store, ticker)
Get industry classification for any ticker.
industry = data.getIndustryByTicker(store, "AAPL") // Returns: "Computer Hardware"
getTickersBySic(store, sic)
Get all companies in a specific SIC code.
software = data.getTickersBySic(store, "7372") // Returns: "MSFT,GOOGL,META,V,MA,CRM,ADBE,ORCL,NOW,INTU"
getTickersByIndustry(store, industry)
Get all companies in an industry.
retail = data.getTickersByIndustry(store, "Retail") // Returns: "AMZN,HD,WMT,TGT,COST,LOW"
📊 Array & Analysis Functions
getTickerArrayBySic(store, sic)
Get tickers as array for processing.
techArray = data.getTickerArrayBySic(store, "7372")
for i = 0 to array.size(techArray) - 1
ticker = array.get(techArray, i)
// Process each tech company
getTickerCountBySic(store, sic)
Count companies in a sector (ultra-fast).
pinescripttechCount = data.getTickerCountBySic(store, "7372") // Returns: 10
🎯 Utility Functions
tickerExists(store, ticker)
Check if ticker exists in database.
exists = data.tickerExists(store, "AAPL") // Returns: true
tickerInSic(store, ticker, sic)
Check if ticker belongs to specific sector.
isInTech = data.tickerInSic(store, "AAPL", "3571") // Returns: true
💡 Usage Examples
Example 1: Basic Ticker Lookup
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Ticker Analysis", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
currentIndustry = data.getIndustryByTicker(store, syminfo.ticker)
if barstate.islast and currentSic != "NOT_FOUND"
label.new(bar_index, high, syminfo.ticker + " SIC: " + currentSic + " Industry: " + currentIndustry)
Example 2: Sector Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Sector Comparison", overlay=false)
store = data.createDataStore()
// Compare sector sizes
techCount = data.getTickerCountBySic(store, "7372") // Software
financeCount = data.getTickerCountBySic(store, "6199") // Finance
healthCount = data.getTickerCountBySic(store, "2834") // Pharmaceutical
plot(techCount, title="Tech Companies", color=color.blue)
plot(financeCount, title="Finance Companies", color=color.green)
plot(healthCount, title="Health Companies", color=color.red)
Example 3: Peer Analysis
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Find Competitors", overlay=true)
store = data.createDataStore()
currentSic = data.getSicByTicker(store, syminfo.ticker)
if currentSic != "NOT_FOUND"
competitors = data.getTickersBySic(store, currentSic)
peerCount = data.getTickerCountBySic(store, currentSic)
if barstate.islast
label.new(bar_index, high, "Competitors (" + str.tostring(peerCount) + "): " + competitors)
Example 4: Portfolio Sector Allocation
// @version=6
import EdgeTerminal/SIC_TICKER_DATA/1 as data
indicator("Portfolio Analysis", overlay=false)
store = data.createDataStore()
// Analyze your portfolio's sector distribution
portfolioTickers = array.from("AAPL", "MSFT", "GOOGL", "JPM", "JNJ")
sectorCount = map.new()
for i = 0 to array.size(portfolioTickers) - 1
ticker = array.get(portfolioTickers, i)
industry = data.getIndustryByTicker(store, ticker)
if industry != "NOT_FOUND"
currentCount = map.get(sectorCount, industry)
newCount = na(currentCount) ? 1 : currentCount + 1
map.put(sectorCount, industry, newCount)
🔧 Advanced Feature
You can also bulk load data for large data sets like this:
// Pre-format your data as pipe-separated string
bulkData = "AAPL:3571:Computer Hardware|MSFT:7372:Software|GOOGL:7372:Software"
store = data.createDataStoreFromBulk(bulkData)
ArraysAssorted🟩 OVERVIEW
This library provides utility methods for working with arrays in Pine Script. The first method finds extreme values (highest/lowest) within a rolling lookback window and returns both the value and its position. I might extend the library for other ad-hoc methods I use to work with arrays.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the method you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/ArraysAssorted/1
See the EXAMPLE USAGE sections within the library for examples of calling the methods.
You do not need permission to use Pine libraries in your open-source scripts.
However, you do need explicit permission to reuse code from a Pine Script library’s functions in a public protected or invite-only publication .
In any case, credit the author in your description. It is also good form to credit in open-source comments.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 METHOD 1: m_getHighestLowestFloat()
Finds the highest or lowest float value from an array. Simple enough. It also returns the index of the value as an offset from the end of the array.
• It works with rolling lookback windows, so you can find extremes within the last N elements
• It includes an offset parameter to skip recent elements if needed
• It handles edge cases like empty arrays and invalid ranges gracefully
• It can find either the first or last occurrence of the extreme value
We also export two enums whose sole purpose is to look pretty as method arguments.
method m_getHighestLowestFloat(_self, _highestLowest, _lookbackBars, _offset, _firstLastType)
Namespace types: array
This method finds the highest or lowest value in a float array within a rolling lookback window, and returns the value along with the offset (number of elements back from the end of the array) of its first or last occurrence.
Parameters:
_self (array) : The array of float values to search for extremes.
_highestLowest (HighestLowest) : Whether to search for the highest or lowest value. Use the enum value HighestLowest.highest or HighestLowest.lowest.
_lookbackBars (int) : The number of array elements to include in the rolling lookback window. Must be positive. Note: Array elements only correspond to bars if the consuming script always adds exactly one element on consecutive bars.
_offset (int) : The number of array elements back from the end of the array to start the lookback window. A value of zero means no offset. The _offset parameter offsets both the beginning and end of the range.
_firstLastType (FirstLast) : Whether to return the offset of the first (lowest index) or last (highest index) occurrence of the extreme value. Use FirstLast.first or FirstLast.last.
Returns: (tuple) A tuple containing the highest or lowest value and its offset -- the number of elements back from the end of the array. If not found, returns . NOTE: The _offsetFromEndOfArray value is not affected by the _offset parameter. In other words, it is not the offset from the end of the range but from the end of the array. This number may or may not have any relation to the number of *bars* back, depending on how the array is populated. The calling code needs to figure that out.
EXPORTED ENUMS
HighestLowest
Whether to return the highest value or lowest value in the range.
• highest : Find the highest value in the specified range
• lowest : Find the lowest value in the specified range
FirstLast
Whether to return the first (lowest index) or last (highest index) occurrence of the extreme value.
• first : Return the offset of the first occurrence of the extreme value
• last : Return the offset of the last occurrence of the extreme value
fibpointLibrary "fibpoint"
A library for generating Fibonacci retracement levels on a chart, including customizable lines, labels, and filled areas between levels. It provides functionality to plot Fibonacci levels based on given price points and bar indices, with options for custom levels and colors.
getFib(startPoint, endPoint, startIdx, endIdx, fibLevels, fibColors, tsp)
Calculates Fibonacci retracement levels between two price points and draws corresponding lines and labels on the chart.
Parameters:
startPoint (float) : The starting price point for the Fibonacci retracement.
endPoint (float) : The ending price point for the Fibonacci retracement.
startIdx (int) : The bar index where the Fibonacci retracement starts.
endIdx (int) : The bar index where the Fibonacci retracement ends.
fibLevels (array) : An optional array of custom Fibonacci levels (default is ).
fibColors (array) : An optional array of colors for each Fibonacci level (default is a predefined color array).
tsp (int) : The transparency level for the fill between Fibonacci levels (default is 90).
Returns: A tuple containing an array of fibItem objects (each with a line and label) and an array of linefill objects for the filled areas between levels.
fibItem
A custom type representing a Fibonacci level with its associated line and label.
Fields:
line (series line) : The line object drawn for the Fibonacci level.
label (series label) : The label object displaying the Fibonacci level value.
lib_core_utilsLibrary "lib_core_utils"
Core utility functions for Pine Script strategies
Provides safe mathematical operations, array management, and basic helpers
Version: 1.0.0
Author: NQ Hybrid Strategy Team
Last Updated: 2025-06-18
===================================================================
safe_division(numerator, denominator)
safe_division
@description Performs division with safety checks for zero denominators and invalid values
Parameters:
numerator (float) : (float) The numerator value
denominator (float) : (float) The denominator value
Returns: (float) Result of division, or 0.0 if invalid
safe_division_detailed(numerator, denominator)
safe_division_detailed
@description Enhanced division with detailed result information
Parameters:
numerator (float) : (float) The numerator value
denominator (float) : (float) The denominator value
Returns: (SafeCalculationResult) Detailed calculation result
safe_multiply(a, b)
safe_multiply
@description Performs multiplication with safety checks for overflow and invalid values
Parameters:
a (float) : (float) First multiplier
b (float) : (float) Second multiplier
Returns: (float) Result of multiplication, or 0.0 if invalid
safe_add(a, b)
safe_add
@description Performs addition with safety checks
Parameters:
a (float) : (float) First addend
b (float) : (float) Second addend
Returns: (float) Result of addition, or 0.0 if invalid
safe_subtract(a, b)
safe_subtract
@description Performs subtraction with safety checks
Parameters:
a (float) : (float) Minuend
b (float) : (float) Subtrahend
Returns: (float) Result of subtraction, or 0.0 if invalid
safe_abs(value)
safe_abs
@description Safe absolute value calculation
Parameters:
value (float) : (float) Input value
Returns: (float) Absolute value, or 0.0 if invalid
safe_max(a, b)
safe_max
@description Safe maximum value calculation
Parameters:
a (float) : (float) First value
b (float) : (float) Second value
Returns: (float) Maximum value, handling NA cases
safe_min(a, b)
safe_min
@description Safe minimum value calculation
Parameters:
a (float) : (float) First value
b (float) : (float) Second value
Returns: (float) Minimum value, handling NA cases
safe_array_get(arr, index)
safe_array_get
@description Safely retrieves value from array with bounds checking
Parameters:
arr (array) : (array) The array to access
index (int) : (int) Index to retrieve
Returns: (float) Value at index, or na if invalid
safe_array_push(arr, value, max_size)
safe_array_push
@description Safely pushes value to array with size management
Parameters:
arr (array) : (array) The array to modify
value (float) : (float) Value to push
max_size (int) : (int) Maximum array size
Returns: (bool) True if push was successful
safe_array_unshift(arr, value, max_size)
safe_array_unshift
@description Safely adds value to beginning of array with size management
Parameters:
arr (array) : (array) The array to modify
value (float) : (float) Value to add at beginning
max_size (int) : (int) Maximum array size
Returns: (bool) True if unshift was successful
get_array_stats(arr, max_size)
get_array_stats
@description Gets statistics about an array
Parameters:
arr (array) : (array) The array to analyze
max_size (int) : (int) The maximum allowed size
Returns: (ArrayStats) Statistics about the array
cleanup_array(arr, target_size)
cleanup_array
@description Cleans up array by removing old elements if it's too large
Parameters:
arr (array) : (array) The array to cleanup
target_size (int) : (int) Target size after cleanup
Returns: (int) Number of elements removed
is_valid_price(price)
is_valid_price
@description Checks if a price value is valid for trading calculations
Parameters:
price (float) : (float) Price to validate
Returns: (bool) True if price is valid
is_valid_volume(vol)
is_valid_volume
@description Checks if a volume value is valid
Parameters:
vol (float) : (float) Volume to validate
Returns: (bool) True if volume is valid
sanitize_price(price, default_value)
sanitize_price
@description Sanitizes price value to ensure it's within valid range
Parameters:
price (float) : (float) Price to sanitize
default_value (float) : (float) Default value if price is invalid
Returns: (float) Sanitized price value
sanitize_percentage(pct)
sanitize_percentage
@description Sanitizes percentage value to 0-100 range
Parameters:
pct (float) : (float) Percentage to sanitize
Returns: (float) Sanitized percentage (0-100)
is_session_active(session_string, timezone)
Parameters:
session_string (string)
timezone (string)
get_session_progress(session_string, timezone)
Parameters:
session_string (string)
timezone (string)
format_price(price, decimals)
Parameters:
price (float)
decimals (int)
format_percentage(pct, decimals)
Parameters:
pct (float)
decimals (int)
bool_to_emoji(condition, true_emoji, false_emoji)
Parameters:
condition (bool)
true_emoji (string)
false_emoji (string)
log_debug(message, level)
Parameters:
message (string)
level (string)
benchmark_start()
benchmark_end(start_time)
Parameters:
start_time (int)
get_library_info()
get_library_version()
SafeCalculationResult
SafeCalculationResult
Fields:
value (series float) : (float) The calculated value
is_valid (series bool) : (bool) Whether the calculation was successful
error_message (series string) : (string) Error description if calculation failed
ArrayStats
ArrayStats
Fields:
size (series int) : (int) Current array size
max_size (series int) : (int) Maximum allowed size
is_full (series bool) : (bool) Whether array has reached max capacity
WebhookGeneratorLibrary "WebhookGenerator"
Generates Json objects for webhook messages.
GenerateOT(license_id, symbol, action, order_type, trade_type, size, price, tp, sl, risk, trailPrice, trailOffset)
CreateOrderTicket: Establishes a order ticket.
Parameters:
license_id (string) : Provide your license index
symbol (string) : Symbol on which to execute the trade
action (string) : Execution method of the trade : "MRKT" or "PENDING"
order_type (string) : Direction type of the order: "BUY" or "SELL"
trade_type (string) : Is it a "SPREAD" trade or a "SINGLE" symbol execution?
size (float) : Size of the trade, in units
price (float) : If the order is pending you must specify the execution price
tp (float) : (Optional) Take profit of the order
sl (float) : (Optional) Stop loss of the order
risk (float) : Percent to risk for the trade, if size not specified
trailPrice (float) : (Optional) Price at which trailing stop is starting
trailOffset (float) : (Optional) Amount to trail by
Returns: Return Order string
AllCandlestickPatternsLibraryAll Candlestick Patterns Library
The Candlestick Patterns Library is a Pine Script (version 6) library extracted from the All Candlestick Patterns indicator. It provides a comprehensive set of functions to calculate candlestick properties, detect market trends, and identify various candlestick patterns (bullish, bearish, and neutral). The library is designed for reusability, enabling TradingView users to incorporate pattern detection into their own scripts, such as indicators or strategies.
The library is organized into three main sections:
Trend Detection: Functions to determine market trends (uptrend or downtrend) based on user-defined rules.
Candlestick Property Calculations: A function to compute core properties of a candlestick, such as body size, shadow lengths, and doji characteristics.
Candlestick Pattern Detection: Functions to detect specific candlestick patterns, each returning a tuple with detection status, pattern name, type, and description.
Library Structure
1. Trend Detection
This section includes the detectTrend function, which identifies whether the market is in an uptrend or downtrend based on user-specified rules, such as the relationship between the closing price and Simple Moving Averages (SMAs).
Function: detectTrend
Parameters:
downTrend (bool): Initial downtrend condition.
upTrend (bool): Initial uptrend condition.
trendRule (string): The rule for trend detection ("SMA50" or "SMA50, SMA200").
p_close (float): Current closing price.
sma50 (float): Simple Moving Average over 50 periods.
sma200 (float): Simple Moving Average over 200 periods.
Returns: A tuple indicating the detected trend.
Logic:
If trendRule is "SMA50", a downtrend is detected when p_close < sma50, and an uptrend when p_close > sma50.
If trendRule is "SMA50, SMA200", a downtrend is detected when p_close < sma50 and sma50 < sma200, and an uptrend when p_close > sma50 and sma50 > sma200.
2. Candlestick Property Calculations
This section includes the calculateCandleProperties function, which computes essential properties of a candlestick based on OHLC (Open, High, Low, Close) data and configuration parameters.
Function: calculateCandleProperties
Parameters:
p_open (float): Candlestick open price.
p_close (float): Candlestick close price.
p_high (float): Candlestick high price.
p_low (float): Candlestick low price.
bodyAvg (float): Average body size (e.g., from EMA of body sizes).
shadowPercent (float): Minimum shadow size as a percentage of body size.
shadowEqualsPercent (float): Tolerance for equal shadows in doji detection.
dojiBodyPercent (float): Maximum body size as a percentage of range for doji detection.
Returns: A tuple containing 17 properties:
C_BodyHi (float): Higher of open or close price.
C_BodyLo (float): Lower of open or close price.
C_Body (float): Body size (difference between C_BodyHi and C_BodyLo).
C_SmallBody (bool): True if body size is below bodyAvg.
C_LongBody (bool): True if body size is above bodyAvg.
C_UpShadow (float): Upper shadow length (p_high - C_BodyHi).
C_DnShadow (float): Lower shadow length (C_BodyLo - p_low).
C_HasUpShadow (bool): True if upper shadow exceeds shadowPercent of body.
C_HasDnShadow (bool): True if lower shadow exceeds shadowPercent of body.
C_WhiteBody (bool): True if candle is bullish (p_open < p_close).
C_BlackBody (bool): True if candle is bearish (p_open > p_close).
C_Range (float): Candlestick range (p_high - p_low).
C_IsInsideBar (bool): True if current candle body is inside the previous candle's body.
C_BodyMiddle (float): Midpoint of the candle body.
C_ShadowEquals (bool): True if upper and lower shadows are equal within shadowEqualsPercent.
C_IsDojiBody (bool): True if body size is small relative to range (C_Body <= C_Range * dojiBodyPercent / 100).
C_Doji (bool): True if the candle is a doji (C_IsDojiBody and C_ShadowEquals).
Purpose: These properties are used by pattern detection functions to evaluate candlestick formations.
3. Candlestick Pattern Detection
This section contains functions to detect specific candlestick patterns, each returning a tuple . The patterns are categorized as bullish, bearish, or neutral, and include detailed descriptions for use in tooltips or alerts.
Supported Patterns
The library supports the following candlestick patterns, grouped by type:
Bullish Patterns:
Rising Window: A two-candle continuation pattern in an uptrend with a price gap between the first candle's high and the second candle's low.
Rising Three Methods: A five-candle continuation pattern with a long green candle, three short red candles, and another long green candle.
Tweezer Bottom: A two-candle reversal pattern in a downtrend with nearly identical lows.
Upside Tasuki Gap: A three-candle continuation pattern in an uptrend with a gap between the first two green candles and a red candle closing partially into the gap.
Doji Star (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji gapping down.
Morning Doji Star: A three-candle reversal pattern with a long red candle, a doji gapping down, and a long green candle.
Piercing: A two-candle reversal pattern in a downtrend with a red candle followed by a green candle closing above the midpoint of the first.
Hammer: A single-candle reversal pattern in a downtrend with a small body and a long lower shadow.
Inverted Hammer: A single-candle reversal pattern in a downtrend with a small body and a long upper shadow.
Morning Star: A three-candle reversal pattern with a long red candle, a short candle gapping down, and a long green candle.
Marubozu White: A single-candle pattern with a long green body and minimal shadows.
Dragonfly Doji: A single-candle reversal pattern in a downtrend with a doji where open and close are at the high.
Harami Cross (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji inside its body.
Harami (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a small green candle inside its body.
Long Lower Shadow: A single-candle pattern with a long lower shadow indicating buyer strength.
Three White Soldiers: A three-candle reversal pattern with three long green candles in a downtrend.
Engulfing (Bullish): A two-candle reversal pattern in a downtrend with a small red candle followed by a larger green candle engulfing it.
Abandoned Baby (Bullish): A three-candle reversal pattern with a long red candle, a doji gapping down, and a green candle gapping up.
Tri-Star (Bullish): A three-candle reversal pattern with three doji candles in a downtrend, with gaps between them.
Kicking (Bullish): A two-candle reversal pattern with a bearish marubozu followed by a bullish marubozu gapping up.
Bearish Patterns:
On Neck: A two-candle continuation pattern in a downtrend with a long red candle followed by a short green candle closing near the first candle's low.
Falling Window: A two-candle continuation pattern in a downtrend with a price gap between the first candle's low and the second candle's high.
Falling Three Methods: A five-candle continuation pattern with a long red candle, three short green candles, and another long red candle.
Tweezer Top: A two-candle reversal pattern in an uptrend with nearly identical highs.
Dark Cloud Cover: A two-candle reversal pattern in an uptrend with a green candle followed by a red candle opening above the high and closing below the midpoint.
Downside Tasuki Gap: A three-candle continuation pattern in a downtrend with a gap between the first two red candles and a green candle closing partially into the gap.
Evening Doji Star: A three-candle reversal pattern with a long green candle, a doji gapping up, and a long red candle.
Doji Star (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji gapping up.
Hanging Man: A single-candle reversal pattern in an uptrend with a small body and a long lower shadow.
Shooting Star: A single-candle reversal pattern in an uptrend with a small body and a long upper shadow.
Evening Star: A three-candle reversal pattern with a long green candle, a short candle gapping up, and a long red candle.
Marubozu Black: A single-candle pattern with a long red body and minimal shadows.
Gravestone Doji: A single-candle reversal pattern in an uptrend with a doji where open and close are at the low.
Harami Cross (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji inside its body.
Harami (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a small red candle inside its body.
Long Upper Shadow: A single-candle pattern with a long upper shadow indicating seller strength.
Three Black Crows: A three-candle reversal pattern with three long red candles in an uptrend.
Engulfing (Bearish): A two-candle reversal pattern in an uptrend with a small green candle followed by a larger red candle engulfing it.
Abandoned Baby (Bearish): A three-candle reversal pattern with a long green candle, a doji gapping up, and a red candle gapping down.
Tri-Star (Bearish): A three-candle reversal pattern with three doji candles in an uptrend, with gaps between them.
Kicking (Bearish): A two-candle reversal pattern with a bullish marubozu followed by a bearish marubozu gapping down.
Neutral Patterns:
Doji: A single-candle pattern with a very small body, indicating indecision.
Spinning Top White: A single-candle pattern with a small green body and long upper and lower shadows, indicating indecision.
Spinning Top Black: A single-candle pattern with a small red body and long upper and lower shadows, indicating indecision.
Pattern Detection Functions
Each pattern detection function evaluates specific conditions based on candlestick properties (from calculateCandleProperties) and trend conditions (from detectTrend). The functions return:
detected (bool): True if the pattern is detected.
name (string): The name of the pattern (e.g., "On Neck").
type (string): The pattern type ("Bullish", "Bearish", or "Neutral").
description (string): A detailed description of the pattern for use in tooltips or alerts.
For example, the detectOnNeckBearish function checks for a bearish On Neck pattern by verifying a downtrend, a long red candle followed by a short green candle, and specific price relationships.
Usage Example
To use the library in a TradingView indicator, you can import it and call its functions as shown below:
//@version=6
indicator("Candlestick Pattern Detector", overlay=true)
import CandlestickPatternsLibrary as cp
// Calculate SMA for trend detection
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
= cp.detectTrend(true, true, "SMA50", close, sma50, sma200)
// Calculate candlestick properties
bodyAvg = ta.ema(math.max(close, open) - math.min(close, open), 14)
= cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 100.0, 5.0)
// Detect a pattern (e.g., On Neck Bearish)
= cp.detectOnNeckBearish(downTrend, blackBody, longBody, whiteBody, open, close, low, bodyAvg, smallBody, candleRange)
if onNeckDetected
label.new(bar_index, low, onNeckName, style=label.style_label_up, color=color.red, textcolor=color.white, tooltip=onNeckDesc)
// Detect another pattern (e.g., Piercing Bullish)
= cp.detectPiercingBullish(downTrend, blackBody, longBody, whiteBody, open, low, close, bodyMiddle)
if piercingDetected
label.new(bar_index, low, piercingName, style=label.style_label_up, color=color.blue, textcolor=color.white, tooltip=piercingDesc)
Steps in the Example
Import the Library: Use import CandlestickPatternsLibrary as cp to access the library's functions.
Calculate Trend: Use detectTrend to determine the market trend based on SMA50 or SMA50/SMA200 rules.
Calculate Candlestick Properties: Use calculateCandleProperties to compute properties like body size, shadow lengths, and doji status.
Detect Patterns: Call specific pattern detection functions (e.g., detectOnNeckBearish, detectPiercingBullish) and use the returned values to display labels or alerts.
Visualize Patterns: Use label.new to display detected patterns on the chart with their names, types, and descriptions.
Key Features
Modularity: The library is designed as a standalone module, making it easy to integrate into other Pine Script projects.
Comprehensive Pattern Coverage: Supports over 40 candlestick patterns, covering bullish, bearish, and neutral formations.
Detailed Documentation: Each function includes comments with @param and @returns annotations for clarity.
Reusability: Can be used in indicators, strategies, or alerts by importing the library and calling its functions.
Extracted from All Candlestick Patterns: The library is derived from the All Candlestick Patterns indicator, ensuring it inherits a well-tested foundation for pattern detection.
Notes for Developers
Pine Script Version: The library uses Pine Script version 6, as specified by //@version=6.
Parameter Naming: Parameters use prefixes like p_ (e.g., p_open, p_close) to avoid conflicts with built-in variables.
Error Handling: The library has been fixed to address issues like undeclared identifiers (C_SmallBody, C_Range), unused arguments (factor), and improper comment formatting.
Testing: Developers should test the library in TradingView to ensure patterns are detected correctly under various market conditions.
Customization: Users can adjust parameters like bodyAvg, shadowPercent, shadowEqualsPercent, and dojiBodyPercent in calculateCandleProperties to fine-tune pattern detection sensitivity.
Conclusion
The Candlestick Patterns Library, extracted from the All Candlestick Patterns indicator, is a powerful tool for traders and developers looking to implement candlestick pattern detection in TradingView. Its modular design, comprehensive pattern support, and detailed documentation make it an ideal choice for building custom indicators or strategies. By leveraging the library's functions, users can analyze market trends, compute candlestick properties, and detect a wide range of patterns to inform their trading decisions.