NormalDistributionFunctionsLibrary "NormalDistributionFunctions"
The NormalDistributionFunctions library encompasses a comprehensive suite of statistical tools for financial market analysis. It provides functions to calculate essential statistical measures such as mean, standard deviation, skewness, and kurtosis, alongside advanced functionalities for computing the probability density function (PDF), cumulative distribution function (CDF), Z-score, and confidence intervals. This library is designed to assist in the assessment of market volatility, distribution characteristics of asset returns, and risk management calculations, making it an invaluable resource for traders and financial analysts.
meanAndStdDev(source, length)
Calculates and returns the mean and standard deviation for a given data series over a specified period.
Parameters:
source (float) : float: The data series to analyze.
length (int) : int: The lookback period for the calculation.
Returns: Returns an array where the first element is the mean and the second element is the standard deviation of the data series for the given period.
skewness(source, mean, stdDev, length)
Calculates and returns skewness for a given data series over a specified period.
Parameters:
source (float) : float: The data series to analyze.
mean (float) : float: The mean of the distribution.
stdDev (float) : float: The standard deviation of the distribution.
length (int) : int: The lookback period for the calculation.
Returns: Returns skewness value
kurtosis(source, mean, stdDev, length)
Calculates and returns kurtosis for a given data series over a specified period.
Parameters:
source (float) : float: The data series to analyze.
mean (float) : float: The mean of the distribution.
stdDev (float) : float: The standard deviation of the distribution.
length (int) : int: The lookback period for the calculation.
Returns: Returns kurtosis value
pdf(x, mean, stdDev)
pdf: Calculates the probability density function for a given value within a normal distribution.
Parameters:
x (float) : float: The value to evaluate the PDF at.
mean (float) : float: The mean of the distribution.
stdDev (float) : float: The standard deviation of the distribution.
Returns: Returns the probability density function value for x.
cdf(x, mean, stdDev)
cdf: Calculates the cumulative distribution function for a given value within a normal distribution.
Parameters:
x (float) : float: The value to evaluate the CDF at.
mean (float) : float: The mean of the distribution.
stdDev (float) : float: The standard deviation of the distribution.
Returns: Returns the cumulative distribution function value for x.
confidenceInterval(mean, stdDev, size, confidenceLevel)
Calculates the confidence interval for a data series mean.
Parameters:
mean (float) : float: The mean of the data series.
stdDev (float) : float: The standard deviation of the data series.
size (int) : int: The sample size.
confidenceLevel (float) : float: The confidence level (e.g., 0.95 for 95% confidence).
Returns: Returns the lower and upper bounds of the confidence interval.
Indicators and strategies
ApproximateGaussianSmoothingLibrary "ApproximateGaussianSmoothing"
This library provides a novel smoothing function for time-series data, serving as an alternative to SMA and EMA. Additionally, it provides some statistical processing, using moving averages as expected values in statistics.
'Approximate Gaussian Smoothing' (AGS) is designed to apply weights to time-series data that closely resemble Gaussian smoothing weights. it is easier to calculate than the similar ALMA.
In case AGS is used as a moving average, I named it 'Approximate Gaussian Weighted Moving Average' (AGWMA).
The formula is:
AGWMA = (EMA + EMA(EMA) + EMA(EMA(EMA)) + EMA(EMA(EMA(EMA)))) / 4
The EMA parameter alpha is 5 / (N + 4) , using time period N (or length).
ma(src, length)
Calculate moving average using AGS (AGWMA).
Parameters:
src (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Moving average.
analyse(src, length)
Calculate mean and variance using AGS.
Parameters:
src (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Mean and variance.
analyse(dimensions, sources, length)
Calculate mean and variance covariance matrix using AGS.
Parameters:
dimensions (simple int) : Dimensions of sources to process.
sources (array) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Mean and variance covariance matrix.
trend(src, length)
Calculate intercept (LSMA) and slope using AGS.
Parameters:
src (float) : Series of values to process.
length (simple int) : Number of bars (length).
Returns: Intercept and slope.
aproxLibrary "aprox"
It's a library of the aproximations of a price or Series float it uses Fourier transform and
Euler's Theoreum for Homogenus White noice operations. Calling functions without source value it automatically take close as the default source value.
Copy this indicator to see how each approximations interact between each other.
import Celje_2300/aprox/1 as aprox
//@version=5
indicator("Close Price with Aproximations", shorttitle="Close and Aproximations", overlay=false)
// Sample input data (replace this with your own data)
inputData = close
// Plot Close Price
plot(inputData, color=color.blue, title="Close Price")
dtf32_result = aprox.DTF32()
plot(dtf32_result, color=color.green, title="DTF32 Aproximation")
fft_result = aprox.FFT()
plot(fft_result, color=color.red, title="DTF32 Aproximation")
wavelet_result = aprox.Wavelet()
plot(wavelet_result, color=color.orange, title="Wavelet Aproximation")
wavelet_std_result = aprox.Wavelet_std()
plot(wavelet_std_result, color=color.yellow, title="Wavelet_std Aproximation")
DFT3(xval, _dir)
Parameters:
xval (float)
_dir (int)
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - DFT3", shorttitle="DFT3 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply DFT3
result = aprox.DFT3(inputData, 2)
// Plot the result
plot(result, color=color.blue, title="DFT3 Result")
DFT2(xval, _dir)
Parameters:
xval (float)
_dir (int)
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - DFT2", shorttitle="DFT2 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply DFT2
result = aprox.DFT2(inputData, inputData, 1)
// Plot the result
plot(result, color=color.green, title="DFT2 Result")
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - DFT2", shorttitle="DFT2 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply DFT2
result = aprox.DFT2(inputData, 1)
// Plot the result
plot(result, color=color.green, title="DFT2 Result")
FFT(xval)
FFT: Fast Fourier Transform
Parameters:
xval (float)
Returns: Aproxiated source value
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - FFT", shorttitle="FFT Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply FFT
result = aprox.FFT(inputData)
// Plot the result
plot(result, color=color.red, title="FFT Result")
DTF32(xval)
DTF32: Combined Discrete Fourier Transforms
Parameters:
xval (float)
Returns: Aproxiated source value
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - DTF32", shorttitle="DTF32 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply DTF32
result = aprox.DTF32(inputData)
// Plot the result
plot(result, color=color.purple, title="DTF32 Result")
whitenoise(indic_, _devided, minEmaLength, maxEmaLength, src)
whitenoise: Ehler's Universal Oscillator with White Noise, without extra aproximated src
Parameters:
indic_ (float)
_devided (int)
minEmaLength (int)
maxEmaLength (int)
src (float)
Returns: Smoothed indicator value
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - whitenoise", shorttitle="whitenoise Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply whitenoise
result = aprox.whitenoise(aprox.FFT(inputData))
// Plot the result
plot(result, color=color.orange, title="whitenoise Result")
whitenoise(indic_, dft1, _devided, minEmaLength, maxEmaLength, src)
whitenoise: Ehler's Universal Oscillator with White Noise and DFT1
Parameters:
indic_ (float)
dft1 (float)
_devided (int)
minEmaLength (int)
maxEmaLength (int)
src (float)
Returns: Smoothed indicator value
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - whitenoise with DFT1", shorttitle="whitenoise-DFT1 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply whitenoise with DFT1
result = aprox.whitenoise(inputData, aprox.DFT1(inputData))
// Plot the result
plot(result, color=color.yellow, title="whitenoise-DFT1 Result")
smooth(dft1, indic__, _devided, minEmaLength, maxEmaLength, src)
smooth: Smoothing source value with help of indicator series and aproximated source value
Parameters:
dft1 (float)
indic__ (float)
_devided (int)
minEmaLength (int)
maxEmaLength (int)
src (float)
Returns: Smoothed source series
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - smooth", shorttitle="smooth Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply smooth
result = aprox.smooth(inputData, aprox.FFT(inputData))
// Plot the result
plot(result, color=color.gray, title="smooth Result")
smooth(indic__, _devided, minEmaLength, maxEmaLength, src)
smooth: Smoothing source value with help of indicator series
Parameters:
indic__ (float)
_devided (int)
minEmaLength (int)
maxEmaLength (int)
src (float)
Returns: Smoothed source series
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - smooth without DFT1", shorttitle="smooth-NoDFT1 Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply smooth without DFT1
result = aprox.smooth(aprox.FFT(inputData))
// Plot the result
plot(result, color=color.teal, title="smooth-NoDFT1 Result")
vzo_ema(src, len)
vzo_ema: Volume Zone Oscillator with EMA smoothing
Parameters:
src (float)
len (simple int)
Returns: VZO value
vzo_sma(src, len)
vzo_sma: Volume Zone Oscillator with SMA smoothing
Parameters:
src (float)
len (int)
Returns: VZO value
vzo_wma(src, len)
vzo_wma: Volume Zone Oscillator with WMA smoothing
Parameters:
src (float)
len (int)
Returns: VZO value
alma2(series, windowsize, offset, sigma)
alma2: Arnaud Legoux Moving Average 2 accepts sigma as series float
Parameters:
series (float)
windowsize (int)
offset (float)
sigma (float)
Returns: ALMA value
Wavelet(src, len, offset, sigma)
Wavelet: Wavelet Transform
Parameters:
src (float)
len (int)
offset (simple float)
sigma (simple float)
Returns: Wavelet-transformed series
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - Wavelet", shorttitle="Wavelet Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply Wavelet
result = aprox.Wavelet(inputData)
// Plot the result
plot(result, color=color.blue, title="Wavelet Result")
Wavelet_std(src, len, offset, mag)
Wavelet_std: Wavelet Transform with Standard Deviation
Parameters:
src (float)
len (int)
offset (float)
mag (int)
Returns: Wavelet-transformed series
//@version=5
import Celje_2300/aprox/1 as aprox
indicator("Example - Wavelet_std", shorttitle="Wavelet_std Example", overlay=true)
// Sample input data (replace this with your own data)
inputData = close
// Apply Wavelet_std
result = aprox.Wavelet_std(inputData)
// Plot the result
plot(result, color=color.green, title="Wavelet_std Result")
FVG Detector LibraryLibrary "FVG Detector Library"
🔵 Introduction
To save time and improve accuracy in your scripts for identifying Fair Value Gaps (FVGs), you can utilize this library. Apart from detecting and plotting FVGs, one of the most significant advantages of this script is the ability to filter FVGs, which you'll learn more about below. Additionally, the plotting of each FVG continues until either a new FVG occurs or the current FVG is mitigated.
🔵 Definition
Fair Value Gap (FVG) refers to a situation where three consecutive candlesticks do not overlap. Based on this definition, the minimum conditions for detecting a fair gap in the ascending scenario are that the minimum price of the last candlestick should be greater than the maximum price of the third candlestick, and in the descending scenario, the maximum price of the last candlestick should be smaller than the minimum price of the third candlestick.
If the filter is turned off, all FVGs that meet at least the minimum conditions are identified. This mode is simplistic and results in a high number of identified FVGs.
If the filter is turned on, you have four options to filter FVGs :
1. Very Aggressive : In addition to the initial condition, another condition is added. For ascending FVGs, the maximum price of the last candlestick should be greater than the maximum price of the middle candlestick. Similarly, for descending FVGs, the minimum price of the last candlestick should be smaller than the minimum price of the middle candlestick. In this mode, a very small number of FVGs are eliminated.
2. Aggressive : In addition to the conditions of the Very Aggressive mode, in this mode, the size of the middle candlestick should not be small. This mode eliminates more FVGs compared to the Very Aggressive mode.
3. Defensive : In addition to the conditions of the Very Aggressive mode, in this mode, the size of the middle candlestick should be relatively large, and most of it should consist of the body. Also, for identifying ascending FVGs, the second and third candlesticks must be positive, and for identifying descending FVGs, the second and third candlesticks must be negative. In this mode, a significant number of FVGs are eliminated, and the remaining FVGs have a decent quality.
4. Very Defensive : In addition to the conditions of the Defensive mode, the first and third candlesticks should not resemble very small-bodied doji candlesticks. In this mode, the majority of FVGs are filtered out, and the remaining ones are of higher quality.
By default, we recommend using the Defensive mode.
🔵 How to Use
🟣 Parameters
To utilize this library, you need to provide four input parameters to the function.
"FVGFilter" determines whether you wish to apply a filter on FVGs or not. The possible inputs for this parameter are "On" and "Off", provided as strings.
"FVGFilterType" determines the type of filter to be applied to the found FVGs. These filters include four modes: "Very Defensive", "Defensive", "Aggressive", and "Very Aggressive", respectively exhibiting decreasing sensitivity and indicating a higher number of Fair Value Gaps (FVG).
The parameter "ShowDeFVG" is a Boolean value defined as either "true" or "false". If this value is "true", FVGs are shown during the Bullish Trend; however, if it is "false", they are not displayed.
The parameter "ShowSuFVG" is a Boolean value defined as either "true" or "false". If this value is "true", FVGs are displayed during the Bearish Trend; however, if it is "false", they are not displayed.
FVGDetector(FVGFilter, FVGFilterType, ShowDeFVG, ShowSuFVG)
Parameters:
FVGFilter (string)
FVGFilterType (string)
ShowDeFVG (bool)
ShowSuFVG (bool)
🟣 Import Library
You can use the "FVG Detector" library in your script using the following expression:
import TFlab/FVGDetectorLibrary/1 as FVG
🟣 Input Parameters
The descriptions related to the input parameters were provided in the "Parameter" section. In this section, for your convenience, the code related to the inputs is also included, and you can copy and paste it into your script.
PFVGFilter = input.string('On', 'FVG Filter', )
PFVGFilterType = input.string('Defensive', 'FVG Filter Type', )
PShowDeFVG = input.bool(true, ' Show Demand FVG')
PShowSuFVG = input.bool(true, ' Show Supply FVG')
🟣 Call Function
You can copy the following code into your script to call the FVG function. This code is based on the naming conventions provided in the "Input Parameter" section, so if you want to use exactly this code, you should have similar parameter names or have copied the "Input Parameter" values.
FVG.FVGDetector(PFVGFilter, PFVGFilterType, PShowDeFVG, PShowSuFVG)
Material Design ColorsThis library provides a standard set of colors defined in Material Design 2.0.
🔵 API
Step 1: Import this library.
import algotraderdev/material/1
// remember to check the latest version of this library and replace the 1 above.
Step 2: Get the color you like. Check the source code or the screenshot above to see all the supported colors.
material.red()
Each color function (except for `black()` and `white()`) accepts an optional `variant` parameter. You can choose any of 50, 100, 200, 300, 400, 500, 600, 700, 800, and 900. By default, 500 is chosen if this parameter is not provided.
FibonacciAveragesOscillatorLibraryLibrary "FibonacciAveragesOscillatorLibrary"
The FibonacciAveragesOscillator library provides a streamlined way to analyze market trends using Fibonacci intervals and smoothed averages.
fibAvgOscillator(maxFibNumber, smoothLevel)
Parameters:
maxFibNumber (string) : string: The maximum Fibonacci number to use, affecting analysis depth.
smoothLevel (simple int) : simple int: Smoothing level for the oscillator, higher values produce smoother results.
@return series float: The Fibonacci averages trend oscillator value, smoothed over the specified level.
MLMomentumIndexLibrary "MLMomentumIndex"
Enables market momentum analysis with k-NN predictions on pivot points, offering customizable parameters for dynamic trading strategies.
momentumIndexPivots(source, pivotBars, momentumWindow, maxData, numNeighbors, predictionSmoothing)
Parameters:
source (float)
pivotBars (int)
momentumWindow (int)
maxData (int)
numNeighbors (int)
predictionSmoothing (int)
MLPivotsBreakoutsLibrary "MLPivotsBreakouts"
Utilizes k-NN machine learning to predict breakout zones from pivot points, aiding traders in identifying potential bullish and bearish market movements. Ideal for trend-following and breakout strategies.
breakouts(source, pivotBars, numNeighbors, maxData, predictionSmoothing)
Parameters:
source (float) : series float: Price data for analysis.
pivotBars (int) : int: Number of bars for pivot point detection.
numNeighbors (int) : int: Neighbors count for k-NN prediction.
maxData (int) : int: Maximum pivot data points for analysis.
predictionSmoothing (int) : int: Smoothing period for predictions.
@return : Lower and higher prediction bands plus pivot signal, 1 for ph and -1 for pl.
DynamicMAsLibrary "DynamicMAs"
Custom MA's that allow a dynamic calculation beginning from the first bar, irrespective of lookback period.
SMA(src, length)
Dynamic SMA
Parameters:
src (float)
length (int)
EMA(src, length)
Dynamic EMA
Parameters:
src (float)
length (int)
DEMA(src, length)
Dynamic DEMA
Parameters:
src (float)
length (int)
TEMA(src, length)
Dynamic TEMA
Parameters:
src (float)
length (int)
WMA(src, length)
Dynamic WMA
Parameters:
src (float)
length (int)
HMA(src, length)
Dynamic HMA
Parameters:
src (float)
length (int)
VWMA(src, length)
Dynamic VWMA
Parameters:
src (float)
length (int)
SMMA(src, length)
Dynamic SMMA
Parameters:
src (float)
length (int)
LSMA(src, length)
Dynamic LSMA
Parameters:
src (float)
length (int)
ALMA(src, length, offset_sigma, sigma)
Dynamic ALMA
Parameters:
src (float)
length (int)
offset_sigma (float)
sigma (float)
HyperMA(src, length)
Dynamic HyperbolicMA
Parameters:
src (float)
length (int)
lib_risk_managementLibrary "lib_risk_management"
a lib to help with dynamic position sizing
position_size(risk, account_balance, entry_price, sl_price)
calculate the position size required to meet the account size based risk given when the stop loss is triggered
Parameters:
risk (float) : percentage of account balance to risk (1-100)
account_balance (float) : account balance in instrument currency
entry_price (float) : entry price
sl_price (float) : stop loss price
Returns: the position size in instrument currency that will loose the given risk percentage of the account balance when a stop loss is triggered
account_balance(to_currency, live)
converts the (current(default)/initial) account balance to the given currency at the daily rate
Parameters:
to_currency (simple string) The currency in which the account balance is to be converted. Possible values: a three-letter string with the currency code in the ISO 4217 format (e.g. "USD"), or one of the built-in variables that return currency codes, like syminfo.currency or currency.USD.
live (bool) converts the current account balance (strategy.equity) (default:true) or otherwise the initial capital (strategy.initial_capital)
Returns: the (current/initial) account balance converted to the given currency with at the current daily rate
TimeSeriesRecurrencePlotLibrary "TimeSeriesRecurrencePlot"
In descriptive statistics and chaos theory, a recurrence plot (RP) is a plot showing, for each moment i i in time, the times at which the state of a dynamical system returns to the previous state at `i`, i.e., when the phase space trajectory visits roughly the same area in the phase space as at time `j`.
```
A recurrence plot (RP) is a graphical representation used in the analysis of time series data and dynamical systems. It visualizes recurring states or events over time by transforming the original time series into a binary matrix, where each element represents whether two consecutive points are above or below a specified threshold. The resulting Recurrence Plot Matrix reveals patterns, structures, and correlations within the data while providing insights into underlying mechanisms of complex systems.
```
~starling7b
___
Reference:
en.wikipedia.org
github.com
github.com
github.com
github.com
juliadynamics.github.io
distance_matrix(series1, series2, max_freq, norm)
Generate distance matrix between two series.
Parameters:
series1 (float) : Source series 1.
series2 (float) : Source series 2.
max_freq (int) : Maximum frequency to inpect or the size of the generated matrix.
norm (string) : Norm of the distance metric, default=`euclidean`, options=`euclidean`, `manhattan`, `max`.
Returns: Matrix with distance values.
method normalize_distance(M)
Normalizes a matrix within its Min-Max range.
Namespace types: matrix
Parameters:
M (matrix) : Source matrix.
Returns: Normalized matrix.
method threshold(M, threshold)
Updates the matrix with the condition `M(i,j) > threshold ? 1 : 0`.
Namespace types: matrix
Parameters:
M (matrix) : Source matrix.
threshold (float)
Returns: Cross matrix.
rolling_window(a, b, sample_size)
An experimental alternative method to plot a recurrence_plot.
Parameters:
a (array) : Array with data.
b (array) : Array with data.
sample_size (int)
Returns: Recurrence_plot matrix.
TimeSeriesGrammianAngularFieldLibrary "TimeSeriesGrammianAngularField"
provides Grammian angular field and associated utility functions.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
www.researchgate.net
method normalize(data, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.
Namespace types: array
Parameters:
data (array) : Sample data to normalize.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized array within new range.
___
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
normalize_series(source, length, a, b)
Normalize the series to a optional range, usualy within `(-1, 1)` or `(0, 1)`.\
*Note that this may provide a different result than the array version due to rolling range*.
Parameters:
source (float) : Series to normalize.
length (int) : Number of bars to sample the range.
a (float) : Minimum target range value, `default=-1.0`.
b (float) : Minimum target range value, `default= 1.0`.
Returns: Normalized series within new range.
method polar(data)
Turns a normalized sample array into polar coordinates.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Converted array into polar coordinates.
polar_series(source)
Turns a normalized series into polar coordinates.
Parameters:
source (float) : Source series.
Returns: Converted series into polar coordinates.
method gasf(data)
Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
method gasf_id(data)
Trig. identity of Gramian Angular Summation Field *`GASF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GASF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
method gadf(data)
Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
method gadf_id(data)
Trig. identity of Gramian Angular Difference Field *`GADF`*.
Namespace types: array
Parameters:
data (array) : Sampled data values.
Returns: Matrix with *`GADF`* values.
Reference:
*Time Series Classification: A review of Algorithms and Implementations*.
ATE_Common_Functions_LibraryLibrary "ATE_Common_Functions_Library"
- ATE_Common_Functions_Library was created to assist in constructing CCOMET Scanners
RCI(_rciLength, _source, _interval)
You will see me using this a lot. DEFINITELY my favorite oscillator to utilize for SO many different things from
timing entries/exits to determining trends.Calculation of this indicator based on Spearmans Correlation.
Parameters:
_rciLength (int) : (int)
Amount of bars back to use in RCI calculations.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). RCI calculation groups bars by this amount and then will.
rank these groups of bars.
Returns: (float)
Returns a single RCI value that will oscillates between -100 and +100.
RCIAVG(_rciSMAlen, _source, _interval, firstLength, lastLength)
20 RCI's are averaged together to get this RCI Avg (Rank Correlation Index Average). Each RCI (of the 20 total RCI)
has a progressively LARGER Lookback Length. Rather than having ALL of the RCI Lengths be individually adjustable (because of too many inputs),
I have made the FIRST Length used (smallest Length value in the set) and the LAST Length used (largest length value in the set) be adjustable
and all other 18 Lengths are equally spread out between the 'firstLength' and the 'lastLength'.
Parameters:
_rciSMAlen (int) : (int)
Unlike the Single RCI Function, this function smooths out the end result using an SMA with a length value that is this parameter.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional (if parameter not included, it defaults to 3). Within the RCI calculation, bars next to each other are grouped together
and then these groups are Ranked against each other. This parameter is the number of adjacent bars that are grouped together.
firstLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 200).
This parameter is the Lookback Length for the 1st RCI used (so the SMALLEST Length used) in the RCI Avg.
lastLength (int) : (int)
Optional (if parameter is not included when the function is called on in the script, then it defaults to 2500).
This parameter is the Lookback Length for the 20th(the LAST) RCI used (so the LARGEST Length used) in the RCI Avg.
***** BEWARE ***** The 'lastLength' must be less than (or possibly equal to) 5000 because Tradingview has capped it at 5000, causing an error.
***** BEWARE ***** If the script gives a compiler "time out" error then the 'lastLength' must be lowered until it no longer times out when compiling.
Returns: (float)
Returns a single RCI value that is the Avg of many RCI values that will oscillate between -100 and +100.
PercentChange(_startingValue, _endingValue)
This is a quick function to calculate how much % change has occurred between the '_startingValue' and the '_endingValue'
that you input into the function.
Parameters:
_startingValue (float) : (float)
The source value to START the % change calculation from.
_endingValue (float) : (float)
The source value to END the % change caluclation from.
Returns: Returns a single output being the % value between 0-100 (with trailing numbers behind a decimal). If you want only
a certain amount of numbers behind the decimal, this function needs to be put within a formatting function to do so.
Rescale(_source, _oldMin, _oldMax, _newMin, _newMax)
Rescales series with a known '_oldMin' & '_oldMax'. Use this when the scale of the '_source' to
rescale is known (bounded).
Parameters:
_source (float) : (float)
Source to be normalized.
_oldMin (int) : (float)
The known minimum of the '_source'.
_oldMax (int) : (float)
The known maximum of the '_source'.
_newMin (int) : (float)
What you want the NEW minimum of the '_source' to be.
_newMax (int) : (float)
What you want the NEW maximum of the '_source' to be.
Returns: Outputs your previously bounded '_source', but now the value will only move between the '_newMin' and '_newMax'
values you set in the variables.
Normalize_Historical(_source, _minimumLvl, _maximumLvl)
Normalizes '_source' that has a previously unknown min/max(unbounded) determining the max & min of the '_source'
FROM THE ENTIRE CHARTS HISTORY. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns your same '_source', but now the value will MOSTLY stay between the minimum and maximum values you set in the
'_minimumLvl' and '_maximumLvl' variables (ie. if the source you input is an RSI...the output is the same RSI value but
instead of moving between 0-100 it will move between the maxand min you set).
Normailize_Local(_source, _length, _minimumLvl, _maximumLvl)
Normalizes series with previously unknown min/max(unbounded). Much like the Normalize_Historical function above this one,
but rather than using the Highest/Lowest Values within the ENTIRE charts history, this on looks for the Highest/Lowest
values of '_source' within the last ___ bars (set by user as/in the '_length' parameter. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_length (int) : (float)
The amount of bars to look back to determine the highest/lowest '_source' value.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns a single output variable being the previously unbounded '_source' that is now normalized and bound between
the values used for '_minimumLvl'/'_maximumLvl' of the '_source' within the user defined lookback period.
CCOMET_Scanner_LibraryLibrary "CCOMET_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing CCOMET Scanners
Loc_tIDs_Col(_string, _firstLocation)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your CCOMET Scanner.
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my CCOMET Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the TickerIDs, 40 variables for the locations for alert labels, and 40 Colors for labels/plots
TickeridForLabelsAndSecurity(_ticker, _includeExchange)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
_includeExchange (simple bool) : (bool)
Optional (if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your CCOMET Scanner as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the CCOMET Scanner's input.
InvalID_LblSz(_barCnt, _close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your CCOMET Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_close (float) : (float)
Put your 'close' variable named '_close' from the security function here.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never registered then the logic counts the asset as INVALID.
This will be the 1st TickerID variable (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (array) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
_tablePosition (simple string) : (string)
Optional (if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional (if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here, otherwise they will all be in a row.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
convergingpatternsLibrary "convergingpatterns"
Library having implementation of converging chart patterns
getPatternNameByType(patternType)
Returns pattern name based on type
Parameters:
patternType (int) : integer value representing pattern type
Returns: string name of the pattern
method find(this, sProperties, dProperties, patterns, ohlcArray)
find converging patterns for given zigzag
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Current zigzag Object
sProperties (ScanProperties) : ScanProperties Object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/5) : DrawingProperties Object
patterns (array type from Trendoscope/abstractchartpatterns/5) : array of existing patterns to check for duplicates
ohlcArray (array type from Trendoscope/ohlc/1) : array of OHLC values for historical reference
Returns: string name of the pattern
ScanProperties
Object containing properties for pattern scanning
Fields:
baseProperties (ScanProperties type from Trendoscope/abstractchartpatterns/5) : Object of Base Scan Properties
convergingDistanceMultiplier (series float) : when multiplied with pattern size gets the max number of bars within which the pattern should converge
simpletradeLibrary "simpletrade"
Library with Simple Trade types and tracking mechanism
method evaluate(this)
Evaluate current trade and update status
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that need to be evaluated
Returns: current SimpleTrade object
method erase(this)
Erase SimpleTrade drawings
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that needs to be erased
Returns: void
method draw(this, offset, gap)
Draw SimpleTrade drawings
Namespace types: SimpleTrade
Parameters:
this (SimpleTrade) : SimpleTrade object that needs to be drawn
offset (int) : offset distance at which the drawing needs to be drawn.
gap (int) : gap between start and end of the Simple trade drawings
Returns: updated offset
TradeDrawing
Object containing Trade drawings
Fields:
entryToStop (series box) : box showing entry to stop range
entryToTarget (series box) : box showing entry to target range
maxGain (series box) : box highlighting max gain of the Trade
maxLoss (series box) : box highlighting max lowss of the Trade
invalidationLine (series line) : line displaying trade invalidation price
invalidationLabel (series label) : label displaying trade invalidation price
stopLabel (series label) : label displaying trade stop price
entryLabel (series label) : label displaying trade entry price
targetLabel (series label) : label displaying trade target price
patternLabel (series label) : label displaying trade pattern details
SimpleTrade
Object containing Simple trade details for tracking
Fields:
id (series int) : Unique trade id
pid (series int) : parent id for trade. Multiple trades can have single parent id
dir (series int) : trade direction
tradeName (series string) : Trade name or description
tradeColor (series color) : color in which the trade needs to be drawn
entry (series float) : trade entry price
stop (series float) : trade stop price
invalidation (series float) : trade invalidation price
target (series float) : trade target price
maxGainPrice (series float) : price at which the trade attained max gain
maxLossPrice (series float) : price at which the trade attained max loss
drawing (TradeDrawing) : TradeDrawing object contianing drawing items
status (series int) : current status of the trade
maxStatus (series int) : max status attained by the trade
HolidayLibrary "Holiday"
- Full Control over Holidays and Daylight Savings Time (DLS)
The Holiday Library is an essential tool for traders and analysts who engage in backtesting and live trading . This comprehensive library enables the incorporation of crucial calendar elements - specifically Daylight Savings Time (DLS) adjustments and public holidays - into trading strategies and backtesting environments.
Key Features:
- DLS Adjustments: The library takes into account the shifts in time due to Daylight Savings. This feature is particularly vital for backtesting strategies, as DLS can impact trading hours, which in turn affects the volatility and liquidity in the market. Accurate DLS adjustments ensure that backtesting scenarios are as close to real-life conditions as possible.
- Comprehensive Holiday Metadata: The library includes a rich set of holiday metadata, allowing for the detailed scheduling of trading activities around public holidays. This feature is crucial for avoiding skewed results in backtesting, where holiday trading sessions might differ significantly in terms of volume and price movement.
- Customizable Holiday Schedules: Users can add or remove specific holidays, tailoring the library to fit various regional market schedules or specific trading requirements.
- Visualization Aids: The library supports on-chart labels, making it visually intuitive to identify holidays and DLS shifts directly on trading charts.
Use Cases:
1. Strategy Development: When developing trading strategies, it’s important to account for non-trading days and altered trading hours due to holidays and DLS. This library enables a realistic and accurate representation of these factors.
2. Risk Management: Trading around holidays can be riskier due to thinner liquidity and greater volatility. By integrating holiday data, traders can better manage their risk exposure.
3. Backtesting Accuracy: For backtesting to be effective, it must simulate the actual market conditions as closely as possible. Incorporating holidays and DLS adjustments contributes to more reliable and realistic backtesting results.
4. Global Trading: For traders active in multiple global markets, this library provides an easy way to handle different holiday schedules and DLS shifts across regions.
The Holiday Library is a versatile tool that enhances the precision and realism of trading simulations and strategy development . Its integration into the trading workflow is straightforward and beneficial for both novice and experienced traders.
EasterAlgo(_year)
Calculates the date of Easter Sunday for a given year using the Anonymous Gregorian algorithm.
`Gauss Algorithm for Easter Sunday` was developed by the mathematician Carl Friedrich Gauss
This algorithm is based on the cycles of the moon and the fact that Easter always falls on the first Sunday after the first ecclesiastical full moon that occurs on or after March 21.
While it's not considered to be 100% accurate due to rare exceptions, it does give the correct date in most cases.
It's important to note that Gauss's formula has been found to be inaccurate for some 21st-century years in the Gregorian calendar. Specifically, the next suggested failure years are 2038, 2051.
This function can be used for Good Friday (Friday before Easter), Easter Sunday, and Easter Monday (following Monday).
en.wikipedia.org
Parameters:
_year (int) : `int` - The year for which to calculate the date of Easter Sunday. This should be a four-digit year (YYYY).
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday for the given year.
easterInit()
Inits the date of Easter Sunday and Good Friday for a given year.
Returns: tuple - The month (1-12) and day (1-31) of Easter Sunday and Good Friday for the given year.
isLeapYear(_year)
Determine if a year is a leap year.
Parameters:
_year (int) : `int` - 4 digit year to check => YYYY
Returns: `bool` - true if input year is a leap year
method timezoneHelper(utc)
Helper function to convert UTC time.
Namespace types: series int, simple int, input int, const int
Parameters:
utc (int) : `int` - UTC time shift in hours.
Returns: `string`- UTC time string with shift applied.
weekofmonth()
Function to find the week of the month of a given Unix Time.
Returns: number - The week of the month of the specified UTC time.
dayLightSavingsAdjustedUTC(utc, adjustForDLS)
dayLightSavingsAdjustedUTC
Parameters:
utc (int) : `int` - The normal UTC timestamp to be used for reference.
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS).
Returns: `int` - The adjusted UTC timestamp for the given normal UTC timestamp.
getDayOfYear(monthOfYear, dayOfMonth, weekOfMonth, dayOfWeek, lastOccurrenceInMonth, holiday)
Function gets the day of the year of a given holiday (1-366)
Parameters:
monthOfYear (int)
dayOfMonth (int)
weekOfMonth (int)
dayOfWeek (int)
lastOccurrenceInMonth (bool)
holiday (string)
Returns: `int` - The day of the year of the holiday 1-366.
method buildMap(holidayMap, holiday, monthOfYear, weekOfMonth, dayOfWeek, dayOfMonth, lastOccurrenceInMonth, closingTime)
Function to build the `holidaysMap`.
Namespace types: map
Parameters:
holidayMap (map) : `map` - The map of holidays.
holiday (string) : `string` - The name of the holiday.
monthOfYear (int) : `int` - The month of the year of the holiday.
weekOfMonth (int) : `int` - The week of the month of the holiday.
dayOfWeek (int) : `int` - The day of the week of the holiday.
dayOfMonth (int) : `int` - The day of the month of the holiday.
lastOccurrenceInMonth (bool) : `bool` - Flag indicating whether the holiday is the last occurrence of the day in the month.
closingTime (int) : `int` - The closing time of the holiday.
Returns: `map` - The updated map of holidays
holidayInit(addHolidaysArray, removeHolidaysArray, defaultHolidays)
Initializes a HolidayStorage object with predefined US holidays.
Parameters:
addHolidaysArray (array) : `array` - The array of additional holidays to be added.
removeHolidaysArray (array) : `array` - The array of holidays to be removed.
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays.
Returns: `map` - The map of holidays.
Holidays(utc, addHolidaysArray, removeHolidaysArray, adjustForDLS, displayLabel, defaultHolidays)
Main function to build the holidays object, this is the only function from this library that should be needed. \
all functionality should be available through this function. \
With the exception of initializing a `HolidayMetaData` object to add a holiday or early close. \
\
**Default Holidays:** \
`DLS begin`, `DLS end`, `New Year's Day`, `MLK Jr. Day`, \
`Washington Day`, `Memorial Day`, `Independence Day`, `Labor Day`, \
`Columbus Day`, `Veterans Day`, `Thanksgiving Day`, `Christmas Day` \
\
**Example**
```
HolidayMetaData valentinesDay = HolidayMetaData.new(holiday="Valentine's Day", monthOfYear=2, dayOfMonth=14)
HolidayMetaData stPatricksDay = HolidayMetaData.new(holiday="St. Patrick's Day", monthOfYear=3, dayOfMonth=17)
HolidayMetaData addHolidaysArray = array.from(valentinesDay, stPatricksDay)
string removeHolidaysArray = array.from("DLS begin", "DLS end")
܂Holidays = Holidays(
܂ utc=-6,
܂ addHolidaysArray=addHolidaysArray,
܂ removeHolidaysArray=removeHolidaysArray,
܂ adjustForDLS=true,
܂ displayLabel=true,
܂ defaultHolidays=true,
܂ )
plot(Holidays.newHoliday ? open : na, title="newHoliday", color=color.red, linewidth=4, style=plot.style_circles)
```
Parameters:
utc (int) : `int` - The UTC time shift in hours
addHolidaysArray (array) : `array` - The array of additional holidays to be added
removeHolidaysArray (array) : `array` - The array of holidays to be removed
adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS)
displayLabel (bool) : `bool` - Flag indicating whether to display a label on the chart
defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays
Returns: `HolidayObject` - The holidays object | Holidays = (holidaysMap: map, newHoliday: bool, holiday: string, dayString: string)
HolidayMetaData
HolidayMetaData
Fields:
holiday (series string) : `string` - The name of the holiday.
dayOfYear (series int) : `int` - The day of the year of the holiday.
monthOfYear (series int) : `int` - The month of the year of the holiday.
dayOfMonth (series int) : `int` - The day of the month of the holiday.
weekOfMonth (series int) : `int` - The week of the month of the holiday.
dayOfWeek (series int) : `int` - The day of the week of the holiday.
lastOccurrenceInMonth (series bool)
closingTime (series int) : `int` - The closing time of the holiday.
utc (series int) : `int` - The UTC time shift in hours.
HolidayObject
HolidayObject
Fields:
holidaysMap (map) : `map` - The map of holidays.
newHoliday (series bool) : `bool` - Flag indicating whether today is a new holiday.
activeHoliday (series bool) : `bool` - Flag indicating whether today is an active holiday.
holiday (series string) : `string` - The name of the holiday.
dayString (series string) : `string` - The day of the week of the holiday.
LIB_TradeAssistLibrary "LIB_TradeAssist"
This library is a collection of assistence tools saving me the need to copy same code again and again in my various indicators and strategies.
Slop_Magnitude(val_now, val_older, mult_factor)
Calculate the slop magnetude betwen current price and an older price. Since the change is usually minimal, we multiply it by def value of 3000 to make it usable.You can optionally pass other multiply factor
Parameters:
val_now (float)
val_older (float)
mult_factor (float)
Returns: : Slop angle magnetude
basechartpatternsLibrary "basechartpatterns"
Library having complete chart pattern implementation
getPatternNameById(id)
Returns pattern name by id
Parameters:
id (int) : pattern id
Returns: Pattern name
method find(points, properties, dProperties, ohlcArray)
Find patterns based on array of points
Namespace types: chart.point
Parameters:
points (chart.point ) : array of chart.point objects
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
method find(this, properties, dProperties, patterns, ohlcArray)
Find patterns based on the currect zigzag object but will not store them in the pattern array.
Namespace types: zg.Zigzag
Parameters:
this (Zigzag type from Trendoscope/ZigzagLite/2) : Zigzag object containing pivots
properties (ScanProperties type from Trendoscope/abstractchartpatterns/1) : ScanProperties object
dProperties (DrawingProperties type from Trendoscope/abstractchartpatterns/1) : DrawingProperties object
patterns (Pattern type from Trendoscope/abstractchartpatterns/1) : Array of Pattern objects
ohlcArray (OHLC type from Trendoscope/ohlc/1)
Returns: Flag indicating if the pattern is valid, Current Pattern object
abstractchartpatternsLibrary "abstractchartpatterns"
Library having abstract types and methods for chart pattern implementations
checkBarRatio(p1, p2, p3, properties)
checks if three zigzag pivot points are having uniform bar ratios
Parameters:
p1 (chart.point) : First pivot point
p2 (chart.point) : Second pivot point
p3 (chart.point) : Third pivot point
properties (ScanProperties)
Returns: true if points are having uniform bar ratio
getRatioDiff(p1, p2, p3)
gets ratio difference between 3 pivot combinations
Parameters:
p1 (chart.point)
p2 (chart.point)
p3 (chart.point)
Returns: returns the ratio difference between pivot2/pivot1 ratio and pivot3/pivot2 ratio
method inspect(points, stratingBar, endingBar, direction, ohlcArray)
Creates a trend line between 2 or 3 points and validates and selects best combination
Namespace types: chart.point
Parameters:
points (chart.point ) : Array of chart.point objects used for drawing trend line
stratingBar (int) : starting bar of the trend line
endingBar (int) : ending bar of the trend line
direction (float) : direction of the last pivot. Tells whether the line is joining upper pivots or the lower pivots
ohlcArray (OHLC type from Trendoscope/ohlc/1) : Array of OHLC values
Returns: boolean flag indicating if the trend line is valid and the trend line object as tuple
method draw(this)
draws pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be drawn
Returns: Current Pattern object
method erase(this)
erase the given pattern on the chart
Namespace types: Pattern
Parameters:
this (Pattern) : Pattern object that needs to be erased
Returns: Current Pattern object
method push(this, p, maxItems)
push Pattern object to the array by keeping maxItems limit
Namespace types: Pattern
Parameters:
this (Pattern ) : array of Pattern objects
p (Pattern) : Pattern object to be added to array
@oaram maxItems Max number of items the array can hold
maxItems (int)
Returns: Current Pattern array
method deepcopy(this)
Perform deep copy of a chart point array
Namespace types: chart.point
Parameters:
this (chart.point ) : array of chart.point objects
Returns: deep copy array
DrawingProperties
Object containing properties for pattern drawing
Fields:
patternLineWidth (series int) : Line width of the pattern trend lines
showZigzag (series bool) : show zigzag associated with pattern
zigzagLineWidth (series int) : line width of the zigzag lines. Used only when showZigzag is set to true
zigzagLineColor (series color) : color of the zigzag lines. Used only when showZigzag is set to true
showPatternLabel (series bool) : display pattern label containing the name
patternLabelSize (series string) : size of the pattern label. Used only when showPatternLabel is set to true
showPivotLabels (series bool) : Display pivot labels of the patterns marking 1-6
pivotLabelSize (series string) : size of the pivot label. Used only when showPivotLabels is set to true
pivotLabelColor (series color) : color of the pivot label outline. chart.bg_color or chart.fg_color are the appropriate values.
deleteOnPop (series bool) : delete the pattern when popping out from the array of Patterns.
Pattern
Object containing Individual Pattern data
Fields:
points (chart.point )
originalPoints (chart.point )
trendLine1 (Line type from Trendoscope/LineWrapper/1) : First trend line joining pivots 1, 3, 5
trendLine2 (Line type from Trendoscope/LineWrapper/1) : Second trend line joining pivots 2, 4 (, 6)
properties (DrawingProperties) : DrawingProperties Object carrying common properties
patternColor (series color) : Individual pattern color. Lines and labels will be using this color.
ratioDiff (series float) : Difference between trendLine1 and trendLine2 ratios
zigzagLine (series polyline) : Internal zigzag line drawing Object
pivotLabels (label ) : array containning Pivot labels
patternLabel (series label) : pattern label Object
patternType (series int) : integer representing the pattern type
patternName (series string) : Type of pattern in string
ScanProperties
Object containing properties for pattern scanning
Fields:
offset (series int) : Zigzag pivot offset. Set it to 1 for non repainting scan.
numberOfPivots (series int) : Number of pivots to be used in pattern search. Can be either 5 or 6
errorRatio (series float) : Error Threshold to be considered for comparing the slope of lines
flatRatio (series float) : Retracement ratio threshold used to determine if the lines are flat
checkBarRatio (series bool) : Also check bar ratio are within the limits while scanning the patterns
barRatioLimit (series float) : Bar ratio limit used for checking the bars. Used only when checkBarRatio is set to true
avoidOverlap (series bool) : avoid overlapping patterns.
allowedPatterns (bool ) : array of bool encoding the allowed pattern types.
allowedLastPivotDirections (int ) : array of int representing allowed last pivot direction for each pattern types
themeColors (color ) : color array of themes to be used.
series_collectionLibrary "series_collection"
A personal collection of commonly used series types like moving averages that are supported directly by
the pinescript library ('ALMA', 'DEMA', 'EMA', 'HMA', 'RMA', 'SMA', 'SWMA', 'VWMA', 'WMA'), highest and lowest source,
median and pivots. One single function (with overloads) that can be configured easily by the user input and can be
used as a core piece of functionality for many user cases. This library was created to abstract away and re-use this
commonly used functionality in my "Two MA Signal Indicator" script and the "Template Trailing Strategy" script. Both
of them use the "two_ma_logic" for defining entry and exit signals. While this piece of work does not contain any
novel mathematical expressions and just adds a convinient (and configurable) way to do things, I hope that might add
value to other scripts as well and future projects.
cust_series(length, seriesType, source)
cust_series - Calculate the custom series of the given source for the given length and type
Parameters:
length (simple int) : - The length of the custom series
seriesType (simple string) : - The type of the custom series
source (float) : - The source of the values
Returns: - The resulting value of the calculations of the custom series
cust_series(length, seriesType, source)
cust_series - Calculate the custom series of the given source for the given length and type
Parameters:
length (simple float) : - The length of the custom series (ceiled)
seriesType (simple string) : - The type of the custom series
source (float) : - The source of the values
Returns: - The resulting value of the calculations of the custom series
TimeSeriesClassificationActivationFunctionsLibrary "TimeSeriesClassificationActivationFunctions"
Provides some activation functions useful in time series classification.
___
reference:
github.com
method scale(dist, weights)
Activate values by a normalized scale.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: Normalized distribution map.
method softmax(dist, weights)
Activate values with a softmax algorithm.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: Normalized distribution map.
method argmax(dist, weights)
Activate values with a argmax algorithm.
Namespace types: map
Parameters:
dist (map) : Source distribution map.
weights (map) : Weights distribution map.
Returns: first key of argmax value of the transformed distribution.
MatrixScaleDownLibrary "MatrixScaleDown"
Provides a function to scale down a matrix into a smaller square format were its values are averaged to mantain matrix topology.
method scale_down(mat, size)
scale a matrix to a new smaller square size.
Namespace types: matrix
Parameters:
mat (matrix) : Source matrix.
size (int) : New matrix size.
Returns: New matrix with scaled down size. Source values will be averaged together.