FiniteStateMachine🟩 OVERVIEW
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events.
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include:
• Explicit logic : You can see all rules easily side-by-side.
• Validation : Tables show your rules and validation results right on the chart.
• Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
• Type safety : Shows how to use enums for robustness while maintaining string compatibility.
• Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
• Priority control : Explicit control over which rules take precedence when multiple conditions are met.
• Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩 SIMPLE FSM (MATRIX-BASED)
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩 CONCURRENT FSM (MAP-BASED)
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩 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 function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/FiniteStateMachine/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 TECHNICAL IMPLEMENTATION
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
• Exact state + exact event match
• Exact state + empty event (event wildcard)
• Empty state + exact event (state wildcard)
• Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
• o_eventRule : Maps a condition name to an output
• o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩 VALIDATION & ERROR HANDLING
The library includes comprehensive validation functions that catch common FSM design errors:
Error detection:
• Empty next states
• Invalid states not in the states array
• Duplicate rules
• Conflicting transitions
• Unreachable states (no entry/exit rules)
Warning detection:
• Redundant wildcards
• Empty states/events (potential unintended wildcards)
• Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩 PRACTICAL EXAMPLES
The library includes four comprehensive demos:
Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
• Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
• Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
• Includes position management, stop losses, and re-entry logic
Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩 BRING ON THE FUNCTIONS
f_printFSMMatrix(_mat_rules, _a_states, _tablePosition)
Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
Parameters:
_mat_rules (matrix)
_a_states (array)
_tablePosition (simple string)
Returns: The table of states and rules.
method m_loadMatrixRulesFromText(_mat_rules, _rulesText)
Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_rulesText (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState)
Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_nextState (string)
Returns: No explicit return. The matrix is modified as a side-effect.
method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition)
Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_a_states (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions)
Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
Namespace types: matrix
Parameters:
_mat_rules (matrix)
_currentState (string)
_event (string)
_strictInput (bool)
_strictTransitions (bool)
Returns: The next state or `na`.
method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output)
Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
Namespace types: map
Parameters:
_map_eventRules (map)
_state (string)
_condName (string)
_output (string)
Returns: No explicit return. The map is modified as a side-effect.
method m_addEventRulesToMapFromText(_map_eventRules, _configText)
Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state | > output" (condition wildcard), " | > output" (full wildcard).
Splits lines by , extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
Namespace types: map
Parameters:
_map_eventRules (map)
_configText (string)
Returns: No explicit return. The map is modified as a side-effect.
f_printFSMMap(_map_eventRules, _a_states, _tablePosition)
Prints a table of map-based event rules to the specified position on the chart.
Parameters:
_map_eventRules (map)
_a_states (array)
_tablePosition (simple string)
Returns: The table of map-based event rules.
method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition)
Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
Namespace types: map
Parameters:
_map_eventRules (map)
_a_states (array)
_a_validEvents (array)
_showTable (bool)
_tablePosition (simple string)
Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules)
Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
Namespace types: series string, simple string, input string, const string
Parameters:
_currentState (string)
_a_activeConditions (array)
_map_eventRules (map)
Returns: The output string (event or state) for the first matching condition, or na if no match found.
o_eventRule
o_eventRule defines a condition-to-output mapping for the concurrent FSM.
Fields:
condName (series string) : The name of the condition to check.
output (series string) : The output (event or state) when the condition is true.
o_eventRuleWrapper
o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
Fields:
a_rules (array) : Array of o_eventRule objects for a specific state.
Göstergeler ve stratejiler
TOTALES_LIBRARY_MAINLibrary "TOTALES_LIBRARY_MAIN"
sigmoid_strategy(source_sigmoid, lookback, volatility_period, base_steepness, base_midpoint, z_period, ma_type, ma_lookback, upper_threshold, lower_threshold)
Parameters:
source_sigmoid (float)
lookback (simple int)
volatility_period (simple int)
base_steepness (simple float)
base_midpoint (simple float)
z_period (simple int)
ma_type (simple string)
ma_lookback (simple int)
upper_threshold (simple float)
lower_threshold (simple float)
fdi_supertrend_strategy(src, per, speed, fdi_mult_upper, fdi_mult_lower, adapt)
Parameters:
src (float)
per (simple int)
speed (simple int)
fdi_mult_upper (simple float)
fdi_mult_lower (simple float)
adapt (simple bool)
volume_trend_strategy(volume_trend_x, volume_trend_y)
Parameters:
volume_trend_x (simple int)
volume_trend_y (simple int)
rti_strategy(rtiTrendDataCount, rtiTrendSensitivityPercentage, rtiSignalLength, upper_threshold_rti, lower_threshold_rti, useSignalLength_rti)
Parameters:
rtiTrendDataCount (simple int)
rtiTrendSensitivityPercentage (simple int)
rtiSignalLength (simple int)
upper_threshold_rti (simple float)
lower_threshold_rti (simple float)
useSignalLength_rti (simple bool)
zscore_heikin_strategy(len_zscore, upper_threshold_zscore, lower_threshold_zscore)
Parameters:
len_zscore (simple int)
upper_threshold_zscore (simple float)
lower_threshold_zscore (simple float)
emd_strategy(input_src_emd, avg_type_emd, length_emd, mult_upper_emd, mult_lower_emd)
Parameters:
input_src_emd (simple string)
avg_type_emd (simple string)
length_emd (simple int)
mult_upper_emd (simple float)
mult_lower_emd (simple float)
bbpct_strategy(length_bbpct, src_bbpct, mult_bbpct, upper_threshold_bbpct, lower_threshold_bbpct)
Parameters:
length_bbpct (simple int)
src_bbpct (float)
mult_bbpct (simple float)
upper_threshold_bbpct (simple float)
lower_threshold_bbpct (simple float)
dega_rma_strategy(src_dema, len_dema, len_FG, sigma_FG, len_rma, len_ATR, mult_ATRup, mult_ATRdn)
Parameters:
src_dema (float)
len_dema (simple int)
len_FG (simple int)
sigma_FG (simple float)
len_rma (simple int)
len_ATR (simple int)
mult_ATRup (simple float)
mult_ATRdn (simple float)
dssd_strategy(DemaLen_dssd, DemaSrc_dssd, PerLen_dssd, pertype_dssd, SDlen_dssd, EmaLen_dssd, IncluedeEma_dssd)
Parameters:
DemaLen_dssd (simple int)
DemaSrc_dssd (float)
PerLen_dssd (simple int)
pertype_dssd (simple string)
SDlen_dssd (simple int)
EmaLen_dssd (simple int)
IncluedeEma_dssd (simple bool)
impulsive_momentum_strategy(Lu_imp, Su_imp, yes_imp, lenEMA, mult, atr_length, lenEMA2, atr_momentum_length, mult2, lenMED, mult3, rsi_length, sma_rsi_length)
Parameters:
Lu_imp (simple float)
Su_imp (simple float)
yes_imp (simple bool)
lenEMA (simple int)
mult (simple float)
atr_length (simple int)
lenEMA2 (simple int)
atr_momentum_length (simple int)
mult2 (simple float)
lenMED (simple int)
mult3 (simple float)
rsi_length (simple int)
sma_rsi_length (simple int)
get_sigmoid_score(source_sigmoid, lookback, volatility_period, base_steepness, base_midpoint, z_period, ma_type, ma_lookback, upper_threshold, lower_threshold)
Parameters:
source_sigmoid (float)
lookback (simple int)
volatility_period (simple int)
base_steepness (simple float)
base_midpoint (simple float)
z_period (simple int)
ma_type (simple string)
ma_lookback (simple int)
upper_threshold (simple float)
lower_threshold (simple float)
get_fdi_supertrend_score(src, per, speed, fdi_mult_upper, fdi_mult_lower, adapt)
Parameters:
src (float)
per (simple int)
speed (simple int)
fdi_mult_upper (simple float)
fdi_mult_lower (simple float)
adapt (simple bool)
get_volume_trend_score(volume_trend_x, volume_trend_y)
Parameters:
volume_trend_x (simple int)
volume_trend_y (simple int)
get_rti_score(rtiTrendDataCount, rtiTrendSensitivityPercentage, rtiSignalLength, upper_threshold_rti, lower_threshold_rti, useSignalLength_rti)
Parameters:
rtiTrendDataCount (simple int)
rtiTrendSensitivityPercentage (simple int)
rtiSignalLength (simple int)
upper_threshold_rti (simple float)
lower_threshold_rti (simple float)
useSignalLength_rti (simple bool)
get_zscore_heikin_score(len_zscore, upper_threshold_zscore, lower_threshold_zscore)
Parameters:
len_zscore (simple int)
upper_threshold_zscore (simple float)
lower_threshold_zscore (simple float)
get_emd_score(input_src_emd, avg_type_emd, length_emd, mult_upper_emd, mult_lower_emd)
Parameters:
input_src_emd (simple string)
avg_type_emd (simple string)
length_emd (simple int)
mult_upper_emd (simple float)
mult_lower_emd (simple float)
get_bbpct_score(length_bbpct, src_bbpct, mult_bbpct, upper_threshold_bbpct, lower_threshold_bbpct)
Parameters:
length_bbpct (simple int)
src_bbpct (float)
mult_bbpct (simple float)
upper_threshold_bbpct (simple float)
lower_threshold_bbpct (simple float)
get_dega_rma_score(src_dema, len_dema, len_FG, sigma_FG, len_rma, len_ATR, mult_ATRup, mult_ATRdn)
Parameters:
src_dema (float)
len_dema (simple int)
len_FG (simple int)
sigma_FG (simple float)
len_rma (simple int)
len_ATR (simple int)
mult_ATRup (simple float)
mult_ATRdn (simple float)
get_dssd_score(DemaLen_dssd, DemaSrc_dssd, PerLen_dssd, pertype_dssd, SDlen_dssd, EmaLen_dssd, IncluedeEma_dssd)
Parameters:
DemaLen_dssd (simple int)
DemaSrc_dssd (float)
PerLen_dssd (simple int)
pertype_dssd (simple string)
SDlen_dssd (simple int)
EmaLen_dssd (simple int)
IncluedeEma_dssd (simple bool)
get_impulsive_momentum_score(Lu_imp, Su_imp, yes_imp, lenEMA, mult, atr_length, lenEMA2, atr_momentum_length, mult2, lenMED, mult3, rsi_length, sma_rsi_length)
Parameters:
Lu_imp (simple float)
Su_imp (simple float)
yes_imp (simple bool)
lenEMA (simple int)
mult (simple float)
atr_length (simple int)
lenEMA2 (simple int)
atr_momentum_length (simple int)
mult2 (simple float)
lenMED (simple int)
mult3 (simple float)
rsi_length (simple int)
sma_rsi_length (simple int)
get_tpi_score(use_sigmoid, use_fdi_supertrend, use_volume_trend, use_rti, use_zscore_heikin, use_emd, use_bbpct, use_dega_rma, use_dssd, use_impulsive_momentum, source_sigmoid, lookback, volatility_period, base_steepness, base_midpoint, z_period, ma_type, ma_lookback, upper_threshold, lower_threshold, src, per, speed, fdi_mult_upper, fdi_mult_lower, adapt, volume_trend_x, volume_trend_y, rtiTrendDataCount, rtiTrendSensitivityPercentage, rtiSignalLength, upper_threshold_rti, lower_threshold_rti, useSignalLength_rti, len_zscore, upper_threshold_zscore, lower_threshold_zscore, input_src_emd, avg_type_emd, length_emd, mult_upper_emd, mult_lower_emd, length_bbpct, src_bbpct, mult_bbpct, upper_threshold_bbpct, lower_threshold_bbpct, src_dema, len_dema, len_FG, sigma_FG, len_rma, len_ATR, mult_ATRup, mult_ATRdn, DemaLen_dssd, DemaSrc_dssd, PerLen_dssd, pertype_dssd, SDlen_dssd, EmaLen_dssd, IncluedeEma_dssd, Lu_imp, Su_imp, yes_imp, lenEMA, mult, atr_length, lenEMA2, atr_momentum_length, mult2, lenMED, mult3, rsi_length, sma_rsi_length)
Parameters:
use_sigmoid (simple bool)
use_fdi_supertrend (simple bool)
use_volume_trend (simple bool)
use_rti (simple bool)
use_zscore_heikin (simple bool)
use_emd (simple bool)
use_bbpct (simple bool)
use_dega_rma (simple bool)
use_dssd (simple bool)
use_impulsive_momentum (simple bool)
source_sigmoid (float)
lookback (simple int)
volatility_period (simple int)
base_steepness (simple float)
base_midpoint (simple float)
z_period (simple int)
ma_type (simple string)
ma_lookback (simple int)
upper_threshold (simple float)
lower_threshold (simple float)
src (float)
per (simple int)
speed (simple int)
fdi_mult_upper (simple float)
fdi_mult_lower (simple float)
adapt (simple bool)
volume_trend_x (simple int)
volume_trend_y (simple int)
rtiTrendDataCount (simple int)
rtiTrendSensitivityPercentage (simple int)
rtiSignalLength (simple int)
upper_threshold_rti (simple float)
lower_threshold_rti (simple float)
useSignalLength_rti (simple bool)
len_zscore (simple int)
upper_threshold_zscore (simple float)
lower_threshold_zscore (simple float)
input_src_emd (simple string)
avg_type_emd (simple string)
length_emd (simple int)
mult_upper_emd (simple float)
mult_lower_emd (simple float)
length_bbpct (simple int)
src_bbpct (float)
mult_bbpct (simple float)
upper_threshold_bbpct (simple float)
lower_threshold_bbpct (simple float)
src_dema (float)
len_dema (simple int)
len_FG (simple int)
sigma_FG (simple float)
len_rma (simple int)
len_ATR (simple int)
mult_ATRup (simple float)
mult_ATRdn (simple float)
DemaLen_dssd (simple int)
DemaSrc_dssd (float)
PerLen_dssd (simple int)
pertype_dssd (simple string)
SDlen_dssd (simple int)
EmaLen_dssd (simple int)
IncluedeEma_dssd (simple bool)
Lu_imp (simple float)
Su_imp (simple float)
yes_imp (simple bool)
lenEMA (simple int)
mult (simple float)
atr_length (simple int)
lenEMA2 (simple int)
atr_momentum_length (simple int)
mult2 (simple float)
lenMED (simple int)
mult3 (simple float)
rsi_length (simple int)
sma_rsi_length (simple int)
get_all_strategy_scores(source_sigmoid, lookback, volatility_period, base_steepness, base_midpoint, z_period, ma_type, ma_lookback, upper_threshold, lower_threshold, src, per, speed, fdi_mult_upper, fdi_mult_lower, adapt, volume_trend_x, volume_trend_y, rtiTrendDataCount, rtiTrendSensitivityPercentage, rtiSignalLength, upper_threshold_rti, lower_threshold_rti, useSignalLength_rti, len_zscore, upper_threshold_zscore, lower_threshold_zscore, input_src_emd, avg_type_emd, length_emd, mult_upper_emd, mult_lower_emd, length_bbpct, src_bbpct, mult_bbpct, upper_threshold_bbpct, lower_threshold_bbpct, src_dema, len_dema, len_FG, sigma_FG, len_rma, len_ATR, mult_ATRup, mult_ATRdn, DemaLen_dssd, DemaSrc_dssd, PerLen_dssd, pertype_dssd, SDlen_dssd, EmaLen_dssd, IncluedeEma_dssd, Lu_imp, Su_imp, yes_imp, lenEMA, mult, atr_length, lenEMA2, atr_momentum_length, mult2, lenMED, mult3, rsi_length, sma_rsi_length)
Parameters:
source_sigmoid (float)
lookback (simple int)
volatility_period (simple int)
base_steepness (simple float)
base_midpoint (simple float)
z_period (simple int)
ma_type (simple string)
ma_lookback (simple int)
upper_threshold (simple float)
lower_threshold (simple float)
src (float)
per (simple int)
speed (simple int)
fdi_mult_upper (simple float)
fdi_mult_lower (simple float)
adapt (simple bool)
volume_trend_x (simple int)
volume_trend_y (simple int)
rtiTrendDataCount (simple int)
rtiTrendSensitivityPercentage (simple int)
rtiSignalLength (simple int)
upper_threshold_rti (simple float)
lower_threshold_rti (simple float)
useSignalLength_rti (simple bool)
len_zscore (simple int)
upper_threshold_zscore (simple float)
lower_threshold_zscore (simple float)
input_src_emd (simple string)
avg_type_emd (simple string)
length_emd (simple int)
mult_upper_emd (simple float)
mult_lower_emd (simple float)
length_bbpct (simple int)
src_bbpct (float)
mult_bbpct (simple float)
upper_threshold_bbpct (simple float)
lower_threshold_bbpct (simple float)
src_dema (float)
len_dema (simple int)
len_FG (simple int)
sigma_FG (simple float)
len_rma (simple int)
len_ATR (simple int)
mult_ATRup (simple float)
mult_ATRdn (simple float)
DemaLen_dssd (simple int)
DemaSrc_dssd (float)
PerLen_dssd (simple int)
pertype_dssd (simple string)
SDlen_dssd (simple int)
EmaLen_dssd (simple int)
IncluedeEma_dssd (simple bool)
Lu_imp (simple float)
Su_imp (simple float)
yes_imp (simple bool)
lenEMA (simple int)
mult (simple float)
atr_length (simple int)
lenEMA2 (simple int)
atr_momentum_length (simple int)
mult2 (simple float)
lenMED (simple int)
mult3 (simple float)
rsi_length (simple int)
sma_rsi_length (simple int)
get_tpi_color(tpi_score)
Parameters:
tpi_score (float)
get_strategy_color(score)
Parameters:
score (float)
format_strategy_score(is_enabled, score)
Parameters:
is_enabled (bool)
score (float)
ApicodeLibrary "Apicode"
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float) : (series int/float) The price from which to calculate the percentage.
percent (float) : (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float) : (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float) : (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float) : (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float) : (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float) : (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float) : (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float) : (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float) : (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string) : (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float) : (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float) : (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
GBB_lib_fiboLibrary "GBB_lib_fibo"
draw_fibo(high_point, low_point)
draw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
Parameters:
high_point (float)
low_point (float)
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_tf_to_display(tf_minutes, tf_string)
gbb_tf_to_display
/ @description Converts minutes and TF string into a short standard label.
/ @param tf_minutes (float)
/ @param tf_string (string)
/ @returns (string) Timeframe label (M1,H1,D1,...)
Parameters:
tf_minutes (float)
tf_string (string)
gbb_convert_bars(_bars)
gbb_convert_bars
/ @description Formats a number of bars into a duration (days, hours, minutes + bar count).
/ @param _bars (int)
/ @returns (string)
Parameters:
_bars (int)
gbb_goldorak_init(_tf5Levels_input)
gbb_goldorak_init
/ @description Builds a contextual message about the current timeframe and optional 5-level TF.
/ @param _tf5Levels_input (string) Alternative timeframe ("" = current timeframe).
/ @returns (string, string, float)
Parameters:
_tf5Levels_input (string)
GGB_lib_fiboLibrary "GGB_lib_fibo"
draw_fibo(high_point, low_point)
draw_fibo
/ @description Draws Fibonacci retracement lines between a high point and a low point.
/ @param high_point (float) Highest point of the move.
/ @param low_point (float) Lowest point of the move.
/ @returns (void) Draws lines on the chart.
Parameters:
high_point (float)
low_point (float)
GGB_lib_utilsLibrary "GGB_lib_utils"
gbb_tf_to_display(tf_minutes, tf_string)
gbb_tf_to_display
/ @description Converts minutes and TF string into a short standard label.
/ @param tf_minutes (float)
/ @param tf_string (string)
/ @returns (string) Timeframe label (M1,H1,D1,...)
Parameters:
tf_minutes (float)
tf_string (string)
gbb_convert_bars(_bars)
gbb_convert_bars
/ @description Formats a number of bars into a duration (days, hours, minutes + bar count).
/ @param _bars (int)
/ @returns (string)
Parameters:
_bars (int)
gbb_goldorak_init(_tf5Levels_input)
gbb_goldorak_init
/ @description Builds a contextual message about the current timeframe and optional 5-level TF.
/ @param _tf5Levels_input (string) Alternative timeframe ("" = current timeframe).
/ @returns (string, string, float)
Parameters:
_tf5Levels_input (string)
delta_leverage_lib🚀 Delta Leverage Library - Exchange Max Leverage Data
Comprehensive Pine v6 library providing maximum leverage data for USDT perpetual contracts across major exchanges. Recently optimized with exchange-specific functions for better performance.
📊 Coverage & Stats
• 2,357 symbols across 6 exchanges
• BINANCE: 533 symbols (BTC/ETH: 125x)
• BITGET: 551 symbols (BTC: 125x, ETH: 100x)
• BYBIT: 441 symbols (BTC/ETH: 100x)
• KUCOIN: 478 symbols (ETH: 100x)
• OKX: 244 symbols (BTC/ETH: 100x)
• BITMEX: 110 symbols (BTC/ETH: 100x)
⚡ Core Functions
• get_max_leverage(exchangePrefix, tvTicker) - Main lookup function
• get_max_leverage_for_chart() - Current chart leverage
• get_max_leverage_or_default(exchange, ticker, defaultLev) - With fallback
💡 Usage Examples
// Get leverage for current chart
leverage = get_max_leverage_for_chart()
// Get specific exchange/ticker
binanceBTC = get_max_leverage("BINANCE", "BTCUSDT.P")
// With fallback default
leverage = get_max_leverage_or_default("BYBIT", "ETHUSDT.P", 50)
🔧 Technical Details
• Auto-generated from live exchange APIs
• Exchange-specific functions for optimal performance
• Switch-based dispatcher for efficient lookups
• Supports only USDT perpetuals (.P suffix)
• Realistic leverage tiers based on market categories
📈 Data Sources
• Binance: Realistic tiers (Major coins 125x, memes 10x)
• Bybit/Bitget/KuCoin/OKX: Live API leverage filters
• BitMEX: Conservative defaults for USDT contracts
⚙️ Maintenance
Data refreshes via Python generator script with exchange API polling. Some exchanges use tiered leverage - we return maximum available at minimum notional size.
Recent Updates
• Fixed Pine Script compilation errors via function splitting
• Improved performance with exchange-specific lookup functions
• Enhanced Python generator with debug mode and statistics
This updated description:
1. **Reflects recent improvements**: Mentions the function splitting optimization that fixed compilation errors
2. **Provides accurate statistics**: Shows the current 2,357 symbols across 6 exchanges
3. **Better organized**: Uses clear sections with emojis for visual appeal
4. **Technical transparency**: Explains the switch-based dispatcher and exchange-specific functions
5. **Practical usage**: Shows realistic code examples
6. **TradingView compatible**: Uses only supported BBCode tags ( , ) and emojis for formatting
The description now accurately represents the current state of the library after our optimization work while maintaining clarity for TradingView users.
get_max_leverage_binance(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bitget(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bitmex(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_bybit(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_kucoin(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage_okx(tvTicker)
Parameters:
tvTicker (string)
get_max_leverage(exchangePrefix, tvTicker)
Parameters:
exchangePrefix (string)
tvTicker (string)
get_max_leverage_for_chart()
get_max_leverage_or_default(exchangePrefix, tvTicker, defaultLev)
Parameters:
exchangePrefix (string)
tvTicker (string)
defaultLev (int)
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:
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
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)