MTF_DrawingsLibrary 'MTF_Drawings'
This library helps with drawing indicators and candle charts on all timeframes.
FEATURES
CHART DRAWING : Library provides functions for drawing High Time Frame (HTF) and Low Time Frame (LTF) candles.
INDICATOR DRAWING : Library provides functions for drawing various types of HTF and LTF indicators.
CUSTOM COLOR DRAWING : Library allows to color candles and indicators based on specific conditions.
LINEFILLS : Library provides functions for drawing linefills.
CATEGORIES
The functions are named in a way that indicates they purpose:
{Ind} : Function is meant only for indicators.
{Hist} : Function is meant only for histograms.
{Candle} : Function is meant only for candles.
{Draw} : Function draws indicators, histograms and candle charts.
{Populate} : Function generates necessary arrays required by drawing functions.
{LTF} : Function is meant only for lower timeframes.
{HTF} : Function is meant only for higher timeframes.
{D} : Function draws indicators that are composed of two lines.
{CC} : Function draws custom colored indicators.
USAGE
Import the library into your script.
Before using any {Draw} function it is necessary to use a {Populate} function.
Choose the appropriate one based on the category, provide the necessary arguments, and then use the {Draw} function, forwarding the arrays generated by the {Populate} function.
This doesn't apply to {Draw_Lines}, {LineFill}, or {Barcolor} functions.
EXAMPLE
import Spacex_trader/MTF_Drawings/1 as tf
//Request lower timeframe data.
Security(simple string Ticker, simple string New_LTF, float Ind) =>
float Value = request.security_lower_tf(Ticker, New_LTF, Ind)
Value
Timeframe = input.timeframe('1', 'Timeframe: ')
tf.Draw_Ind(tf.Populate_LTF_Ind(Security(syminfo.tickerid, Timeframe, ta.rsi(close, 14)), 498, color.purple), 1, true)
FUNCTION LIST
HTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, HTF_Open, HTF_High, HTF_Low, HTF_Close, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
HTF_Open (float) : HTF open price.
HTF_High (float) : HTF high price.
HTF_Low (float) : HTF low price.
HTF_Close (float) : HTF close price.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF candles.
LTF_Candle(BarsBack, BodyBear, BodyBull, BordersBear, BordersBull, WickBear, WickBull, LineStyle, BoxStyle, LineWidth, LTF_Open, LTF_High, LTF_Low, LTF_Close)
Populates two arrays with drawing data of the LTF candles.
Parameters:
BarsBack (int) : Bars number to display.
BodyBear (color) : Candle body bear color.
BodyBull (color) : Candle body bull color.
BordersBear (color) : Candle border bear color.
BordersBull (color) : Candle border bull color.
WickBear (color) : Candle wick bear color.
WickBull (color) : Candle wick bull color.
LineStyle (string) : Wick style (Solid-Dotted-Dashed).
BoxStyle (string) : Border style (Solid-Dotted-Dashed).
LineWidth (int) : Wick width.
LTF_Open (float ) : LTF open price.
LTF_High (float ) : LTF high price.
LTF_Low (float ) : LTF low price.
LTF_Close (float ) : LTF close price.
Returns: Two arrays with drawing data of the LTF candles.
Draw_Candle(Box, Line, Offset)
Draws HTF or LTF candles.
Parameters:
Box (box ) : Box array with drawing data.
Line (line ) : Line array with drawing data.
Offset (int) : Offset of the candles.
Returns: Drawing of the candles.
Populate_HTF_Ind(IndValue, BarsBack, IndColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator.
Parameters:
IndValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: An array with drawing data of the HTF indicator.
Populate_LTF_Ind(IndValue, BarsBack, IndColor)
Populates one array with drawing data of the LTF indicator.
Parameters:
IndValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
IndColor (color) : Indicator color.
Returns: An array with drawing data of the LTF indicator.
Draw_Ind(Line, Mult, Exe)
Draws one HTF or LTF indicator.
Parameters:
Line (line ) : Line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the indicator.
Returns: Drawing of the indicator.
Populate_HTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2, HTF_Bar_Index)
Populates two arrays with drawing data of the HTF indicators.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Two arrays with drawing data of the HTF indicators.
Populate_LTF_Ind_D(IndValue_1, IndValue_2, BarsBack, IndColor_1, IndColor_2)
Populates two arrays with drawing data of the LTF indicators.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
IndColor_1 (color) : First indicator color.
IndColor_2 (color) : Second indicator color.
Returns: Two arrays with drawing data of the LTF indicators.
Draw_Ind_D(Line_1, Line_2, Mult, Exe_1, Exe_2)
Draws two LTF or HTF indicators.
Parameters:
Line_1 (line ) : First line array with drawing data.
Line_2 (line ) : Second line array with drawing data.
Mult (int) : Coordinates multiplier.
Exe_1 (bool) : Display the first indicator.
Exe_2 (bool) : Display the second indicator.
Returns: Drawings of the indicators.
Barcolor(Box, Line, BarColor)
Colors the candles based on indicators output.
Parameters:
Box (box ) : Candle box array.
Line (line ) : Candle line array.
BarColor (color ) : Indicator color array.
Returns: Colored candles.
Populate_HTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1, HTF_Bar_Index)
Populates two array with drawing data of the HTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bear color.
IndColor_1 (color) : First indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: Three arrays with drawing and color data of the HTF indicators.
Populate_LTF_Ind_D_CC(IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, IndColor_1)
Populates two arrays with drawing data of the LTF indicators with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
IndColor_1 (color) : First indicator color.
Returns: Three arrays with drawing and color data of the LTF indicators.
Populate_HTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float) : Indicator value.
IndValue_1 (float) : First indicator value.
IndValue_2 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF histogram.
Populate_LTF_Hist_CC(HistValue, IndValue_1, IndValue_2, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: IndValue_1 >= IndValue_2 ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
IndValue_1 (float ) : First indicator value.
IndValue_2 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_LTF_Hist_CC_VA(HistValue, Value, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF histogram with color based on: HistValue >= Value ? BullColor : BearColor.
Parameters:
HistValue (float ) : Indicator value.
Value (float) : First indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two array with drawing and color data of the LTF histogram.
Populate_HTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float) : Indicator value.
IndValue_1 (float) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
HTF_Bar_Index (int) : HTF bar_index
Returns: Two arrays with drawing and color data of the HTF indicator.
Populate_LTF_Ind_CC(IndValue, IndValue_1, BarsBack, BullColor, BearColor)
Populates one array with drawing data of the LTF indicator with color based on: IndValue >= IndValue_1 ? BullColor : BearColor.
Parameters:
IndValue (float ) : Indicator value.
IndValue_1 (float ) : Second indicator value.
BarsBack (int) : Indicator lines to display.
BullColor (color) : Bull color.
BearColor (color) : Bearcolor.
Returns: Two arrays with drawing and color data of the LTF indicator.
Draw_Lines(BarsBack, y1, y2, LineType, Fill)
Draws price lines on indicators.
Parameters:
BarsBack (int) : Indicator lines to display.
y1 (float) : Coordinates of the first line.
y2 (float) : Coordinates of the second line.
LineType (string) : Line type.
Fill (color) : Fill color.
Returns: Drawing of the lines.
LineFill(Upper, Lower, BarsBack, FillColor)
Fills two lines with linefill HTF or LTF.
Parameters:
Upper (line ) : Upper line.
Lower (line ) : Lower line.
BarsBack (int) : Indicator lines to display.
FillColor (color) : Fill color.
Returns: Linefill of the lines.
Populate_LTF_Hist(HistValue, BarsBack, HistColor)
Populates one array with drawing data of the LTF histogram.
Parameters:
HistValue (float ) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
Returns: One array with drawing data of the LTF histogram.
Populate_HTF_Hist(HistValue, BarsBack, HistColor, HTF_Bar_Index)
Populates one array with drawing data of the HTF histogram.
Parameters:
HistValue (float) : Indicator value.
BarsBack (int) : Indicator lines to display.
HistColor (color) : Indicator color.
HTF_Bar_Index (int) : HTF bar_index.
Returns: One array with drawing data of the HTF histogram.
Draw_Hist(Box, Mult, Exe)
Draws HTF or LTF histogram.
Parameters:
Box (box ) : Box Array.
Mult (int) : Coordinates multiplier.
Exe (bool) : Display the histogram.
Returns: Drawing of the histogram.
Arrays
WIPFunctionLyaponovLibrary "WIPFunctionLyaponov"
Lyapunov exponents are mathematical measures used to describe the behavior of a system over
time. They are named after Russian mathematician Alexei Lyapunov, who first introduced the concept in the
late 19th century. The exponent is defined as the rate at which a particular function or variable changes
over time, and can be positive, negative, or zero.
Positive exponents indicate that a system tends to grow or expand over time, while negative exponents
indicate that a system tends to shrink or decay. Zero exponents indicate that the system does not change
significantly over time. Lyapunov exponents are used in various fields of science and engineering, including
physics, economics, and biology, to study the long-term behavior of complex systems.
~ generated description from vicuna13b
---
To calculate the Lyapunov Exponent (LE) of a given Time Series, we need to follow these steps:
1. Firstly, you should have access to your data in some format like CSV or Excel file. If not, then you can collect it manually using tools such as stopwatches and measuring tapes.
2. Once the data is collected, clean it up by removing any outliers that may skew results. This step involves checking for inconsistencies within your dataset (e.g., extremely large or small values) and either discarding them entirely or replacing with more reasonable estimates based on surrounding values.
3. Next, you need to determine the dimension of your time series data. In most cases, this will be equal to the number of variables being measured in each observation period (e.g., temperature, humidity, wind speed).
4. Now that we have a clean dataset with known dimensions, we can calculate the LE for our Time Series using the following formula:
λ = log(||M^T * M - I||)/log(||v||)
where:
λ (Lyapunov Exponent) is the quantity that will be calculated.
||...|| denotes an Euclidean norm of a vector or matrix, which essentially means taking the square root of the sum of squares for each element in the vector/matrix.
M represents our Jacobian Matrix whose elements are given by:
J_ij = (∂fj / ∂xj) where fj is the jth variable and xj is the ith component of the initial condition vector x(t). In other words, each element in this matrix represents how much a small change in one variable affects another.
I denotes an identity matrix whose elements are all equal to 1 (or any constant value if you prefer). This term essentially acts as a baseline for comparison purposes since we want our Jacobian Matrix M^T * M to be close to it when the system is stable and far away from it when the system is unstable.
v represents an arbitrary vector whose Euclidean norm ||v|| will serve as a scaling factor in our calculation. The choice of this particular vector does not matter since we are only interested in its magnitude (i.e., length) for purposes of normalization. However, if you want to ensure that your results are accurate and consistent across different datasets or scenarios, it is recommended to use the same initial condition vector x(t) as used earlier when calculating our Jacobian Matrix M.
5. Finally, once we have calculated λ using the formula above, we can interpret its value in terms of stability/instability for our Time Series data:
- If λ < 0, then this indicates that the system is stable (i.e., nearby trajectories will converge towards each other over time).
- On the other hand, if λ > 0, then this implies that the system is unstable (i.e., nearby trajectories will diverge away from one another over time).
~ generated description from airoboros33b
---
Reference:
en.wikipedia.org
www.collimator.ai
blog.abhranil.net
www.researchgate.net
physics.stackexchange.com
---
This is a work in progress, it may contain errors so use with caution.
If you find flaws or suggest something new, please leave a comment bellow.
_measure_function(i)
helper function to get the name of distance function by a index (0 -> 13).\
Functions: SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl.
Parameters:
i (int)
_test(L)
Helper function to test the output exponents state system and outputs description into a string.
Parameters:
L (float )
estimate(X, initial_distance, distance_function)
Estimate the Lyaponov Exponents for multiple series in a row matrix.
Parameters:
X (map)
initial_distance (float) : Initial distance limit.
distance_function (string) : Name of the distance function to be used, default:`ssd`.
Returns: List of Lyaponov exponents.
max(L)
Maximal Lyaponov Exponent.
Parameters:
L (float ) : List of Lyapunov exponents.
Returns: Highest exponent.
CommonTypesMapUtilLibrary "CommonTypesMapUtil"
Common type Container library, for central usage across other reference libraries.
ArrayBool
Fields:
v (bool )
ArrayBox
Fields:
v (box )
ArrayPoint
Fields:
v (chart.point )
ArrayColor
Fields:
v (color )
ArrayFloat
Fields:
v (float )
ArrayInt
Fields:
v (int )
ArrayLabel
Fields:
v (label )
ArrayLine
Fields:
v (line )
ArrayLinefill
Fields:
v (linefill )
ArrayString
Fields:
v (string )
ArrayTable
Fields:
v (table )
SimilarityMeasuresLibrary "SimilarityMeasures"
Similarity measures are statistical methods used to quantify the distance between different data sets
or strings. There are various types of similarity measures, including those that compare:
- data points (SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl),
- strings (Edit(Levenshtein), Lee, Hamming, Jaro),
- probability distributions (Mahalanobis, Fidelity, Bhattacharyya, Hellinger),
- sets (Kumar Hassebrook, Jaccard, Sorensen, Chi Square).
---
These measures are used in various fields such as data analysis, machine learning, and pattern recognition. They
help to compare and analyze similarities and differences between different data sets or strings, which
can be useful for making predictions, classifications, and decisions.
---
References:
en.wikipedia.org
cran.r-project.org
numerics.mathdotnet.com
github.com
github.com
github.com
Encyclopedia of Distances, doi.org
ssd(p, q)
Sum of squared difference for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of distance that calculates the squared euclidean distance.
euclidean(p, q)
Euclidean distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of distance that calculates the straight-line (or Euclidean).
manhattan(p, q)
Manhattan distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of absolute differences between both points.
minkowski(p, q, p_value)
Minkowsky Distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
p_value (float) : `float` P value, default=1.0(1: manhatan, 2: euclidean), does not support chebychev.
Returns: Measure of similarity in the normed vector space.
chebyshev(p, q)
Chebyshev distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of maximum absolute difference.
correlation(p, q)
Correlation distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Measure of maximum absolute difference.
cosine(p, q)
Cosine distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Cosine distance between vectors `p` and `q`.
---
angiogenesis.dkfz.de
camberra(p, q)
Camberra distance for N dimensions.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Weighted measure of absolute differences between both points.
mae(p, q)
Mean absolute error is a normalized version of the sum of absolute difference (manhattan).
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Mean absolute error of vectors `p` and `q`.
mse(p, q)
Mean squared error is a normalized version of the sum of squared difference.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Mean squared error of vectors `p` and `q`.
lorentzian(p, q)
Lorentzian distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Lorentzian distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
intersection(p, q)
Intersection distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Intersection distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
penrose(p, q)
Penrose Shape distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Penrose shape distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
meehl(p, q)
Meehl distance between provided vectors.
Parameters:
p (float ) : `array` Vector with first numeric distribution.
q (float ) : `array` Vector with second numeric distribution.
Returns: Meehl distance of vectors `p` and `q`.
---
angiogenesis.dkfz.de
edit(x, y)
Edit (aka Levenshtein) distance for indexed strings.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Number of deletions, insertions, or substitutions required to transform source string into target string.
---
generated description:
The Edit distance is a measure of similarity used to compare two strings. It is defined as the minimum number of
operations (insertions, deletions, or substitutions) required to transform one string into another. The operations
are performed on the characters of the strings, and the cost of each operation depends on the specific algorithm
used.
The Edit distance is widely used in various applications such as spell checking, text similarity, and machine
translation. It can also be used for other purposes like finding the closest match between two strings or
identifying the common prefixes or suffixes between them.
---
github.com
www.red-gate.com
planetcalc.com
lee(x, y, dsize)
Distance between two indexed strings of equal length.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
dsize (int) : `int` Dictionary size.
Returns: Distance between two strings by accounting for dictionary size.
---
www.johndcook.com
hamming(x, y)
Distance between two indexed strings of equal length.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Length of different components on both sequences.
---
en.wikipedia.org
jaro(x, y)
Distance between two indexed strings.
Parameters:
x (int ) : `array` Indexed array.
y (int ) : `array` Indexed array.
Returns: Measure of two strings' similarity: the higher the value, the more similar the strings are.
The score is normalized such that `0` equates to no similarities and `1` is an exact match.
---
rosettacode.org
mahalanobis(p, q, VI)
Mahalanobis distance between two vectors with population inverse covariance matrix.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
VI (matrix) : `matrix` Inverse of the covariance matrix.
Returns: The mahalanobis distance between vectors `p` and `q`.
---
people.revoledu.com
stat.ethz.ch
docs.scipy.org
fidelity(p, q)
Fidelity distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Bhattacharyya Coefficient between vectors `p` and `q`.
---
en.wikipedia.org
bhattacharyya(p, q)
Bhattacharyya distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Bhattacharyya distance between vectors `p` and `q`.
---
en.wikipedia.org
hellinger(p, q)
Hellinger distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The hellinger distance between vectors `p` and `q`.
---
en.wikipedia.org
jamesmccaffrey.wordpress.com
kumar_hassebrook(p, q)
Kumar Hassebrook distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Kumar Hassebrook distance between vectors `p` and `q`.
---
github.com
jaccard(p, q)
Jaccard distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Jaccard distance between vectors `p` and `q`.
---
github.com
sorensen(p, q)
Sorensen distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
Returns: The Sorensen distance between vectors `p` and `q`.
---
people.revoledu.com
chi_square(p, q, eps)
Chi Square distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
eps (float)
Returns: The Chi Square distance between vectors `p` and `q`.
---
uw.pressbooks.pub
stats.stackexchange.com
www.itl.nist.gov
kulczynsky(p, q, eps)
Kulczynsky distance between provided vectors.
Parameters:
p (float ) : `array` 1D Vector.
q (float ) : `array` 1D Vector.
eps (float)
Returns: The Kulczynsky distance between vectors `p` and `q`.
---
github.com
FunctionMatrixCovarianceLibrary "FunctionMatrixCovariance"
In probability theory and statistics, a covariance matrix (also known as auto-covariance matrix, dispersion matrix, variance matrix, or variance–covariance matrix) is a square matrix giving the covariance between each pair of elements of a given random vector.
Intuitively, the covariance matrix generalizes the notion of variance to multiple dimensions. As an example, the variation in a collection of random points in two-dimensional space cannot be characterized fully by a single number, nor would the variances in the `x` and `y` directions contain all of the necessary information; a `2 × 2` matrix would be necessary to fully characterize the two-dimensional variation.
Any covariance matrix is symmetric and positive semi-definite and its main diagonal contains variances (i.e., the covariance of each element with itself).
The covariance matrix of a random vector `X` is typically denoted by `Kxx`, `Σ` or `S`.
~wikipedia.
method cov(M, bias)
Estimate Covariance matrix with provided data.
Namespace types: matrix
Parameters:
M (matrix) : `matrix` Matrix with vectors in column order.
bias (bool)
Returns: Covariance matrix of provided vectors.
---
en.wikipedia.org
numpy.org
TradeLibrary "Trade"
A Trade Tracking Library
Monitor conditions with less code by using Arrays. When your conditions are met in chronologically, a signal is returned and the scanning starts again.
Create trades automatically with Stop Loss, Take Profit and Entry. The trades will automatically track based on the market movement and update when the targets are hit.
Sample Usage
Enter a buy trade when RSI crosses below 70 then crosses above 80 before it crosses 40.
Note: If RSI crosses 40 before 80, No trade will be entered.
rsi = ta.rsi(close, 21)
buyConditions = array.new_bool()
buyConditions.push(ta.crossunder(rsi, 70))
buyConditions.push(ta.crossover(rsi, 80))
buy = Trade.signal(buyConditions, ta.crossunder(rsi, 40))
trade = Trade.new(close-(100*syminfo.mintick), close +(200*syminfo.mintick), condition=buy)
plot(trade.takeprofit, "TP", style=plot.style_circles, linewidth=4, color=color.lime)
alertcondition(trade.tp_hit, "TP Hit")
method signal(conditions, reset)
Signal Conditions
Namespace types: bool
Parameters:
conditions (bool )
reset (bool)
Returns: Boolean: True when all the conditions have occured
method update(this, stoploss, takeprofit, entry)
Update Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
stoploss (float)
takeprofit (float)
entry (float)
Returns: nothing
method clear(this)
Clear Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
Returns: nothing
method track(this, _high, _low)
Track Trade Parameters
Namespace types: Trade
Parameters:
this (Trade)
_high (float)
_low (float)
Returns: nothing
new(stoploss, takeprofit, entry, _high, _low, condition, update)
New Trade with tracking
Parameters:
stoploss (float)
takeprofit (float)
entry (float)
_high (float)
_low (float)
condition (bool)
update (bool)
Returns: a Trade with targets and updates if stoploss or takeprofit is hit
new()
New Empty Trade
Returns: an empty trade
Trade
Fields:
stoploss (series__float)
takeprofit (series__float)
entry (series__float)
sl_hit (series__bool)
tp_hit (series__bool)
open (series__integer)
multidataLibrary "multidata"
A library for multi-dimensional data arrays.
Full documentation: faiyaz7283.github.io
This library is designed to enhance data storage capabilities in Pine Script, enabling users to work with two separate data structures: data2d (key -> main-value | alternate-value) and data3d (primary key -> data key-> main-value | alternate-value). These structures facilitate storing key-value pairs in a flexible and efficient manner, offering various methods for manipulation and retrieval of data. Please check out the full documentation at faiyaz7283.github.io .
debugLibrary "debug"
Show Array or Matrix Elements In Table
Use anytime you want to see the elements in an array or a matrix displayed.
Effective debugger, particularly for strategies and complex logic structures.
Look in code to find instructions. Reach out if you need assistance.
Functionality includes:
Viewing the contents of an array or matrix on screen.
Track variables and variable updates using debug()
Track if and when local scopes fire using debugs()
Types Allowed:
string
float
int
string
debug(_col, _row, _name, _value, _msg, _ip)
Debug Variables in Matrix
Parameters:
_col (int) : (int) Assign Column
_row (int) : (int) Assign Row
_name (matrix) : (simple matrix) Matrix Name
_value (string) : (string) Assign variable as a string (str.tostring())
_msg (string)
_ip (int) : (int) (default 1) 1 for continuous updates. 2 for barstate.isnew updates. 3 for barstate.isconfirmed updates. -1 to only add once
Returns: Returns Variable _value output and _msg formatted as '_msg: variableOutput' in designated column and row
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (float)
_msg (string)
_ip (int)
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (int)
_msg (string)
_ip (int)
debug(_col, _row, _name, _value, _msg, _ip)
Parameters:
_col (int)
_row (int)
_name (matrix)
_value (bool)
_msg (string)
_ip (int)
debugs(_col, _row, _name, _msg)
Debug Scope in Matrix - Identify When Scope Is Accessed
Parameters:
_col (int) : (int) Column Number
_row (int) : (int) Row Number
_name (matrix) : (simple matrix) Matrix Name
_msg (string) : (string) Message
Returns: Message appears in debug panel using _col/_row as the identifier
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Array Element Display (Supports float , int , string , and bool )
Parameters:
_arrayName (float ) : ID of Array to be Displayed
_pos (string) : Position for Table
_txtSize (string) : Size of Table Cell Text
_tRows (int) : Number of Rows to Display Data In (columns will be calculated accordingly)
s_index (bool) : (Optional. Default True.) Show/Hide Index Numbers
s_border (bool) : (Optional. Default False.) Show/Hide Border
_rowCol (string)
bCol (color) : = (Optional. Default Black.) Frame/Border Color.
_fillCond (bool) : (Optional) Conditional statement. Function displays array only when true. For instances where size is not immediately known or indices are na. Default = true, indicating array size is set at bar_index 0.
_offset (int) : (Optional) Use to view historical array states. Default = 0, displaying realtime bar.
Returns: A Display of Array Values in a Table
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (int )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (string )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewArray(_arrayName, _pos, _txtSize, _tRows, s_index, s_border, _rowCol, bCol, _fillCond, _offset)
Parameters:
_arrayName (bool )
_pos (string)
_txtSize (string)
_tRows (int)
s_index (bool)
s_border (bool)
_rowCol (string)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Matrix Element Display (Supports , , , and )
Parameters:
_matrixName (matrix) : ID of Matrix to be Displayed
_pos (string) : Position for Table
_txtSize (string) : Size of Table Cell Text
s_index (bool) : (Optional. Default True.) Show/Hide Index Numbers
_resetIdx (bool)
s_border (bool) : (Optional. Default False.) Show/Hide Border
bCol (color) : = (Optional. Default Black.) Frame/Border Color.
_fillCond (bool) : (Optional) Conditional statement. Function displays matrix only when true. For instances where size is not immediately known or indices are na. Default = true, indicating matrix size is set at bar_index 0.
_offset (int) : (Optional) Use to view historical matrix states. Default = 0, displaying realtime bar.
Returns: A Display of Matrix Values in a Table
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
viewMatrix(_matrixName, _pos, _txtSize, s_index, _resetIdx, s_border, bCol, _fillCond, _offset)
Parameters:
_matrixName (matrix)
_pos (string)
_txtSize (string)
s_index (bool)
_resetIdx (bool)
s_border (bool)
bCol (color)
_fillCond (bool)
_offset (int)
CandlesGroup_TypesLibrary "CandlesGroup_Types"
CandlesGroup Type allows you to efficiently store and access properties of all the candles in your chart.
You can easily manipulate large datasets, work with multiple timeframes, or analyze multiple symbols simultaneously. By encapsulating the properties of each candle within a CandlesGroup object, you gain a convenient and organized way to handle complex candlestick patterns and data.
For usage instructions and detailed examples, please refer to the comments and examples provided in the source code.
method init(_self)
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup)
method init(_self, propertyNames)
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup)
propertyNames (string )
method get(_self, key)
get values array from a given property name
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
key (string) : : key name of selected property. Default is "index"
Returns: values array
method size(_self)
get size of values array. By default it equals to current bar_index
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
Returns: size of values array
method push(_self, key, value)
push single value to specific property
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
key (string) : : key name of selected property
value (float) : : property value
Returns: CandlesGroup object
method push(_self, arr)
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup)
arr (float )
method populate(_self, ohlc)
populate ohlc to CandlesGroup
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
ohlc (float ) : : array of ohlc
Returns: CandlesGroup object
method populate(_self, values, propertiesNames)
populate values base on given properties Names
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
values (float ) : : array of property values
propertiesNames (string ) : : an array stores property names. Use as keys to get values
Returns: CandlesGroup object
method populate(_self)
populate values (default setup)
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
Returns: CandlesGroup object
method lookback(arr, bars_lookback)
get property value on previous candles. For current candle, use *.lookback()
Namespace types: float
Parameters:
arr (float ) : : array of selected property values
bars_lookback (int) : : number of candles lookback. 0 = current candle. Default is 0
Returns: single property value
method highest_within_bars(_self, hiSource, start, end, useIndex)
get the highest property value between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
hiSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns: the highest value within candles
method highest_within_bars(_self, returnWithIndex, hiSource, start, end, useIndex)
get the highest property value and bar index between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
returnWithIndex (bool) : : the function only applicable when it is true
hiSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns:
method highest_point_within_bars(_self, hiSource, start, end, useIndex)
get a Point object which contains highest property value between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
hiSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns: Point object contains highest property value
method lowest_within_bars(_self, loSource, start, end, useIndex)
get the lowest property value between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
loSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns: the lowest value within candles
method lowest_within_bars(_self, returnWithIndex, loSource, start, end, useIndex)
get the lowest property value and bar index between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
returnWithIndex (bool) : : the function only applicable when it is true
loSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns:
method lowest_point_within_bars(_self, loSource, start, end, useIndex)
get a Point object which contains lowest property value between specific candles
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
loSource (string) : : key name of selected property
start (int) : : start bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true
end (int) : : end bar for calculation. Default is candles lookback value from current candle. 'index' value is used if 'useIndex' = true. Default is 0
useIndex (bool) : : use index instead of lookback value. Default = false
Returns: Point object contains lowest property value
method time2bar(_self, t)
Convert UNIX time to bar index of active chart
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
t (int) : : UNIX time
Returns: bar index
method time2bar(_self, timezone, YYYY, MMM, DD, hh, mm, ss)
Convert timestamp to bar index of active chart. User defined timezone required
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
timezone (string) : : User defined timezone
YYYY (int) : : Year
MMM (int) : : Month
DD (int) : : Day
hh (int) : : Hour. Default is 0
mm (int) : : Minute. Default is 0
ss (int) : : Second. Default is 0
Returns: bar index
method time2bar(_self, YYYY, MMM, DD, hh, mm, ss)
Convert timestamp to bar index of active chart
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
YYYY (int) : : Year
MMM (int) : : Month
DD (int) : : Day
hh (int) : : Hour. Default is 0
mm (int) : : Minute. Default is 0
ss (int) : : Second. Default is 0
Returns: bar index
method get_prop_from_time(_self, key, t)
get single property value from UNIX time
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
key (string) : : key name of selected property
t (int) : : UNIX time
Returns: single property value
method get_prop_from_time(_self, key, timezone, YYYY, MMM, DD, hh, mm, ss)
get single property value from timestamp. User defined timezone required
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
key (string) : : key name of selected property
timezone (string) : : User defined timezone
YYYY (int) : : Year
MMM (int) : : Month
DD (int) : : Day
hh (int) : : Hour. Default is 0
mm (int) : : Minute. Default is 0
ss (int) : : Second. Default is 0
Returns: single property value
method get_prop_from_time(_self, key, YYYY, MMM, DD, hh, mm, ss)
get single property value from timestamp
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
key (string) : : key name of selected property
YYYY (int) : : Year
MMM (int) : : Month
DD (int) : : Day
hh (int) : : Hour. Default is 0
mm (int) : : Minute. Default is 0
ss (int) : : Second. Default is 0
Returns: single property value
method bar2time(_self, index)
Convert bar index of active chart to UNIX time
Namespace types: CandlesGroup
Parameters:
_self (CandlesGroup) : : CandlesGroup object
index (int) : : bar index
Returns: UNIX time
Point
A point on chart
Fields:
price (series float) : : price value
bar (series int) : : bar index
bartime (series int) : : time in UNIX format of bar
Property
Property object which contains values of all candles
Fields:
name (series string) : : name of property
values (float ) : : an array stores values of all candles. Size of array = bar_index
CandlesGroup
Candles Group object which contains properties of all candles
Fields:
propertyNames (string ) : : an array stores property names. Use as keys to get values
properties (Property ) : : array of Property objects
lib_trackingLibrary "lib_tracking"
tracking highest and lowest with anchor point to track over dynamic periods, e.g. to track a Session HH/LL live and get the bar/time of the LTF wick that matches the HTF HH/LL
// DESIGN DECISION
// why anchored replacements for ta.highest / ta.highestbars / ta.lowest / ta.lowestbars:
// 1. they require a fixed length/lookback which makes it easier to calculate, but
// 2. this prevents us from tracking the HH/LL of a changing timeframe, e.g. live tracking the HH/LL of a running session or unfinished higher timeframe
// 3. tracking with anchor/start/reset flag allows to persist values until the next start/reset, so no other external storage is required
track_highest(value, reset, track_this_bar)
Parameters:
value (float)
reset (bool) : boolean flag to restart tracking from this point (a.k.a anchor)
track_this_bar (bool) : allows enabling and disabling of tracking, e.g. before a session starts or after it ends, values can be kept until next reset.
track_lowest(value, reset, track_this_bar)
Parameters:
value (float)
reset (bool) : boolean flag to restart tracking from this point (a.k.a anchor)
track_this_bar (bool) : allows enabling and disabling of tracking, e.g. before a session starts or after it ends, values can be kept until next reset.
track_hl_htf(htf, value_high, value_low)
Parameters:
htf (string) : the higher timeframe in pinescript string notation
value_high (float)
value_low (float)
Returns:
lib_arrayLibrary "lib_array"
several array functions for chained calls, batch conversion, incrementing and comparing arrays.
method sort(id, descending)
Namespace types: int
Parameters:
id (int ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method sort(id, descending)
Namespace types: float
Parameters:
id (float ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method sort(id, descending)
Namespace types: string
Parameters:
id (string ) : The array to sort (and return again)
descending (bool) : The sort order: order.ascending (default:false, meaning omit this param and just call myArray.sort()) or order.descending => set descending=true
@return The array that was passed as parameter id
method increment(id, by_value)
Namespace types: int
Parameters:
id (int ) : The array to increment (and return again)
by_value (int) : The value by which to increment (default: 1)
@return The array that was passed as parameter id
method increment(id, by_value)
Namespace types: float
Parameters:
id (float ) : The array to increment (and return again)
by_value (float) : The value by which to increment (default: 1.0)
@return The array that was passed as parameter id
method decrement(id, by_value)
Namespace types: int
Parameters:
id (int ) : The array to increment (and return again)
by_value (int) : The value by which to increment (default: 1)
@return The array that was passed as parameter id
method decrement(id, by_value)
Namespace types: float
Parameters:
id (float ) : The array to increment (and return again)
by_value (float) : The value by which to increment (default: 1.0)
@return The array that was passed as parameter id
method toint(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method toint(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tofloat(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method tofloat(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tostring(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tostring(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tobool(id)
Namespace types: float
Parameters:
id (float ) : The array to convert
method tobool(id)
Namespace types: int
Parameters:
id (int ) : The array to convert
method tobool(id)
Namespace types: string
Parameters:
id (string ) : The array to convert
method sum(id)
Namespace types: bool
Parameters:
id (bool ) : The array to convert
method enqueue(id, item, max, condition, lifo)
Namespace types: int
Parameters:
id (int ) : The array that is used as queue
item (int) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: float
Parameters:
id (float ) : The array that is used as queue
item (float) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: string
Parameters:
id (string ) : The array that is used as queue
item (string) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: line
Parameters:
id (line ) : The array that is used as queue
item (line) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
method enqueue(id, item, max, condition, lifo)
Namespace types: box
Parameters:
id (box ) : The array that is used as queue
item (box) : The item to enqueue (at pos 0, unless lifo = true)
max (int) : The max size of the queue
condition (bool) : An optional flag that allows disabling the adding, which in turn will prevent for in loops from ever running and save performance where not needed
lifo (bool) : An optional flag that allows to change the behavior from First In Last Out (default and consistent with pine scripts history operator with most recent elements at index 0) to a more common and resource efficient approach in programming languages: Last In First Out
Returns: The queue passed as param id
PivotLibrary "Pivot"
This library helps you store and manage pivots.
bias(isHigh, isHigher, prevWasHigher)
Helper function to calculate bias.
Parameters:
isHigh (bool) : (bool) Wether the pivot is a pivot high or not.
isHigher (bool) : (bool) Wether the pivot is a higher pivot or not.
@return (bool) The bias (true = bullish, false = bearish, na = neutral).
prevWasHigher (bool)
biasToString(bias)
Parameters:
bias (bool)
biasToColor(bias, theme)
Parameters:
bias (bool)
theme (Theme)
nameString(isHigh, isHigher)
Parameters:
isHigh (bool)
isHigher (bool)
abbrString(isHigh, isHigher)
Parameters:
isHigh (bool)
isHigher (bool)
tooltipString(y, isHigh, isHigher, bias, theme)
Parameters:
y (float)
isHigh (bool)
isHigher (bool)
bias (bool)
theme (Theme)
createLabel(x, y, isHigh, isHigher, prevWasHigher, settings)
Parameters:
x (int)
y (float)
isHigh (bool)
isHigher (bool)
prevWasHigher (bool)
settings (Settings)
new(x, y, isHigh, isHigher, settings)
Parameters:
x (int)
y (float)
isHigh (bool)
isHigher (bool)
settings (Settings)
newArray(size, initialValue)
Parameters:
size (int)
initialValue (Pivot)
method getFirst(this)
Namespace types: Pivot
Parameters:
this (Pivot )
method getLast(this, isHigh)
Namespace types: Pivot
Parameters:
this (Pivot )
isHigh (bool)
method getLastHigh(this)
Namespace types: Pivot
Parameters:
this (Pivot )
method getLastLow(this)
Namespace types: Pivot
Parameters:
this (Pivot )
method getPrev(this, numBack, isHigh)
Namespace types: Pivot
Parameters:
this (Pivot )
numBack (int)
isHigh (bool)
method getPrevHigh(this, numBack)
Namespace types: Pivot
Parameters:
this (Pivot )
numBack (int)
method getPrevLow(this, numBack)
Namespace types: Pivot
Parameters:
this (Pivot )
numBack (int)
method getText(this)
Namespace types: Pivot
Parameters:
this (Pivot)
method setX(this, value)
Namespace types: Pivot
Parameters:
this (Pivot)
value (int)
method setY(this, value)
Namespace types: Pivot
Parameters:
this (Pivot)
value (float)
method setXY(this, x, y)
Namespace types: Pivot
Parameters:
this (Pivot)
x (int)
y (float)
method setBias(this, value)
Namespace types: Pivot
Parameters:
this (Pivot)
value (int)
method setColor(this, value)
Namespace types: Pivot
Parameters:
this (Pivot)
value (color)
method setText(this, value)
Namespace types: Pivot
Parameters:
this (Pivot)
value (string)
method add(this, pivot)
Namespace types: Pivot
Parameters:
this (Pivot )
pivot (Pivot)
method updateLast(this, y, settings)
Namespace types: Pivot
Parameters:
this (Pivot )
y (float)
settings (Settings)
method update(this, y, isHigh, settings)
Namespace types: Pivot
Parameters:
this (Pivot )
y (float)
isHigh (bool)
settings (Settings)
Pivot
Stores Pivot data.
Fields:
x (series int)
y (series float)
isHigh (series bool)
isHigher (series bool)
bias (series bool)
lb (series label)
Theme
Attributes for customizable look and feel.
Fields:
size (series string)
colorDefault (series color)
colorNeutral (series color)
colorBullish (series color)
colorBearish (series color)
colored (series bool)
showTooltips (series bool)
showTooltipName (series bool)
showTooltipValue (series bool)
showTooltipBias (series bool)
Settings
All settings for the pivot.
Fields:
theme (Theme)
RelativeValue█ OVERVIEW
This library is a Pine Script™ programmer's tool offering the ability to compute relative values, which represent comparisons of current data points, such as volume, price, or custom indicators, with their analogous historical data points from corresponding time offsets. This approach can provide insightful perspectives into the intricate dynamics of relative market behavior over time.
█ CONCEPTS
Relative values
In this library, a relative value is a metric that compares a current data point in a time interval to an average of data points with corresponding time offsets across historical periods. Its purpose is to assess the significance of a value by considering the historical context within past time intervals.
For instance, suppose we wanted to calculate relative volume on an hourly chart over five daily periods, and the last chart bar is two hours into the current trading day. In this case, we would compare the current volume to the average of volume in the second hour of trading across five days. We obtain the relative volume value by dividing the current volume by this average.
This form of analysis rests on the hypothesis that substantial discrepancies or aberrations in present market activity relative to historical time intervals might help indicate upcoming changes in market trends.
Cumulative and non-cumulative values
In the context of this library, a cumulative value refers to the cumulative sum of a series since the last occurrence of a specific condition (referred to as `anchor` in the function definitions). Given that relative values depend on time, we use time-based conditions such as the onset of a new hour, day, etc. On the other hand, a non-cumulative value is simply the series value at a specific time without accumulation.
Calculating relative values
Four main functions coordinate together to compute the relative values: `maintainArray()`, `calcAverageByTime()`, `calcCumulativeSeries()`, and `averageAtTime()`. These functions are underpinned by a `collectedData` user-defined type (UDT), which stores data collected since the last reset of the timeframe along with their corresponding timestamps. The relative values are calculated using the following procedure:
1. The `averageAtTime()` function invokes the process leveraging all four of the methods and acts as the main driver of the calculations. For each bar, this function adds the current bar's source and corresponding time value to a `collectedData` object.
2. Within the `averageAtTime()` function, the `maintainArray()` function is called at the start of each anchor period. It adds a new `collectedData` object to the array and ensures the array size does not exceed the predefined `maxSize` by removing the oldest element when necessary. This method plays an essential role in limiting memory usage and ensuring only relevant data over the desired number of periods is in the calculation window.
3. Next, the `calcAverageByTime()` function calculates the average value of elements within the `data` field for each `collectedData` object that corresponds to the same time offset from each anchor condition. This method accounts for cases where the current index of a `collectedData` object exceeds the last index of any past objects by using the last available values instead.
4. For cumulative calculations, the `averageAtTime()` function utilizes the `isCumulative` boolean parameter. If true, the `calcCumulativeSeries()` function will track the running total of the source data from the last bar where the anchor condition was met, providing a cumulative sum of the source values from one anchor point to the next.
To summarize, the `averageAtTime()` function continually stores values with their corresponding times in a `collectedData` object for each bar in the anchor period. When the anchor resets, this object is added to a larger array. The array's size is limited by the specified number of periods to be averaged. To correlate data across these periods, time indexing is employed, enabling the function to compare corresponding points across multiple periods.
█ USING THIS LIBRARY
The library simplifies the complex process of calculating relative values through its intuitive functions. Follow the steps below to use this library in your scripts.
Step 1: Import the library and declare inputs
Import the library and declare variables based on the user's input. These can include the timeframe for each period, the number of time intervals to include in the average, and whether the calculation uses cumulative values. For example:
//@version=5
import TradingView/RelativeValue/1 as TVrv
indicator("Relative Range Demo")
string resetTimeInput = input.timeframe("D")
int lengthInput = input.int(5, "No. of periods")
Step 2: Define the anchor condition
With these inputs declared, create a condition to define the start of a new period (anchor). For this, we use the change in the time value from the input timeframe:
bool anchor = timeframe.change(resetTimeInput)
Step 3: Calculate the average
At this point, one can calculate the average of a value's history at the time offset from the anchor over a number of periods using the `averageAtTime()` function. In this example, we use True Range (TR) as the `source` and set `isCumulative` to false:
float pastRange = TVrv.averageAtTime(ta.tr, lengthInput, anchor, false)
Step 4: Display the data
You can visualize the results by plotting the returned series. These lines display the non-cumulative TR alongside the average value over `lengthInput` periods for relative comparison:
plot(pastRange, "Past True Range Avg", color.new(chart.bg_color, 70), 1, plot.style_columns)
plot(ta.tr, "True Range", close >= open ? color.new(color.teal, 50) : color.new(color.red, 50), 1, plot.style_columns)
This example will display two overlapping series of columns. The green and red columns depict the current TR on each bar, and the light gray columns show the average over a defined number of periods, e.g., the default inputs on an hourly chart will show the average value at the hour over the past five days. This comparative analysis aids in determining whether the range of a bar aligns with its typical historical values or if it's an outlier.
█ NOTES
• The foundational concept of this library was derived from our initial Relative Volume at Time script. This library's logic significantly boosts its performance. Keep an eye out for a forthcoming updated version of the indicator. The demonstration code included in the library emulates a streamlined version of the indicator utilizing the library functions.
• Key efficiencies in the data management are realized through array.binary_search_leftmost() , which offers a performance improvement in comparison to its loop-dependent counterpart.
• This library's architecture utilizes user-defined types (UDTs) to create custom objects which are the equivalent of variables containing multiple parts, each able to hold independent values of different types . The recently added feature was announced in this blog post.
• To enhance readability, the code substitutes array functions with equivalent methods .
Look first. Then leap.
█ FUNCTIONS
This library contains the following functions:
calcCumulativeSeries(source, anchor)
Calculates the cumulative sum of `source` since the last bar where `anchor` was `true`.
Parameters:
source (series float) : Source used for the calculation.
anchor (series bool) : The condition that triggers the reset of the calculation. The calculation is reset when `anchor` evaluates to `true`, and continues using the values accumulated since the previous reset when `anchor` is `false`.
Returns: (float) The cumulative sum of `source`.
averageAtTime(source, length, anchor, isCumulative)
Calculates the average of all `source` values that share the same time difference from the `anchor` as the current bar for the most recent `length` bars.
Parameters:
source (series float) : Source used for the calculation.
length (simple int) : The number of reset periods to consider for the average calculation of historical data.
anchor (series bool) : The condition that triggers the reset of the average calculation. The calculation is reset when `anchor` evaluates to `true`, and continues using the values accumulated since the previous reset when `anchor` is `false`.
isCumulative (simple bool) : If `true`, `source` values are accumulated until the next time `anchor` is `true`. Optional. The default is `true`.
Returns: (float) The average of the source series at the specified time difference.
cphelperLibrary "cphelper"
ACPU helper library - for private use. Not so meaningful for others.
calculate_rr(targetArray, rrArray, breakevenOnTarget1)
calculates risk reward for given targets
Parameters:
targetArray (float ) : array of targets
rrArray (float ) : array of risk reward
breakevenOnTarget1 (simple bool) : option to breakeven
Returns: array rrArray
trendPairs(l1StartX, l1StartY, l1EndX, l1EndY, l2StartX, l2StartY, l2EndX, l2EndY, zgColor)
creates trendline pairs
Parameters:
l1StartX (int) : startX of first line
l1StartY (float) : startY of first line
l1EndX (int) : endX of first line
l1EndY (float) : endY of first line
l2StartX (int) : startX of second line
l2StartY (float) : startY of second line
l2EndX (int) : endX of second line
l2EndY (float) : endY of second line
zgColor (color) : line color
Returns:
find_type(l1t, l2t, channelThreshold)
Finds type based on trendline pairs
Parameters:
l1t (line) : line1
l2t (line) : line2
channelThreshold (simple float) : theshold for channel identification
Returns: pattern type and flags
getFlags(flags)
Flatten flags
Parameters:
flags (bool ) : array of flags
Returns: - flattened flags isChannel, isTriangle, isWedge, isExpanding, isContracting, isFlat, isRising, isFalling
getType(typeNum)
Get type based on type number
Parameters:
typeNum (int) : number representing type
Returns: String value of type
getStatus(status, maxStatus)
Get status based on integer value representations
Parameters:
status (int) : integer representing current status
maxStatus (int) : integer representing max status
Returns: String status value
calculate_simple_targets(trendLines, settingsMatrix, patternTypeMapping, patternType)
Calculate targets based on trend lines
Parameters:
trendLines (line ) : trendline pair array
settingsMatrix (matrix) : matrix containing settings
patternTypeMapping (string ) : array containing pattern type mapping
patternType (int) : pattern type
Returns: arrays containing long and short calculated targets
recalculate_position(patternTypeAndStatusMatrix, targetMatrix, index, pIndex, status, maxStatus, targetValue, stopValue, dir, breakevenOnTarget1)
Recalculate position values
Parameters:
patternTypeAndStatusMatrix (matrix) : matrix containing pattern type and status
targetMatrix (matrix) : matrix containing targets
index (int) : current index
pIndex (int) : pattern index
status (int) : current status
maxStatus (int) : max status reached
targetValue (float) : current target value
stopValue (float) : current stop value
dir (int) : direction
breakevenOnTarget1 (simple bool) : flag to breakeven upon target1
Returns: new status and maxStatus values
draw_targets(longTargets, shortTargets, index, labelColor, patternName, positionIndex, longMaxStatus, longStatus, shortMaxStatus, shortStatus, tempBoxes, tempLines, tempLabels)
Draw targets on chart
Parameters:
longTargets (matrix) : matrix containing long targets
shortTargets (matrix) : matrix containing short targets
index (int) : current index
labelColor (color) : color of lines and labels
patternName (string) : Pattern name
positionIndex (int) : position on the chart
longMaxStatus (int) : max status for long
longStatus (int) : long status value
shortMaxStatus (int) : max status for short
shortStatus (int) : short status value
tempBoxes (box ) : temporary box array
tempLines (line ) : temporary lines array
tempLabels (label ) : temporary labels array
Returns: void
populate_open_stats(patternIdArray, barMatrix, patternTypeAndStatusMatrix, patternColorArray, longTargets, shortTargets, patternRRMatrix, OpenStatPosition, lblSizeOpenTrades)
Populate open stats table
Parameters:
patternIdArray (int ) : pattern Ids
barMatrix (matrix) : matrix containing bars
patternTypeAndStatusMatrix (matrix) : matrix containing pattern type and status
patternColorArray (color ) : array containing current patter colors
longTargets (matrix) : matrix of long targets
shortTargets (matrix) : matrix of short targets
patternRRMatrix (matrix) : pattern risk reward matrix
OpenStatPosition (simple string) : table position
lblSizeOpenTrades (simple string) : text size
Returns: void
draw_pattern_label(trendLines, patternFlagMatrix, patternTypeAndStatusMatrix, patternColorArray, patternFlags, patternLabelArray, zgColor, patternType, drawLabel, clearOldPatterns, safeRepaint, maxPatternsReference)
Parameters:
trendLines (line )
patternFlagMatrix (matrix)
patternTypeAndStatusMatrix (matrix)
patternColorArray (color )
patternFlags (bool )
patternLabelArray (label )
zgColor (color)
patternType (int)
drawLabel (simple bool)
clearOldPatterns (simple bool)
safeRepaint (simple bool)
maxPatternsReference (simple int)
populate_closed_stats(patternTypeAndStatusMatrix, bullishCounts, bearishCounts, bullishRetouchCounts, bearishRetouchCounts, bullishSizeMatrix, bearishSizeMatrix, bullishRR, bearishRR, ClosedStatsPosition, lblSizeClosedTrades, showSelectivePatternStats, showPatternStats, showStatsInPercentage)
Parameters:
patternTypeAndStatusMatrix (matrix)
bullishCounts (matrix)
bearishCounts (matrix)
bullishRetouchCounts (matrix)
bearishRetouchCounts (matrix)
bullishSizeMatrix (matrix)
bearishSizeMatrix (matrix)
bullishRR (matrix)
bearishRR (matrix)
ClosedStatsPosition (simple string)
lblSizeClosedTrades (simple string)
showSelectivePatternStats (simple bool)
showPatternStats (simple bool)
showStatsInPercentage (simple bool)
Vector3Library "Vector3"
Representation of 3D vectors and points.
This structure is used to pass 3D positions and directions around. It also contains functions for doing common vector operations.
Besides the functions listed below, other classes can be used to manipulate vectors and points as well.
For example the Quaternion and the Matrix4x4 classes are useful for rotating or transforming vectors and points.
___
**Reference:**
- github.com
- github.com
- github.com
- www.movable-type.co.uk
- docs.unity3d.com
- referencesource.microsoft.com
- github.com
\
new(x, y, z)
Create a new `Vector3`.
Parameters:
x (float) : `float` Property `x` value, (optional, default=na).
y (float) : `float` Property `y` value, (optional, default=na).
z (float) : `float` Property `z` value, (optional, default=na).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.new(1.1, 1, 1)
```
from(value)
Create a new `Vector3` from a single value.
Parameters:
value (float) : `float` Properties positional value, (optional, default=na).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.from(1.1)
```
from_Array(values, fill_na)
Create a new `Vector3` from a list of values, only reads up to the third item.
Parameters:
values (float ) : `array` Vector property values.
fill_na (float) : `float` Parameter value to replace missing indexes, (optional, defualt=na).
Returns: `Vector3` Generated new vector.
___
**Notes:**
- Supports any size of array, fills non available fields with `na`.
___
**Usage:**
```
.from_Array(array.from(1.1, fill_na=33))
.from_Array(array.from(1.1, 2, 3))
```
from_Vector2(values)
Create a new `Vector3` from a `Vector2`.
Parameters:
values (Vector2 type from RicardoSantos/CommonTypesMath/1) : `Vector2` Vector property values.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.from:Vector2(.Vector2.new(1, 2.0))
```
___
**Notes:**
- Type `Vector2` from CommonTypesMath library.
from_Quaternion(values)
Create a new `Vector3` from a `Quaternion`'s `x, y, z` properties.
Parameters:
values (Quaternion type from RicardoSantos/CommonTypesMath/1) : `Quaternion` Vector property values.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.from_Quaternion(.Quaternion.new(1, 2, 3, 4))
```
___
**Notes:**
- Type `Quaternion` from CommonTypesMath library.
from_String(expression, separator, fill_na)
Create a new `Vector3` from a list of values in a formated string.
Parameters:
expression (string) : `array` String with the list of vector properties.
separator (string) : `string` Separator between entries, (optional, default=`","`).
fill_na (float) : `float` Parameter value to replace missing indexes, (optional, defualt=na).
Returns: `Vector3` Generated new vector.
___
**Notes:**
- Supports any size of array, fills non available fields with `na`.
- `",,"` Empty fields will be ignored.
___
**Usage:**
```
.from_String("1.1", fill_na=33))
.from_String("(1.1,, 3)") // 1.1 , 3.0, NaN // empty field will be ignored!!
```
back()
Create a new `Vector3` object in the form `(0, 0, -1)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.back()
```
front()
Create a new `Vector3` object in the form `(0, 0, 1)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.front()
```
up()
Create a new `Vector3` object in the form `(0, 1, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.up()
```
down()
Create a new `Vector3` object in the form `(0, -1, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.down()
```
left()
Create a new `Vector3` object in the form `(-1, 0, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.left()
```
right()
Create a new `Vector3` object in the form `(1, 0, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.right()
```
zero()
Create a new `Vector3` object in the form `(0, 0, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.zero()
```
one()
Create a new `Vector3` object in the form `(1, 1, 1)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.one()
```
minus_one()
Create a new `Vector3` object in the form `(-1, -1, -1)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.minus_one()
```
unit_x()
Create a new `Vector3` object in the form `(1, 0, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.unit_x()
```
unit_y()
Create a new `Vector3` object in the form `(0, 1, 0)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.unit_y()
```
unit_z()
Create a new `Vector3` object in the form `(0, 0, 1)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.unit_z()
```
nan()
Create a new `Vector3` object in the form `(na, na, na)`.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.nan()
```
random(max, min)
Generate a vector with random properties.
Parameters:
max (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Maximum defined range of the vector properties.
min (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Minimum defined range of the vector properties.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.random(.from(math.pi), .from(-math.pi))
```
random(max)
Generate a vector with random properties (min set to 0.0).
Parameters:
max (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Maximum defined range of the vector properties.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
.random(.from(math.pi))
```
method copy(this)
Copy a existing `Vector3`
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .one().copy()
```
method i_add(this, other)
Modify a instance of a vector by adding a vector to it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_add(.up())
```
method i_add(this, value)
Modify a instance of a vector by adding a vector to it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_add(3.2)
```
method i_subtract(this, other)
Modify a instance of a vector by subtracting a vector to it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_subtract(.down())
```
method i_subtract(this, value)
Modify a instance of a vector by subtracting a vector to it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_subtract(3)
```
method i_multiply(this, other)
Modify a instance of a vector by multiplying a vector with it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_multiply(.left())
```
method i_multiply(this, value)
Modify a instance of a vector by multiplying a vector with it.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_multiply(3)
```
method i_divide(this, other)
Modify a instance of a vector by dividing it by another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_divide(.forward())
```
method i_divide(this, value)
Modify a instance of a vector by dividing it by another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_divide(3)
```
method i_mod(this, other)
Modify a instance of a vector by modulo assignment with another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_mod(.back())
```
method i_mod(this, value)
Modify a instance of a vector by modulo assignment with another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_mod(3)
```
method i_pow(this, exponent)
Modify a instance of a vector by modulo assignment with another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
exponent (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Exponent Vector.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_pow(.up())
```
method i_pow(this, exponent)
Modify a instance of a vector by modulo assignment with another vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
exponent (float) : `float` Exponent Value.
Returns: `Vector3` Updated source vector.
___
**Usage:**
```
a = .from(1) , a.i_pow(2)
```
method length_squared(this)
Squared length of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1)
Returns: `float` The squared length of this vector.
___
**Usage:**
```
a = .one().length_squared()
```
method magnitude_squared(this)
Squared magnitude of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `float` The length squared of this vector.
___
**Usage:**
```
a = .one().magnitude_squared()
```
method length(this)
Length of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `float` The length of this vector.
___
**Usage:**
```
a = .one().length()
```
method magnitude(this)
Magnitude of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `float` The Length of this vector.
___
**Usage:**
```
a = .one().magnitude()
```
method normalize(this, magnitude, eps)
Normalize a vector with a magnitude of 1(optional).
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
magnitude (float) : `float` Value to manipulate the magnitude of normalization, (optional, default=1.0).
eps (float)
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .new(33, 50, 100).normalize() // (x=0.283, y=0.429, z=0.858)
a = .new(33, 50, 100).normalize(2) // (x=0.142, y=0.214, z=0.429)
```
method to_String(this, precision)
Converts source vector to a string format, in the form `"(x, y, z)"`.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
precision (string) : `string` Precision format to apply to values (optional, default='').
Returns: `string` Formated string in a `"(x, y, z)"` format.
___
**Usage:**
```
a = .one().to_String("#.###")
```
method to_Array(this)
Converts source vector to a array format.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `array` List of the vector properties.
___
**Usage:**
```
a = .new(1, 2, 3).to_Array()
```
method to_Vector2(this)
Converts source vector to a Vector2 in the form `x, y`.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector2` Generated new vector.
___
**Usage:**
```
a = .from(1).to_Vector2()
```
method to_Quaternion(this, w)
Converts source vector to a Quaternion in the form `x, y, z, w`.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Sorce vector.
w (float) : `float` Property of `w` new value.
Returns: `Quaternion` Generated new vector.
___
**Usage:**
```
a = .from(1).to_Quaternion(w=1)
```
method add(this, other)
Add a vector to source vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).add(.unit_z())
```
method add(this, value)
Add a value to each property of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).add(2.0)
```
add(value, other)
Add each property of a vector to a base value as a new vector.
Parameters:
value (float) : `float` Value.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(2) , b = .add(1.0, a)
```
method subtract(this, other)
Subtract vector from source vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).subtract(.left())
```
method subtract(this, value)
Subtract a value from each property in source vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).subtract(2.0)
```
subtract(value, other)
Subtract each property in a vector from a base value and create a new vector.
Parameters:
value (float) : `float` Value.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .subtract(1.0, .right())
```
method multiply(this, other)
Multiply a vector by another.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).multiply(.up())
```
method multiply(this, value)
Multiply each element in source vector with a value.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).multiply(2.0)
```
multiply(value, other)
Multiply a value with each property in a vector and create a new vector.
Parameters:
value (float) : `float` Value.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .multiply(1.0, .new(1, 2, 1))
```
method divide(this, other)
Divide a vector by another.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).divide(.from(2))
```
method divide(this, value)
Divide each property in a vector by a value.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).divide(2.0)
```
divide(value, other)
Divide a base value by each property in a vector and create a new vector.
Parameters:
value (float) : `float` Value.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .divide(1.0, .from(2))
```
method mod(this, other)
Modulo a vector by another.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).mod(.from(2))
```
method mod(this, value)
Modulo each property in a vector by a value.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
value (float) : `float` Value.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).mod(2.0)
```
mod(value, other)
Modulo a base value by each property in a vector and create a new vector.
Parameters:
value (float) : `float` Value.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .mod(1.0, .from(2))
```
method negate(this)
Negate a vector in the form `(zero - this)`.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .one().negate()
```
method pow(this, other)
Modulo a vector by another.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(2).pow(.from(3))
```
method pow(this, exponent)
Raise the vector elements by a exponent.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
exponent (float) : `float` The exponent to raise the vector by.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).pow(2.0)
```
pow(value, exponent)
Raise value into a vector raised by the elements in exponent vector.
Parameters:
value (float) : `float` Base value.
exponent (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` The exponent to raise the vector of base value by.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .pow(1.0, .from(2))
```
method sqrt(this)
Square root of the elements in a vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).sqrt()
```
method abs(this)
Absolute properties of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).abs()
```
method max(this)
Highest property of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `float` Highest value amongst the vector properties.
___
**Usage:**
```
a = .new(1, 2, 3).max()
```
method min(this)
Lowest element of the vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `float` Lowest values amongst the vector properties.
___
**Usage:**
```
a = .new(1, 2, 3).min()
```
method floor(this)
Floor of vector a.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .new(1.33, 1.66, 1.99).floor()
```
method ceil(this)
Ceil of vector a.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .new(1.33, 1.66, 1.99).ceil()
```
method round(this)
Round of vector elements.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .new(1.33, 1.66, 1.99).round()
```
method round(this, precision)
Round of vector elements to n digits.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
precision (int) : `int` Number of digits to round the vector elements.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .new(1.33, 1.66, 1.99).round(1) // 1.3, 1.7, 2
```
method fractional(this)
Fractional parts of vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1.337).fractional() // 0.337
```
method dot_product(this, other)
Dot product of two vectors.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `float` Dot product.
___
**Usage:**
```
a = .from(2).dot_product(.left())
```
method cross_product(this, other)
Cross product of two vectors.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).cross_produc(.right())
```
method scale(this, scalar)
Scale vector by a scalar value.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
scalar (float) : `float` Value to scale the the vector by.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).scale(2)
```
method rescale(this, magnitude)
Rescale a vector to a new magnitude.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
magnitude (float) : `float` Value to manipulate the magnitude of normalization.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(20).rescale(1)
```
method equals(this, other)
Compares two vectors.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
other (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Other vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).equals(.one())
```
method sin(this)
Sine of vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).sin()
```
method cos(this)
Cosine of vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).cos()
```
method tan(this)
Tangent of vector.
Namespace types: TMath.Vector3
Parameters:
this (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .from(1).tan()
```
vmax(a, b)
Highest elements of the properties from two vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .vmax(.one(), .from(2))
```
vmax(a, b, c)
Highest elements of the properties from three vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
c (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .vmax(.new(0.1, 2.5, 3.4), .from(2), .from(3))
```
vmin(a, b)
Lowest elements of the properties from two vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .vmin(.one(), .from(2))
```
vmin(a, b, c)
Lowest elements of the properties from three vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
c (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .vmin(.one(), .from(2), .new(3.3, 2.2, 0.5))
```
distance(a, b)
Distance between vector `a` and `b`.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = distance(.from(3), .unit_z())
```
clamp(a, min, max)
Restrict a vector between a min and max vector.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
min (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Minimum boundary vector.
max (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Maximum boundary vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .clamp(a=.new(2.9, 1.5, 3.9), min=.from(2), max=.new(2.5, 3.0, 3.5))
```
clamp_magnitude(a, radius)
Vector with its magnitude clamped to a radius.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.object, vector with properties that should be restricted to a radius.
radius (float) : `float` Maximum radius to restrict magnitude of vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .clamp_magnitude(.from(21), 7)
```
lerp_unclamped(a, b, rate)
`Unclamped` linearly interpolates between provided vectors by a rate.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
rate (float) : `float` Rate of interpolation, range(0 > 1) where 0 == source vector and 1 == target vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .lerp_unclamped(.from(1), .from(2), 1.2)
```
lerp(a, b, rate)
Linearly interpolates between provided vectors by a rate.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
rate (float) : `float` Rate of interpolation, range(0 > 1) where 0 == source vector and 1 == target vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = lerp(.one(), .from(2), 0.2)
```
herp(start, start_tangent, end, end_tangent, rate)
Hermite curve interpolation between provided vectors.
Parameters:
start (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Start vector.
start_tangent (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Start vector tangent.
end (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` End vector.
end_tangent (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` End vector tangent.
rate (int) : `float` Rate of the movement from `start` to `end` to get position, should be range(0 > 1).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
s = .new(0, 0, 0) , st = .new(0, 1, 1)
e = .new(1, 2, 2) , et = .new(-1, -1, 3)
h = .herp(s, st, e, et, 0.3)
```
___
**Reference:** en.m.wikibooks.org
herp_2(a, b, rate)
Hermite curve interpolation between provided vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
rate (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Rate of the movement per component from `start` to `end` to get position, should be range(0 > 1).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
h = .herp_2(.one(), .new(0.1, 3, 2), 0.6)
```
noise(a)
3D Noise based on Morgan McGuire @morgan3d
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = noise(.one())
```
___
**Reference:**
- thebookofshaders.com
- www.shadertoy.com
rotate(a, axis, angle)
Rotate a vector around a axis.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
axis (string) : `string` The plane to rotate around, `option="x", "y", "z"`.
angle (float) : `float` Angle in radians.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .rotate(.from(3), 'y', math.toradians(45.0))
```
rotate_x(a, angle)
Rotate a vector on a fixed `x`.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
angle (float) : `float` Angle in radians.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .rotate_x(.from(3), math.toradians(90.0))
```
rotate_y(a, angle)
Rotate a vector on a fixed `y`.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
angle (float) : `float` Angle in radians.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .rotate_y(.from(3), math.toradians(90.0))
```
rotate_yaw_pitch(a, yaw, pitch)
Rotate a vector by yaw and pitch values.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
yaw (float) : `float` Angle in radians.
pitch (float) : `float` Angle in radians.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .rotate_yaw_pitch(.from(3), math.toradians(90.0), math.toradians(45.0))
```
project(a, normal, eps)
Project a vector off a plane defined by a normal.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
normal (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` The normal of the surface being reflected off.
eps (float) : `float` Minimum resolution to void division by zero (default=0.000001).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .project(.one(), .down())
```
project_on_plane(a, normal, eps)
Projects a vector onto a plane defined by a normal orthogonal to the plane.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
normal (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` The normal of the surface being reflected off.
eps (float) : `float` Minimum resolution to void division by zero (default=0.000001).
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .project_on_plane(.one(), .left())
```
project_to_2d(a, camera_position, camera_target)
Project a vector onto a two dimensions plane.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
camera_position (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Camera position.
camera_target (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Camera target plane position.
Returns: `Vector2` Generated new vector.
___
**Usage:**
```
a = .project_to_2d(.one(), .new(2, 2, 3), .zero())
```
reflect(a, normal)
Reflects a vector off a plane defined by a normal.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
normal (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` The normal of the surface being reflected off.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .reflect(.one(), .right())
```
angle(a, b, eps)
Angle in degrees between two vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
eps (float) : `float` Minimum resolution to void division by zero (default=1.0e-15).
Returns: `float` Angle value in degrees.
___
**Usage:**
```
a = .angle(.one(), .up())
```
angle_signed(a, b, axis)
Signed angle in degrees between two vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
axis (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Axis vector.
Returns: `float` Angle value in degrees.
___
**Usage:**
```
a = .angle_signed(.one(), .left(), .down())
```
___
**Notes:**
- The smaller of the two possible angles between the two vectors is returned, therefore the result will never
be greater than 180 degrees or smaller than -180 degrees.
- If you imagine the from and to vectors as lines on a piece of paper, both originating from the same point,
then the /axis/ vector would point up out of the paper.
- The measured angle between the two vectors would be positive in a clockwise direction and negative in an
anti-clockwise direction.
___
**Reference:**
- github.com
angle2d(a, b)
2D angle between two vectors.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
b (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Target vector.
Returns: `float` Angle value in degrees.
___
**Usage:**
```
a = .angle2d(.one(), .left())
```
transform_Matrix(a, M)
Transforms a vector by the given matrix.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
M (matrix) : `matrix` A 4x4 matrix. The transformation matrix.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
mat = matrix.new(4, 0)
mat.add_row(0, array.from(0.0, 0.0, 0.0, 1.0))
mat.add_row(1, array.from(0.0, 0.0, 1.0, 0.0))
mat.add_row(2, array.from(0.0, 1.0, 0.0, 0.0))
mat.add_row(3, array.from(1.0, 0.0, 0.0, 0.0))
b = .transform_Matrix(.one(), mat)
```
transform_M44(a, M)
Transforms a vector by the given matrix.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
M (M44 type from RicardoSantos/CommonTypesMath/1) : `M44` A 4x4 matrix. The transformation matrix.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .transform_M44(.one(), .M44.new(0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0))
```
___
**Notes:**
- Type `M44` from `CommonTypesMath` library.
transform_normal_Matrix(a, M)
Transforms a vector by the given matrix.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
M (matrix) : `matrix` A 4x4 matrix. The transformation matrix.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
mat = matrix.new(4, 0)
mat.add_row(0, array.from(0.0, 0.0, 0.0, 1.0))
mat.add_row(1, array.from(0.0, 0.0, 1.0, 0.0))
mat.add_row(2, array.from(0.0, 1.0, 0.0, 0.0))
mat.add_row(3, array.from(1.0, 0.0, 0.0, 0.0))
b = .transform_normal_Matrix(.one(), mat)
```
transform_normal_M44(a, M)
Transforms a vector by the given matrix.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector.
M (M44 type from RicardoSantos/CommonTypesMath/1) : `M44` A 4x4 matrix. The transformation matrix.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .transform_normal_M44(.one(), .M44.new(0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0))
```
___
**Notes:**
- Type `M44` from `CommonTypesMath` library.
transform_Array(a, rotation)
Transforms a vector by the given Quaternion rotation value.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector. The source vector to be rotated.
rotation (float ) : `array` A 4 element array. Quaternion. The rotation to apply.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .transform_Array(.one(), array.from(0.2, 0.2, 0.2, 1.0))
```
___
**Reference:**
- referencesource.microsoft.com
transform_Quaternion(a, rotation)
Transforms a vector by the given Quaternion rotation value.
Parameters:
a (Vector3 type from RicardoSantos/CommonTypesMath/1) : `Vector3` Source vector. The source vector to be rotated.
rotation (Quaternion type from RicardoSantos/CommonTypesMath/1) : `array` A 4 element array. Quaternion. The rotation to apply.
Returns: `Vector3` Generated new vector.
___
**Usage:**
```
a = .transform_Quaternion(.one(), .Quaternion.new(0.2, 0.2, 0.2, 1.0))
```
___
**Notes:**
- Type `Quaternion` from `CommonTypesMath` library.
___
**Reference:**
- referencesource.microsoft.com
arraybrowser█ ARRAY BROWSER
Add you arrays to the array browser window and scroll them away left and right.
Flexible formatting options (see below).
Many thanks to @kaigouthro for his beautiful matrixautotable library. (import kaigouthro/matrixautotable/14)
How to use
Copy the "ARRAY BROWSER" commented code section below to your script and uncomment.
See DEMO section in the library for usage examples.
Basically: add() your arrays and draw() on barstate.islast.
If your script adds the arrays every calculation do not forget to clear() before adding.
Otherwise, since the arrays are added by reference, no need to add them on every bar, every time you draw() the actual values are retrieved.
Up to 10 arrays of each type (float/string/line/label/box) are supported (total 50 arrays).
Change offset in the input settings to scroll left/right.
Usage example:
import moebius1977/arraybrowser/1 as arraybrowser // this alias is used in the copied section, so better keep it
arbr.clear() // clears all rows and deletes the table
arbr.add(arrayFloat, format = "0.00") // adds an array with title
arbr.add(arrayInt) // adds an array without title
arbr.add(arrayTimes, "array of times 1", "date time") // format date and time so as to fit in the cell.
arbr.add(arrayTimes, "array of times 2", "{0, time, HH:mm}") // format date and time so as to fit in the cell.
arbr.add(arrayString) //
arbr.add(arrayLine, "arrayLines", "(x1, y1) (x2,y2)") // use your own format combining "x1", "y1", "x2", "y2"
arbr.add(arrayLabel, "arrayLabel", "txt") // only print label text, no coordinates
arbr.add(arrayBox, showIds = true) // show ID's for this array if input setting is "individually"
arbr.draw() // shows the table with arrays, use on barstate.islast
Formatting options
For float/int you can always use format string like "{0, time, HH:mm:ss}" or "{0.00}".
Additional options are
- --- Number formats ---
- "number"
- "0"
- "0.0"
- "0.00"
- "0.000"
- "0.0000"
- "0.00000"
- "0.000000"
- "0.0000000"
- --- Date formats ---
- "date"
- "date : time"
- "dd.MM"
- "dd"
- --- Time formats ---
- "time"
- "HH:mm"
- "mm:ss"
- "date time"
- "date, time"
- "date,time"
- "date\time"
For line and box : Empty `format` returns coordinates as "(x1, y1) - (x2, y2)". Otherwise "x1", "x2", "y1", "y2" in `format` string are replaced by values. (e.g. toS(line, "x1, x2") will only return x1 and x2 separated by comma).
For label : Empty `format` returns coordinates and text as "(x, y): text = text". Otherwise "x1", "y1", "txt" in `format` string are replaced by values. (e.g. toS(label, "txt") will only return text of the label)
Boxes_PlotIn the world of data visualization, heatmaps are an invaluable tool for understanding complex datasets. They use color gradients to represent the values of individual data points, allowing users to quickly identify patterns, trends, and outliers in their data. In this post, we will delve into the history of heatmaps, and then discuss how its implemented.
The "Boxes_Plot" library is a powerful and versatile tool for visualizing multiple indicators on a trading chart using colored boxes, commonly known as heatmaps. These heatmaps provide a user-friendly and efficient method for analyzing the performance and trends of various indicators simultaneously. The library can be customized to display multiple charts, adjust the number of rows, and set the appropriate offset for proper spacing. This allows traders to gain insights into the market and make informed decisions.
Heatmaps with cells are interesting and useful for several reasons. Firstly, they allow for the visualization of large datasets in a compact and organized manner. This is especially beneficial when working with multiple indicators, as it enables traders to easily compare and contrast their performance. Secondly, heatmaps provide a clear and intuitive representation of the data, making it easier for traders to identify trends and patterns. Finally, heatmaps offer a visually appealing way to present complex information, which can help to engage and maintain the interest of traders.
History of Heatmaps
The concept of heatmaps can be traced back to the 19th century when French cartographer and sociologist Charles Joseph Minard used color gradients to visualize statistical data. He is well-known for his 1869 map, which depicted Napoleon's disastrous Russian campaign of 1812 using a color gradient to represent the dwindling size of Napoleon's army.
In the 20th century, heatmaps gained popularity in the fields of biology and genetics, where they were used to visualize gene expression data. In the early 2000s, heatmaps found their way into the world of finance, where they are now used to display stock market data, such as price, volume, and performance.
The boxes_plot function in the library expects a normalized value from 0 to 100 as input. Normalizing the data ensures that all values are on a consistent scale, making it easier to compare different indicators. The function also allows for easy customization, enabling users to adjust the number of rows displayed, the size of the boxes, and the offset for proper spacing.
One of the key features of the library is its ability to automatically scale the chart to the screen. This ensures that the heatmap remains clear and visible, regardless of the size or resolution of the user's monitor. This functionality is essential for traders who may be using various devices and screen sizes, as it enables them to easily access and interpret the heatmap without needing to make manual adjustments.
In order to create a heatmap using the boxes_plot function, users need to supply several parameters:
1. Source: An array of floating-point values representing the indicator values to display.
2. Name: An array of strings representing the names of the indicators.
3. Boxes_per_row: The number of boxes to display per row.
4. Offset (optional): An integer to offset the boxes horizontally (default: 0).
5. Scale (optional): A floating-point value to scale the size of the boxes (default: 1).
The library also includes a gradient function (grad) that is used to generate the colors for the heatmap. This function is responsible for determining the appropriate color based on the value of the indicator, with higher values typically represented by warmer colors such as red and lower values by cooler colors such as blue.
Implementing Heatmaps as a Pine Script Library
In this section, we'll explore how to create a Pine Script library that can be used to generate heatmaps for various indicators on the TradingView platform. The library utilizes colored boxes to represent the values of multiple indicators, making it simple to visualize complex data.
We'll now go over the key components of the code:
grad(src) function: This function takes an integer input 'src' and returns a color based on a predefined color gradient. The gradient ranges from dark blue (#1500FF) for low values to dark red (#FF0000) for high values.
boxes_plot() function: This is the main function of the library, and it takes the following parameters:
source: an array of floating-point values representing the indicator values to display
name: an array of strings representing the names of the indicators
boxes_per_row: the number of boxes to display per row
offset (optional): an integer to offset the boxes horizontally (default: 0)
scale (optional): a floating-point value to scale the size of the boxes (default: 1)
The function first calculates the screen size and unit size based on the visible chart area. Then, it creates an array of box objects representing each data point. Each box is assigned a color based on the value of the data point using the grad() function. The boxes are then plotted on the chart using the box.new() function.
Example Usage:
In the example provided in the source code, we use the Relative Strength Index (RSI) and the Stochastic Oscillator as the input data for the heatmap. We create two arrays, 'data_1' containing the RSI and Stochastic Oscillator values, and 'data_names_1' containing the names of the indicators. We then call the 'boxes_plot()' function with these arrays, specifying the desired number of boxes per row, offset, and scale.
Conclusion
Heatmaps are a versatile and powerful data visualization tool with a rich history, spanning multiple fields of study. By implementing a heatmap library in Pine Script, we can enhance the capabilities of the TradingView platform, making it easier for users to visualize and understand complex financial data. The provided library can be easily customized and extended to suit various use cases and can be a valuable addition to any trader's toolbox.
Library "Boxes_Plot"
boxes_plot(source, name, boxes_per_row, offset, scale)
Parameters:
source (float ) : - an array of floating-point values representing the indicator values to display
name (string ) : - an array of strings representing the names of the indicators
boxes_per_row (int) : - the number of boxes to display per row
offset (int) : - an optional integer to offset the boxes horizontally (default: 0)
scale (float) : - an optional floating-point value to scale the size of the boxes (default: 1)
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)
ReversalChartPatternLibraryLibrary "ReversalChartPatternLibrary"
User Defined Types and Methods for reversal chart patterns - Double Top, Double Bottom, Triple Top, Triple Bottom, Cup and Handle, Inverted Cup and Handle, Head and Shoulders, Inverse Head and Shoulders
method delete(this)
Deletes the drawing components of ReversalChartPatternDrawing object
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method delete(this)
Deletes the drawing components of ReversalChartPattern object. In turn calls the delete of ReversalChartPatternDrawing
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method lpush(this, obj, limit, deleteOld)
Array push with limited number of items in the array. Old items are deleted when new one comes and exceeds the limit
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern ) : array object
obj (ReversalChartPattern) : ReversalChartPattern object which need to be pushed to the array
limit (int) : max items on the array. Default is 10
deleteOld (bool) : If set to true, also deletes the drawing objects. If not, the drawing objects are kept but the pattern object is removed from array. Default is false.
Returns: current ReversalChartPattern object
method draw(this)
Draws the components of ReversalChartPatternDrawing
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method draw(this)
Draws the components of ReversalChartPatternDrawing within the ReversalChartPattern object.
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method scan(zigzag, patterns, errorPercent, shoulderStart, shoulderEnd)
Scans zigzag for ReversalChartPattern occurences
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from HeWhoMustNotBeNamed/ZigzagTypes/2) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patterns (ReversalChartPattern ) : Existing patterns array. Used for validating duplicates
errorPercent (float) : Error threshold for considering ratios. Default is 13
shoulderStart (float) : Starting range of shoulder ratio. Used for identifying shoulders, handles and necklines
shoulderEnd (float) : Ending range of shoulder ratio. Used for identifying shoulders, handles and necklines
Returns: int pattern type
method createPattern(zigzag, patternType, patternColor, riskAdjustment)
Create Pattern from ZigzagTypes.Zigzag object
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from HeWhoMustNotBeNamed/ZigzagTypes/2) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patternType (int) : Type of pattern being created. 1 - Double Tap, 2 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders
patternColor (color) : Color in which the patterns are drawn
riskAdjustment (float) : Used for calculating stops
Returns: ReversalChartPattern object created
method getName(this)
get pattern name of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string name of the pattern
method getDescription(this)
get consolidated description of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string consolidated description
method init(this)
initializes the ReversalChartPattern object and creates sub object types
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: ReversalChartPattern current object
ReversalChartPatternDrawing
Type which holds the drawing objects for Reversal Chart Pattern Types
Fields:
patternLines (Line type from HeWhoMustNotBeNamed/DrawingTypes/1) : array of Line objects representing pattern
entry (Line type from HeWhoMustNotBeNamed/DrawingTypes/1) : Entry price Line
target (Line type from HeWhoMustNotBeNamed/DrawingTypes/1) : Target price Line
patternLabel (Label type from HeWhoMustNotBeNamed/DrawingTypes/1)
ReversalChartPattern
Reversal Chart Pattern master type which holds the pattern components, drawings and trade details
Fields:
pivots (Pivot type from HeWhoMustNotBeNamed/ZigzagTypes/2) : Array of Zigzag Pivots forming the pattern
patternType (series int) : Defines the main type of pattern 1 - Double Tap, 1 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders
patternColor (series color) : Color in which the pattern will be drawn on chart
riskAdjustment (series float) : Percentage adjustment of risk. Used for setting stops
drawing (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object which holds the drawing components
trade (Trade type from HeWhoMustNotBeNamed/TradeTracker/1) : TradeTracker.Trade object holding trade components
Branch CurveLibrary "branch"
Generates a branch made of segments with a starting angle
and a turning angle for each segment. The branch is generated from a starting point
and a number of nodes to generate. The length of each segment and angle of each segment
can be adjusted. The branch can be generated in 2D or 3D, render as you wish.
method branch(origin, nodes, segment_length, segment_growth, angle_start, angle_turn)
# Branch Generation.
- `origin`: CommonTypesMath.Vector3 - The starting point of the branch. If the z value is not zero, it will be used as the starting angle.
- `nodes`: int - The number of nodes to generate.
- `segment_length`: float - The length of each segment.
- `segment_growth`: float - The growth of each segment. 0 = no growth, 100 = double the length of the previous segment.
- `angle_start`: float - The starting angle of the branch in degrees.
- `angle_turn`: float - The turning angle of each segment in degrees.
Namespace types: CommonTypesMath.Vector3
Parameters:
origin (Vector3 type from RicardoSantos/CommonTypesMath/1) : The starting point of the branch. If the z value is not zero, it will be used as the starting angle.
nodes (int) : The number of nodes to generate.
segment_length (float) : The length of each segment.
segment_growth (float) : The growth of each segment. 0 = no growth, 100 = double the length of the previous segment.
angle_start (float) : The starting angle of the branch in degrees.
angle_turn (float) : The turning angle of each segment in degrees.
@return segments The list of segments that make up the branch.
HarmonicPatternTrackingLibrary "HarmonicPatternTracking"
Library contains few data structures and methods for tracking harmonic pattern trades via pinescript.
method draw(this)
Creates and draws HarmonicDrawing object for given HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
method addTrade(this)
calculates HarmonicTrade and sets trade object for HarmonicPattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: bool true if pattern trades are valid, false otherwise
method delete(this)
Deletes drawing objects of HarmonicDrawing
Namespace types: HarmonicDrawing
Parameters:
this (HarmonicDrawing) : HarmonicDrawing object
Returns: current HarmonicDrawing object
method delete(this)
Deletes drawings of harmonic pattern
Namespace types: HarmonicPattern
Parameters:
this (HarmonicPattern) : HarmonicPattern object
Returns: current HarmonicPattern object
HarmonicDrawing
Drawing objects of Harmonic Pattern
Fields:
xa (series line) : xa line
ab (series line) : ab line
bc (series line) : bc line
cd (series line) : cd line
xb (series line) : xb line
bd (series line) : bd line
ac (series line) : ac line
xd (series line) : xd line
x (series label) : label for pivot x
a (series label) : label for pivot a
b (series label) : label for pivot b
c (series label) : label for pivot c
d (series label) : label for pivot d
xabRatio (series label) : label for XAB Ratio
abcRatio (series label) : label for ABC Ratio
bcdRatio (series label) : label for BCD Ratio
xadRatio (series label) : label for XAD Ratio
HarmonicTrade
Trade tracking parameters of Harmonic Patterns
Fields:
initialEntry (series float) : initial entry when pattern first formed.
entry (series float) : trailed entry price.
initialStop (series float) : initial stop when trade first entered.
stop (series float) : current stop updated as per trailing rules.
target1 (series float) : First target value
target2 (series float) : Second target value
target3 (series float) : Third target value
target4 (series float) : Fourth target value
status (series int) : Trade status referenced as integer
retouch (series bool) : Flag to show if the price retouched after entry
HarmonicProperties
Display and trade calculation properties for Harmonic Patterns
Fields:
fillMajorTriangles (series bool) : Display property used for using linefill for harmonic major triangles
fillMinorTriangles (series bool) : Display property used for using linefill for harmonic minor triangles
majorFillTransparency (series int) : transparency setting for major triangles
minorFillTransparency (series int) : transparency setting for minor triangles
showXABCD (series bool) : Display XABCD pivot labels
lblSizePivots (series string) : Pivot label size
showRatios (series bool) : Display Ratio labels
useLogScaleForScan (series bool) : Use log scale to determine fib ratios for pattern scanning
useLogScaleForTargets (series bool) : Use log scale to determine fib ratios for target calculation
base (series string) : base on which calculation of stop/targets are made.
entryRatio (series float) : fib ratio to calculate entry
stopRatio (series float) : fib ratio to calculate initial stop
target1Ratio (series float) : fib ratio to calculate first target
target2Ratio (series float) : fib ratio to calculate second target
target3Ratio (series float) : fib ratio to calculate third target
target4Ratio (series float) : fib ratio to calculate fourth target
HarmonicPattern
Harmonic pattern object to track entire pattern trade life cycle
Fields:
id (series int) : Pattern Id
dir (series int) : pattern direction
x (series float) : X Pivot
a (series float) : A Pivot
b (series float) : B Pivot
c (series float) : C Pivot
d (series float) : D Pivot
xBar (series int) : Bar index of X Pivot
aBar (series int) : Bar index of A Pivot
bBar (series int) : Bar index of B Pivot
cBar (series int) : Bar index of C Pivot
dBar (series int) : Bar index of D Pivot
przStart (series float) : Start of PRZ range
przEnd (series float) : End of PRZ range
patterns (bool ) : array representing the patterns
patternLabel (series string) : string representation of list of patterns
patternColor (series color) : color assigned to pattern
properties (HarmonicProperties) : HarmonicProperties object containing display and calculation properties
trade (HarmonicTrade) : HarmonicTrade object to track trades
drawing (HarmonicDrawing) : HarmonicDrawing object to manage drawings
MarkovAlgorithmLibrary "MarkovAlgorithm"
Markov algorithm is a string rewriting system that uses grammar-like rules to operate on strings of
symbols. Markov algorithms have been shown to be Turing-complete, which means that they are suitable as a
general model of computation and can represent any mathematical expression from its simple notation.
~ wikipedia
.
reference:
en.wikipedia.org
rosettacode.org
parse(rules, separator)
Parameters:
rules (string)
separator (string)
Returns: - `array _rules`: List of rules.
---
Usage:
- `parse("|0 -> 0|| 1 -> 0| 0 -> ")`
apply(expression, rules)
Aplies rules to a expression.
Parameters:
expression (string) : `string`: Text expression to be formated by the rules.
rules (rule ) : `string`: Rules to apply to expression on a string format to be parsed.
Returns: - `string _result`: Formated expression.
---
Usage:
- `apply("101", parse("|0 -> 0|| 1 -> 0| 0 -> "))`
apply(expression, rules)
Parameters:
expression (string)
rules (string)
Returns: - `string _result`: Formated expression.
---
Usage:
- `apply("101", parse("|0 -> 0|| 1 -> 0| 0 -> "))`
rule
String pair that represents `pattern -> replace`, each rule may be ordinary or terminating.
Fields:
pattern (series string) : Pattern to replace.
replacement (series string) : Replacement patterns.
termination (series bool) : Termination rule.
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`