Statistics TableStrategy Statistics
This library will add a table with statistics from your strategy. With this library, you won't have to switch to your strategy tester tab to view your results and positions.
Usage:
You can choose whether to set the table by input fields by adding the below code to your strategy or replace the parameters with the ones you would like to use manually.
// Statistics table options.
statistics_table_enabled = input.string(title='Show a table with statistics', defval='YES', options= , group='STATISTICS')
statistics_table_position = input.string(title='Position', defval='RIGHT', options= , group='STATISTICS')
statistics_table_margin = input.int(title='Table Margin', defval=10, minval=0, maxval=100, step=1, group='STATISTICS')
statistics_table_transparency = input.int(title='Cell Transparency', defval=20, minval=1, maxval=100, step=1, group='STATISTICS')
statistics_table_text_color = input.color(title='Text Color', defval=color.new(color.white, 0), group='STATISTICS')
statistics_table_title_cell_color = input.color(title='Title Cell Color', defval=color.new(color.gray, 80), group='STATISTICS')
statistics_table_cell_color = input.color(title='Cell Color', defval=color.new(color.purple, 0), group='STATISTICS')
// Statistics table init.
statistics.table(strategy.initial_capital, close, statistics_table_enabled, statistics_table_position, statistics_table_margin, statistics_table_transparency, statistics_table_text_color, statistics_table_title_cell_color, statistics_table_cell_color)
Sample:
If you are interested in the strategy used for this statistics table, you can browse the strategies on my profile.
지표 및 전략
Price - TP/SLPrices
With this library, you can easily manage prices such as stop loss, take profit, calculate differences, prices from a lower timeframe, and get the order size and commission from the strategy properties tab.
Note that the order size and commission only work with strategies!
Usage
Take Profit & Stop Loss
var bool open_trade = false
open_trade := strategy.position_size != 0
bars_since_opened = strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1 : 0
// ############################################################
// # TAKE PROFIT
// ############################################################
take_profit = input.string(title='Take Profit', defval='OFF', options= , group='TAKE PROFIT')
take_profit_percentage = input.float(title='Take Profit (% or X)', defval=0, minval=0, step=0.1, group='TAKE PROFIT')
take_profit_bars = input.int(title='Take Profit Bars', defval=0, minval=0, step=1, group='TAKE PROFIT')
take_profit_indication = input.string(title='Take Profit Plot', defval='OFF', options= , group='TAKE PROFIT')
take_profit_color = input.color(title='Take Profit Color', defval=#26A69A, group='TAKE PROFIT')
take_profit_price = math.round_to_mintick(strategy.position_avg_price)
take_profit_plot = plot(take_profit == 'ON' and take_profit_indication == 'ON' and open_trade and bars_since_opened >= take_profit_bars and take_profit_percentage > 0 and nz(take_profit_price) ? take_profit_price : na, color=take_profit_color, style=plot.style_linebr, linewidth=1, title='TP', offset=0)
// ############################################################
// # STOP LOSS
// ############################################################
stop_loss = input.string(title='Stop Loss', defval='OFF', options= , group='STOP LOSS')
stop_loss_percentage = input.float(title='Stop Loss (% or X)', defval=0, minval=0, step=0.1, group='STOP LOSS')
stop_loss_bars = input.int(title='Stop Loss Bars', defval=0, minval=0, step=1, group='STOP LOSS')
stop_loss_indication = input.string(title='Stop Loss Plot', defval='OFF', options= , group='STOP LOSS')
stop_loss_color = input.color(title='Stop Loss Color', defval=#FF5252, group='STOP LOSS')
stop_loss_price = math.round_to_mintick(strategy.position_avg_price)
stop_loss_plot = plot(stop_loss == 'ON' and stop_loss_indication == 'ON' and open_trade and bars_since_opened >= stop_loss_bars and stop_loss_percentage > 0 and nz(stop_loss_price) ? stop_loss_price : na, color=stop_loss_color, style=plot.style_linebr, linewidth=1, title='SL', offset=0)
// ############################################################
// # STRATEGY
// ############################################################
var limit_price = 0.0
var stop_price = 0.0
limit_price := take_profit == 'ON' ? price.take_profit_price(take_profit_price, take_profit_percentage, take_profit_bars, bars_since_opened) : na
stop_price := stop_loss == 'ON' ? price.stop_loss_price(stop_loss_price, stop_loss_percentage, stop_loss_bars, bars_since_opened) : na
strategy.exit(id='TP/SL', comment='TP/SL', from_entry='LONG', limit=limit_price, stop=stop_price)
Calculate difference between 2 prices:
price.difference(close, close )
Get last price from lower timeframe:
price.ltf(request.security_lower_tf(ticker, '1', close))
Get the order size from the properties tab:
price.order_size()
Get the commission from the properties tab.
price.commission()
Margin/Leverage CalculationMargin
This library calculates margin liquidation prices and quantities for long and short positions in your strategies.
Usage example
// ############################################################
// # INVESTMENT SETTINGS / INPUT
// ############################################################
// Get the investment capital from the properties tab of the strategy settings.
investment_capital = strategy.initial_capital
// Get the leverage from the properties tab of the strategy settings.
// The leverage is calculated from the order size for example: (300% = x3 leverage)
investment_leverage = margin.leverage()
// The maintainance rate and amount.
investment_leverage_maintenance_rate = input.float(title='Maintanance Rate (%)', defval=default_investment_leverage_maintenance_rate, minval=0, maxval=100, step=0.1, tooltip=tt_investment_leverage_maintenance_rate, group='MARGIN') / 100
investment_leverage_maintenance_amount = input.float(title='Maintanance Amount (%)', defval=default_investment_leverage_maintenance_amount, minval=0, maxval=100, step=0.1, tooltip=tt_investment_leverage_maintenance_amount, group='MARGIN')
// ############################################################
// # LIQUIDATION PRICES
// ############################################################
leverage_liquidation_price_long = 0.0
leverage_liquidation_price_long := na(leverage_liquidation_price_long ) ? na : leverage_liquidation_price_long
leverage_liquidation_price_short = 0.0
leverage_liquidation_price_short := na(leverage_liquidation_price_short ) ? na : leverage_liquidation_price_short
leverage_liquidation_price_long := margin.liquidation_price_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
leverage_liquidation_price_short := margin.liquidation_price_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
Get the qty for margin long or short position.
margin.qty_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
margin.qty_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
Get the price and qty for margin long or short position.
= margin.qty_long(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
= margin.qty_short(investment_capital, strategy.position_avg_price, investment_leverage, investment_leverage_maintenance_rate, investment_leverage_maintenance_amount)
Backtest Strategy Optimizer AdapterBacktest Strategy Optimizer Adapter
With this library, you will be able to run one or multiple backtests with different variables (combinations). For example, you can run 100 backtests of Supertrend at once with an increment factor of 0.1. This way, you can easily fetch the most profitable settings and apply them to your strategy.
To get a better understanding of the code, you can check the code below.
Single backtest results
= backtest.results(date_start, date_end, long_entry, long_exit, take_profit_percentage, stop_loss_percentage, atr_length, initial_capital, order_size, commission)
Add backtest results to a table
backtest.table(initial_capital, profit_and_loss, open_balance, winrate, entries, exits, wins, losses, backtest_table_position, backtest_table_margin, backtest_table_transparency, backtest_table_cell_color, backtest_table_title_cell_color, backtest_table_text_color)
Backtest result without chart labels
= backtest.run(date_start, date_end, long_entry, long_exit, take_profit_percentage, stop_loss_percentage, atr_length, initial_capital, order_size, commission)
Backtest result profit
profit = backtest.profit(date_start, date_end, long_entry, long_exit, take_profit_percentage, stop_loss_percentage, atr_length, initial_capital, order_size, commission)
Backtest result winrate
winrate = backtest.winrate(date_start, date_end, long_entry, long_exit, take_profit_percentage, stop_loss_percentage, atr_length, initial_capital, order_size, commission)
Start Date
You can set the start date either by using a timestamp or a number that refers to the number of bars back.
Stop Loss / Take Profit Issue
Unfortunately, I did not manage to achieve 100% accuracy for the take profit and stop loss. The original TradingView backtest can stop at the correct position within a bar using the strategy.exit stop and limit variables. However, it seems unachievable with a crossunder/crossover function in PineScript unless it is calculated on every tick (which would make the backtesting results invalid). So far, I have not found a workaround, and I would be grateful if someone could solve this issue, if it is even possible. If you have any solutions or fixes, please let me know!
Multiple Backtest Results / Optimizer
You can run multiple backtests in a single strategy or indicator, but there are certain requirements for placing the correct code in the right way. To view examples of running multiple backtests, you can refer to the links provided in the updates I posted below. In the samples I have also explained how you can auto-generate code for your backtest strategy.
map_custom_value_usefullLibrary "map_custom_value_usefull"
makes it possible to create:
1.map with array value:
for this purpose need:
1.create map with arrays type value
2.put your array in this map, overloaded put method itself will put the array based on the type into the required field
3.next you can get this array with help standard get function, which will determine which field you need to get.(But because of this, only arrays of the same type can be used in one map)
2.map with map value:
for this purpose need:
1.create map with maps type value
2.put your other map in how value in your based map, need you need to put it in the field corresponding to your map type
3.next you can get this map with help standard get function.You need to specify a special field name here, because the get function cannot be overloaded without additional variables(
map_custom_value_fullLibrary "map_custom_value_full"
makes it possible to create:
1.map with array value:
for this purpose need:
1.create map with arrays type value
2.put your array in this map, overloaded put method itself will put the array based on the type into the required field
3.next you can get this array with help standard get function, by specifying the type field of your array
2.map with map value:
for this purpose need:
1.create map with maps type value
2.put your other map in how value in your based map, need you need to put it in the field corresponding to your map type
3.next you can get this map with help standard get function, by specifying the type field of your array
3.maps with value in array with maps:
for this purpose need:
1.create map with arrays type value
2.put as value maps_arrays fild with array from maps_arrays type fild which should already contain map of the type you need (there are not all map type fields here you can add a map of the required type by adding a corresponding field of map_arrays type.)
3.next you can get this array from map with help standard get function, by specifying the type field of your array
TableLibrary "Table"
This library provides an easy way to convert arrays and matrixes of data into tables. There are a few different implementations of each function so you can get more or less control over the appearance of the tables. The basic rule of thumb is that all matrix rows must have the same number of columns, and if you are providing multiple arrays/matrixes to specify additional colors (background/text), they must have the same number of rows/columns as the data array. Finally, you do have the option of spanning cells across rows or columns with some special syntax in the data cell. Look at the examples to see how the arrays and matrixes need to be built before they can be used by the functions.
floatArrayToCellArray(floatArray)
Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function
Parameters:
floatArray (float ) : (array) the float array to convert to a Cell array.
Returns: array The Cell array to return.
stringArrayToCellArray(stringArray)
Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function
Parameters:
stringArray (string ) : (array) the array to convert to a Cell array.
Returns: array The Cell array to return.
floatMatrixToCellMatrix(floatMatrix)
Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
floatMatrix (matrix) : (matrix) the float matrix to convert to a string matrix.
Returns: matrix The Cell matrix to render.
stringMatrixToCellMatrix(stringMatrix)
Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
stringMatrix (matrix) : (matrix) the string matrix to convert to a Cell matrix.
Returns: matrix The Cell matrix to return.
fromMatrix(CellMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Takes a CellMatrix and renders it as a table.
Parameters:
CellMatrix (matrix) : (matrix) The Cells to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a float matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a string matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a Cell array as a table.
Parameters:
dataArray (Cell ) : (array) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a string array as a table.
Parameters:
dataArray (string ) : (array_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a float array as a table.
Parameters:
dataArray (float ) : (array_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
debug(message, position)
Renders a debug message in a table at the desired location on screen.
Parameters:
message (string) : (string) The message to render.
position (string) : (string) Optional. The position of the debug message. Defaults to position.middle_right.
Cell
Type for each cell's content and appearance
Fields:
content (series string)
bgColor (series color)
textColor (series color)
align (series string)
colspan (series int)
rowspan (series int)
UtilsLibrary "Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float) : (float) the number to be formatted
Returns: (string) The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int) : (int) The timestamp to stringify
Returns: (int) The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int) : (int) The timestamp to stringify
Returns: (int) The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: (int) The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: . This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool) : (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int) : (int) The hour number
minuteNumber (int) : (int) The minute number
Returns: (int) The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: (float) The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple)
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: . This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string) : (string) Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool) : (bool) If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: (string) The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: (float) The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: . This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string) : (string) Plain english position string
Returns: (string) The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: (string) The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int) : (int) The number of items to find singular/plural for.
Returns: (int) The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: (float) The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: (bool) True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string) : (string) The string to be padded
labelStyle (string) : (string) The style of the label being padded for.
Returns: (string) The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int) : (int) The number of items to find singular/plural for.
singular (string) : (string) The string to return if num is singular. Defaults to an empty string.
plural (string) : (string) The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: (string) The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: (int) The number of secondsof that timeframe
timeframeToString(tf)
Convert a timeframe string to a consistent standard.
Parameters:
tf (string) : (string) The timeframe string to convert
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
Polyline PlusThis library introduces the `PolylinePlus` type, which is an enhanced version of the built-in PineScript `polyline`. It enables two features that are absent from the built-in type:
1. Developers can now efficiently add or remove points from the polyline. In contrast, the built-in `polyline` type is immutable, requiring developers to create a new instance of the polyline to make changes, which is cumbersome and incurs a significant performance penalty.
2. Each `PolylinePlus` instance can theoretically hold up to ~1M points, surpassing the built-in `polyline` type's limit of 10K points, as long as it does not exceed the memory limit of the PineScript runtime.
Internally, each `PolylinePlus` instance utilizes an array of `line`s and an array of `polyline`s. The `line`s array serves as a buffer to store lines formed by recently added points. When the buffer reaches its capacity, it flushes the contents and converts the lines into polylines. These polylines are expected to undergo fewer updates. This approach is similiar to the concept of "Buffered I/O" in file and network systems. By connecting the underlying lines and polylines, this library achieves an enhanced polyline that is dynamic, efficient, and capable of surpassing the maximum number of points imposed by the built-in polyline.
🔵 API
Step 1: Import this library
import algotraderdev/polylineplus/1 as pp
// remember to check the latest version of this library and replace the 1 above.
Step 2: Initialize the `PolylinePlus` type.
var p = pp.PolylinePlus.new()
There are a few optional params that developers can specify in the constructor to modify the behavior and appearance of the polyline instance.
var p = pp.PolylinePlus.new(
// If true, the drawing will also connect the first point to the last point, resulting in a closed polyline.
closed = false,
// Determines the field of the chart.point objects that the polyline will use for its x coordinates. Either xloc.bar_index (default), or xloc.bar_time.
xloc = xloc.bar_index,
// Color of the polyline. Default is blue.
line_color = color.blue,
// Style of the polyline. Default is line.style_solid.
line_style = line.style_solid,
// Width of the polyline. Default is 1.
line_width = 1,
// The maximum number of points that each built-in `polyline` instance can contain.
// NOTE: this is not to be confused with the maximum of points that each `PolylinePlus` instance can contain.
max_points_per_builtin_polyline = 10000,
// The number of lines to keep in the buffer. If more points are to be added while the buffer is full, then all the lines in the buffer will be flushed into the poylines.
// The higher the number, the less frequent we'll need to // flush the buffer, and thus lead to better performance.
// NOTE: the maximum total number of lines per chart allowed by PineScript is 500. But given there might be other places where the indicator or strategy are drawing lines outside this polyline context, the default value is 50 to be safe.
lines_bffer_size = 50)
Step 3: Push / Pop Points
// Push a single point
p.push_point(chart.point.now())
// Push multiple points
chart.point points = array.from(p1, p2, p3) // Where p1, p2, p3 are all chart.point type.
p.push_points(points)
// Pop point
p.pop_point()
// Resets all the points in the polyline.
p.set_points(points)
// Deletes the polyline.
p.delete()
🔵 Benchmark
Below is a simple benchmark comparing the performance between `PolylinePlus` and the native `polyline` type for incrementally adding 10K points to a polyline.
import algotraderdev/polylineplus/2 as pp
var t1 = 0
var t2 = 0
if bar_index < 10000
int start = timenow
var p = pp.PolylinePlus.new(xloc = xloc.bar_time, closed = true)
p.push_point(chart.point.now())
t1 += timenow - start
start := timenow
var polyline pl = na
var points = array.new()
points.push(chart.point.now())
if not na(pl)
pl.delete()
pl := polyline.new(points)
t2 += timenow - start
if barstate.islast
log.info('{0} {1}', t1, t2)
For this benchmark, `PolylinePlus` took ~300ms, whereas the native `polyline` type took ~6000ms.
We can also fine-tune the parameters for `PolylinePlus` to have a larger buffer size for `line`s and a smaller buffer for `polyline`s.
var p = pp.PolylinePlus.new(xloc = xloc.bar_time, closed = true, lines_buffer_size = 500, max_points_per_builtin_polyline = 1000)
With the above optimization, it only took `PolylinePlus` ~80ms to process the same 10K points, which is ~75x the performance compared to the native `polyline`.
SPTS_StatsPakLibFinally getting around to releasing the library component to the SPTS indicator!
This library is packed with a ton of great statistics functions to supplement SPTS, these functions add to the capabilities of SPTS including a forecast function.
The library includes the following functions
1. Linear Regression (single independent and single dependent)
2. Multiple Regression (2 independent variables, 1 dependent)
3. Standard Error of Residual Assessment
4. Z-Score
5. Effect Size
6. Confidence Interval
7. Paired Sample Test
8. Two Tailed T-Test
9. Qualitative assessment of T-Test
10. T-test table and p value assigner
11. Correlation of two arrays
12. Quadratic correlation (curvlinear)
13. R Squared value of 2 arrays
14. R Squared value of 2 floats
15. Test of normality
16. Forecast function which will push the desired forecasted variables into an array.
One of the biggest added functionalities of this library is the forecasting function.
This function provides an autoregressive, trainable model that will export forecasted values to 3 arrays, one contains the autoregressed forecasted results, the other two contain the upper confidence forecast and the lower confidence forecast.
Hope you enjoy and find use for this!
Library "SPTS_StatsPakLib"
f_linear_regression(independent, dependent, len, variable)
TODO: creates a simple linear regression model between two variables.
Parameters:
independent (float)
dependent (float)
len (int)
variable (float)
Returns: TODO: returns 6 float variables
result: The result of the regression model
pear_cor: The pearson correlation of the regresion model
rsqrd: the R2 of the regression model
std_err: the error of residuals
slope: the slope of the model (coefficient)
intercept: the intercept of the model (y = mx + b is y = slope x + intercept)
f_multiple_regression(y, x1, x2, input1, input2, len)
TODO: creates a multiple regression model between two independent variables and 1 dependent variable.
Parameters:
y (float)
x1 (float)
x2 (float)
input1 (float)
input2 (float)
len (int)
Returns: TODO: returns 7 float variables
result: The result of the regression model
pear_cor: The pearson correlation of the regresion model
rsqrd: the R2 of the regression model
std_err: the error of residuals
b1 & b2: the slopes of the model (coefficients)
intercept: the intercept of the model (y = mx + b is y = b1 x + b2 x + intercept)
f_stanard_error(result, dependent, length)
x TODO: performs an assessment on the error of residuals, can be used with any variable in which there are residual values (such as moving averages or more comlpex models)
param x TODO: result is the output, for example, if you are calculating the residuals of a 200 EMA, the result would be the 200 EMA
dependent: is the dependent variable. In the above example with the 200 EMA, your dependent would be the source for your 200 EMA
Parameters:
result (float)
dependent (float)
length (int)
Returns: x TODO: the standard error of the residual, which can then be multiplied by standard deviations or used as is.
f_zscore(variable, length)
TODO: Calculates the z-score
Parameters:
variable (float)
length (int)
Returns: TODO: returns float z-score
f_effect_size(array1, array2)
TODO: Calculates the effect size between two arrays of equal scale.
Parameters:
array1 (float )
array2 (float )
Returns: TODO: returns the effect size (float)
f_confidence_interval(array1, array2, ci_input)
TODO: Calculates the confidence interval between two arrays
Parameters:
array1 (float )
array2 (float )
ci_input (float)
Returns: TODO: returns the upper_bound and lower_bound cofidence interval as float values
paired_sample_t(src1, src2, len)
TODO: Performs a paired sample t-test
Parameters:
src1 (float)
src2 (float)
len (int)
Returns: TODO: Returns the t-statistic and degrees of freedom of a paired sample t-test
two_tail_t_test(array1, array2)
TODO: Perofrms a two tailed t-test
Parameters:
array1 (float )
array2 (float )
Returns: TODO: Returns the t-statistic and degrees of freedom of a two_tail_t_test sample t-test
t_table_analysis(t_stat, df)
TODO: This is to make a qualitative assessment of your paired and single sample t-test
Parameters:
t_stat (float)
df (float)
Returns: TODO: the function will return 2 string variables and 1 colour variable. The 2 string variables indicate whether the results are significant or not and the colour will
output red for insigificant and green for significant
t_table_p_value(df, t_stat)
TODO: This performs a quantaitive assessment on your t-tests to determine the statistical significance p value
Parameters:
df (float)
t_stat (float)
Returns: TODO: The function will return 1 float variable, the p value of the t-test.
cor_of_array(array1, array2)
TODO: This performs a pearson correlation assessment of two arrays. They need to be of equal size!
Parameters:
array1 (float )
array2 (float )
Returns: TODO: The function will return the pearson correlation.
quadratic_correlation(src1, src2, len)
TODO: This performs a quadratic (curvlinear) pearson correlation between two values.
Parameters:
src1 (float)
src2 (float)
len (int)
Returns: TODO: The function will return the pearson correlation (quadratic based).
f_r2_array(array1, array2)
TODO: Calculates the r2 of two arrays
Parameters:
array1 (float )
array2 (float )
Returns: TODO: returns the R2 value
f_rsqrd(src1, src2, len)
TODO: Calculates the r2 of two float variables
Parameters:
src1 (float)
src2 (float)
len (int)
Returns: TODO: returns the R2 value
test_of_normality(array, src)
TODO: tests the normal distribution hypothesis
Parameters:
array (float )
src (float)
Returns: TODO: returns 4 variables, 2 float and 2 string
Skew: the skewness of the dataset
Kurt: the kurtosis of the dataset
dist = the distribution type (recognizes 7 different distribution types)
implication = a string assessment of the implication of the distribution (qualitative)
f_forecast(output, input, train_len, forecast_length, output_array, upper_array, lower_array)
TODO: This performs a simple forecast function on a single dependent variable. It will autoregress this based on the train time, to the desired length of output,
then it will push the forecasted values to 3 float arrays, one that contains the forecasted result, 1 that contains the Upper Confidence Result and one with the lower confidence
result.
Parameters:
output (float)
input (float)
train_len (int)
forecast_length (int)
output_array (float )
upper_array (float )
lower_array (float )
Returns: TODO: Will return 3 arrays, one with the forecasted results, one with the upper confidence results, and a final with the lower confidence results. Example is given below.
[Library] VAccThis is the library version of VAcc (Velocity & Acceleration), a momentum indicator published by Scott Cong in Stocks & Commodities V. 41:09 (8–15). It applies concepts from physics, namely velocity and acceleration, to financial markets. VAcc functions similarly to the popular MACD (Moving Average Convergence Divergence) indicator when using a longer lookback period, but produces more responsive results. With shorter periods, VAcc exhibits characteristics reminiscent of the stochastic oscillator.
The indicator version of this algorithm is linked below:
🟠 Algorithm
The average velocity over the past n periods is defined as
((C - C_n) / n + (C - C_{n-1}) / (n - 1) + … + (C - C_i) / i + (C - C_1) / 1) / n
At its core, the velocity is a weighted average of the rate of change over the past n periods.
The calculation of the acceleration follows a similar process, where it’s defined as
((V - V_n) / n + (V - V_{n - 1}) / (n - 1) + … + (V - V_i) / i + (V - V_1) / 1) / n
🟠 Comparison with MACD
A comparison of VAcc and MACD on the daily Nasdaq 100 (NDX) chart from August 2022 helps demonstrate VAcc's improved sensitivity. Both indicators utilized a lookback period of 26 days and smoothing of 9 periods.
The VAcc histogram clearly shows a divergence forming, with momentum weakening as prices reached new highs. In contrast, the corresponding MACD histogram significantly lagged in confirming the divergence, highlighting VAcc's ability to identify subtle shifts in trend momentum more immediately than the traditional MACD.
XLibrary "X"
a collection of 'special' methods/functions ('special' at the time of conception)
Initial functions includes:
• count of a given number in a given array
• array.get() but option added to use negative index
• sum of all digits until the output < 10
• slope/angle calculation of lines
method count_num_in_array(arr, num)
counts how many times a given number is present in a given array (0 when not present)
Namespace types: int
Parameters:
arr (int ) : Array (int, float )
num (int) : Number that needs to be counted (int, float)
Returns: count of number in array (0 when not present)
method count_num_in_array(arr, num)
Namespace types: float
Parameters:
arr (float )
num (float)
method get_(arr, idx)
array.get() but you can use negative index (-1 is last of array, -2 is second last,...)
Namespace types: int
Parameters:
arr (int ) : Array (int, float, string, bool, label, line, box, color )
idx (int) : Index
Returns: value/object at index, 'na' if index is outside array
method get_(arr, idx)
Namespace types: float
Parameters:
arr (float )
idx (int)
method get_(arr, idx)
Namespace types: string
Parameters:
arr (string )
idx (int)
method get_(arr, idx)
Namespace types: bool
Parameters:
arr (bool )
idx (int)
method get_(arr, idx)
Namespace types: label
Parameters:
arr (label )
idx (int)
method get_(arr, idx)
Namespace types: line
Parameters:
arr (line )
idx (int)
method get_(arr, idx)
Namespace types: box
Parameters:
arr (box )
idx (int)
method get_(arr, idx)
Namespace types: color
Parameters:
arr (color )
idx (int)
method sumAllNumbers_till_under_10(num)
sums all separate digit numbers, it repeats the process until sum < 10
Namespace types: series int, simple int, input int, const int
Parameters:
num (int) : Number (int, float)
Returns: value between 0 and 9
method sumAllNumbers_till_under_10(num)
Namespace types: series float, simple float, input float, const float
Parameters:
num (float)
method XYaxis(width)
Global function to calculate Yaxis, which is used in calculate_slope() method
Namespace types: series int, simple int, input int, const int
Parameters:
width (int) : Amount of bars for reference X-axis
Returns: Yaxis
method calculate_slope(width, XYratio, Yaxis, x1, y1, x2, y2)
Returns a normalised slope
Namespace types: series int, simple int, input int, const int
Parameters:
width (int) : Amount of bars to calculate height
XYratio (float) : Ratio to calculate height (from width) normalised_slope calculation
Yaxis (float) : Y-axis from XYaxis() method
x1 (int) : x1 of line
y1 (float) : y1 of line
x2 (int) : x2 of line
y2 (float) : y2 of line
Returns: Tuple of -> slope = price difference per bar
PineUnitPineUnit by Guardian667
A comprehensive testing framework for Pine Script on TradingView. Built with well-known testing paradigms like Assertions, Units and Suites. It offers the ability to log test results in TradingView's built-in Pine Protocol view, as well as displaying them in a compact table directly on your chart, ensuring your scripts are both robust and reliable.
Unit testing Pine Script indicators, libraries, and strategies becomes seamless, ensuring the precision and dependability of your TradingView scripts. Beyond standard function testing based on predefined input values, PineUnit supports series value testing. This means a test can run on every bar, taking into account its specific values. Moreover, you can specify the exact conditions under which a test should execute, allowing for series-based testing only on bars fitting a designated scenario.
Detailed Guide & Source Code
Quick Start
To get started swiftly with PineUnit, follow this minimalistic example.
import Guardian667/PineUnit/1 as PineUnit
var testSession = PineUnit.createTestSession()
var trueTest = testSession.createSimpleTest("True is always True")
trueTest.assertTrue(true)
testSession.report()
After running your script, you'll notice a table on your chart displaying the test results. For a detailed log output, you can also utilize the Pine Protocol view in TradingView.
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 1, Failures: 0, Not executed: 0, Skipped: 0
To further illustrate, let's introduce a test that's destined to fail:
var bullTest = testSession.createSeriesTest("It's allways Bull Market")
bullTest.assertTrue(close > open, "Uhoh... it's not always bullish")
After executing, the test results will reflect this intentional discrepancy:
--------------------------------------------------------------
T E S T S
--------------------------------------------------------------
Running Default Unit
Tests run: 2, Failures: 1, Not executed: 0, Skipped: 0 <<< FAILURE! - in
It's allways Bull Market
Uhoh... it's not always bullish ==> expected: , but was
This shows how PineUnit efficiently captures and reports discrepancies in test expectations.
It's important to recognise the difference between `createSimpleTest()` and `createSeriesTest()`. In contrast to a simple test, a series-based test is executed on each bar, making assertions on series values.
License
This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
@ Guardian667
A Personal Note
As a software developer experienced in OO-based languages, diving into Pine Script is a unique journey. While many aspects of it are smooth and efficient, there are also notable gaps, particularly in the realm of testing. We've all been there: using `plotchar()` for debugging, trying to pinpoint those elusive issues in our scripts. I've come to appreciate the value of writing tests, which often obviates the need for such debugging. My hope is that this Testing Framework serves you well and saves you a significant amount of time, more that I invested into developing this "baby."
mathLibrary "math"
TODO: Math custom MA and more
pine_ema(src, length)
Parameters:
src (float)
length (int)
pine_dema(src, length)
Parameters:
src (float)
length (int)
pine_tema(src, length)
Parameters:
src (float)
length (int)
pine_sma(src, length)
Parameters:
src (float)
length (int)
pine_smma(src, length)
Parameters:
src (float)
length (int)
pine_ssma(src, length)
Parameters:
src (float)
length (int)
pine_rma(src, length)
Parameters:
src (float)
length (int)
pine_wma(x, y)
Parameters:
x (float)
y (int)
pine_hma(src, length)
Parameters:
src (float)
length (int)
pine_vwma(x, y)
Parameters:
x (float)
y (int)
pine_swma(x)
Parameters:
x (float)
pine_alma(src, length, offset, sigma)
Parameters:
src (float)
length (int)
offset (float)
sigma (float)
ZigLibLibrary "ZigLib"
Calculate the points for ZigZag++.
You can use custom data and resolution for your ZigZag++.
Sample Usage
import DevLucem/ZigLib/1 as ZigZag
= ZigZag.zigzag(low, high)
bgcolor(direction<0? color.rgb(255, 82, 82, 80): color.rgb(0, 230, 119, 80))
line zz = line.new(z1.time, z1.price, z2.time, z2.price, xloc.bar_time, width=3)
if direction==direction
line.delete(zz )
zigzag(_low, _high, depth, deviation, backstep)
Get current zigzag points and direction
Parameters:
_low (float)
_high (float)
depth (int)
deviation (int)
backstep (int)
Returns direction, chart point 1 and chart point 2
MTF_DrawingsLibrary 'MTF_Drawings'
This library helps with drawing indicators and candle charts on all timeframes.
FEATURES
CHART DRAWING : Library provides functions for drawing High Time Frame (HTF) and Low Time Frame (LTF) candles.
INDICATOR DRAWING : Library provides functions for drawing various types of HTF and LTF indicators.
CUSTOM COLOR DRAWING : Library allows to color candles and indicators based on specific conditions.
LINEFILLS : Library provides functions for drawing linefills.
CATEGORIES
The functions are named in a way that indicates they purpose:
{Ind} : Function is meant only for indicators.
{Hist} : Function is meant only for histograms.
{Candle} : Function is meant only for candles.
{Draw} : Function draws indicators, histograms and candle charts.
{Populate} : Function generates necessary arrays required by drawing functions.
{LTF} : Function is meant only for lower timeframes.
{HTF} : Function is meant only for higher timeframes.
{D} : Function draws indicators that are composed of two lines.
{CC} : Function draws custom colored indicators.
USAGE
Import the library into your script.
Before using any {Draw} function it is necessary to use a {Populate} function.
Choose the appropriate one based on the category, provide the necessary arguments, and then use the {Draw} function, forwarding the arrays generated by the {Populate} function.
This doesn't apply to {Draw_Lines}, {LineFill}, or {Barcolor} functions.
EXAMPLE
import Spacex_trader/MTF_Drawings/1 as tf
//Request lower timeframe data.
Security(simple string Ticker, simple string New_LTF, float Ind) =>
float Value = request.security_lower_tf(Ticker, New_LTF, Ind)
Value
Timeframe = input.timeframe('1', 'Timeframe: ')
tf.Draw_Ind(tf.Populate_LTF_Ind(Security(syminfo.tickerid, Timeframe, ta.rsi(close, 14)), 498, color.purple), 1, true)
FUNCTION LIST
HTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, HTF_Open, HTF_High, HTF_Low, HTF_Close, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
HTF_Open (float) : HTF open price.
HTF_High (float) : HTF high price.
HTF_Low (float) : HTF low price.
HTF_Close (float) : HTF close price.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF candles.
LTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, LTF_Open, LTF_High, LTF_Low, LTF_Close)
Populates two arrays with drawing data of the LTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
LTF_Open (float ) : LTF open price.
LTF_High (float ) : LTF high price.
LTF_Low (float ) : LTF low price.
LTF_Close (float ) : LTF close price.
Returns: Two arrays with drawing data of the LTF candles.
Draw_Candle(Box, Line, Offset)
Draws HTF or LTF candles.
Parameters:
Box (box ) : Box array with drawing data.
Line (line ) : Line array with drawing data.
Offset (int) : Offset of the candles.
Returns: Drawing of the candles.
Populate_HTF_Ind(IndValue, BarsBack, IndColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator.
Parameters:
IndValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: An array with drawing data of the HTF indicator.
Populate_LTF_Ind(IndValue, BarsBack, IndColor)
Populates one array with drawing data of the LTF indicator.
Parameters:
IndValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
Returns: An array with drawing data of the LTF indicator.
Draw_Ind(Line, Mult, Exe)
Draws one HTF or LTF indicator.
Parameters:
Line (line ) : Line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the indicator.
Returns: Drawing of the indicator.
Populate_HTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF indicators.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF indicators.
Populate_LTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2)
Populates two arrays with drawing data of the LTF indicators.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
Returns: Two arrays with drawing data of the LTF indicators.
Draw_Ind_D(Line_1, Line_2, Mult, Exe_1, Exe_2)
Draws two LTF or HTF indicators.
Parameters:
Line_1 (line ) : First line array with drawing data.
Line_2 (line ) : Second line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe_1 (bool) : Display the first indicator.
Exe_2 (bool) : Display the second indicator.
Returns: Drawings of the indicators.
Barcolor(Box, Line, BarColor)
Colors the candles based on indicators output.
Parameters:
Box (box ) : Candle box array.
Line (line ) : Candle line array.
BarColor (color ) : Indicator color array.
Returns: Colored candles.
Populate_HTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1, HTF_Bar_Index)
Populates two array with drawing data of the HTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bear color.
IndColor_1 (color) : First indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Three arrays with drawing and color data of the HTF indicators.
Populate_LTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1)
Populates two arrays with drawing data of the LTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
IndColor_1 (color) : First indicator color.
Returns: Three arrays with drawing and color data of the LTF indicators.
Populate_HTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float) : Indicator value.
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF histogram.
Populate_LTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_LTF_Hist_CC_VA(HistValue, Value, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: HistValue >= Value ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
Value (float) : First indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_HTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float) : Indicator value.
IndValue_1 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF indicator.
Populate_LTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float ) : Indicator value.
IndValue_1 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two arrays with drawing and color data of the LTF indicator.
Draw_Lines(BarsBack, y1, y2, LineType, Fill)
Draws price lines on indicators.
Parameters:
BarsBack (int) : Indicator lines to display.
y1 (float) : Coordinates of the first line.
y2 (float) : Coordinates of the second line.
LineType (string) : Line type.
Fill (color) : Fill color.
Returns: Drawing of the lines.
LineFill(Upper, Lower, BarsBack, FillColor)
Fills two lines with linefill HTF or LTF.
Parameters:
Upper (line ) : Upper line.
Lower (line ) : Lower line.
BarsBack (int) : Indicator lines to display.
FillColor (color) : Fill color.
Returns: Linefill of the lines.
Populate_LTF_Hist(HistValue, BarsBack, HistColor)
Populates one array with drawing data of the LTF histogram.
Parameters:
HistValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
Returns: One array with drawing data of the LTF histogram.
Populate_HTF_Hist(HistValue, BarsBack, HistColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram.
Parameters:
HistValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: One array with drawing data of the HTF histogram.
Draw_Hist(Box, Mult, Exe)
Draws HTF or LTF histogram.
Parameters:
Box (box ) : Box Array.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the histogram.
Returns: Drawing of the histogram.
lib_retracement_patternsLibrary "lib_retracement_patterns"
types and functions for XABCD pattern detection and plotting
method set_tolerances(this, tolerance_Bmin, tolerance_Bmax, tolerance_Cmin, tolerance_Cmax, tolerance_Dmin, tolerance_Dmax)
sets tolerances for B, C and D retracements. This creates another Pattern instance that is set as tolerances field on the original and will be used for detection instead of the original ratios.
Namespace types: Pattern
create_config(pattern_line_args, pattern_point_args, name_label_args, retracement_line_args, retracement_label_args, line_args_Dtarget, line_args_completion, line_args_tp1, line_args_tp2, line_args_sl, label_args_completion, label_args_tp1, label_args_tp2, label_args_sl, label_terminal, label_terminal_up_char, label_terminal_down_char, color_bull, color_bear, color_muted, fill_opacity, draw_point_labels, draw_retracements, draw_target_range, draw_levels, hide_shorter_if_shared_legs_greater_than_max, hide_engulfed_pattern, hide_engulfed_pattern_of_same_type, hide_longer_pattern_with_same_X, mute_previous_pattern_when_next_overlaps, keep_failed_patterns)
method direction(this)
Namespace types: Match
method length(this)
return the length of this pattern, determined by the distance between X and D point
Namespace types: Match
method height(this)
return the height of this pattern, determined by the distance between the biggest distance between A/C and X/D
Namespace types: Match
method is_forming(this)
returns true if not complete, not expired and not invalidated
Namespace types: Match
method tostring(this)
return a string representation of all Matches in this map
Namespace types: Match
method tostring(this)
Namespace types: map
remove_complete_and_expired(this)
method add(this, item)
Namespace types: map
method is_engulfed_by(this, other)
checks if this Match is engulfed by the other
Namespace types: Match
method update(tracking_matches, zigzag, patterns, max_age_idx, detect_dir, pattern_minlen, pattern_maxlen, max_sub_waves, max_shared_legs, max_XB_BD_ratio, debug_log)
checks this map of tracking Matches if any of them was completed or invalidated in
Namespace types: map
method mute(this, mute_color, mute_fill_color)
mute this pattern by making it all one color (lines and labels, for pattern fill there's another)
Namespace types: Match
method mute(this, mute_color, mute_fill_color)
mute all patterns in this map by making it all one color (lines and labels, for pattern fill there's another)
Namespace types: map
method hide(this)
hide this pattern by muting it with a transparent color
Namespace types: Match
method reset_styles(this)
reset the style of a muted or hidden match back to the preset configuration
Namespace types: Match
method delete(this)
remove the plot of this Match from the chart
Namespace types: Match
method delete(this)
remove all the plots of the Matches in this map from the chart
Namespace types: map
method draw(this)
draw this Match on the chart
Namespace types: Match
method draw(this, config, all_patterns, debug_log)
draw all Matches in this map, considering all other patterns for engulfing and overlapping
Namespace types: map
method check_hide_or_mute(this, all, config, debug_log)
checks if this pattern needs to be hidden or muted based on other plotted patterns and given configuration
Namespace types: Match
method add_if(id, item, condition)
convenience function to add a search pattern to a list, only if given condition (input.bool) is true
Namespace types: Pattern
Pattern
type to hold retracement ratios and tolerances for this pattern, as well as targets for trades
Config
allows control of pattern plotting shape and colors, as well as settings for hiding overlapped patterns etc.
Match
holds all information on a Pattern and a successful match in the chart. Includes XABCD pivot points as well as all Line and Label objects to draw it
AGbayLIBLibrary "AGbayLIB"
Changes the timeframe period to the given period and returns the data matrix and sets the timeframe to the active time period
getTimeFrameValues(active_period_, period_, max_bars_)
: add function description here
Parameters:
active_period_ (string) : Current time frame period to be set after getting period_ data
period_ (string) : Target time period for returning data
max_bars_ (int) : The historical bar count to be get
Returns: An array of data_row type with size of max_bars_ which includes rows of data:
data_row
Fields:
year (series__integer)
month (series__integer)
day (series__integer)
hour (series__integer)
minute (series__integer)
second (series__integer)
fulltime (series__string)
open (series__float)
close (series__float)
high (series__float)
low (series__float)
volume (series__float)
EphemerisLibrary "Ephemeris"
TODO: add library description here
mercuryElements()
mercuryRates()
venusElements()
venusRates()
earthElements()
earthRates()
marsElements()
marsRates()
jupiterElements()
jupiterRates()
saturnElements()
saturnRates()
uranusElements()
uranusRates()
neptuneElements()
neptuneRates()
rev360(x)
Normalize degrees to within [0, 360)
Parameters:
x (float) : degrees to be normalized
Returns: Normalized degrees
scaleAngle(longitude, magnitude, harmonic)
Scale angle in degrees
Parameters:
longitude (float)
magnitude (float)
harmonic (int)
Returns: Scaled angle in degrees
julianCenturyInJulianDays()
Constant Julian days per century
Returns: 36525
julianEpochJ2000()
Julian date on J2000 epoch start (2000-01-01)
Returns: 2451545.0
meanObliquityForJ2000()
Mean obliquity of the ecliptic on J2000 epoch start (2000-01-01)
Returns: 23.43928
getJulianDate(Year, Month, Day, Hour, Minute)
Convert calendar date to Julian date
Parameters:
Year (int) : calendar year as integer (e.g. 2018)
Month (int) : calendar month (January = 1, December = 12)
Day (int) : calendar day of month (e.g. January valid days are 1-31)
Hour (int) : valid values 0-23
Minute (int) : valid values 0-60
julianCenturies(date, epoch_start)
Centuries since Julian Epoch 2000-01-01
Parameters:
date (float) : Julian date to conver to Julian centuries
epoch_start (float) : Julian date of epoch start (e.g. J2000 epoch = 2451545)
Returns: Julian date converted to Julian centuries
julianCenturiesSinceEpochJ2000(julianDate)
Calculate Julian centuries since epoch J2000 (2000-01-01)
Parameters:
julianDate (float) : Julian Date in days
Returns: Julian centuries since epoch J2000 (2000-01-01)
atan2(y, x)
Specialized arctan function
Parameters:
y (float) : radians
x (float) : radians
Returns: special arctan of y/x
eccAnom(ec, m_param, dp)
Compute eccentricity of the anomaly
Parameters:
ec (float) : Eccentricity of Orbit
m_param (float) : Mean Anomaly ?
dp (int) : Decimal places to round to
Returns: Eccentricity of the Anomaly
planetEphemerisCalc(TGen, planetElementId, planetRatesId)
Compute planetary ephemeris (longtude relative to Earth or Sun) on a Julian date
Parameters:
TGen (float) : Julian Date
planetElementId (float ) : All planet orbital elements in an array. This index references a specific planet's elements.
planetRatesId (float ) : All planet orbital rates in an array. This index references a specific planet's rates.
Returns: X,Y,Z ecliptic rectangular coordinates and R radius from reference body.
calculateRightAscensionAndDeclination(earthX, earthY, earthZ, planetX, planetY, planetZ)
Calculate right ascension and declination for a planet relative to Earth
Parameters:
earthX (float) : Earth X ecliptic rectangular coordinate relative to Sun
earthY (float) : Earth Y ecliptic rectangular coordinate relative to Sun
earthZ (float) : Earth Z ecliptic rectangular coordinate relative to Sun
planetX (float) : Planet X ecliptic rectangular coordinate relative to Sun
planetY (float) : Planet Y ecliptic rectangular coordinate relative to Sun
planetZ (float) : Planet Z ecliptic rectangular coordinate relative to Sun
Returns: Planet geocentric orbital radius, geocentric right ascension, and geocentric declination
mercuryHelio(T)
Compute Mercury heliocentric longitude on date
Parameters:
T (float)
Returns: Mercury heliocentric longitude on date
venusHelio(T)
Compute Venus heliocentric longitude on date
Parameters:
T (float)
Returns: Venus heliocentric longitude on date
earthHelio(T)
Compute Earth heliocentric longitude on date
Parameters:
T (float)
Returns: Earth heliocentric longitude on date
marsHelio(T)
Compute Mars heliocentric longitude on date
Parameters:
T (float)
Returns: Mars heliocentric longitude on date
jupiterHelio(T)
Compute Jupiter heliocentric longitude on date
Parameters:
T (float)
Returns: Jupiter heliocentric longitude on date
saturnHelio(T)
Compute Saturn heliocentric longitude on date
Parameters:
T (float)
Returns: Saturn heliocentric longitude on date
neptuneHelio(T)
Compute Neptune heliocentric longitude on date
Parameters:
T (float)
Returns: Neptune heliocentric longitude on date
uranusHelio(T)
Compute Uranus heliocentric longitude on date
Parameters:
T (float)
Returns: Uranus heliocentric longitude on date
sunGeo(T)
Parameters:
T (float)
mercuryGeo(T)
Parameters:
T (float)
venusGeo(T)
Parameters:
T (float)
marsGeo(T)
Parameters:
T (float)
jupiterGeo(T)
Parameters:
T (float)
saturnGeo(T)
Parameters:
T (float)
neptuneGeo(T)
Parameters:
T (float)
uranusGeo(T)
Parameters:
T (float)
moonGeo(T_JD)
Parameters:
T_JD (float)
mercuryOrbitalPeriod()
Mercury orbital period in Earth days
Returns: 87.9691
venusOrbitalPeriod()
Venus orbital period in Earth days
Returns: 224.701
earthOrbitalPeriod()
Earth orbital period in Earth days
Returns: 365.256363004
marsOrbitalPeriod()
Mars orbital period in Earth days
Returns: 686.980
jupiterOrbitalPeriod()
Jupiter orbital period in Earth days
Returns: 4332.59
saturnOrbitalPeriod()
Saturn orbital period in Earth days
Returns: 10759.22
uranusOrbitalPeriod()
Uranus orbital period in Earth days
Returns: 30688.5
neptuneOrbitalPeriod()
Neptune orbital period in Earth days
Returns: 60195.0
jupiterSaturnCompositePeriod()
jupiterNeptuneCompositePeriod()
jupiterUranusCompositePeriod()
saturnNeptuneCompositePeriod()
saturnUranusCompositePeriod()
planetSineWave(julianDateInCenturies, planetOrbitalPeriod, planetHelio)
Convert heliocentric longitude of planet into a sine wave
Parameters:
julianDateInCenturies (float)
planetOrbitalPeriod (float) : Orbital period of planet in Earth days
planetHelio (float) : Heliocentric longitude of planet in degrees
Returns: Sine of heliocentric longitude on a Julian date
lib_plot_composite_objectsLibrary "lib_plot_composite_objects"
library building on top of lib_plot_objects for composite objects such as Triangles and Polygons. heavily using chart.points
method tostring(this, date_format)
Namespace types: Triangle
Parameters:
this (Triangle)
date_format (simple string)
method tostring(this, date_format)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
date_format (simple string)
method tostring(this, date_format)
Namespace types: Polygon
Parameters:
this (Polygon)
date_format (simple string)
method tostring(this, date_format)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
date_format (simple string)
method tostring(this, date_format)
Namespace types: Triangle
Parameters:
this (Triangle )
date_format (simple string)
method tostring(this, date_format)
Namespace types: Polygon
Parameters:
this (Polygon )
date_format (simple string)
method tostring(this, date_format)
Namespace types: TriangleFill
Parameters:
this (TriangleFill )
date_format (simple string)
method tostring(this, date_format)
Namespace types: PolygonFill
Parameters:
this (PolygonFill )
date_format (simple string)
method create_triangle(this, b, c, args)
Namespace types: chart.point
Parameters:
this (chart.point)
b (chart.point)
c (chart.point)
args (LineArgs type from robbatt/lib_plot_objects/32)
method create_triangle(this, c)
Namespace types: D.Line
Parameters:
this (Line type from robbatt/lib_plot_objects/32)
c (chart.point)
method create_polygon(points, args)
Namespace types: chart.point
Parameters:
points (chart.point )
args (LineArgs type from robbatt/lib_plot_objects/32)
method create_polygon(start, others, args)
Namespace types: chart.point
Parameters:
start (chart.point)
others (chart.point )
args (LineArgs type from robbatt/lib_plot_objects/32)
method create_fill(this, fill_color)
Namespace types: Triangle
Parameters:
this (Triangle)
fill_color (color)
method create_fill(this, fill_color)
Namespace types: Polygon
Parameters:
this (Polygon)
fill_color (color)
method create_center_label(this, txt, args, tooltip)
Namespace types: Triangle
Parameters:
this (Triangle)
txt (string)
args (LabelArgs type from robbatt/lib_plot_objects/32)
tooltip (string)
method create_label(this, txt, args, tooltip)
Namespace types: Polygon
Parameters:
this (Polygon)
txt (string)
args (LabelArgs type from robbatt/lib_plot_objects/32)
tooltip (string)
method nz(this, default)
Namespace types: Triangle
Parameters:
this (Triangle)
default (Triangle)
method nz(this, default)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
default (TriangleFill)
method nz(this, default)
Namespace types: Polygon
Parameters:
this (Polygon)
default (Polygon)
method nz(this, default)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
default (PolygonFill)
method enqueue(id, item, max)
Namespace types: Triangle
Parameters:
id (Triangle )
item (Triangle)
max (int)
method enqueue(id, item, max)
Namespace types: Polygon
Parameters:
id (Polygon )
item (Polygon)
max (int)
method enqueue(id, item, max)
Namespace types: TriangleFill
Parameters:
id (TriangleFill )
item (TriangleFill)
max (int)
method enqueue(id, item, max)
Namespace types: PolygonFill
Parameters:
id (PolygonFill )
item (PolygonFill)
max (int)
method update(this, a, b, c)
Namespace types: Triangle
Parameters:
this (Triangle)
a (chart.point)
b (chart.point)
c (chart.point)
method update(this, points)
Namespace types: Polygon
Parameters:
this (Polygon)
points (chart.point )
method delete(this)
Namespace types: Triangle
Parameters:
this (Triangle)
method delete(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
method delete(this)
Namespace types: Polygon
Parameters:
this (Polygon)
method delete(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
method delete(this)
Namespace types: Triangle
Parameters:
this (Triangle )
method delete(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill )
method delete(this)
Namespace types: Polygon
Parameters:
this (Polygon )
method delete(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill )
method draw(this, ab_args_override, ac_args_override, bc_args_override)
Namespace types: Triangle
Parameters:
this (Triangle)
ab_args_override (LineArgs type from robbatt/lib_plot_objects/32)
ac_args_override (LineArgs type from robbatt/lib_plot_objects/32)
bc_args_override (LineArgs type from robbatt/lib_plot_objects/32)
method draw(this)
Namespace types: Polygon
Parameters:
this (Polygon)
method draw(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill)
method draw(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill)
method draw(this)
Namespace types: Triangle
Parameters:
this (Triangle )
method draw(this)
Namespace types: TriangleFill
Parameters:
this (TriangleFill )
method draw(this)
Namespace types: Polygon
Parameters:
this (Polygon )
method draw(this)
Namespace types: PolygonFill
Parameters:
this (PolygonFill )
method apply_style(this, args)
Namespace types: Triangle
Parameters:
this (Triangle)
args (LineArgs type from robbatt/lib_plot_objects/32)
method apply_style(this, args)
Namespace types: Polygon
Parameters:
this (Polygon)
args (LineArgs type from robbatt/lib_plot_objects/32)
method apply_style(this, args)
Namespace types: Triangle
Parameters:
this (Triangle )
args (LineArgs type from robbatt/lib_plot_objects/32)
method apply_style(this, args)
Namespace types: Polygon
Parameters:
this (Polygon )
args (LineArgs type from robbatt/lib_plot_objects/32)
Triangle
Fields:
a (chart.point) : first Corner
b (chart.point) : second Corner
c (chart.point) : third Corner
args (LineArgs type from robbatt/lib_plot_objects/32) : Wrapper for reusable arguments for line.new()
ab (Line type from robbatt/lib_plot_objects/32)
ac (Line type from robbatt/lib_plot_objects/32)
bc (Line type from robbatt/lib_plot_objects/32)
TriangleFill
Fields:
triangle (Triangle) : The Triangle object
plot (LineFill type from robbatt/lib_plot_objects/32) : The linefill object to be added and plotted via draw()
Polygon
Fields:
points (chart.point ) : array of points that make up the Polygon
center (chart.point) : Center point of the Polygon, can be used for a label and will be center for PolygonFill
args (LineArgs type from robbatt/lib_plot_objects/32) : Wrapper for reusable arguments for line.new()
plot (Line type from robbatt/lib_plot_objects/32) : An array of Lines that form Polygon Border
PolygonFill
Fields:
poly (Polygon) : the Polygon
fill_color (series color) : The color used to fill the space between the lines.
plot (TriangleFill )
WIPFunctionLyaponovLibrary "WIPFunctionLyaponov"
Lyapunov exponents are mathematical measures used to describe the behavior of a system over
time. They are named after Russian mathematician Alexei Lyapunov, who first introduced the concept in the
late 19th century. The exponent is defined as the rate at which a particular function or variable changes
over time, and can be positive, negative, or zero.
Positive exponents indicate that a system tends to grow or expand over time, while negative exponents
indicate that a system tends to shrink or decay. Zero exponents indicate that the system does not change
significantly over time. Lyapunov exponents are used in various fields of science and engineering, including
physics, economics, and biology, to study the long-term behavior of complex systems.
~ generated description from vicuna13b
---
To calculate the Lyapunov Exponent (LE) of a given Time Series, we need to follow these steps:
1. Firstly, you should have access to your data in some format like CSV or Excel file. If not, then you can collect it manually using tools such as stopwatches and measuring tapes.
2. Once the data is collected, clean it up by removing any outliers that may skew results. This step involves checking for inconsistencies within your dataset (e.g., extremely large or small values) and either discarding them entirely or replacing with more reasonable estimates based on surrounding values.
3. Next, you need to determine the dimension of your time series data. In most cases, this will be equal to the number of variables being measured in each observation period (e.g., temperature, humidity, wind speed).
4. Now that we have a clean dataset with known dimensions, we can calculate the LE for our Time Series using the following formula:
λ = log(||M^T * M - I||)/log(||v||)
where:
λ (Lyapunov Exponent) is the quantity that will be calculated.
||...|| denotes an Euclidean norm of a vector or matrix, which essentially means taking the square root of the sum of squares for each element in the vector/matrix.
M represents our Jacobian Matrix whose elements are given by:
J_ij = (∂fj / ∂xj) where fj is the jth variable and xj is the ith component of the initial condition vector x(t). In other words, each element in this matrix represents how much a small change in one variable affects another.
I denotes an identity matrix whose elements are all equal to 1 (or any constant value if you prefer). This term essentially acts as a baseline for comparison purposes since we want our Jacobian Matrix M^T * M to be close to it when the system is stable and far away from it when the system is unstable.
v represents an arbitrary vector whose Euclidean norm ||v|| will serve as a scaling factor in our calculation. The choice of this particular vector does not matter since we are only interested in its magnitude (i.e., length) for purposes of normalization. However, if you want to ensure that your results are accurate and consistent across different datasets or scenarios, it is recommended to use the same initial condition vector x(t) as used earlier when calculating our Jacobian Matrix M.
5. Finally, once we have calculated λ using the formula above, we can interpret its value in terms of stability/instability for our Time Series data:
- If λ < 0, then this indicates that the system is stable (i.e., nearby trajectories will converge towards each other over time).
- On the other hand, if λ > 0, then this implies that the system is unstable (i.e., nearby trajectories will diverge away from one another over time).
~ generated description from airoboros33b
---
Reference:
en.wikipedia.org
www.collimator.ai
blog.abhranil.net
www.researchgate.net
physics.stackexchange.com
---
This is a work in progress, it may contain errors so use with caution.
If you find flaws or suggest something new, please leave a comment bellow.
_measure_function(i)
helper function to get the name of distance function by a index (0 -> 13).\
Functions: SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl.
Parameters:
i (int)
_test(L)
Helper function to test the output exponents state system and outputs description into a string.
Parameters:
L (float )
estimate(X, initial_distance, distance_function)
Estimate the Lyaponov Exponents for multiple series in a row matrix.
Parameters:
X (map)
initial_distance (float) : Initial distance limit.
distance_function (string) : Name of the distance function to be used, default:`ssd`.
Returns: List of Lyaponov exponents.
max(L)
Maximal Lyaponov Exponent.
Parameters:
L (float ) : List of Lyapunov exponents.
Returns: Highest exponent.
printerLibrary "printer"
Printer Library, designed to streamline the process of printing data directly onto charts while offering advanced features for enhanced functionality.
For full documentation, please visit faiyaz7283.github.io
Contrast Color LibraryThis lightweight library provides a utility method that analyzes any provided background color and automatically chooses the optimal black or white foreground color to ensure maximum visual contrast and readability.
🟠 Algorithm
The library utilizes the HSP Color Model to calculate the brightness of the background color. The formula for this calculation is as follows:
brightness = sqrt(0.299 * R^2 + 0.587 * G^2 + 0.114 * B^2 )
The library chooses black as the foreground color if the brightness exceeds the threshold (default 0.5), and white otherwise.