TimeLockedMALibrary "TimeLockedMA"
Library & function(s) which generates a moving average that stays locked to users desired time preference.
TODO - Add functionality for more moving average types. IE: smooth, weighted etc...
Example:
time_locked_ma(close, length=1, timeframe='days', type='ema')
Will generate a 1 day exponential moving average that will stay consistent across all chart intervals.
Error Handling
On small time frames with large moving averages (IE: 1min chart with a 50 week moving average), you'll get a study error that says "(function "sma") references too many candles in history" .
To fix this, make sure you have timeframe="" as an indicator() header. Next, in the indicator settings, increase the timeframe from to a higher interval until the error goes away.
By default, it's set to "Chart". Bringing the interval up to 1hr will usually solve the issue.
Furthermore, adding timeframe_gaps=false to your indicator() header will give you an approximation of real-time values.
Misc Info
For time_lock_ma() setting type='na' will return the relative length value that adjusts dynamically to user's chart time interval.
This is good for plugging into other functions where a lookback or length is required. (IE: Bollinger Bands)
time_locked_ma(source, length, timeframe, type) Creates a moving average that is locked to a desired timeframe
Parameters:
source : float, Moving average source
length : int, Moving average length
timeframe : string, Desired timeframe. Use: "minutes", "hours", "days", "weeks", "months", "chart"
type : string, string Moving average type. Use "SMA" (default) or "EMA". Value of "NA" will return relative lookback length.
Returns: moving average that is locked to desired timeframe.
timeframe_convert(t, a, b) Converts timeframe to desired timeframe. From a --> b
Parameters:
t : int, Time interval
a : string, Time period
b : string, Time period to convert to
Returns: Converted timeframe value
chart_time(timeframe_period, timeframe_multiplier) Separates timeframe.period function and returns chart interval and period
Parameters:
timeframe_period : string, timeframe.period
timeframe_multiplier : int, timeframe.multiplier
Enjoy :)
MATH
FunctionGenerateRandomPointsInShapeLibrary "FunctionGenerateRandomPointsInShape"
Generate random vector points in geometric shape (parallelogram, triangle)
random_parallelogram(vector_a, vector_b) Generate random vector point in a parallelogram shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
random_triangle(vector_a, vector_b) Generate random vector point in a triangle shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
Punchline_LibLibrary "Punchline_Lib"
roundSmart(float) Truncates decimal points of a float value based on the amount of digits before the decimal point
Parameters:
float : _value any number
Returns: float
tostring_smart(float) converts a float to a string, intelligently cutting off decimal points
Parameters:
float : _value any number
Returns: string
FunctionNNLayerLibrary "FunctionNNLayer"
Generalized Neural Network Layer method.
function(inputs, weights, n_nodes, activation_function, bias, alpha, scale) Generalized Layer.
Parameters:
inputs : float array, input values.
weights : float array, weight values.
n_nodes : int, number of nodes in layer.
activation_function : string, default='sigmoid', name of the activation function used.
bias : float, default=1.0, bias to pass into activation function.
alpha : float, default=na, if required to pass into activation function.
scale : float, default=na, if required to pass into activation function.
Returns: float
FunctionNNPerceptronLibrary "FunctionNNPerceptron"
Perceptron Function for Neural networks.
function(inputs, weights, bias, activation_function, alpha, scale) generalized perceptron node for Neural Networks.
Parameters:
inputs : float array, the inputs of the perceptron.
weights : float array, the weights for inputs.
bias : float, default=1.0, the default bias of the perceptron.
activation_function : string, default='sigmoid', activation function applied to the output.
alpha : float, default=na, if required for activation.
scale : float, default=na, if required for activation.
@outputs float
InterpolationLibrary "Interpolation"
Functions for interpolating values. Can be useful in signal processing or applied as a sigmoid function.
linear(k, delta, offset, unbound) Returns the linear adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the line the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
quadIn(k, delta, offset, unbound) Returns the quadratic (easing-in) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
quadOut(k, delta, offset, unbound) Returns the quadratic (easing-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
quadInOut(k, delta, offset, unbound) Returns the quadratic (easing-in-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
cubicIn(k, delta, offset, unbound) Returns the cubic (easing-in) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
cubicOut(k, delta, offset, unbound) Returns the cubic (easing-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
cubicInOut(k, delta, offset, unbound) Returns the cubic (easing-in-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
expoIn(k, delta, offset, unbound) Returns the exponential (easing-in) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
expoOut(k, delta, offset, unbound) Returns the exponential (easing-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
expoInOut(k, delta, offset, unbound) Returns the exponential (easing-in-out) adjusted value.
Parameters:
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
using(fn, k, delta, offset, unbound) Returns the adjusted value by function name.
Parameters:
fn : The name of the function. Allowed values: linear, quadIn, quadOut, quadInOut, cubicIn, cubicOut, cubicInOut, expoIn, expoOut, expoInOut.
k : A number (float) from 0 to 1 representing where the on the curve the value is.
delta : The amount the value should change as k reaches 1.
offset : The start value.
unbound : When true, k values less than 0 or greater than 1 are still calculated. When false (default), k values less than 0 will return the offset value and values greater than 1 will return (offset + delta).
CRC.lib Log FunctionsLibrary "CRCLog"
default_params() Returns default high/low intercept/slope parameter values for Bitcoin that can be adjusted and used to calculate new Regression Log lines
log_regression() Returns set of (fib) spaced lines representing log regression (default values attempt fitted to INDEX:BTCUSD genesis-2021)
CRC.lib Bars - Bar FunctionsLibrary "CRCBars"
min_max(open, open) Get bar min (low) and max (high) price points
Parameters:
open : Open price data
open : Close price data
Returns:
is_bullish_bearish(open, open) Get bar bullish/bearish boolean signals
Parameters:
open : Open price data
open : Close price data
Returns:
sizes(open, open, open, open) Get bar sizes based on open/high/low/close data
Parameters:
open : Open price data
open : High price data
open : Low price data
open : Close price data
Returns:
options_expiration_and_strike_price_calculatorLibrary "options_expiration_and_strike_price_calculator"
TODO: add library description here
fun()
this is a library to help calculate options strike price and expiration that you can add to a script i use it mainly for symbol calulation to place orders to buy options on TD ameritrade so it will be set up to order options on TD ameritrade using json order placer and webhook it fills in the area in the json under symbol i suggest manually adding the year it should look like this is an example of an order to buy 10 call options using json through td ameritrade api
"complexOrderStrategyType": "NONE",
"orderType": "LIMIT",
"session": "NORMAL",
"price": "6.45",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection":
}
GenericTALibrary "GenericTA"
What is it?
The real generic library. Which means it is just covering most built-in indicators / functions, but with more parameters, so the user don't have to write more few lines to achieve something simple and replicative.
Development process?
Will tidy it up, and setting up in later stage.
Welcome to inbox me to improve the library ------
If you are finding a similar thing. That's a good news. Because I am making it.
FFTLibraryLibrary "FFTLibrary" contains a function for performing Fast Fourier Transform (FFT) along with a few helper functions. In general, FFT is defined for complex inputs and outputs. The real and imaginary parts of formally complex data are treated as separate arrays (denoted as x and y). For real-valued data, the array of imaginary parts should be filled with zeros.
FFT function
fft(x, y, dir) : Computes the one-dimensional discrete Fourier transform using an in-place complex-to-complex FFT algorithm . Note: The transform also produces a mirror copy of the frequency components, which correspond to the signal's negative frequencies.
Parameters:
x : float array, real part of the data, array size must be a power of 2
y : float array, imaginary part of the data, array size must be the same as x ; for real-valued input, y must be an array of zeros
dir : string, options = , defines the direction of the transform: forward" (time-to-frequency) or inverse (frequency-to-time)
Returns: x, y : tuple (float array, float array), real and imaginary parts of the transformed data (original x and y are changed on output)
Helper functions
fftPower(x, y) : Helper function that computes the power of each frequency component (in other words, Fourier amplitudes squared).
Parameters:
x : float array, real part of the Fourier amplitudes
y : float array, imaginary part of the Fourier amplitudes
Returns: power : float array of the same length as x and y , Fourier amplitudes squared
fftFreq(N) : Helper function that returns the FFT sample frequencies defined in cycles per timeframe unit. For example, if the timeframe is 5m, the frequencies are in cycles/(5 minutes).
Parameters:
N : int, window length (number of points in the transformed dataset)
Returns: freq : float array of N, contains the sample frequencies (with zero at the start).
FunctionArrayReduceLibrary "FunctionArrayReduce"
A limited method to reduce a array using a mathematical formula.
float_(formula, samples, arguments, initial_value) Method to reduce a array using a mathematical formula.
Parameters:
formula : string, the mathematical formula, accepts some default name codes (index, output, previous, current, integer index of arguments array).
samples : float array, the data to process.
arguments : float array, the extra arguments of the formula.
initial_value : float, default=0, a initial base value for the process.
Returns: float.
Notes:
** if initial value is specified as "na" it will default to the first element of samples.
FunctionProbabilityDistributionSamplingLibrary "FunctionProbabilityDistributionSampling"
Methods for probability distribution sampling selection.
sample(probabilities) Computes a random selected index from a probability distribution.
Parameters:
probabilities : float array, probabilities of sample.
Returns: int.
FunctionElementsInArrayLibrary "FunctionElementsInArray"
Methods to count number of elements in arrays
count_float(sample, value) Counts the number of elements equal to provided value in array.
Parameters:
sample : float array, sample data to process.
value : float value to check for equality.
Returns: int.
count_int(sample, value) Counts the number of elements equal to provided value in array.
Parameters:
sample : int array, sample data to process.
value : int value to check for equality.
Returns: int.
count_string(sample, value) Counts the number of elements equal to provided value in array.
Parameters:
sample : string array, sample data to process.
value : string value to check for equality.
Returns: int.
count_bool(sample, value) Counts the number of elements equal to provided value in array.
Parameters:
sample : bool array, sample data to process.
value : bool value to check for equality.
Returns: int.
count_color(sample, value) Counts the number of elements equal to provided value in array.
Parameters:
sample : color array, sample data to process.
value : color value to check for equality.
Returns: int.
extract_indices_float(sample, value) Counts the number of elements equal to provided value in array, and returns its indices.
Parameters:
sample : float array, sample data to process.
value : float value to check for equality.
Returns: int.
extract_indices_int(sample, value) Counts the number of elements equal to provided value in array, and returns its indices.
Parameters:
sample : int array, sample data to process.
value : int value to check for equality.
Returns: int.
extract_indices_string(sample, value) Counts the number of elements equal to provided value in array, and returns its indices.
Parameters:
sample : string array, sample data to process.
value : string value to check for equality.
Returns: int.
extract_indices_bool(sample, value) Counts the number of elements equal to provided value in array, and returns its indices.
Parameters:
sample : bool array, sample data to process.
value : bool value to check for equality.
Returns: int.
extract_indices_color(sample, value) Counts the number of elements equal to provided value in array, and returns its indices.
Parameters:
sample : color array, sample data to process.
value : color value to check for equality.
Returns: int.
LinearRegressionLibraryLibrary "LinearRegressionLibrary" contains functions for fitting a regression line to the time series by means of different models, as well as functions for estimating the accuracy of the fit.
Linear regression algorithms:
RepeatedMedian(y, n, lastBar) applies repeated median regression (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
mSlope :: float, slope of the regression line
mInter :: float, intercept of the regression line
TheilSen(y, n, lastBar) applies the Theil-Sen estimator (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
tsSlope :: float, slope of the regression line
tsInter :: float, intercept of the regression line
OrdinaryLeastSquares(y, n, lastBar) applies the ordinary least squares regression (non-robust) to the input time series within the selected interval.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
olsSlope :: float, slope of the regression line
olsInter :: float, intercept of the regression line
Model performance metrics:
metricRMSE(y, n, lastBar, slope, intercept) returns the Root-Mean-Square Error (RMSE) of the regression. The better the model, the lower the RMSE.
Parameters:
y :: float series, source time series (e.g. close)
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
rmse :: float, RMSE value
metricMAE(y, n, lastBar, slope, intercept) returns the Mean Absolute Error (MAE) of the regression. MAE is is similar to RMSE but is less sensitive to outliers. The better the model, the lower the MAE.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
mae :: float, MAE value
metricR2(y, n, lastBar, slope, intercept) returns the coefficient of determination (R squared) of the regression. The better the linear regression fits the data (compared to the sample mean), the closer the value of the R squared is to 1.
Parameters:
y :: float series, source time series
n :: integer, the length of the selected time interval
lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
slope :: float, slope of the evaluated linear regression line
intercept :: float, intercept of the evaluated linear regression line
Output:
Rsq :: float, R-sqared score
Usage example:
//@version=5
indicator('ExampleLinReg', overlay=true)
// import the library
import tbiktag/LinearRegressionLibrary/1 as linreg
// define the studied interval: last 100 bars
int Npoints = 100
int lastBar = bar_index
int firstBar = bar_index - Npoints
// apply repeated median regression to the closing price time series within the specified interval
{square bracket}slope, intercept{square bracket} = linreg.RepeatedMedian(close, Npoints, lastBar)
// calculate the root-mean-square error of the obtained linear fit
rmse = linreg.metricRMSE(close, Npoints, lastBar, slope, intercept)
// plot the line and print the RMSE value
float y1 = intercept
float y2 = intercept + slope * (Npoints - 1)
if barstate.islast
{indent} line.new(firstBar,y1, lastBar,y2)
{indent} label.new(lastBar,y2,text='RMSE = '+str.format("{0,number,#.#}", rmse))
FunctionCompoundInterestLibrary "FunctionCompoundInterest"
Method for compound interest.
simple_compound(principal, rate, duration) Computes compound interest for given duration.
Parameters:
principal : float, the principal or starting value.
rate : float, the rate of interest.
duration : float, the period of growth.
Returns: float.
variable_compound(principal, rates, duration) Computes variable compound interest for given duration.
Parameters:
principal : float, the principal or starting value.
rates : float array, the rates of interest.
duration : int, the period of growth.
Returns: float array.
simple_compound_array(principal, rates, duration) Computes variable compound interest for given duration.
Parameters:
principal : float, the principal or starting value.
rates : float array, the rates of interest.
duration : int, the period of growth.
Returns: float array.
variable_compound_array(principal, rates, duration) Computes variable compound interest for given duration.
Parameters:
principal : float, the principal or starting value.
rates : float array, the rates of interest.
duration : int, the period of growth.
Returns: float array.
FunctionSMCMCLibrary "FunctionSMCMC"
Methods to implement Markov Chain Monte Carlo Simulation (MCMC)
markov_chain(weights, actions, target_path, position, last_value) a basic implementation of the markov chain algorithm
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
target_path : float array, target path array.
position : int, index of the path.
last_value : float, base value to increment.
Returns: void, updates target array
mcmc(weights, actions, start_value, n_iterations) uses a monte carlo algorithm to simulate a markov chain at each step.
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
start_value : float, base value to start simulation.
n_iterations : integer, number of iterations to run.
Returns: float array with path.
LibraryPrivateUsage001This is a public library that include the functions explained below. The libraries are considered public domain code and permission is not required from the author if you reuse these functions in your open-source scripts
LibraryCheckNthBarLibrary "LibraryCheckNthBar"
TODO: add library description here
canwestart(UTC, prd) this function can be used if current bar is in last Nth bar
Parameters:
UTC : is UTC of the chart
prd : is the length of last Nth bar
Returns: true if the current bar is in N bar
FunctionDecisionTreeLibrary "FunctionDecisionTree"
Method to generate decision tree based on weights.
decision_tree(weights, depth) Method to generate decision tree based on weights.
Parameters:
weights : float array, weights for decision consideration.
depth : int, depth of the tree.
Returns: int array
FunctionDaysInMonthLibrary "FunctionDaysInMonth"
Method to find the number of days in a given month of year.
days_in_month(year, month) Method to find the number of days in a given month of year.
Parameters:
year : int, year of month, so we know if year is a leap year or not.
month : int, month number.
Returns: int
FunctionForecastLinearLibrary "FunctionForecastLinear"
Method for linear Forecast, same as found in excel and other sheet packages.
forecast(sample_x, sample_y, target_x) linear forecast method.
Parameters:
sample_x : float array, sample data X value.
sample_y : float array, sample data Y value.
target_x : float, target X to get Y forecast value.
Returns: float
FunctionBoxCoxTransformLibrary "FunctionBoxCoxTransform"
Methods to compute the Box-Cox Transformer.
regular(sample, lambda) Regular transform.
Parameters:
sample : float array, sample data values.
lambda : float, scaling factor.
Returns: float array.
inverse(sample, lambda) Regular transform.
Parameters:
sample : float array, sample data values.
lambda : float, scaling factor.
Returns: float array.