StringStringHashmapLibrary "StringStringHashmap"
A simple implementation of a key string-to-string value dictionary in pine script
create_ss_dict()
Create an empty string-string dictionary
Returns: the indices and elements of the dict
add_key_value(key, value, i, e)
Add new key-value pair in the dictionary
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
get_value(key, i, e)
Get the value of the given key
Parameters:
key : string
i : string the indices of the dictionary
e : string the element of the dictionary
Returns: return the value of the given key
change_value(key, value, i, e)
Change the value of the given key
Parameters:
key : string
value : string
i : string the indices of the dictionary
e : string the element of the dictionary
Arrays
ReduceSecurityCallsLibrary "ReduceSecurityCalls"
This library allows you to reduce the number of request.security calls to 1 per symbol per timeframe. Script provides example how to use it with request.security and possible optimisation applied to htf data call.
This data can be used to calculate everything you need and more than that (for example you can calculate 4 emas with one function call on mat_out).
ParseSource(mat_outs, o)
Should be used inside request.security call. Optimise your calls using timeframe.change when htf data parsing! Supports up to 5 expressions (results of expressions must be float or int)
Parameters:
mat_outs : Matrix to be used as outputs, first value is newest
o : Please use parametres in the order they specified (o should be 1st, h should be 2nd etc..)
Returns: outs array, due to weird limitations do not try this :matrix_out = matrix.copy(ParseSource)
String_Encoder_DecoderLibrary "String_Encoder_Decoder"
String encoder and decoder to use in internal data tranfer in script calculations.
In example, script encode 125 values once and then decode them every candle.
encode(array or values (val1,val2,val3,val4,val5,val6)
encode: encode some values into string
Parameters:
array : of values or values1, value2 (up to 6 values)
(input values must be stringified)
Returns: encoded value
decode(val)
decode: decode into string
Parameters:
val : value to decode, must be stringified
Returns: decoded array of stringified values
fast_utilsLibrary "fast_utils"
This library contains my favourite functions. Will be updated frequently
count_int_digits()
Count int digits in number
Returns: : number of int digits in number
count_float_digits()
Count float digits in number
Returns: : number of float digits in number
stringify()
Convert values in array or matrix into string values
Returns: : array or matrix of string values
arrcompare()
Compare values in arrays
Returns: : bool value
arrdedup()
Remove duplicate values in array
Returns: : array without duplicates
ResInMins()
Converts current resolution in minutes
Returns: : return float number of minuted
MultOfRes(res, mult)
Convert current float TF in minutes to target string TF in "timeframe.period" format.
Parameters:
res : : current resolution in minutes
mult : : Multiple of current TF to be calculated.
Returns: : timeframe format string
Global_Economic_CalendarLibrary of economic events. Created to display events on the desired chart through the indicator.
Countries: USA, China, Eurozone, Russia
Importance: 3 stars
Source: Investing
Библиотека экономических событий. Создана для отображения событий на нужном графике через индикатор.
Страны: США, Китай, Еврозона, Россия
Важность: 3 звезды
Источник: Investing
columnsLibrary "columns"
Error Tolerant Matrix Setter/Getter Operations. Easy ways to add/remove items into start and end of Columns as well as arrays to grow and shrink matrix.
if mismatched sizes occur the typified NA value will be there to prevent catastrophic crashing.
Rows and Columns are split into 2 libraries due to limitations on number of exports as well as ease of style (columns.shift(), rows.pop() )
pop(_matrix)
do pop last Column off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of Last Column, removing it from matrix
shift(_matrix)
do shift the first Column off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of First Column, removing it from matrix
get(_matrix, _clmnNum)
retrieve specific Column of matrix
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
Returns: Array of selected Column number, leaving in place
push(_matrix, _clmnNum, _item)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_item : Item to Push on Column
Returns: shifted item from Column start
push(_matrix, _array)
add single item onto end of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to Push on Matrix
Returns: Void
unshift(_matrix, _clmnNum, _item)
slide single item into start of Column remove last
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_item : Item to Unshift on Column
Returns: popped item from Column end
unshift(_matrix, _array)
add single item into first Column of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift into Matrix
Returns: Void
set(_matrix, _clmnNum, _array)
replace an array to an existing Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_array : Array to place in Matrix
Returns: Column that was replaced
insert(_matrix, _clmnNum, _array)
insert an array to a new Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
_array : Array to place in Matrix
Returns: void
slideDown(_matrix, _array)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_array : Array to push to Matrix
Returns: shifted first Column
slideUp(_matrix, _array)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift to Matrix
Returns: poppeed last Column
pullOut(_matrix, _clmnNum)
add single item onto end of Column
Parameters:
_matrix : Matrix To Edit
_clmnNum : Column being Targeted
Returns: removed selected Column
rowsLibrary "rows"
Error Tolerant Matrix Setter/Getter Operations. Easy ways to add/remove items into start and end of rows as well as arrays to grow and shrink matrix.
if mismatched sizes occur the typified NA value will be there to prevent catastrophic crashing.
columns and rows are split into 2 libraries due to limitations on number of exports as well as ease of style (columns.shift(), rows.pop() )
pop(_matrix)
do pop last row off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of Last row, removing it from matrix
shift(_matrix)
do shift the first row off of matrix
Parameters:
_matrix : Matrix To Edit
Returns: Array of First row, removing it from matrix
get(_matrix, _rowNum)
retrieve specific row of matrix
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
Returns: Array of selected row number, leaving in place
push(_matrix, _rowNum, _item)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_item : Item to Push on Row
Returns: shifted item from row start
push(_matrix, _array)
add single item onto end of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to Push on Matrix
Returns: Void
unshift(_matrix, _rowNum, _item)
slide single item into start of row remove last
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_item : Item to Unshift on Row
Returns: popped item from row end
unshift(_matrix, _array)
add single item into first row of matrix
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift into Matrix
Returns: Void
set(_matrix, _rowNum, _array)
replace an array to an existing row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_array : Array to place in Matrix
Returns: row that was replaced
insert(_matrix, _rowNum, _array)
insert an array to a new row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
_array : Array to place in Matrix
Returns: void
slideDown(_matrix, _array)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_array : Array to push to Matrix
Returns: shifted first row
slideUp(_matrix, _array)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_array : Array to unshift to Matrix
Returns: popped last row
pullOut(_matrix, _rowNum)
add single item onto end of row
Parameters:
_matrix : Matrix To Edit
_rowNum : Row being Targeted
Returns: removed selected row
lower_tf█ OVERVIEW
This library is a Pine programmer’s tool containing functions to help those who use the request.security_lower_tf() function. Its `ltf()` function helps translate user inputs into a lower timeframe string usable with request.security_lower_tf() . Another function, `ltfStats()`, accumulates statistics on processed chart bars and intrabars.
█ CONCEPTS
Chart bars
Chart bars , as referred to in our publications, are bars that occur at the current chart timeframe, as opposed to those that occur at a timeframe that is higher or lower than that of the chart view.
Intrabars
Intrabars are chart bars at a lower timeframe than the chart's. Each 1H chart bar of a 24x7 market will, for example, usually contain 60 intrabars at the LTF of 1min, provided there was market activity during each minute of the hour. Mining information from intrabars can be useful in that it offers traders visibility on the activity inside a chart bar.
Lower timeframes (LTFs)
A lower timeframe is a timeframe that is smaller than the chart's timeframe. This framework exemplifies how authors can determine which LTF to use by examining the chart's timeframe. The LTF determines how many intrabars are examined for each chart bar; the lower the timeframe, the more intrabars are analyzed.
Intrabar precision
The precision of calculations increases with the number of intrabars analyzed for each chart bar. As there is a 100K limit to the number of intrabars that can be analyzed by a script, a trade-off occurs between the number of intrabars analyzed per chart bar and the chart bars for which calculations are possible.
█ `ltf()`
This function returns a timeframe string usable with request.security_lower_tf() . It calculates the returned timeframe by taking into account a user selection between eight different calculation modes and the chart's timeframe. You send it the user's selection, along with the text corresponding to the eight choices from which the user has chosen, and the function returns a corresponding LTF string.
Because the function processes strings and doesn't require recalculation on each bar, using var to declare the variable to which its result is assigned will execute the function only once on bar zero and speed up your script:
var string ltfString = ltf(ltfModeInput, LTF1, LTF2, LTF3, LTF4, LTF5, LTF6, LTF7, LTF8)
The eight choices users can select from are of two types: the first four allow a selection from the desired amount of chart bars to be covered, the last four are choices of a fixed number of intrabars to be analyzed per chart bar. Our example code shows how to structure your input call and then make the call to `ltf()`. By changing the text associated with the `LTF1` to `LTF8` constants, you can tailor it to your preferences while preserving the functionality of `ltf()` because you will be sending those string constants as the function's arguments so it can determine the user's selection. The association between each `LTFx` constant and its calculation mode is fixed, so the order of the arguments is important when you call `ltf()`.
These are the first four modes and the `LTFx` constants corresponding to each:
Covering most chart bars (least precise) — LTF1
Covers all chart bars. This is accomplished by dividing the current timeframe in seconds by 4 and converting that number back to a string in timeframe.period format using secondsToTfString() . Due to the fact that, on premium subscriptions, the typical historical bar count is between 20-25k bars, dividing the timeframe by 4 ensures the highest level of intrabar precision possible while achieving complete coverage for the entire dataset with the maximum allowed 100K intrabars.
Covering some chart bars (less precise) — LTF2
Covering less chart bars (more precise) — LTF3
These levels offer a stepped LTF in relation to the chart timeframe with slightly more, or slightly less precision. The stepped lower timeframe tiers are calculated from the chart timeframe as follows:
Chart Timeframe Lower Timeframe
Less Precise More Precise
< 1hr 1min 1min
< 1D 15min 1min
< 1W 2hr 30min
> 1W 1D 60min
Covering the least chart bars (most precise) — LTF4
Analyzes the maximum quantity of intrabars possible by using the 1min LTF, which also allows the least amount of chart bars to be covered.
The last four modes allow the user to specify a fixed number of intrabars to analyze per chart bar. Users can choose from 12, 24, 50 or 100 intrabars, respectively corresponding to the `LTF5`, `LTF6`, `LTF7` and `LTF8` constants. The value is a target; the function will do its best to come up with a LTF producing the required number of intrabars. Because of considerations such as the length of a ticker's session, rounding of the LTF to the closest allowable timeframe, or the lowest allowable timeframe of 1min intrabars, it is often impossible for the function to find a LTF producing the exact number of intrabars. Requesting 100 intrabars on a 60min chart, for example, can only produce 60 1min intrabars. Higher chart timeframes, tickers with high liquidity or 24x7 markets will produce optimal results.
█ `ltfStats()`
`ltfStats()` returns statistics that will be useful to programmers using intrabar inspection. By analyzing the arrays returned by request.security_lower_tf() in can determine:
• intrabarsInChartBar : The number of intrabars analyzed for each chart bar.
• chartBarsCovered : The number of chart bars where intrabar information is available.
• avgIntrabars : The average number of intrabars analyzed per chart bar. Events like holidays, market activity, or reduced hours sessions can cause the number of intrabars to vary, bar to bar.
The function must be called on each bar to produce reliable results.
█ DEMONSTRATION CODE
Our example code shows how to provide users with an input from which they can select a LTF calculation mode. If you use this library's functions, feel free to reuse our input setup code, including the tooltip providing users with explanations on how it works for them.
We make a simple call to request.security_lower_tf() to fetch the close values of intrabars, but we do not use those values. We simply send the returned array to `ltfStats()` and then plot in the indicator's pane the number of intrabars examined on each bar and its average. We also display an information box showing the user's selection of the LTF calculation mode, the resulting LTF calculated by `ltf()` and some statistics.
█ NOTES
• As in several of our recent publications, this script uses secondsToTfString() to produce a timeframe string in timeframe.period format from a timeframe expressed in seconds.
• The script utilizes display.data_window and display.status_line to restrict the display of certain plots.
These new built-ins allow coders to fine-tune where a script’s plot values are displayed.
• We implement a new recommended best practice for tables which works faster and reduces memory consumption.
Using this new method, tables are declared only once with var , as usual. Then, on bar zero only, we use table.cell() calls to populate the table.
Finally, table.set_*() functions are used to update attributes of table cells on the last bar of the dataset.
This greatly reduces the resources required to render tables. We encourage all Pine Script™ programmers to do the same.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
ltf(userSelection, choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8)
Selects a LTF from the chart's TF, depending on the `userSelection` input string.
Parameters:
userSelection : (simple string) User-selected input string which must be one of the `choicex` arguments.
choice1 : (simple string) Input selection corresponding to "Least precise, covering most chart bars".
choice2 : (simple string) Input selection corresponding to "Less precise, covering some chart bars".
choice3 : (simple string) Input selection corresponding to "More precise, covering less chart bars".
choice4 : (simple string) Input selection corresponding to "Most precise, 1min intrabars".
choice5 : (simple string) Input selection corresponding to "~12 intrabars per chart bar".
choice6 : (simple string) Input selection corresponding to "~24 intrabars per chart bar".
choice7 : (simple string) Input selection corresponding to "~50 intrabars per chart bar".
choice8 : (simple string) Input selection corresponding to "~100 intrabars per chart bar".
Returns: (simple string) A timeframe string to be used with `request.security_lower_tf()`.
ltfStats()
Returns statistics about analyzed intrabars and chart bars covered by calls to `request.security_lower_tf()`.
Parameters:
intrabarValues : (float [ ]) The ID of a float array containing values fetched by a call to `request.security_lower_tf()`.
Returns: A 3-element tuple: [ (series int) intrabarsInChartBar, (series int) chartBarsCovered, (series float) avgIntrabars ].
Library: ArrayLibrary "xarray"
Additional functions for array.
remove_duplicates(array_in)
Remove duplicates in array.
Parameters:
array_in : (int /float /string ) Array contains duplicates.
Returns: Array without duplicates.
// Example: int
import tuele99/xarray/1 as xarray
c = xarray.remove_duplicates(array.from(1, 4, 2, 1, 2))
plot(array.size(c))
plot(array.get(c, 0))
plot(array.get(c, 1))
// Example: float
import tuele99/xarray/1 as xarray
c = xarray.remove_duplicates(array.from(1.0, 4.0, 2.0, 1.0, 2.0))
plot(array.size(c))
plot(array.get(c, 0))
plot(array.get(c, 1))
// Example: string
import tuele99/xarray/1 as xarray
c = xarray.remove_duplicates(array.from("green", "red", "green", "red", "green"))
plot(array.size(c)) // value = 2
label0 = label.new(x=last_bar_index, y=0, yloc=yloc.belowbar, text=array.get(c, 0), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.green) // below text = "green"
label1 = label.new(x=last_bar_index, y=0, yloc=yloc.abovebar, text=array.get(c, 1), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.red) // above text = "red"
FunctionLAPACKdsyrkLibrary "FunctionLAPACKdsyrk"
subroutine part of LAPACK: Linear Algebra Package,
performs one of the symmetric rank k operations
.
C := alpha*A*A**T + beta*C, or C := alpha*A**T*A + beta*C,
.
where alpha and beta are scalars, C is an n by n symmetric matrix
and A is an n by k matrix in the first case and a k by n matrix
in the second case.
.
reference:
netlib.org
dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
performs one of the symmetric rank k operations
.
C := alpha*A*A**T + beta*C, or C := alpha*A**T*A + beta*C,
.
where alpha and beta are scalars, C is an n by n symmetric matrix
and A is an n by k matrix in the first case and a k by n matrix
in the second case.
.
Parameters:
uplo : string specifies whether the upper or lower triangular part of
the array C is to be referenced as follows:
UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced.
UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced.
.
trans : string specifies the operation to be performed as follows:
TRANS = 'N' or 'n' C := alpha*A*A**T + beta*C.
TRANS = 'T' or 't' C := alpha*A**T*A + beta*C.
TRANS = 'C' or 'c' C := alpha*A**T*A + beta*C.
.
n : int specifies the order of the matrix C. N must be at least zero.
k : int On entry with:
TRANS = 'N' or 'n', K specifies the number of columns of the matrix A.
TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrix A.
K must be at least zero.
.
alpha : float scalar.
a : matrix matrix A.
lda : int specifies the first dimension of A.
beta : float scalar.
c : matrix matrix C, is overwritten by the lower triangular part of the updated matrix.
ldc : int specifies the first dimension of C
Returns: void, C is overwritten by the lower triangular part of the updated matrix.
FunctionLAPACKdtrsmLibrary "FunctionLAPACKdtrsm"
subroutine in the LAPACK:linear algebra package, used to solve one of the following matrix equations:
op( A )*X = alpha*B, or X*op( A ) = alpha*B,
where alpha is a scalar, X and B are m by n matrices, A is a unit, or
non-unit, upper or lower triangular matrix and op( A ) is one of
op( A ) = A or op( A ) = A**T.
The matrix X is overwritten on B.
reference:
netlib.org
dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
solves one of the matrix equations
op( A )*X = alpha*B, or X*op( A ) = alpha*B,
where alpha is a scalar, X and B are m by n matrices, A is a unit, or
non-unit, upper or lower triangular matrix and op( A ) is one of
op( A ) = A or op( A ) = A**T.
The matrix X is overwritten on B.
Parameters:
side : string , On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows:
SIDE = 'L' or 'l' op( A )*X = alpha*B.
SIDE = 'R' or 'r' X*op( A ) = alpha*B.
uplo : string , specifies whether the matrix A is an upper or lower triangular matrix as follows:
UPLO = 'U' or 'u' A is an upper triangular matrix.
UPLO = 'L' or 'l' A is a lower triangular matrix.
transa : string , specifies the form of op( A ) to be used in the matrix multiplication as follows:
TRANSA = 'N' or 'n' op( A ) = A.
TRANSA = 'T' or 't' op( A ) = A**T.
TRANSA = 'C' or 'c' op( A ) = A**T.
diag : string , specifies whether or not A is unit triangular as follows:
DIAG = 'U' or 'u' A is assumed to be unit triangular.
DIAG = 'N' or 'n' A is not assumed to be unit triangular.
m : int , the number of rows of B. M must be at least zero.
n : int , the number of columns of B. N must be at least zero.
alpha : float , specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry.
a : matrix, Triangular matrix.
lda : int , specifies the first dimension of A.
b : matrix, right-hand side matrix B, and on exit is overwritten by the solution matrix X.
ldb : int , specifies the first dimension of B.
Returns: void, modifies matrix b.
usage:
dtrsm ('L', 'U', 'N', 'N', 5, 3, 1.0, a, 7, b, 6)
MYX_ACE_DBLibrary "MYX_ACE_DB"
TODO: Library for Malaysia ACE Market
db(x)
TODO: Library for Malaysia ACE Market
Parameters:
x : TODO: id
Returns: TODO: id
MYX_LEAP_DBLibrary "MYX_LEAP_DB"
TODO: Library for Malaysia LEAP Market
db(x)
TODO: Library for Malaysia LEAP Market
Parameters:
x : TODO: id
Returns: TODO: id
FunctionPatternFrequencyLibrary "FunctionPatternFrequency"
Counts the word or integer number pattern frequency on a array.
reference:
rosettacode.org
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from('a','b','c','a','b','a'))
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from(1,2,3,1,2,1))
Binance_Min_Limit_Order_amount_libraryLibrary "Binance_Min_Limit_Order_amount_library"
TODO: This library give us the minimum Limit Order amount for the contract in Binance.
m_qty(n_v, m_fee, t_fee, cost, m_t)
TODO: it give us the Minimum Qty for the trading in Binance
Parameters:
n_v : TODO: min_notional_value. 5 dollar is the minimum notional amount in Binance at the moment.
m_fee : TODO: maker_fee %
t_fee : TODO: taker_fee %
cost : TODO: your investing money
m_t : TODO: if you want Limit_Order, put the "T", if you want Market_Order, put the "M" defval="M"
Returns: TODO: for the coin of binance on your chart,
Reference: www.binance.com
DatasetWeatherTokyoMeanAirTemperatureLibrary "DatasetWeatherTokyoMeanAirTemperature"
Provides a data set of the monthly mean air temperature (°C) for the city of Tokyo in Japan.
this was just for fun, no financial implications in this.
reference:
www.data.jma.go.jp
TOKYO WMO Station ID:47662 Lat 35o41.5'N Lon 139o45.0'E
year_()
the years of the data set.
Returns: array : year values.
january()
the january values of the dataset
Returns: array\ : data values for january.
february()
the february values of the dataset
Returns: array\ : data values for february.
march()
the march values of the dataset
Returns: array\ : data values for march.
april()
the april values of the dataset
Returns: array\ : data values for april.
may()
the may values of the dataset
Returns: array\ : data values for may.
june()
the june values of the dataset
Returns: array\ : data values for june.
july()
the july values of the dataset
Returns: array\ : data values for july.
august()
the august values of the dataset
Returns: array\ : data values for august.
september()
the september values of the dataset
Returns: array\ : data values for september.
october()
the october values of the dataset
Returns: array\ : data values for october.
november()
the november values of the dataset
Returns: array\ : data values for november.
december()
the december values of the dataset
Returns: array\ : data values for december.
annual()
the annual values of the dataset
Returns: array\ : data values for annual.
select_month(idx)
get the temperature values for a specific month.
Parameters:
idx : int, month index (1 -> 12 | any other value returns annual average values).
Returns: array\ : data values for selected month.
select_value(year_, month_)
get the temperature value of a specified year and month.
Parameters:
year_ : int, year value.
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : value of specified year and month.
diff_to_median(month_)
the difference of the month air temperature (ºC) to the median of the sample.
Parameters:
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : difference of current month to median in (Cº)
FunctionDynamicTimeWarpingLibrary "FunctionDynamicTimeWarping"
"In time series analysis, dynamic time warping (DTW) is an algorithm for
measuring similarity between two temporal sequences, which may vary in
speed. For instance, similarities in walking could be detected using DTW,
even if one person was walking faster than the other, or if there were
accelerations and decelerations during the course of an observation.
DTW has been applied to temporal sequences of video, audio, and graphics
data — indeed, any data that can be turned into a linear sequence can be
analyzed with DTW. A well-known application has been automatic speech
recognition, to cope with different speaking speeds. Other applications
include speaker recognition and online signature recognition.
It can also be used in partial shape matching applications."
"Dynamic time warping is used in finance and econometrics to assess the
quality of the prediction versus real-world data."
~~ wikipedia
reference:
en.wikipedia.org
towardsdatascience.com
github.com
cost_matrix(a, b, w)
Dynamic Time Warping procedure.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: matrix optimum match matrix.
traceback(M)
perform a backtrace on the cost matrix and retrieve optimal paths and cost between arrays.
Parameters:
M : matrix, cost matrix.
Returns: tuple:
array aligned 1st array of indices.
array aligned 2nd array of indices.
float final cost.
reference:
github.com
report(a, b, w)
report ordered arrays, cost and cost matrix.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: string report.
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.
MiteTricksLibrary "MiteTricks"
Matrix Global Registry.
Get, Set, automatic growing, universal get/set,
multi-matrix dictionaries, multi-dictionary matrixes..
add slice matrixes of any type, share one common global key registry
pull up an item from a category, and item name ie a table of info.
same cell needs a color, a size, a string, a value, etc..
all of which can be pulled up with the same group id, and key id.
just swap which matrix you pull the value from.
this has a side benefit of non-repainting and recalculating
when pulling values, changing inputs..
makes for very fast/clean usage..
benefit :
floats = value
strings = names
lines = drawn items
table =table of data items for this key
colors = color for line/table/fill,label..
all of those can be pulled with "get(_VALUES,_groupIDX,_keyIDX)" where only the values matrix needs be swapped, and the same item/coordinates remains for all the possible matrixes that item appears in.
also useful as a dictionary/registry for any given type of item,,
and goes very handy with floats/strings/colors/bools with my matrixautotable
very helpful when prototyping or doing development work as a shortcut.
initRegistry()
Registry inititalizer
Returns: registry of string matrix type
newbool(optional, optional, optional)
create bool type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is bool (na)
Returns: bool matrix of specified size and fill, or blank 2x2 for registry use
newbox(optional, optional, optional)
create box type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is box (na)
Returns: box matrix of specified size and fill, or blank 2x2 for registry use
newcolor(optional, optional, optional)
create color type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is color (na)
Returns: color matrix of specified size and fill, or blank 2x2 for registry use
newfloat(optional, optional, optional)
create float type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is float (na)
Returns: float matrix of specified size and fill, or blank 2x2 for registry use
newint(optional, optional, optional)
create int type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is int (na)
Returns: int matrix of specified size and fill, or blank 2x2 for registry use
newlabel(optional, optional, optional)
create label type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is label (na)
Returns: label matrix of specified size and fill, or blank 2x2 for registry use
newline(optional, optional, optional)
create line type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is line (na)
Returns: line matrix of specified size and fill, or blank 2x2 for registry use
newlinefill(optional, optional, optional)
create linefill type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is linefill(na)
Returns: linefill matrix of specified size and fill, or blank 2x2 for registry use
newstring(optional, optional, optional)
create string type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is string (na)
Returns: string matrix of specified size and fill, or blank 2x2 for registry use
newtable(optional, optional, optional)
create table type new matrix presized 2x2 for reg
Parameters:
optional: row size
optional: column size
optional: fill value(default is table (na)
Returns: table matrix of specified size and fill, or blank 2x2 for registry use
newfrom(INIT_FILL)
newfrom Matrix full of item input
Parameters:
INIT_FILL: item to fill (2x2) the matri and set type. a type(na) works
addrow(m, v)
addrow Add new row to matrix
Parameters:
m: matrix of type being added to
v: value of type being added to ( best leave NA on string for registry purposes)
addcolumn(matrix, value)
addcolumn
Parameters:
matrix: of type being added to
value: of type being added to ( best leave NA on string for registry purposes)
get(_VALS, _KEYREG, _GROUP, _KEY)
get Grabs value and returns single item
Parameters:
_VALS: Matrix Values slice
_KEYREG: Registry values matrix (strings)
_GROUP: name of group/category or int group key
_KEY: name of item to fetch from value registry or int key id
Returns: item
get(_VALS, _GROUP, _KEY)
get Grabs value and returns single item
Parameters:
_VALS: Matrix Values slice
_GROUP: name of group/category
_KEY: name of item to fetch from value registry
getgid(_KEYREG, _GROUP)
getgid
Parameters:
_KEYREG: Reg to pull group id from
_GROUP: group index int, or string name to get the other missing type
getkid(_KEYREG, _GROUP, _KEY)
getkid
Parameters:
_KEYREG: Reg to pull Key id from
_GROUP: group index int, or string name
_KEY: index of string key id to get it's ID int
getkey(_KEYREG, _GROUP, _KEY)
getkey
Parameters:
_KEYREG: Reg to pull Key id from
_GROUP: group index int, or string name for getting key string
_KEY: index of string key id to get it's match of other type
set(_VALS, _KEYREG, _GROUP, _KEY, _value)
set items to reg and matrix container
Parameters:
_VALS: Values matrix container
_KEYREG: Key registry
_GROUP: (string) Group/Category name
_KEY: (string) Key for item
_value: item
Returns: void
del(_VALS, _KEYREG, _GROUP, _KEY)
del grroup id
Parameters:
_VALS: Matrix Values slice
_KEYREG: Registry values matrix (strings)
_GROUP: name of group/category
_KEY: name of item to Delete from values and key
detached(_GROUP, _KEY, _VALUE)
detached make detached registry/val matrix
Parameters:
_GROUP: Name of first group
_KEY: Name of first item
_VALUE: Item of any type, sets the output type too.
pta_plotLibrary "pta_plot"
pta_plot: This library will help you to plot different value. I will keep updating with your requirement
print_array(array_id, border_color)
Display array element as a table.
Parameters:
array_id : Id of your array.
border_color : Color for border (`color.black` is used if no argument is supplied).
Returns: Display array element in bottom of the pane.
FunctionArrayUniqueLibrary "FunctionArrayUnique"
Method for retrieving the unique elements in a array.
for example would retrieve a array with ,
the elements retrieved will be sorted by its first seen index in
parent array.
note: float values have no precision option.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
unique(source)
method for retrieving the unique elements in a array.
Parameters:
source : array source array to extract elements.
Returns: array unique elements in the source array.
functionStringToMatrixLibrary "functionStringToMatrix"
Provides unbound methods (no error checking) to parse a string into a float or int matrix.
to_matrix_float(str, interval_sep, start_tk, end_tk)
Parse a string into a float matrix.
Parameters:
str : , string, the formated string to parse.
interval_sep : , string, cell interval separator token.
start_tk : , string, row start token.
end_tk : , string, row end token.
Returns: matrix, parsed float matrix.
to_matrix_int(str, interval_sep, start_tk, end_tk)
Parse a string into a int matrix.
Parameters:
str : , string, the formated string to parse.
interval_sep : , string, cell interval separator token.
start_tk : , string, row start token.
end_tk : , string, row end token.
Returns: matrix, parsed int matrix.
CyclicRsiLib█ OVERVIEW
This library is complementary for Cyclic RSI High Low With Noise Filter.
█ CREDITS
LoneSomeTheBlue
WhenToTrade
AlertFrequency()
: AlertFrequency
Parameters:
: : _string
Returns: : _freq
CyclicRSI()
: CyclicRSI
Parameters:
: : _source, _length, _expression
Returns: : osc
Credits to WhenToTrade
AddToZigzag()
: AddToZigzag
Parameters:
: : _id, value, max_array_size
Returns: : array.unshift, array.pop
Credits to LonesomeTheBlue
UpdateZigzag()
: UpdateZigzag
Parameters:
: : _id, value, max_array_size, dir
Returns: : AddToZigzag, array.set
Credits to LonesomeTheBlue
BoolZigzag()
: BoolZigzag
Parameters:
: : ph, pl, dirchanged, _id, dir
Returns: : AddToZigzag, UpdateZigzag
Credits to LonesomeTheBlue
NoiseSwitch()
: NoiseSwitch
Parameters:
: : _string, _id
Returns: : FilterNoise
LineGray()
: LineGray
Parameters:
: : _id
Returns: : LineGray
LabelDir()
: LabelDir
Parameters:
: : _id, _string, _color, _float
Returns: : LabelDir
TernaryLabel()
: TernaryLabel
Parameters:
: : _dir, _bool1, _bool2, _string1, _string2
Returns: : str_label
TernaryColor()
: TernaryColor
Parameters:
: : _dir, _bool1, _bool2
Returns: : col_label