biased_price_targetLibrary "biased_price_target"
Collection of functions that can be used for the calculation of biased price targets like stop loss and
take profit from a reference price using several methods that are already provided by the "distance_ratio" library plus
the 'HHLL'. Methods supported are percentagewise (PERC), atr-based (ATR), fixed profit (PROF), tick-based (TICKS),
risk reward ratio (RR), and highest high/lowest low (HHLL)
MATH
Mad_StandardpartsLibrary "Mad_Standardparts"
This are my Standardparts used in upcoming scipts
roundTo(_value, _decimals)
Round a floating point value to a specified number of decimal places.
@description This function takes a floating point value and rounds it to a specified number of decimal places.
Parameters:
_value (float) : The floating point value to be rounded.
_decimals (int) : The number of decimal places to round to. Must be a non-negative integer.
Returns: The rounded value, as a floating point number.
clear_all()
Delete all drawings on the chart.
@description This function deletes all drawings on the chart, including lines, boxes, and labels.
Returns: None.
shifting(_value)
Create a string of spaces to shift text over by a specified amount.
@description This function takes an integer value and returns a string consisting of that many spaces, which can be used to shift text over in a PineScript chart.
Parameters:
_value (int) : The number of spaces to create in the output string.
Returns: A string consisting of the specified number of spaces.
fromLog(_value)
Convert a linear value to a logarithmic value.
@description This function takes a linear value and converts it to a logarithmic value, using the formula specified in the code.
Parameters:
_value (float)
Returns: The corresponding logarithmic value, as a floating point number.
toLog(_value)
Convert a logarithmic value to a linear value.
@description This function takes a logarithmic value and converts it to a linear value, using the formula specified in the code.
Parameters:
_value (float)
Returns: The corresponding linear value, as a floating point number.
f_getbartime()
Calculate the time per bar on the chart.
@description This function calculates the time per bar on the chart based on the first 100 bars.
Returns: The time per bar, as an integer value.
BenfordsLawLibrary "BenfordsLaw"
Methods to deal with Benford's law which states that a distribution of first and higher order digits
of numerical strings has a characteristic pattern.
"Benford's law is an observation about the leading digits of the numbers found in real-world data sets.
Intuitively, one might expect that the leading digits of these numbers would be uniformly distributed so that
each of the digits from 1 to 9 is equally likely to appear. In fact, it is often the case that 1 occurs more
frequently than 2, 2 more frequently than 3, and so on. This observation is a simplified version of Benford's law.
More precisely, the law gives a prediction of the frequency of leading digits using base-10 logarithms that
predicts specific frequencies which decrease as the digits increase from 1 to 9." ~(2)
---
reference:
- 1: en.wikipedia.org
- 2: brilliant.org
- 4: github.com
cumsum_difference(a, b)
Calculate the cumulative sum difference of two arrays of same size.
Parameters:
a (float ) : `array` List of values.
b (float ) : `array` List of values.
Returns: List with CumSum Difference between arrays.
fractional_int(number)
Transform a floating number including its fractional part to integer form ex:. `1.2345 -> 12345`.
Parameters:
number (float) : `float` The number to transform.
Returns: Transformed number.
split_to_digits(number, reverse)
Transforms a integer number into a list of its digits.
Parameters:
number (int) : `int` Number to transform.
reverse (bool) : `bool` `default=true`, Reverse the order of the digits, if true, last will be first.
Returns: Transformed number digits list.
digit_in(number, digit)
Digit at index.
Parameters:
number (int) : `int` Number to parse.
digit (int) : `int` `default=0`, Index of digit.
Returns: Digit found at the index.
digits_from(data, dindex)
Process a list of `int` values and get the list of digits.
Parameters:
data (int ) : `array` List of numbers.
dindex (int) : `int` `default=0`, Index of digit.
Returns: List of digits at the index.
digit_counters(digits)
Score digits.
Parameters:
digits (int ) : `array` List of digits.
Returns: List of counters per digit (1-9).
digit_distribution(counters)
Calculates the frequency distribution based on counters provided.
Parameters:
counters (int ) : `array` List of counters, must have size(9).
Returns: Distribution of the frequency of the digits.
digit_p(digit)
Expected probability for digit according to Benford.
Parameters:
digit (int) : `int` Digit number reference in range `1 -> 9`.
Returns: Probability of digit according to Benford's law.
benfords_distribution()
Calculated Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
benfords_distribution_aprox()
Aproximate Expected distribution per digit according to Benford's Law.
Returns: List with the expected distribution.
test_benfords(digits, calculate_benfords)
Tests Benford's Law on provided list of digits.
Parameters:
digits (int ) : `array` List of digits.
calculate_benfords (bool)
Returns: Tuple with:
- Counters: Score of each digit.
- Sample distribution: Frequency for each digit.
- Expected distribution: Expected frequency according to Benford's.
- Cumulative Sum of difference:
to_table(digits, _text_color, _border_color, _frame_color)
Parameters:
digits (int )
_text_color (color)
_border_color (color)
_frame_color (color)
MathEasingFunctionsLibrary "MathEasingFunctions"
A collection of Easing functions.
Easing functions are commonly used for smoothing actions over time, They are used to smooth out the sharp edges
of a function and make it more pleasing to the eye, like for example the motion of a object through time.
Easing functions can be used in a variety of applications, including animation, video games, and scientific
simulations. They are a powerful tool for creating realistic visual effects and can help to make your work more
engaging and enjoyable to the eye.
---
Includes functions for ease in, ease out, and, ease in and out, for the following constructs:
sine, quadratic, cubic, quartic, quintic, exponential, elastic, circle, back, bounce.
---
Reference:
easings.net
learn.microsoft.com
ease_in_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_sine_unbound(v)
Sinusoidal function, the position over elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_sine(v)
Sinusoidal function, the position over elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quad_unbound(v)
Quadratic function, the position equals the square of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quad(v)
Quadratic function, the position equals the square of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_cubic_unbound(v)
Cubic function, the position equals the cube of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_cubic(v)
Cubic function, the position equals the cube of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quart_unbound(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quart(v)
Quartic function, the position equals the formula `f(t)=t^4` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quint_unbound(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_quint(v)
Quintic function, the position equals the formula `f(t)=t^5` of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_expo_unbound(v)
Exponential function, the position equals the exponential formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_expo(v)
Exponential function, the position equals the exponential formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_circ_unbound(v)
Circular function, the position equals the circular formula of elapsed time (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_circ(v)
Circular function, the position equals the circular formula of elapsed time (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_back_unbound(v)
Back function, the position retreats a bit before resuming (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_back(v)
Back function, the position retreats a bit before resuming (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_elastic_unbound(v)
Elastic function, the position oscilates back and forth like a spring (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_elastic(v)
Elastic function, the position oscilates back and forth like a spring (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_out_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_bounce_unbound(v)
Bounce function, the position bonces from the boundery (unbound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
ease_in_out_bounce(v)
Bounce function, the position bonces from the boundery (bound).
Parameters:
v (float) : `float` Elapsed time.
Returns: Ratio of change.
select(v, formula, effect, bounded)
Parameters:
v (float)
formula (string)
effect (string)
bounded (bool)
UtilityLibrary "Utility"
dema(src, length)
Parameters:
src (float)
length (simple int)
tema(src, length)
Parameters:
src (float)
length (simple int)
hma(src, length)
Parameters:
src (float)
length (int)
zlema(src, length)
Parameters:
src (float)
length (simple int)
stochRSI(src, lengthRSI, lengthStoch, smoothK, smoothD)
Parameters:
src (float)
lengthRSI (simple int)
lengthStoch (int)
smoothK (int)
smoothD (int)
slope(src, length)
Parameters:
src (float)
length (int)
loxxfftLibrary "loxxfft"
This code is a library for performing Fast Fourier Transform (FFT) operations. FFT is an algorithm that can quickly compute the discrete Fourier transform (DFT) of a sequence. The library includes functions for performing FFTs on both real and complex data. It also includes functions for fast correlation and convolution, which are operations that can be performed efficiently using FFTs. Additionally, the library includes functions for fast sine and cosine transforms.
Reference:
www.alglib.net
fastfouriertransform(a, nn, inversefft)
Returns Fast Fourier Transform
Parameters:
a (float ) : float , An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
nn (int) : int, The number of function values. It must be a power of two, but the algorithm does not validate this.
inversefft (bool) : bool, A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
Returns: float , Modifies the input array a in-place, which means that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution. The transformed data will have real and imaginary parts interleaved, with the real parts at even indices and the imaginary parts at odd indices.
realfastfouriertransform(a, tnn, inversefft)
Returns Real Fast Fourier Transform
Parameters:
a (float ) : float , A float array containing the real-valued function samples.
tnn (int) : int, The number of function values (must be a power of 2, but the algorithm does not validate this condition).
inversefft (bool) : bool, A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
Returns: float , Modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
fastsinetransform(a, tnn, inversefst)
Returns Fast Discrete Sine Conversion
Parameters:
a (float ) : float , An array of real numbers representing the function values.
tnn (int) : int, Number of function values (must be a power of two, but the code doesn't validate this).
inversefst (bool) : bool, A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
Returns: float , The output is the transformed array 'a', which will contain the result of the transformation.
fastcosinetransform(a, tnn, inversefct)
Returns Fast Discrete Cosine Transform
Parameters:
a (float ) : float , This is a floating-point array representing the sequence of values (time-domain) that you want to transform. The function will perform the Fast Cosine Transform (FCT) or the inverse FCT on this input array, depending on the value of the inversefct parameter. The transformed result will also be stored in this same array, which means the function modifies the input array in-place.
tnn (int) : int, This is an integer value representing the number of data points in the input array a. It is used to determine the size of the input array and control the loops in the algorithm. Note that the size of the input array should be a power of 2 for the Fast Cosine Transform algorithm to work correctly.
inversefct (bool) : bool, This is a boolean value that controls whether the function performs the regular Fast Cosine Transform or the inverse FCT. If inversefct is set to true, the function will perform the inverse FCT, and if set to false, the regular FCT will be performed. The inverse FCT can be used to transform data back into its original form (time-domain) after the regular FCT has been applied.
Returns: float , The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
fastconvolution(signal, signallen, response, negativelen, positivelen)
Convolution using FFT
Parameters:
signal (float ) : float , This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
response (float ) : float , This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
negativelen (int) : int, This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
positivelen (int) : int, This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
Returns: float , The resulting convolved values are stored back in the input signal array.
fastcorrelation(signal, signallen, pattern, patternlen)
Returns Correlation using FFT
Parameters:
signal (float ) : float ,This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
signallen (int) : int, This is an integer representing the length of the input signal array.
pattern (float ) : float , This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
patternlen (int) : int, This is an integer representing the length of the pattern array.
Returns: float , The signal array containing the correlation values at points from 0 to SignalLen-1.
tworealffts(a1, a2, a, b, tn)
Returns Fast Fourier Transform of Two Real Functions
Parameters:
a1 (float ) : float , An array of real numbers, representing the values of the first function.
a2 (float ) : float , An array of real numbers, representing the values of the second function.
a (float ) : float , An output array to store the Fourier transform of the first function.
b (float ) : float , An output array to store the Fourier transform of the second function.
tn (int) : float , An integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
Returns: float , The a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Detailed explaination of each function
Fast Fourier Transform
The fastfouriertransform() function takes three input parameters:
1. a: An array of real and imaginary parts of the function values. The real part is stored at even indices, and the imaginary part is stored at odd indices.
2. nn: The number of function values. It must be a power of two, but the algorithm does not validate this.
3. inversefft: A boolean value that indicates the direction of the transformation. If True, it performs the inverse FFT; if False, it performs the direct FFT.
The function performs the FFT using the Cooley-Tukey algorithm, which is an efficient algorithm for computing the discrete Fourier transform (DFT) and its inverse. The Cooley-Tukey algorithm recursively breaks down the DFT of a sequence into smaller DFTs of subsequences, leading to a significant reduction in computational complexity. The algorithm's time complexity is O(n log n), where n is the number of samples.
The fastfouriertransform() function first initializes variables and determines the direction of the transformation based on the inversefft parameter. If inversefft is True, the isign variable is set to -1; otherwise, it is set to 1.
Next, the function performs the bit-reversal operation. This is a necessary step before calculating the FFT, as it rearranges the input data in a specific order required by the Cooley-Tukey algorithm. The bit-reversal is performed using a loop that iterates through the nn samples, swapping the data elements according to their bit-reversed index.
After the bit-reversal operation, the function iteratively computes the FFT using the Cooley-Tukey algorithm. It performs calculations in a loop that goes through different stages, doubling the size of the sub-FFT at each stage. Within each stage, the Cooley-Tukey algorithm calculates the butterfly operations, which are mathematical operations that combine the results of smaller DFTs into the final DFT. The butterfly operations involve complex number multiplication and addition, updating the input array a with the computed values.
The loop also calculates the twiddle factors, which are complex exponential factors used in the butterfly operations. The twiddle factors are calculated using trigonometric functions, such as sine and cosine, based on the angle theta. The variables wpr, wpi, wr, and wi are used to store intermediate values of the twiddle factors, which are updated in each iteration of the loop.
Finally, if the inversefft parameter is True, the function divides the result by the number of samples nn to obtain the correct inverse FFT result. This normalization step is performed using a loop that iterates through the array a and divides each element by nn.
In summary, the fastfouriertransform() function is an implementation of the Cooley-Tukey FFT algorithm, which is an efficient algorithm for computing the DFT and its inverse. This FFT library can be used for a variety of applications, such as signal processing, image processing, audio processing, and more.
Feal Fast Fourier Transform
The realfastfouriertransform() function performs a fast Fourier transform (FFT) specifically for real-valued functions. The FFT is an efficient algorithm used to compute the discrete Fourier transform (DFT) and its inverse, which are fundamental tools in signal processing, image processing, and other related fields.
This function takes three input parameters:
1. a - A float array containing the real-valued function samples.
2. tnn - The number of function values (must be a power of 2, but the algorithm does not validate this condition).
3. inversefft - A boolean flag that indicates the direction of the transformation (True for inverse, False for direct).
The function modifies the input array a in-place, meaning that the transformed data (the FFT result for direct transformation or the inverse FFT result for inverse transformation) will be stored in the same array a after the function execution.
The algorithm uses a combination of complex-to-complex FFT and additional transformations specific to real-valued data to optimize the computation. It takes into account the symmetry properties of the real-valued input data to reduce the computational complexity.
Here's a detailed walkthrough of the algorithm:
1. Depending on the inversefft flag, the initial values for ttheta, c1, and c2 are determined. These values are used for the initial data preprocessing and post-processing steps specific to the real-valued FFT.
2. The preprocessing step computes the initial real and imaginary parts of the data using a combination of sine and cosine terms with the input data. This step effectively converts the real-valued input data into complex-valued data suitable for the complex-to-complex FFT.
3. The complex-to-complex FFT is then performed on the preprocessed complex data. This involves bit-reversal reordering, followed by the Cooley-Tukey radix-2 decimation-in-time algorithm. This part of the code is similar to the fastfouriertransform() function you provided earlier.
4. After the complex-to-complex FFT, a post-processing step is performed to obtain the final real-valued output data. This involves updating the real and imaginary parts of the transformed data using sine and cosine terms, as well as the values c1 and c2.
5. Finally, if the inversefft flag is True, the output data is divided by the number of samples (nn) to obtain the inverse DFT.
The function does not return a value explicitly. Instead, the transformed data is stored in the input array a. After the function execution, you can access the transformed data in the a array, which will have the real part at even indices and the imaginary part at odd indices.
Fast Sine Transform
This code defines a function called fastsinetransform that performs a Fast Discrete Sine Transform (FST) on an array of real numbers. The function takes three input parameters:
1. a (float array): An array of real numbers representing the function values.
2. tnn (int): Number of function values (must be a power of two, but the code doesn't validate this).
3. inversefst (bool): A boolean flag indicating the direction of the transformation. If True, it performs the inverse FST, and if False, it performs the direct FST.
The output is the transformed array 'a', which will contain the result of the transformation.
The code starts by initializing several variables, including trigonometric constants for the sine transform. It then sets the first value of the array 'a' to 0 and calculates the initial values of 'y1' and 'y2', which are used to update the input array 'a' in the following loop.
The first loop (with index 'jx') iterates from 2 to (tm + 1), where 'tm' is half of the number of input samples 'tnn'. This loop is responsible for calculating the initial sine transform of the input data.
The second loop (with index 'ii') is a bit-reversal loop. It reorders the elements in the array 'a' based on the bit-reversed indices of the original order.
The third loop (with index 'ii') iterates while 'n' is greater than 'mmax', which starts at 2 and doubles each iteration. This loop performs the actual Fast Discrete Sine Transform. It calculates the sine transform using the Danielson-Lanczos lemma, which is a divide-and-conquer strategy for calculating Discrete Fourier Transforms (DFTs) efficiently.
The fourth loop (with index 'ix') is responsible for the final phase adjustments needed for the sine transform, updating the array 'a' accordingly.
The fifth loop (with index 'jj') updates the array 'a' one more time by dividing each element by 2 and calculating the sum of the even-indexed elements.
Finally, if the 'inversefst' flag is True, the code scales the transformed data by a factor of 2/tnn to get the inverse Fast Sine Transform.
In summary, the code performs a Fast Discrete Sine Transform on an input array of real numbers, either in the direct or inverse direction, and returns the transformed array. The algorithm is based on the Danielson-Lanczos lemma and uses a divide-and-conquer strategy for efficient computation.
Fast Cosine Transform
This code defines a function called fastcosinetransform that takes three parameters: a floating-point array a, an integer tnn, and a boolean inversefct. The function calculates the Fast Cosine Transform (FCT) or the inverse FCT of the input array, depending on the value of the inversefct parameter.
The Fast Cosine Transform is an algorithm that converts a sequence of values (time-domain) into a frequency domain representation. It is closely related to the Fast Fourier Transform (FFT) and can be used in various applications, such as signal processing and image compression.
Here's a detailed explanation of the code:
1. The function starts by initializing a number of variables, including counters, intermediate values, and constants.
2. The initial steps of the algorithm are performed. This includes calculating some trigonometric values and updating the input array a with the help of intermediate variables.
3. The code then enters a loop (from jx = 2 to tnn / 2). Within this loop, the algorithm computes and updates the elements of the input array a.
4. After the loop, the function prepares some variables for the next stage of the algorithm.
5. The next part of the algorithm is a series of nested loops that perform the bit-reversal permutation and apply the FCT to the input array a.
6. The code then calculates some additional trigonometric values, which are used in the next loop.
7. The following loop (from ix = 2 to tnn / 4 + 1) computes and updates the elements of the input array a using the previously calculated trigonometric values.
8. The input array a is further updated with the final calculations.
9. In the last loop (from j = 4 to tnn), the algorithm computes and updates the sum of elements in the input array a.
10. Finally, if the inversefct parameter is set to true, the function scales the input array a to obtain the inverse FCT.
The resulting transformed array is stored in the input array a. This means that the function modifies the input array in-place and does not return a new array.
Fast Convolution
This code defines a function called fastconvolution that performs the convolution of a given signal with a response function using the Fast Fourier Transform (FFT) technique. Convolution is a mathematical operation used in signal processing to combine two signals, producing a third signal representing how the shape of one signal is modified by the other.
The fastconvolution function takes the following input parameters:
1. float signal: This is an array of real numbers representing the input signal that will be convolved with the response function. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array. It specifies the number of elements in the signal array.
3. float response: This is an array of real numbers representing the response function used for convolution. The response function consists of two parts: one corresponding to positive argument values and the other to negative argument values. Array elements with numbers from 0 to NegativeLen match the response values at points from -NegativeLen to 0, respectively. Array elements with numbers from NegativeLen+1 to NegativeLen+PositiveLen correspond to the response values in points from 1 to PositiveLen, respectively.
4. int negativelen: This is an integer representing the "negative length" of the response function. It indicates the number of elements in the response function array that correspond to negative argument values. Outside the range , the response function is considered zero.
5. int positivelen: This is an integer representing the "positive length" of the response function. It indicates the number of elements in the response function array that correspond to positive argument values. Similar to negativelen, outside the range , the response function is considered zero.
The function works by:
1. Calculating the length nl of the arrays used for FFT, ensuring it's a power of 2 and large enough to hold the signal and response.
2. Creating two new arrays, a1 and a2, of length nl and initializing them with the input signal and response function, respectively.
3. Applying the forward FFT (realfastfouriertransform) to both arrays, a1 and a2.
4. Performing element-wise multiplication of the FFT results in the frequency domain.
5. Applying the inverse FFT (realfastfouriertransform) to the multiplied results in a1.
6. Updating the original signal array with the convolution result, which is stored in the a1 array.
The result of the convolution is stored in the input signal array at the function exit.
Fast Correlation
This code defines a function called fastcorrelation that computes the correlation between a signal and a pattern using the Fast Fourier Transform (FFT) method. The function takes four input arguments and modifies the input signal array to store the correlation values.
Input arguments:
1. float signal: This is an array of real numbers representing the signal to be correlated with the pattern. The elements are numbered from 0 to SignalLen-1.
2. int signallen: This is an integer representing the length of the input signal array.
3. float pattern: This is an array of real numbers representing the pattern to be correlated with the signal. The elements are numbered from 0 to PatternLen-1.
4. int patternlen: This is an integer representing the length of the pattern array.
The function performs the following steps:
1. Calculate the required size nl for the FFT by finding the smallest power of 2 that is greater than or equal to the sum of the lengths of the signal and the pattern.
2. Create two new arrays a1 and a2 with the length nl and initialize them to 0.
3. Copy the signal array into a1 and pad it with zeros up to the length nl.
4. Copy the pattern array into a2 and pad it with zeros up to the length nl.
5. Compute the FFT of both a1 and a2.
6. Perform element-wise multiplication of the frequency-domain representation of a1 and the complex conjugate of the frequency-domain representation of a2.
7. Compute the inverse FFT of the result obtained in step 6.
8. Store the resulting correlation values in the original signal array.
At the end of the function, the signal array contains the correlation values at points from 0 to SignalLen-1.
Fast Fourier Transform of Two Real Functions
This code defines a function called tworealffts that computes the Fast Fourier Transform (FFT) of two real-valued functions (a1 and a2) using a Cooley-Tukey-based radix-2 Decimation in Time (DIT) algorithm. The FFT is a widely used algorithm for computing the discrete Fourier transform (DFT) and its inverse.
Input parameters:
1. float a1: an array of real numbers, representing the values of the first function.
2. float a2: an array of real numbers, representing the values of the second function.
3. float a: an output array to store the Fourier transform of the first function.
4. float b: an output array to store the Fourier transform of the second function.
5. int tn: an integer representing the number of function values. It must be a power of two, but the algorithm doesn't validate this condition.
The function performs the following steps:
1. Combine the two input arrays, a1 and a2, into a single array a by interleaving their elements.
2. Perform a 1D FFT on the combined array a using the radix-2 DIT algorithm.
3. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
Here is a detailed breakdown of the radix-2 DIT algorithm used in this code:
1. Bit-reverse the order of the elements in the combined array a.
2. Initialize the loop variables mmax, istep, and theta.
3. Enter the main loop that iterates through different stages of the FFT.
a. Compute the sine and cosine values for the current stage using the theta variable.
b. Initialize the loop variables wr and wi for the current stage.
c. Enter the inner loop that iterates through the butterfly operations within each stage.
i. Perform the butterfly operation on the elements of array a.
ii. Update the loop variables wr and wi for the next butterfly operation.
d. Update the loop variables mmax, istep, and theta for the next stage.
4. Separate the FFT results of the two input functions from the combined array a and store them in output arrays a and b.
At the end of the function, the a and b arrays will contain the Fourier transform of the first and second functions, respectively. Note that the function overwrites the input arrays a and b.
█ Example scripts using functions contained in loxxfft
Real-Fast Fourier Transform of Price w/ Linear Regression
Real-Fast Fourier Transform of Price Oscillator
Normalized, Variety, Fast Fourier Transform Explorer
Variety RSI of Fast Discrete Cosine Transform
STD-Stepped Fast Cosine Transform Moving Average
peterzorve-libraryLibrary "library"
is_bullish_engulfing()
is_bearish_engulfing()
is_hammer(fib_level)
Parameters:
fib_level (float)
is_shooting_star(fib_level)
Parameters:
fib_level (float)
is_hammer_and_star(fib_level)
Parameters:
fib_level (float)
is_star_and_hammer(fib_level)
Parameters:
fib_level (float)
is_dogi(dogi_body_ratio)
Parameters:
dogi_body_ratio (float)
is_bear_bear_bullish_engulf()
is_atr_stoploss_takeprofit(atr_multiplier, atr_length, reward_ratio)
Parameters:
atr_multiplier (float)
atr_length (simple int)
reward_ratio (float)
is_fixed_stoploss_takeprofit(stoploss_pips, reward_ratio)
Parameters:
stoploss_pips (float)
reward_ratio (float)
is_step_trailing_stoploss(stoploss_pips)
Parameters:
stoploss_pips (float)
is_atr_trailing_stoploss(atr_multiplier, break_even_pip)
Parameters:
atr_multiplier (float)
break_even_pip (int)
is_pull_back_strategy(length)
Parameters:
length (simple int)
is_trade_statistics(condition, entrypoint, stoploss, takeprofit)
Parameters:
condition (bool)
entrypoint (float)
stoploss (float)
takeprofit (float)
is_table_of_statistics(win_trades, lost_trades, even_trades, pips_won, pips_lost)
Parameters:
win_trades (int)
lost_trades (int)
even_trades (int)
pips_won (float)
pips_lost (float)
is_pine_info(lotsize, stoploss, takeprofit)
Parameters:
lotsize (float)
stoploss (float)
takeprofit (float)
is_support_and_resistance_strategy(look_back, look_forward)
Parameters:
look_back (int)
look_forward (int)
is_choral_strategy(smoothing_period, constant_d)
Parameters:
smoothing_period (int)
constant_d (float)
is_bollinger_band_strategy(length, dev_entry, dev_stoploss, dev_takeprofit)
Parameters:
length (int)
dev_entry (simple float)
dev_stoploss (simple float)
dev_takeprofit (simple float)
LibAndyLibrary "LibAndy"
TODO: add library description here
greencandlme(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
greencandle()
Whether this candle is green or not
Returns: Whether this candle is green or not
redcandle()
Whether this candle is red or not
Returns: Whether this candle is red or not
boostrapSeries(bsSeries)
Parameters:
bsSeries (float)
PolynomialLibrary "Polynomial"
TODO: add library description here
PolyNomial(Dop, n, step, nonp)
TODO: add function description here
Parameters:
Dop (int)
n (int)
step (int)
nonp (int)
Returns: TODO: add what function returns
AstroLibLibrary "AstroLib", or Astro Library, is a collection of public Pinescript functions & calculations for use in astrology & astronomy indicators. Unless noted otherwise, this library was written jointly by @badsector666 and @BarefootJoey.
Library "AstroLib"
t_(txt)
Parameters:
txt (string)
JDNv2(t, withFraction)
Parameters:
t (float)
withFraction (bool)
J2K(t)
Parameters:
t (float)
J2KtoUnix(TimeInJDN)
Parameters:
TimeInJDN (float)
atan2(y, x)
Parameters:
y (float)
x (float)
DegSin(x)
Parameters:
x (float)
DegCos(x)
Parameters:
x (float)
DegTan(x)
Parameters:
x (float)
DegArcsin(x)
Parameters:
x (float)
DegArccos(x)
Parameters:
x (float)
DegArctan(x)
Parameters:
x (float)
DegAtan2(y, x)
Parameters:
y (float)
x (float)
range2pi(x)
Parameters:
x (float)
range360(x)
Parameters:
x (float)
gst(days)
Parameters:
days (float)
DegDecimal(Degrees, Minutes, Seconds)
Parameters:
Degrees (float)
Minutes (float)
Seconds (float)
Rectangular(R, theta, phi, Index)
Parameters:
R (float)
theta (float)
phi (float)
Index (float)
rLength(x, y, z)
Parameters:
x (float)
y (float)
z (float)
spherical(x, y, z, Index)
Parameters:
x (float)
y (float)
z (float)
Index (float)
obliquity(d)
Parameters:
d (float)
requatorial(x, y, z, d, Index)
Parameters:
x (float)
y (float)
z (float)
d (float)
Index (float)
recliptic(x, y, z, d, Index)
Parameters:
x (float)
y (float)
z (float)
d (float)
Index (float)
sequatorial(R, theta, phi, d, Index)
Parameters:
R (float)
theta (float)
phi (float)
d (float)
Index (float)
secliptic(R, theta, phi, d, Index)
Parameters:
R (float)
theta (float)
phi (float)
d (float)
Index (float)
precess(d1, d2, DEC, RA, Index, ddec, dra)
Parameters:
d1 (float)
d2 (float)
DEC (float)
RA (float)
Index (float)
ddec (float)
dra (float)
riset(J2000, DEC, RA, GLat, GLong, Index)
Parameters:
J2000 (float)
DEC (float)
RA (float)
GLat (float)
GLong (float)
Index (float)
ssun(d, Index)
Parameters:
d (float)
Index (float)
rsun(d, Index)
Parameters:
d (float)
Index (float)
sun(d, Index)
Parameters:
d (float)
Index (float)
SunLongitude(d, Index)
Parameters:
d (float)
Index (float)
Sunrise(J2000, GLat, GLong, Index, altitudex)
Parameters:
J2000 (float)
GLat (float)
GLong (float)
Index (float)
altitudex (float)
smoon(dx, Index)
Parameters:
dx (float)
Index (float)
rmoon(d, Index)
Parameters:
d (float)
Index (float)
tmoon(d, GLat, GLong, Index)
Parameters:
d (float)
GLat (float)
GLong (float)
Index (float)
moon(d, Index)
Parameters:
d (float)
Index (float)
Element(d, pnum)
Parameters:
d (float)
pnum (int)
kepler(m, ecc, eps)
Parameters:
m (float)
ecc (float)
eps (float)
rplanet(d, pnumber, Index)
Parameters:
d (float)
pnumber (int)
Index (float)
planet(d, pnumber, Index)
Parameters:
d (float)
pnumber (int)
Index (float)
altaz(d, DEC, RA, GLat, GLong, Index)
Parameters:
d (float)
DEC (float)
RA (float)
GLat (float)
GLong (float)
Index (float)
prise(d, P, GLat, GLong, Index)
Parameters:
d (float)
P (int)
GLat (float)
GLong (float)
Index (float)
MoonSize(d)
Parameters:
d (float)
Refraction(Temperature_C, Atmospheric_Pressure_mBar, Altitude_Deg)
Parameters:
Temperature_C (float)
Atmospheric_Pressure_mBar (float)
Altitude_Deg (float)
MoonRise(d, Longitude, Latitude, Index)
Parameters:
d (float)
Longitude (float)
Latitude (float)
Index (float)
f_to_sec(dec)
Parameters:
dec (float)
f_to_time(sec)
Parameters:
sec (float)
deg_to_time(deg)
Parameters:
deg (float)
toDMS(coordinate)
Parameters:
coordinate (float)
convertDMS(lat, lng)
Parameters:
lat (float)
lng (float)
convlatdec(deg)
Parameters:
deg (float)
PlanetName(pnum)
Parameters:
pnum (int)
PlanetNameV(pnum)
Parameters:
pnum (int)
PlanetSign(pnum)
Parameters:
pnum (int)
PlanetColor(pnum)
Parameters:
pnum (int)
zodiaccolor(deg)
Parameters:
deg (float)
degsign(deg)
Parameters:
deg (float)
degsignf(deg)
Parameters:
deg (float)
degnash(deg)
Parameters:
deg (float)
degname(deg)
Parameters:
deg (float)
retrogradesym(deg)
Parameters:
deg (float)
degaspsign(deg)
Parameters:
deg (float)
degaspname(deg)
Parameters:
deg (float)
degaspfull(deg)
Parameters:
deg (float)
degaspfullV2(deg)
Parameters:
deg (float)
degaspnameV2(deg)
Parameters:
deg (float)
degtolowest180(deg)
Parameters:
deg (float)
degaspfullapproach(deg)
Parameters:
deg (float)
virinchiaspectcol(deg, bull_col, bear_col)
Parameters:
deg (float)
bull_col (color)
bear_col (color)
virinchiaspectemo(deg, bull_emo, bear_emo)
Parameters:
deg (float)
bull_emo (string)
bear_emo (string)
aspectfastsigndeg(deg)
Parameters:
deg (float)
aspectfastfull(deg)
Parameters:
deg (float)
aspectslowfull(deg)
Parameters:
deg (float)
aspectslowsigndeg(deg)
Parameters:
deg (float)
aspectslowsign(deg)
Parameters:
deg (float)
aspectsignprecision(deg, precision)
Parameters:
deg (float)
precision (int)
aspectsignprecisionV2(deg, precision)
Parameters:
deg (float)
precision (float)
aspectsignprecisionV2ext(deg, precision)
Parameters:
deg (float)
precision (float)
IPaspectsignprecision(planet1, planet2, precision)
Parameters:
planet1 (float)
planet2 (float)
precision (float)
IPaspectsignprecisionFull(planet1, planet2, precision)
Parameters:
planet1 (float)
planet2 (float)
precision (float)
IPaspectlineprecision(planet1, planet2, precision, style, width)
Parameters:
planet1 (float)
planet2 (float)
precision (float)
style (string)
width (int)
rDeg(deg)
Parameters:
deg (float)
AngToCirc(angle)
Parameters:
angle (float)
AngToCirc180(angle)
Parameters:
angle (float)
sidereal(deg, sidereal)
Parameters:
deg (float)
sidereal (bool)
J2000(JDN)
Parameters:
JDN (float)
JDN(t, d, tz)
Parameters:
t (float)
d (float)
tz (float)
getsun(index, day, dayr, latitude, longitude, tz)
Parameters:
index (int)
day (float)
dayr (float)
latitude (float)
longitude (float)
tz (float)
getmoon(index, day, dayr, latitude, longitude)
Parameters:
index (int)
day (float)
dayr (float)
latitude (float)
longitude (float)
getplanet(planet, index, day, dayr, latitude, longitude, tz)
Parameters:
planet (int)
index (int)
day (float)
dayr (float)
latitude (float)
longitude (float)
tz (float)
FunctionBaumWelchLibrary "FunctionBaumWelch"
Baum-Welch Algorithm, also known as Forward-Backward Algorithm, uses the well known EM algorithm
to find the maximum likelihood estimate of the parameters of a hidden Markov model given a set of observed
feature vectors.
---
### Function List:
> `forward (array pi, matrix a, matrix b, array obs)`
> `forward (array pi, matrix a, matrix b, array obs, bool scaling)`
> `backward (matrix a, matrix b, array obs)`
> `backward (matrix a, matrix b, array obs, array c)`
> `baumwelch (array observations, int nstates)`
> `baumwelch (array observations, array pi, matrix a, matrix b)`
---
### Reference:
> en.wikipedia.org
> github.com
> en.wikipedia.org
> www.rdocumentation.org
> www.rdocumentation.org
forward(pi, a, b, obs)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
Returns: - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
forward(pi, a, b, obs, scaling)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
scaling (bool) : Normalize `alpha` scale.
Returns: - #### Tuple with:
> - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
> - `array _c`: Array with normalization scale.
backward(a, b, obs)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
backward(a, b, obs, c)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
c (float ) : Array with Normalization scaling coefficients.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
baumwelch(observations, nstates)
**(Random Initialization)** Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
nstates (int)
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
baumwelch(observations, pi, a, b)
Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
pi (float ) : Initial probaility distribution.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
Scaled Order Sizing and Take Profit Target ArraysWOAH Order Scaling!
This Provides a user with methods to create a list of profit targets and order sizes which grow or shrink. For size, the will add up to specific sum. for Targets they will include the first and last, and can lean towards either, to scale the order grid.
And thanks to @Hoanghetti for the markdown, i've included a basic usage example within the hover , o you don't need to search for the usage example, simply import, and when writing, the code hint contains a full example.
scaled_sizes(total_size, count, weight, min_size, as_percent)
create an array of sizes which grow or shrink from first to last
which add up to 1.0 if set the as_percent flag , or a total value / sum.
Parameters:
total_size : (float) total size to divide ito split
count : (int ) desired number of splits to create
weight : (float) a weight to apply to grow or shrink the split either towards the last being most, or the first being most, or 1.0 being each is equally sized as 1/n count
min_size : (float) a minimum size for the smallest value (in value of ttotal_size units)
as_percent : (float) a minimum size for the smallest value (in value of total_size units)
Returns: Array of Sizes for each split
scaled_targets(count, weight, minimum, maximum)
create a list of take profitt targets from the smallest to larget distance
Parameters:
count : (int ) number of targets
weight : (float) weight to apply to growing or shrinking
minimum : (float) first value of the output
maximum : (float) last value of the output
Returns: Array of percentage targets
UtilsLibrary "Utils"
Utility functions. Mathematics, colors, and auxiliary algorithms.
setTheme(vc, theme)
Set theme for levels (predefined colors).
Parameters:
vc : (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels.
theme : (int) Theme (predefined colors).
0 = 'User defined'
1 = 'Spectrum Blue-Green-Red'
2 = 'Monokai'
3 = 'Green'
4 = 'Purple'
5 = 'Blue'
6 = 'Red'
Returns: (void)
setTheme(vc, colorLevel_Lv1, colorLevel_Lv1_Lv2, colorLevel_Lv2_Lv3, colorLevel_Lv3_Lv4, colorLevel_Lv4_Lv5, colorLevel_Lv5)
Set theme for levels (customized colors).
Parameters:
vc : (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
colorLevel_Lv1 : (color) Color associeted with value when below Level 1.
colorLevel_Lv1_Lv2 : (color) Color associeted with value when between Level 1 and 2.
colorLevel_Lv2_Lv3 : (color) Color associeted with value when between Level 2 and 3.
colorLevel_Lv3_Lv4 : (color) Color associeted with value when between Level 3 and 4.
colorLevel_Lv4_Lv5 : (color) Color associeted with value when between Level 4 and 5.
colorLevel_Lv5 : (color) Color associeted with value when above Level 5.
Returns: (void)
setCurrentColorValue(vc)
Set color to a current value, taking into account the previous value and its levels
Parameters:
vc : (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
Returns: (void)
setCurrentColorValue(vc, gradient)
Set color to a current value, taking into account the previous value.
Parameters:
vc : (valueColor) Object to associate a color with a value, taking into account the previous value
gradient
Returns: (void)
setCustomLevels(vc, level1, level2, level3, level4, level5)
Set boundaries for custom levels.
Parameters:
vc : (valueColorSpectrum) Object to associate a color with a value, taking into account the previous value and its levels
level1 : (float) Boundary for level 1
level2 : (float) Boundary for level 2
level3 : (float) Boundary for level 3
level4 : (float) Boundary for level 4
level5 : (float) Boundary for level 5
Returns: (void)
getPeriodicColor(originalColor, density)
Returns a periodic color. Useful for creating dotted lines for example.
Parameters:
originalColor : (color) Original color.
density : (float) Density of color. Expression used in modulo to obtain the integer remainder.
If the remainder equals zero, the color appears, otherwise it remains hidden.
Returns: (color) Periodic color.
dinamicZone(source, sampleLength, pcntAbove, pcntBelow)
Get Dynamic Zones
Parameters:
source : (float) Source
sampleLength : (int) Sample Length
pcntAbove : (float) Calculates the top of the dynamic zone, considering that the maximum values are above x% of the sample
pcntBelow : (float) Calculates the bottom of the dynamic zone, considering that the minimum values are below x% of the sample
Returns: A tuple with 3 series of values: (1) Upper Line of Dynamic Zone;
(2) Lower Line of Dynamic Zone; (3) Center of Dynamic Zone (x = 50%)
valueColorSpectrum
# Object to associate a color with a value, taking into account the previous value and its levels.
Fields:
currentValue
previousValue
level1
level2
level3
level4
level5
currentColorValue
colorLevel_Lv1
colorLevel_Lv1_Lv2
colorLevel_Lv2_Lv3
colorLevel_Lv3_Lv4
colorLevel_Lv4_Lv5
colorLevel_Lv5
theme
valueColor
# Object to associate a color with a value, taking into account the previous value
Fields:
currentValue
previousValue
currentColorValue
colorUp
colorDown
[VWMA] Net Volume LibraryLibrary " Net Volume Library"
TODO: The underlying logic and function that calculates the net volume for the Net Volume indicator. Exposes the nv function and nvPoint fields for use.
nv(src, length, useVwma, offset, sigma, multHigh, multMed, multLow)
Parameters:
src : (float) The source price value
length : (int) The lookback length
useVwma : (bool) To use VWMA in the calculation or not
offset : (float) The ALMA offset value
sigma : (int) The ALMA sigma value
multHigh : (float) The multiplier high band
multMed : (float) The multiplier medium band
multLow : (float) The multiplier low band
Returns: Returns the calculated net volume for each band in an nvPoint object
nvPoint
Fields:
h2
h1
h
n
l
l1
l2
distance_ratioLibrary "distance_ratio"
Collection of types and functions that can be used for the calculation of the ratio of a distance
from a barrier price using several methods. Methods supported are percentagewise (PERC), atr-based (ATR), fixed
profit (PROF), tick-based (TICKS), risk reward ratio (RR) and local extrema (LOC).
This library is meant to replace my previously published "distance_percentile" library since it offers a more intuitive interface by using the method syntax.
Feature ScalingLibrary "Feature_Scaling"
FS: This library helps you scale your data to certain ranges or standarize, normalize, unit scale or min-max scale your data in your prefered way. Mostly used for normalization purposes.
minmaxscale(source, min, max, length)
minmaxscale: Min-max normalization scales your data to set minimum and maximum range
Parameters:
source
min
max
length
Returns: res: Data scaled to the set minimum and maximum range
meanscale(source, length)
meanscale: Mean normalization of your data
Parameters:
source
length
Returns: res: Mean normalization result of the source
standarize(source, length, biased)
standarize: Standarization of your data
Parameters:
source
length
biased
Returns: res: Standarized data
unitlength(source, length)
unitlength: Scales your data into overall unit length
Parameters:
source
length
Returns: res: Your data scaled to the unit length
SILLibrary "SIL"
mean_src(x, y)
calculates moving average : x is the source of price (OHLC) & y = the lookback period
Parameters:
x
y
stan_dev(x, y, z)
calculates standard deviation, x = source of price (OHLC), y = the average lookback, z = average given prior two float and intger inputs, call the f_avg_src() function in f_stan_dev()
Parameters:
x
y
z
vawma(x, y)
calculates volume weighted moving average, x = source of price (OHLC), y = loookback period
Parameters:
x
y
gethurst(x, y, z)
calculates the Hurst Exponent and Hurst Exponent average, x = source of price (OHLC), y = lookback period for Hurst Exponent Calculation, z = lookback period for average Hurst Exponent
Parameters:
x
y
z
libKageMiscLibrary "libKageMisc"
Kage's Miscelaneous library
print(_value)
Print a numerical value in a label at last historical bar.
Parameters:
_value : (float) The value to be printed.
Returns: Nothing.
barsBackToDate(_year, _month, _day)
Get the number of bars we have to go back to get data from a specific date.
Parameters:
_year : (int) Year of the specific date.
_month : (int) Month of the specific date. Optional. Default = 1.
_day : (int) Day of the specific date. Optional. Default = 1.
Returns: (int) Number of bars to go back until reach the specific date.
bodySize(_index)
Calculates the size of the bar's body.
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.
Returns: (float) The size of the bar's body in price units.
shadowSize(_direction)
Size of the current bar shadow. Either "top" or "bottom".
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) The size of the chosen bar's shadow in price units.
shadowBodyRatio(_direction)
Proportion of current bar shadow to the bar size
Parameters:
_direction : (string) Direction of the desired shadow.
Returns: (float) Ratio of the shadow size per body size.
bodyCloseRatio(_index)
Proportion of chosen bar body size to the close price
Parameters:
_index : (simple int) The historical index of the bar. Optional. Default = 0.()
Returns: (float) Ratio of the body size per close price.
lastDayOfMonth(_month)
Returns the last day of a month.
Parameters:
_month : (int) Month number.
Returns: (int) The number (28, 30 or 31) of the last day of a given month.
nameOfMonth(_month)
Return the short name of a month.
Parameters:
_month : (int) Month number.
Returns: (string) The short name ("Jan", "Feb"...) of a given month.
pl(_initialValue, _finalValue)
Calculate Profit/Loss between two values.
Parameters:
_initialValue : (float) Initial value.
_finalValue : (float) Final value = Initial value + delta.
Returns: (float) Profit/Loss as a percentual change.
gma(_Type, _Source, _Length)
Generalist Moving Average (GMA).
Parameters:
_Type : (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA".
_Source : (series float) Series of values to process.
_Length : (simple int) Number of bars (length).
Returns: (float) The value of the chosen moving average.
xFormat(_percentValue, _minXFactor)
Transform a percentual value in a X Factor value.
Parameters:
_percentValue : (float) Percentual value to be transformed.
_minXFactor : (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10.
Returns: (string) A formated string.
isLong()
Check if the open trade direction is long.
Returns: (bool) True if the open position is long.
isShort()
Check if the open trade direction is short.
Returns: (bool) True if the open position is short.
lastPrice()
Returns the entry price of the last openned trade.
Returns: (float) The last entry price.
barsSinceLastEntry()
Returns the number of bars since last trade was oppened.
Returns: (series int)
getBotNameFrosty()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getBotNameZig()
Return the name of the FrostyBot Bot.
Returns: (string) A string containing the name.
getTicksValue(_currencyValue)
Converts currency value to ticks
Parameters:
_currencyValue : (float) Value to be converted.
Returns: (float) Value converted to minticks.
getSymbol(_botName, _botCustomSymbol)
Formats the symbol string to be used with a bot
Parameters:
_botName : (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string.
_botCustomSymbol : (string) Custom string. Optional. Default is empy string.
Returns: (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format.
showProfitLossBoard()
Calculates and shows a board of Profit/Loss through the years.
Returns: Nothing.
Linear_Regression_SlopeLibrary "Linear_Regression_Slope"
linreg_slope(a, b)
Parameters:
a
b
This library is available to anyone.
This library calculates the linear regression slope.
Be sure to use the source value for a.
(End price, high price, low price, market price)
Please set a period for b.
Overlay is set to false.
Vector2FunctionClipLibrary "Vector2FunctionClip"
Sutherland-Hodgman polygon clipping algorithm.
reference:
.
rosettacode.org
.
clip(source, reference)
Perform Clip operation on a vector with another.
Parameters:
source : array . Source polygon to be clipped.
reference : array . Reference polygon to clip source.
Returns: array.
Vector2ArrayLibrary "Vector2Array"
functions to handle vector2 Array operations.
.
references:
docs.unity3d.com
gist.github.com
github.com
gist.github.com
gist.github.com
gist.github.com
.
from(source, prop_sep, vect_sep)
Generate array of vector2 from string.
Parameters:
source : string Source string of the vectors.
prop_sep : string Separator character of the vector properties (x`,`y).
vect_sep : string Separator character of the vectors ((x,y)`;`(x,y)).
Returns: array.
max(vectors)
Combination of the highest elements in column of a array of vectors.
Parameters:
vectors : array, Array of Vector2 objects.
Returns: Vector2.Vector2, Vector2 object.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = max(array.from(a, b, c)) , plot(d.x)`
min(vectors)
Combination of the lowest elements in column of a array of vectors.
Parameters:
vectors : array, Array of Vector2 objects.
Returns: Vector2.Vector2, Vector2 object.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = min(array.from(a, b, c)) , plot(d.x)`
sum(vectors)
Total sum of all vectors.
Parameters:
vectors : array, ID of the vector2 array.
Returns: Vector2.Vector2, vector2 object.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = sum(array.from(a, b, c)) , plot(d.x)`
center(vectors)
Finds the vector center of the array.
Parameters:
vectors : array, ID of the vector2 array.
Returns: Vector2.Vector2, vector2 object.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = center(array.from(a, b, c)) , plot(d.x)`
rotate(vectors, center, degree)
Rotate Array vectors around origin vector by a angle.
Parameters:
vectors : array, ID of the vector2 array.
center : Vector2.Vector2 , Vector2 object. Center of the rotation.
degree : float , Angle value.
Returns: rotated points array.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = rotate(array.from(a, b, c), b, 45.0)`
scale(vectors, center, rate)
Scale Array vectors based on a origin vector perspective.
Parameters:
vectors : array, ID of the vector2 array.
center : Vector2.Vector2 , Vector2 object. Origin center of the transformation.
rate : float , Rate to apply transformation.
Returns: rotated points array.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = scale(array.from(a, b, c), b, 1.25)`
move(vectors, center, rate)
Move Array vectors by a rate of the distance to center position (LERP).
Parameters:
vectors : array, ID of the vector2 array.
center
rate
Returns: Moved points array.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = move(array.from(a, b, c), b, 1.25)`
to_string(id, separator)
Reads a array of vectors into a string, of the form ` `.
Parameters:
id : array, ID of the vector2 array.
separator : string separator for cell splitting.
Returns: string Translated complex array into string.
-> usage:
`a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = to_string(array.from(a, b, c))`
to_string(id, format, separator)
Reads a array of vectors into a string, of the form ` `.
Parameters:
id : array, ID of the vector2 array.
format : string , Format to apply transformation.
separator : string , Separator for cell splitting.
Returns: string Translated complex array into string.
-> usage:
`a = Vector2.from(1.234) , b = Vector2.from(2.23), c = Vector2.from(3.1234), d = to_string(array.from(a, b, c), "#.##")`
Segment2Library "Segment2"
Structure representation of a directed straight line in two dimensions from origin to target vectors.
.
reference:
graphics.stanford.edu
.
new(origin, target)
Generate a new segment.
Parameters:
origin : Vector2 . Origin of the segment.
target : Vector2 . Target of the segment.
Returns: Segment2.
new(origin_x, origin_y, target_x, target_y)
Generate a new segment.
Parameters:
origin_x : float . Origin of the segment x coordinate.
origin_y : float . Origin of the segment y coordinate.
target_x : float . Target of the segment x coordinate.
target_y : float . Target of the segment y coordinate.
Returns: Segment2.
copy(this)
Copy a segment.
Parameters:
this : Vector2 . Segment to copy.
Returns: Segment2.
length_squared(this)
Squared length of the normalized segment vector. For comparing vectors this is computationaly lighter.
Parameters:
this : Segment2 . Sorce segment.
Returns: float.
length(this)
Length of the normalized segment vector.
Parameters:
this : Segment2 . Sorce segment.
Returns: float.
opposite(this)
Reverse the direction of the segment.
Parameters:
this : Segment2 . Source segment.
Returns: Segment2.
is_degenerate(this)
Segment is degenerate when origin and target are equal.
Parameters:
this : Segment2 . Source segment.
Returns: bool.
is_horizontal(this)
Segment is horizontal?.
Parameters:
this : Segment2 . Source segment.
Returns: bool.
is_horizontal(this, precision)
Segment is horizontal?.
Parameters:
this : Segment2 . Source segment.
precision : float . Limit of precision.
Returns: bool.
is_vertical(this)
Segment is vertical?.
Parameters:
this : Segment2 . Source segment.
Returns: bool.
is_vertical(this, precision)
Segment is vertical?.
Parameters:
this : Segment2 . Source segment.
precision : float . Limit of precision.
Returns: bool.
equals(this, other)
Tests two segments for equality (share same origin and target).
Parameters:
this : Segment2 . Source segment.
other : Segment2 . Target segment.
Returns: bool.
nearest_to_point(this, point)
Find the nearest point in a segment to another point.
Parameters:
this : Segment2 . Source segment.
point : Vector2 . Point to aproximate.
Returns: Vector2.
intersection(this, other)
Find the intersection vector of 2 lines.
Parameters:
this : Segment2 . Segment A.
other : Segment2 . Segment B.
Returns: Vector2.Vector2 Object.
extend(this, at_origin, at_target)
Extend a segment by the percent ratio provided.
Parameters:
this : Segment2 . Source segment.
at_origin : float . Percent ratio to extend at origin vector.
at_target : float . Percent ratio to extend at target vector.
Returns: Segment2.
to_string(this)
Translate segment to string format `( (x,y), (x,y) )`.
Parameters:
this : Segment2 . Source segment.
Returns: string.
to_string(this, format)
Translate segment to string format `((x,y), (x,y))`.
Parameters:
this : Segment2 . Source segment.
format : string . Format string to apply.
Returns: string.
to_array(this)
Translate segment to array format.
Parameters:
this : Segment2 . Source segment.
Returns: array.